modelsdev 0.11.4

A fast TUI and CLI for browsing AI models, benchmarks, and coding agents
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
use anyhow::Result;
use crossterm::{
    event::{DisableMouseCapture, EnableMouseCapture},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{backend::CrosstermBackend, Terminal};
use std::io;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;

pub mod agents;
pub mod app;
pub mod benchmarks;
pub mod event;
pub mod markdown;
pub mod models;
pub mod status;
pub mod ui;
pub mod widgets;

use crate::agents::{
    load_agents, AsyncGitHubClient, ConditionalFetchResult, GitHubCache, GitHubData,
};
use crate::benchmarks::{BenchmarkFetchResult, BenchmarkFetcher, BenchmarkStore};
use crate::config::Config;
use crate::data::ProvidersMap;
use crate::status::{StatusFetchResult, StatusFetcher};
use std::sync::Arc;
use tokio::sync::RwLock;

/// Copy text to clipboard, keeping it alive on Linux.
/// On Linux, the clipboard is selection-based and needs the source app to stay alive.
/// We spawn a thread to hold the clipboard for a few seconds.
fn copy_to_clipboard(text: String) {
    std::thread::spawn(move || {
        if let Ok(mut clipboard) = arboard::Clipboard::new() {
            let _ = clipboard.set_text(&text);
            // Keep clipboard alive for other apps to read on Linux
            std::thread::sleep(std::time::Duration::from_secs(2));
        }
    });
}

/// Result of a GitHub fetch operation for an agent.
#[derive(Debug)]
pub enum FetchResult {
    /// Successful fetch: (agent_id, github_data)
    Success(String, GitHubData),
    /// Failed fetch: (agent_id, error_message)
    Failure(String, String),
}

struct StatusRuntime {
    rx: mpsc::Receiver<(u64, StatusFetchResult)>,
    tx: mpsc::Sender<(u64, StatusFetchResult)>,
    client: reqwest::Client,
    last_fetch_time: Option<Instant>,
    fetch_generation: u64,
}

struct RuntimeHandles {
    github_rx: mpsc::Receiver<FetchResult>,
    github_tx: mpsc::Sender<FetchResult>,
    client: AsyncGitHubClient,
    disk_cache: Arc<RwLock<GitHubCache>>,
    bench_rx: mpsc::Receiver<BenchmarkFetchResult>,
    status: StatusRuntime,
}
pub async fn run(providers: ProvidersMap) -> Result<()> {
    use crate::agents::FetchStatus;

    // Load remaining data
    let agents_file = load_agents().ok();
    let config = Config::load().ok();

    // Benchmark data fetched from CDN in background; starts empty until loaded.
    let benchmark_store = BenchmarkStore::empty();

    // Load disk cache for GitHub data (load before wrapping to avoid blocking in async)
    let disk_cache = GitHubCache::load();

    // Create app BEFORE entering alternate screen
    let mut app = app::App::new(providers, agents_file.as_ref(), config, benchmark_store);

    // Install panic hook to restore terminal on crash
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |panic_info| {
        // Restore terminal before printing panic message
        let _ = disable_raw_mode();
        let _ = execute!(io::stdout(), LeaveAlternateScreen, DisableMouseCapture);
        original_hook(panic_info);
    }));

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

    // Pre-populate agent entries from disk cache for instant display
    if let Some(ref mut agents_app) = app.agents_app {
        for entry in &mut agents_app.entries {
            if entry.tracked {
                // Look up cached data by repo (cache keys are repos)
                if let Some(cached) = disk_cache.get(&entry.agent.repo) {
                    entry.github = cached.data.clone().into();
                    entry.fetch_status = FetchStatus::Loaded;
                }
            }
        }
        // Re-apply sorting after populating cache data (in case sorted by stars/updated)
        agents_app.apply_sort();
    }

    // Now wrap cache in Arc<RwLock> for async sharing
    let disk_cache = Arc::new(RwLock::new(disk_cache));

    // Create GitHub client and channel for fetch results
    let token = crate::agents::github::detect_github_token();
    let client = AsyncGitHubClient::with_disk_cache(token, disk_cache.clone());
    let (tx, rx) = mpsc::channel(100);

    // Spawn background GitHub fetches for agents (non-blocking)
    // Uses conditional fetches with ETag to avoid re-downloading unchanged data
    let fetch_handles = if let Some(ref agents_app) = app.agents_app {
        let tracked_entries: Vec<_> = agents_app.entries.iter().filter(|e| e.tracked).collect();
        let mut handles = Vec::with_capacity(tracked_entries.len());

        for entry in tracked_entries {
            let tx = tx.clone();
            let client = client.clone();
            let id = entry.id.clone();
            let repo = entry.agent.repo.clone();
            let cache = disk_cache.clone();

            let handle = tokio::spawn(async move {
                let result = match client.fetch_conditional(&repo).await {
                    ConditionalFetchResult::Fresh(data, _etag) => FetchResult::Success(id, data),
                    ConditionalFetchResult::NotModified => {
                        let cache_guard = cache.read().await;
                        if let Some(cached) = cache_guard.get(&repo) {
                            FetchResult::Success(id, cached.data.clone().into())
                        } else {
                            FetchResult::Failure(id, "Cache miss on NotModified".to_string())
                        }
                    }
                    ConditionalFetchResult::Error(e) => FetchResult::Failure(id, e),
                };
                let _ = tx.send(result).await;
            });
            handles.push(handle);
        }
        handles
    } else {
        Vec::new()
    };

    // Spawn background benchmark fetch from CDN
    let (bench_tx, bench_rx) = mpsc::channel(1);
    tokio::spawn(async move {
        let fetcher = BenchmarkFetcher::new();
        let result = fetcher.fetch().await;
        let _ = bench_tx.send(result).await;
    });

    let (status_tx, status_rx) = mpsc::channel(4);
    let status_client = reqwest::Client::builder()
        .user_agent("models-tui")
        .connect_timeout(Duration::from_secs(5))
        .build()
        .expect("Failed to build HTTP client");
    if let Some(ref status_app) = app.status_app {
        let seeds = status_app.fetch_seeds();
        let tx = status_tx.clone();
        let fetcher = StatusFetcher::with_client(status_client.clone());
        tokio::spawn(async move {
            let result = fetcher.fetch(&seeds).await;
            let _ = tx.send((0, result)).await;
        });
    }

    let status_runtime = StatusRuntime {
        rx: status_rx,
        tx: status_tx,
        client: status_client,
        last_fetch_time: None,
        fetch_generation: 0,
    };
    let runtime_handles = RuntimeHandles {
        github_rx: rx,
        github_tx: tx,
        client,
        disk_cache: disk_cache.clone(),
        bench_rx,
        status: status_runtime,
    };
    let result = run_app(&mut terminal, &mut app, runtime_handles);

    // Abort any remaining fetch tasks to allow clean shutdown
    for handle in fetch_handles {
        handle.abort();
    }

    // Save cache to disk before exiting (best-effort, don't crash on failure)
    // Use try_read() to avoid blocking in async context
    if let Ok(cache_guard) = disk_cache.try_read() {
        // Ignore save errors - cache is not critical and we don't want to crash on exit
        let _ = cache_guard.save();
    }

    // Restore terminal
    disable_raw_mode()?;
    execute!(
        terminal.backend_mut(),
        LeaveAlternateScreen,
        DisableMouseCapture
    )?;
    terminal.show_cursor()?;

    result
}

