pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
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
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
use tokio::sync::mpsc;

use crate::state::{AppState, PackageDetails, PackageItem, SearchResults, Source};

/// What: Handle search results update event.
///
/// Inputs:
/// - `app`: Application state
/// - `new_results`: New search results
/// - `details_req_tx`: Channel sender for detail requests
/// - `index_notify_tx`: Channel sender for index update notifications
///
/// Details:
/// - Filters results based on installed-only mode if enabled
/// - Updates selection to preserve previously selected item
/// - Triggers detail fetch and ring prefetch for selected item
/// - Requests index enrichment for official packages near selection
pub fn handle_search_results(
    app: &mut AppState,
    new_results: SearchResults,
    details_req_tx: &mpsc::UnboundedSender<PackageItem>,
    index_notify_tx: &mpsc::UnboundedSender<()>,
) {
    if new_results.id != app.latest_query_id {
        return;
    }

    // Always process incoming worker results, even if query text is unchanged.
    // Startup index refresh can produce newer non-empty data for the same empty query.
    let query_text = app.input.trim().to_string();

    let prev_selected_name = app.results.get(app.selected).map(|p| p.name.clone());
    // Respect installed-only mode: keep results restricted to explicit installs
    let mut incoming = new_results.items;
    if app.installed_only_mode {
        use std::collections::HashSet;
        let explicit = crate::index::explicit_names();
        if app.input.trim().is_empty() {
            // For empty query, reconstruct full installed list (official + AUR fallbacks)
            let mut items: Vec<PackageItem> = crate::index::all_official()
                .into_iter()
                .filter(|p| explicit.contains(&p.name))
                .collect();
            let official_names: HashSet<String> = items.iter().map(|p| p.name.clone()).collect();
            for name in explicit {
                if !official_names.contains(&name) {
                    let is_eos = name.to_lowercase().contains("eos-");
                    let src = if is_eos {
                        Source::Official {
                            repo: "EOS".to_string(),
                            arch: String::new(),
                        }
                    } else {
                        Source::Aur
                    };
                    items.push(PackageItem {
                        name: name.clone(),
                        version: String::new(),
                        description: String::new(),
                        source: src,
                        popularity: None,
                        out_of_date: None,
                        orphaned: false,
                    });
                }
            }
            incoming = items;
        } else {
            // For non-empty query, just intersect results with explicit installed set
            incoming.retain(|p| explicit.contains(&p.name));
        }
    }
    app.all_results = incoming;
    crate::logic::apply_filters_and_sort_preserve_selection(app);
    let new_sel = prev_selected_name
        .and_then(|name| app.results.iter().position(|p| p.name == name))
        .unwrap_or(0);
    app.selected = new_sel.min(app.results.len().saturating_sub(1));
    app.list_state.select(if app.results.is_empty() {
        None
    } else {
        Some(app.selected)
    });
    if let Some(item) = app.results.get(app.selected).cloned() {
        app.details_focus = Some(item.name.clone());
        crate::logic::clear_stale_pkgbuild_checks_for_selection(app, item.name.as_str());
        if let Some(cached) = app.details_cache.get(&item.name).cloned() {
            app.details = cached;
        } else {
            let _ = details_req_tx.send(item);
        }
    }
    crate::events::utils::queue_selected_aur_vote_state_check(app);
    crate::logic::set_allowed_ring(app, 30);
    if app.need_ring_prefetch {
        /* defer */
    } else {
        crate::logic::ring_prefetch_from_selected(app, details_req_tx);
    }
    let len_u = app.results.len();
    let mut enrich_names: Vec<String> = Vec::new();
    if let Some(sel) = app.results.get(app.selected)
        && matches!(sel.source, Source::Official { .. })
    {
        enrich_names.push(sel.name.clone());
    }
    let max_radius: usize = 30;
    let mut step: usize = 1;
    while step <= max_radius {
        if let Some(i) = app.selected.checked_sub(step)
            && let Some(it) = app.results.get(i)
            && matches!(it.source, Source::Official { .. })
        {
            enrich_names.push(it.name.clone());
        }
        let below = app.selected + step;
        if below < len_u
            && let Some(it) = app.results.get(below)
            && matches!(it.source, Source::Official { .. })
        {
            enrich_names.push(it.name.clone());
        }
        step += 1;
    }
    if !enrich_names.is_empty() {
        crate::index::request_enrich_for(
            app.official_index_path.clone(),
            index_notify_tx.clone(),
            enrich_names,
        );
    }

    // Update search cache with current query and results
    app.search_cache_query = Some(query_text);
    app.search_cache_fuzzy = app.fuzzy_search_enabled;
    app.search_cache_results = Some(app.results.clone());
}