fn run_app(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut app::App,
    mut runtime: RuntimeHandles,
) -> Result<()> {
    let mut last_status_time: Option<std::time::Instant> = None;

    loop {
        terminal.draw(|f| ui::draw(f, app))?;

        // Clear status after 2 seconds
        if let Some(time) = last_status_time {
            if time.elapsed() > std::time::Duration::from_secs(2) {
                app.clear_status();
                last_status_time = None;
            }
        }

        // Spawn fetches for newly tracked agents
        if !app.pending_fetches.is_empty() {
            let fetches = std::mem::take(&mut app.pending_fetches);
            for (agent_id, repo) in fetches {
                let tx = runtime.github_tx.clone();
                let client = runtime.client.clone();
                let cache = runtime.disk_cache.clone();

                tokio::spawn(async move {
                    let result = match client.fetch_conditional(&repo).await {
                        ConditionalFetchResult::Fresh(data, _etag) => {
                            FetchResult::Success(agent_id, data)
                        }
                        ConditionalFetchResult::NotModified => {
                            let cache_guard = cache.read().await;
                            if let Some(cached) = cache_guard.get(&repo) {
                                FetchResult::Success(agent_id, cached.data.clone().into())
                            } else {
                                FetchResult::Failure(
                                    agent_id,
                                    "Cache miss on NotModified".to_string(),
                                )
                            }
                        }
                        ConditionalFetchResult::Error(e) => FetchResult::Failure(agent_id, e),
                    };
                    let _ = tx.send(result).await;
                });
            }
        }

        // Check for GitHub updates (non-blocking)
        while let Ok(result) = runtime.github_rx.try_recv() {
            match result {
                FetchResult::Success(id, data) => {
                    app.update(app::Message::GitHubDataReceived(id, data));
                }
                FetchResult::Failure(id, error) => {
                    app.update(app::Message::GitHubFetchFailed(id, error));
                }
            }
        }

        // Check for benchmark data updates (non-blocking)
        if let Ok(result) = runtime.bench_rx.try_recv() {
            match result {
                BenchmarkFetchResult::Fresh(entries) => {
                    app.update(app::Message::BenchmarkDataReceived(entries));
                }
                BenchmarkFetchResult::Error => {
                    app.update(app::Message::BenchmarkFetchFailed);
                }
            }
        }

        if app.pending_status_refresh {
            app.pending_status_refresh = false;
            let force = app.force_status_refresh;
            app.force_status_refresh = false;
            let stale = runtime
                .status
                .last_fetch_time
                .is_none_or(|t| t.elapsed() > Duration::from_secs(60));
            let recent = runtime
                .status
                .last_fetch_time
                .is_some_and(|t| t.elapsed() < Duration::from_secs(2));
            if force || (stale && !recent) {
                if let Some(ref status_app) = app.status_app {
                    runtime.status.fetch_generation += 1;
                    let gen = runtime.status.fetch_generation;
                    runtime.status.last_fetch_time = Some(Instant::now());
                    let seeds = status_app.fetch_seeds();
                    let tx = runtime.status.tx.clone();
                    let fetcher = StatusFetcher::with_client(runtime.status.client.clone());
                    tokio::spawn(async move {
                        let result = fetcher.fetch(&seeds).await;
                        let _ = tx.send((gen, result)).await;
                    });
                }
            } else if let Some(ref mut status_app) = app.status_app {
                status_app.loading = false;
            }
        }

        if let Ok((gen, result)) = runtime.status.rx.try_recv() {
            if gen >= runtime.status.fetch_generation {
                let StatusFetchResult::Fresh(entries) = result;
                app.update(app::Message::StatusDataReceived(entries));
            }
        }

        if let Some(msg) = event::handle_events(app)? {
            // Handle clipboard operations and set status with timer
            match &msg {
                app::Message::CopyFull => {
                    if let Some(text) = app.get_copy_full() {
                        copy_to_clipboard(text.clone());
                        app.set_status(format!("Copied: {}", text));
                        last_status_time = Some(std::time::Instant::now());
                    }
                }
                app::Message::CopyModelId => {
                    if let Some(text) = app.get_copy_model_id() {
                        copy_to_clipboard(text.clone());
                        app.set_status(format!("Copied: {}", text));
                        last_status_time = Some(std::time::Instant::now());
                    }
                }
                app::Message::CopyProviderDoc => {
                    if let Some(text) = app.get_provider_doc() {
                        copy_to_clipboard(text.clone());
                        app.set_status(format!("Copied: {}", text));
                        last_status_time = Some(std::time::Instant::now());
                    }
                }
                app::Message::CopyProviderApi => {
                    if let Some(text) = app.get_provider_api() {
                        copy_to_clipboard(text.clone());
                        app.set_status(format!("Copied: {}", text));
                        last_status_time = Some(std::time::Instant::now());
                    }
                }
                app::Message::OpenProviderDoc => {
                    if let Some(url) = app.get_provider_doc() {
                        let _ = open::that_in_background(&url);
                        app.set_status(format!("Opened: {}", url));
                        last_status_time = Some(std::time::Instant::now());
                    }
                }
                app::Message::OpenAgentDocs => {
                    if let Some(ref agents_app) = app.agents_app {
                        if let Some(entry) = agents_app.current_entry() {
                            if let Some(ref url) = entry.agent.docs {
                                let _ = open::that_in_background(url);
                                app.set_status(format!("Opened: {}", url));
                                last_status_time = Some(std::time::Instant::now());
                            } else if let Some(ref url) = entry.agent.homepage {
                                let _ = open::that_in_background(url);
                                app.set_status(format!("Opened: {}", url));
                                last_status_time = Some(std::time::Instant::now());
                            }
                        }
                    }
                }
                app::Message::OpenAgentRepo => {
                    if let Some(ref agents_app) = app.agents_app {
                        if let Some(entry) = agents_app.current_entry() {
                            let url = format!("https://github.com/{}", entry.agent.repo);
                            let _ = open::that_in_background(&url);
                            app.set_status(format!("Opened: {}", url));
                            last_status_time = Some(std::time::Instant::now());
                        }
                    }
                }
                app::Message::CopyAgentName => {
                    if let Some(ref agents_app) = app.agents_app {
                        if let Some(entry) = agents_app.current_entry() {
                            copy_to_clipboard(entry.agent.name.clone());
                            app.set_status(format!("Copied: {}", entry.agent.name));
                            last_status_time = Some(std::time::Instant::now());
                        }
                    }
                }
                app::Message::CopyBenchmarkName => {
                    if let Some(entry) = app.benchmarks_app.current_entry(&app.benchmark_store) {
                        copy_to_clipboard(entry.name.clone());
                        app.set_status(format!("Copied: {}", entry.name));
                        last_status_time = Some(std::time::Instant::now());
                    }
                }
                app::Message::OpenBenchmarkUrl => {
                    if let Some(entry) = app.benchmarks_app.current_entry(&app.benchmark_store) {
                        let url = format!("https://artificialanalysis.ai/models/{}", entry.slug);
                        let _ = open::that_in_background(&url);
                        app.set_status(format!("Opened: {}", url));
                        last_status_time = Some(std::time::Instant::now());
                    }
                }
                app::Message::OpenStatusPage => {
                    if let Some(entry) = app.status_app.as_ref().and_then(|a| a.current_entry()) {
                        if let Some(url) = entry.best_open_url() {
                            let _ = open::that_in_background(url);
                            app.set_status(format!("Opened: {}", url));
                            last_status_time = Some(std::time::Instant::now());
                        }
                    }
                }
                app::Message::RefreshStatus => {
                    app.set_status("Refreshing provider status…".to_string());
                    last_status_time = Some(std::time::Instant::now());
                }
                app::Message::PickerSave => {
                    // Picker save sets its own status message via app.update
                    last_status_time = Some(std::time::Instant::now());
                }
                app::Message::ToggleBenchmarkSelection => {
                    // Look up the model name for the status message
                    if let Some(&store_idx) = app
                        .benchmarks_app
                        .filtered_indices
                        .get(app.benchmarks_app.selected)
                    {
                        let name = app
                            .benchmark_store
                            .entries()
                            .get(store_idx)
                            .map(|e| e.name.as_str())
                            .unwrap_or("?");
                        let is_already_selected = app.selections.contains(&store_idx);
                        if is_already_selected {
                            let count = app.selections.len() - 1;
                            app.set_status(format!(
                                "Removed {} ({}/{})",
                                name,
                                count,
                                app::MAX_SELECTIONS
                            ));
                        } else if app.selections.len() < app::MAX_SELECTIONS {
                            let count = app.selections.len() + 1;
                            app.set_status(format!(
                                "Added {} ({}/{})",
                                name,
                                count,
                                app::MAX_SELECTIONS
                            ));
                        }
                        last_status_time = Some(std::time::Instant::now());
                    }
                }
                app::Message::ClearBenchmarkSelections => {
                    let count = app.selections.len();
                    if count > 0 {
                        app.set_status(format!(
                            "Cleared {} selection{}",
                            count,
                            if count == 1 { "" } else { "s" }
                        ));
                        last_status_time = Some(std::time::Instant::now());
                    }
                }
                app::Message::CycleBenchmarkView => {
                    // Show status after the update processes the cycle
                    // We need to peek at what the NEXT view will be
                    let next_view = match app.benchmarks_app.bottom_view {
                        crate::tui::benchmarks::BottomView::H2H => "Scatter",
                        crate::tui::benchmarks::BottomView::Scatter => "Radar",
                        crate::tui::benchmarks::BottomView::Radar => "H2H",
                        crate::tui::benchmarks::BottomView::Detail => "H2H",
                    };
                    app.set_status(format!("View: {}", next_view));
                    last_status_time = Some(std::time::Instant::now());
                }
                app::Message::CycleScatterX => {
                    let next_axis = app.benchmarks_app.scatter_x.next();
                    app.set_status(format!("X-axis: {}", next_axis.label()));
                    last_status_time = Some(std::time::Instant::now());
                }
                app::Message::CycleScatterY => {
                    let next_axis = app.benchmarks_app.scatter_y.next();
                    app.set_status(format!("Y-axis: {}", next_axis.label()));
                    last_status_time = Some(std::time::Instant::now());
                }
                app::Message::CycleRadarPreset => {
                    let next_preset = app.benchmarks_app.radar_preset.next();
                    app.set_status(format!("Radar: {}", next_preset.label()));
                    last_status_time = Some(std::time::Instant::now());
                }
                _ => {}
            }

            if !app.update(msg) {
                return Ok(());
            }
        }
    }
}