/// What: Handle package details update event.
///
/// Inputs:
/// - `app`: Application state
/// - `details`: New package details
/// - `tick_tx`: Channel sender for tick events
///
/// Details:
/// - Updates details cache and current details if focused
/// - Updates result list entry with new information
pub fn handle_details_update(
    app: &mut AppState,
    details: &PackageDetails,
    tick_tx: &mpsc::UnboundedSender<()>,
) {
    let details_clone = details.clone();
    if app.details_focus.as_deref() == Some(details.name.as_str()) {
        app.details = details_clone.clone();
    }
    app.details_cache
        .insert(details_clone.name.clone(), details_clone.clone());
    app.cache_dirty = true;
    if let Some(pos) = app.results.iter().position(|p| p.name == details.name) {
        app.results[pos].description = details_clone.description;
        if !details_clone.version.is_empty() && app.results[pos].version != details_clone.version {
            app.results[pos].version = details_clone.version;
        }
        if details_clone.popularity.is_some() {
            app.results[pos].popularity = details_clone.popularity;
        }
        if let crate::state::Source::Official { repo, arch } = &mut app.results[pos].source {
            if repo.is_empty() && !details_clone.repository.is_empty() {
                *repo = details_clone.repository;
            }
            if arch.is_empty() && !details_clone.architecture.is_empty() {
                *arch = details_clone.architecture;
            }
        }
    }
    let _ = tick_tx.send(());
}

/// What: Handle preview item event.
///
/// Inputs:
/// - `app`: Application state
/// - `item`: Package item to preview
/// - `details_req_tx`: Channel sender for detail requests
///
/// Details:
/// - Loads details for previewed item (from cache or network)
/// - Adjusts selection if needed
pub fn handle_preview(
    app: &mut AppState,
    item: PackageItem,
    details_req_tx: &mpsc::UnboundedSender<PackageItem>,
) {
    if let Some(cached) = app.details_cache.get(&item.name).cloned() {
        app.details = cached;
    } else {
        let _ = details_req_tx.send(item);
    }
    if !app.results.is_empty() && app.selected >= app.results.len() {
        app.selected = app.results.len() - 1;
        app.list_state.select(Some(app.selected));
    }
}

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

    /// What: Provide a baseline `AppState` for handler tests.
    ///
    /// Inputs: None
    /// Output: Fresh `AppState` with default values
    fn new_app() -> AppState {
        AppState::default()
    }

    #[test]
    /// What: Verify that `handle_search_results` ignores results with mismatched query ID.
    ///
    /// Inputs:
    /// - `AppState` with `latest_query_id` = 1
    /// - `SearchResults` with `id` = 2
    ///
    /// Output:
    /// - Results are ignored, app state unchanged
    ///
    /// Details:
    /// - Tests that stale results are properly filtered
    fn handle_search_results_ignores_stale_results() {
        let mut app = new_app();
        app.latest_query_id = 1;
        app.results = vec![PackageItem {
            name: "old-package".to_string(),
            version: "1.0.0".to_string(),
            description: "Old".to_string(),
            source: Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        }];

        let (details_tx, _details_rx) = mpsc::unbounded_channel();
        let (index_tx, _index_rx) = mpsc::unbounded_channel();

        let stale_results = SearchResults {
            id: 2, // Different from app.latest_query_id
            items: vec![PackageItem {
                name: "new-package".to_string(),
                version: "2.0.0".to_string(),
                description: "New".to_string(),
                source: Source::Aur,
                popularity: None,
                out_of_date: None,
                orphaned: false,
            }],
        };

        handle_search_results(&mut app, stale_results, &details_tx, &index_tx);

        // Results should not be updated
        assert_eq!(app.results.len(), 1);
        assert_eq!(app.results[0].name, "old-package");
    }

    #[test]
    /// What: Verify that `handle_search_results` updates results when query ID matches.
    ///
    /// Inputs:
    /// - `AppState` with `latest_query_id` = 1
    /// - `SearchResults` with `id` = 1 and new items
    ///
    /// Output:
    /// - Results are updated with new items
    /// - Selection is preserved or adjusted
    ///
    /// Details:
    /// - Tests that valid results are properly processed
    fn handle_search_results_updates_when_id_matches() {
        let mut app = new_app();
        app.latest_query_id = 1;
        app.input = "hello".to_string();
        app.results = vec![PackageItem {
            name: "old-package".to_string(),
            version: "1.0.0".to_string(),
            description: "Old".to_string(),
            source: Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        }];

        let (details_tx, _details_rx) = mpsc::unbounded_channel();
        let (index_tx, _index_rx) = mpsc::unbounded_channel();

        let new_results = SearchResults {
            id: 1, // Matches app.latest_query_id
            items: vec![PackageItem {
                name: "new-package".to_string(),
                version: "2.0.0".to_string(),
                description: "New".to_string(),
                source: Source::Aur,
                popularity: None,
                out_of_date: None,
                orphaned: false,
            }],
        };

        handle_search_results(&mut app, new_results, &details_tx, &index_tx);

        // Results should be updated
        assert_eq!(app.results.len(), 1);
        assert_eq!(app.results[0].name, "new-package");
        // Cache should be updated
        assert_eq!(app.search_cache_query.as_deref(), Some("hello"));
        assert_eq!(app.search_cache_results.as_ref().map(Vec::len), Some(1));
    }

    #[tokio::test]
    /// What: Verify newer results replace stale cached results for identical query text.
    ///
    /// Inputs:
    /// - `AppState` with empty-query cache containing zero results.
    /// - Incoming `SearchResults` for the same query ID/text with one package.
    ///
    /// Output:
    /// - New incoming result is applied and displayed.
    ///
    /// Details:
    /// - Reproduces startup flow where first empty query caches an empty list before index is ready.
    /// - Ensures later index-backed results are not discarded by cache short-circuiting.
    async fn handle_search_results_prefers_fresh_results_over_stale_cache() {
        let mut app = new_app();
        app.latest_query_id = 5;
        app.input.clear();
        app.search_cache_query = Some(String::new());
        app.search_cache_fuzzy = app.fuzzy_search_enabled;
        app.search_cache_results = Some(Vec::new());

        let (details_tx, _details_rx) = mpsc::unbounded_channel();
        let (index_tx, _index_rx) = mpsc::unbounded_channel();
        let fresh_results = SearchResults {
            id: 5,
            items: vec![PackageItem {
                name: "linux".to_string(),
                version: "6.0".to_string(),
                description: "Kernel".to_string(),
                source: Source::Official {
                    repo: "core".to_string(),
                    arch: "x86_64".to_string(),
                },
                popularity: None,
                out_of_date: None,
                orphaned: false,
            }],
        };

        handle_search_results(&mut app, fresh_results, &details_tx, &index_tx);

        assert_eq!(app.results.len(), 1);
        assert_eq!(app.results[0].name, "linux");
        assert_eq!(app.search_cache_results.as_ref().map(Vec::len), Some(1));
    }

    #[test]
    /// What: Verify that `handle_details_update` updates cache and current details.
    ///
    /// Inputs:
    /// - `AppState` with `details_focus` set
    /// - `PackageDetails` for focused package
    ///
    /// Output:
    /// - Details cache is updated
    /// - Current details are updated if focused
    ///
    /// Details:
    /// - Tests that details are properly cached and displayed
    fn handle_details_update_updates_cache_and_details() {
        let mut app = new_app();
        app.details_focus = Some("test-package".to_string());
        app.details_cache = std::collections::HashMap::new();

        let (tick_tx, _tick_rx) = mpsc::unbounded_channel();

        let details = PackageDetails {
            name: "test-package".to_string(),
            version: "1.0.0".to_string(),
            description: "Test package".to_string(),
            repository: String::new(),
            architecture: String::new(),
            url: String::new(),
            licenses: Vec::new(),
            groups: Vec::new(),
            provides: Vec::new(),
            depends: Vec::new(),
            opt_depends: Vec::new(),
            required_by: Vec::new(),
            optional_for: Vec::new(),
            conflicts: Vec::new(),
            replaces: Vec::new(),
            download_size: None,
            install_size: None,
            owner: String::new(),
            build_date: String::new(),
            popularity: None,
            out_of_date: None,
            orphaned: false,
        };

        handle_details_update(&mut app, &details, &tick_tx);

        // Cache should be updated
        assert!(app.details_cache.contains_key("test-package"));
        // Current details should be updated if focused
        assert_eq!(app.details.name, "test-package");
        // Cache dirty flag should be set
        assert!(app.cache_dirty);
    }

    #[test]
    /// What: Verify that `handle_preview` loads details from cache when available.
    ///
    /// Inputs:
    /// - `AppState` with cached details
    /// - `PackageItem` to preview
    ///
    /// Output:
    /// - Details are loaded from cache
    /// - No network request is made
    ///
    /// Details:
    /// - Tests that cached details are used when available
    fn handle_preview_uses_cache_when_available() {
        let mut app = new_app();
        let cached_details = PackageDetails {
            name: "test-package".to_string(),
            version: "1.0.0".to_string(),
            description: "Cached".to_string(),
            repository: String::new(),
            architecture: String::new(),
            url: String::new(),
            licenses: Vec::new(),
            groups: Vec::new(),
            provides: Vec::new(),
            depends: Vec::new(),
            opt_depends: Vec::new(),
            required_by: Vec::new(),
            optional_for: Vec::new(),
            conflicts: Vec::new(),
            replaces: Vec::new(),
            download_size: None,
            install_size: None,
            owner: String::new(),
            build_date: String::new(),
            popularity: None,
            out_of_date: None,
            orphaned: false,
        };
        app.details_cache
            .insert("test-package".to_string(), cached_details);

        let (details_tx, mut details_rx) = mpsc::unbounded_channel();

        let item = PackageItem {
            name: "test-package".to_string(),
            version: "1.0.0".to_string(),
            description: "Test".to_string(),
            source: Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        };

        handle_preview(&mut app, item, &details_tx);

        // Details should be loaded from cache
        assert_eq!(app.details.name, "test-package");
        // No request should be sent (channel should be empty)
        assert!(details_rx.try_recv().is_err());
    }
}