void-audit-tui 0.0.4

Audit viewer TUI for void — integrity and encryption inspection
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
//! Main application for void-audit-tui.
//!
//! Provides an interactive TUI for auditing repository objects.

use std::io::{self, Stdout};
use std::sync::Arc;
use std::time::Instant;

use crossterm::{
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use rayon::prelude::*;
use ratatui::{
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph},
    Frame, Terminal,
};
use thiserror::Error;
use void_core::VoidContext;

use crate::{
    color::ColorTheme,
    event::{init as init_events, AppEvent, UserEvent},
    keybind::KeyBind,
    void_backend::{
        self, AuditResult, Format, ObjectInfo, ObjectType,
    },
    widget::{
        audit_detail::{AuditDetail, AuditDetailState, AuditLoading},
        object_list::{ObjectList, ObjectListState},
    },
};

/// Error type for application operations.
#[derive(Debug, Error)]
pub enum AppError {
    #[error("io error: {0}")]
    Io(#[from] io::Error),

    #[error("backend error: {0}")]
    Backend(#[from] crate::void_backend::VoidBackendError),

    #[error("void error: {0}")]
    Void(#[from] void_core::VoidError),
}

/// Result type for application operations.
pub type Result<T> = std::result::Result<T, AppError>;

/// Current view state of the application.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AppView {
    /// Main object list view
    List,
    /// Help overlay
    Help,
}

/// Run the void-audit-tui application.
///
/// Takes a fully constructed `VoidContext` from the CLI caller.
pub fn run(ctx: VoidContext) -> Result<()> {
    let store = ctx.open_store()?;

    // Enumerate all objects
    let cids = void_backend::list_all_objects(&ctx);
    if cids.is_empty() {
        eprintln!("No objects found in repository");
        return Ok(());
    }

    // Show loading message
    eprintln!("Building index...");
    let start = Instant::now();

    // Build index by walking commit history once
    let index = void_backend::build_index(&ctx, &store, 1000)?;

    let index_time = start.elapsed();
    eprintln!("Index built in {:.2}s", index_time.as_secs_f64());

    // Wrap shared state in Arc for parallel access
    let ctx = Arc::new(ctx);
    let store = Arc::new(store);
    let index = Arc::new(index);

    // Now audit all objects in parallel using the index
    eprintln!("Categorizing {} objects...", cids.len());
    let audit_start = Instant::now();

    let audit_results: Vec<(ObjectInfo, AuditResult)> = cids
        .par_iter()
        .map(|cid| {
            let mut info = void_backend::categorize_object(&store, &index, cid);
            let audit = void_backend::audit_object_indexed(&ctx, &store, &index, cid);
            // Update type and format from audit result
            info.object_type = match &audit {
                AuditResult::Commit(_) => ObjectType::Commit,
                AuditResult::Metadata(_) => ObjectType::Metadata,
                AuditResult::Manifest(_) => ObjectType::Manifest,
                AuditResult::RepoManifest(_) => ObjectType::RepoManifest,
                AuditResult::Shard(_) => ObjectType::Shard,
                AuditResult::Error(_) => ObjectType::Unknown,
            };
            info.format = match &audit {
                AuditResult::Commit(_) => Format::CommitV1,
                AuditResult::Metadata(_) => Format::MetadataV1,
                AuditResult::Manifest(_) => Format::ManifestV1,
                AuditResult::RepoManifest(_) => Format::RepoManifestV1,
                AuditResult::Shard(_) => Format::ShardV1,
                AuditResult::Error(_) => Format::Unknown,
            };
            (info, audit)
        })
        .collect();

    let audit_time = audit_start.elapsed();
    let total_time = start.elapsed();
    eprintln!(
        "Categorized {} objects in {:.2}s ({:.0} objects/sec)",
        cids.len(),
        audit_time.as_secs_f64(),
        cids.len() as f64 / audit_time.as_secs_f64()
    );
    eprintln!("Total startup: {:.2}s", total_time.as_secs_f64());

    // Split into objects and pre-populated cache
    let mut objects = Vec::with_capacity(audit_results.len());
    let mut audit_cache: rustc_hash::FxHashMap<String, AuditResult> =
        rustc_hash::FxHashMap::default();

    for (info, audit) in audit_results {
        audit_cache.insert(info.cid.clone(), audit);
        objects.push(info);
    }

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

    // Run the app and capture result
    let result = run_app_with_cache(&mut terminal, objects, audit_cache);

    // Cleanup terminal (always, even on error)
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    result
}

/// Main application loop with pre-populated audit cache.
fn run_app_with_cache(
    terminal: &mut Terminal<CrosstermBackend<Stdout>>,
    objects: Vec<ObjectInfo>,
    audit_cache: rustc_hash::FxHashMap<String, AuditResult>,
) -> Result<()> {
    // Initialize resources
    let theme = ColorTheme::default();
    let keybind = KeyBind::new();
    let (_tx, rx) = init_events();

    // Initialize state
    let mut list_state = ObjectListState::new(objects);
    let mut detail_state = AuditDetailState::new();
    let mut app_view = AppView::List;

    // Track viewport height for navigation
    let mut viewport_height: usize = 20;

    // Main loop
    loop {
        // Render
        terminal.draw(|frame| {
            let area = frame.area();
            viewport_height = area.height.saturating_sub(4) as usize; // Account for borders + status

            match app_view {
                AppView::List => {
                    render_main_view(
                        frame,
                        area,
                        &mut list_state,
                        &mut detail_state,
                        &audit_cache,
                        &theme,
                        &keybind,
                    );
                }
                AppView::Help => {
                    // Render main view in background, then help overlay
                    render_main_view(
                        frame,
                        area,
                        &mut list_state,
                        &mut detail_state,
                        &audit_cache,
                        &theme,
                        &keybind,
                    );
                    render_help_overlay(frame, area, &keybind, &theme);
                }
            }
        })?;

        // Handle events
        match rx.recv() {
            AppEvent::Key(key) => {
                if let Some(user_event) = keybind.get(&key) {
                    match handle_event(
                        *user_event,
                        &mut app_view,
                        &mut list_state,
                        &mut detail_state,
                        viewport_height,
                    ) {
                        EventResult::Continue => {}
                        EventResult::Quit => break,
                    }
                }
            }
            AppEvent::Resize(_, _) => {
                // Terminal will handle resize automatically
            }
            AppEvent::Quit => break,
        }
    }

    Ok(())
}

/// Result of handling an event.
enum EventResult {
    Continue,
    Quit,
}

/// Handle a user event and return the result.
fn handle_event(
    event: UserEvent,
    view: &mut AppView,
    list_state: &mut ObjectListState,
    detail_state: &mut AuditDetailState,
    viewport_height: usize,
) -> EventResult {
    match event {
        // Quit events
        UserEvent::Quit | UserEvent::ForceQuit => {
            return EventResult::Quit;
        }

        // Help toggle
        UserEvent::HelpToggle => {
            *view = match *view {
                AppView::Help => AppView::List,
                _ => AppView::Help,
            };
        }

        // Cancel/close - return to list from help
        UserEvent::Cancel | UserEvent::Close => {
            if *view != AppView::List {
                *view = AppView::List;
            }
        }

        // Navigation events
        UserEvent::NavigateDown => {
            list_state.select_next(viewport_height);
            detail_state.reset();
        }
        UserEvent::NavigateUp => {
            list_state.select_prev();
            detail_state.reset();
        }
        UserEvent::HalfPageDown => {
            list_state.scroll_down_half(viewport_height);
            detail_state.reset();
        }
        UserEvent::HalfPageUp => {
            list_state.scroll_up_half(viewport_height);
            detail_state.reset();
        }
        UserEvent::PageDown => {
            list_state.scroll_down_page(viewport_height);
            detail_state.reset();
        }
        UserEvent::PageUp => {
            list_state.scroll_up_page(viewport_height);
            detail_state.reset();
        }
        UserEvent::GoToTop => {
            list_state.select_first();
            detail_state.reset();
        }
        UserEvent::GoToBottom => {
            list_state.select_last(viewport_height);
            detail_state.reset();
        }

        // Scroll detail view content
        UserEvent::ScrollDown => {
            detail_state.scroll_down();
        }
        UserEvent::ScrollUp => {
            detail_state.scroll_up();
        }

        // Confirm - could be used for future expansion (e.g., copy CID)
        UserEvent::Confirm => {
            // Currently no action
        }
    }

    EventResult::Continue
}

/// Render the main split-pane view.
fn render_main_view(
    frame: &mut Frame,
    area: Rect,
    list_state: &mut ObjectListState,
    detail_state: &mut AuditDetailState,
    audit_cache: &rustc_hash::FxHashMap<String, AuditResult>,
    theme: &ColorTheme,
    _keybind: &KeyBind,
) {
    // Split into three areas: list, detail, and status bar
    let main_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(5), Constraint::Length(1)])
        .split(area);

    let content_area = main_chunks[0];
    let status_area = main_chunks[1];

    // Split content into left (list) and right (detail)
    let chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(40), Constraint::Percentage(60)])
        .split(content_area);

    // Render object list
    let list_widget = ObjectList::new(theme);
    frame.render_stateful_widget(list_widget, chunks[0], list_state);

    // Render detail panel
    if let Some(obj) = list_state.selected_object() {
        if let Some(audit) = audit_cache.get(&obj.cid) {
            let detail_widget = AuditDetail::new(obj, audit, theme);
            frame.render_stateful_widget(detail_widget, chunks[1], detail_state);
        } else {
            let loading_widget = AuditLoading::new(obj, theme);
            frame.render_widget(loading_widget, chunks[1]);
        }
    }

    // Render status bar
    render_status_bar(frame, status_area, _keybind, theme);
}

/// Render the status bar with key hints.
fn render_status_bar(frame: &mut Frame, area: Rect, _keybind: &KeyBind, theme: &ColorTheme) {
    let hints = [
        ("j/k", "navigate"),
        ("Ctrl-d/u", "scroll"),
        ("g/G", "top/bottom"),
        ("?", "help"),
        ("q", "quit"),
    ];

    let spans: Vec<Span> = hints
        .iter()
        .enumerate()
        .flat_map(|(i, (key, desc))| {
            let mut result = vec![
                Span::styled(
                    *key,
                    Style::default()
                        .fg(theme.help_key_fg)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::raw(": "),
                Span::raw(*desc),
            ];
            if i < hints.len() - 1 {
                result.push(Span::raw("  "));
            }
            result
        })
        .collect();

    let line = Line::from(spans);
    let paragraph = Paragraph::new(line);
    frame.render_widget(paragraph, area);
}

/// Render the help overlay.
fn render_help_overlay(frame: &mut Frame, area: Rect, keybind: &KeyBind, theme: &ColorTheme) {
    // Calculate centered popup area
    let popup_width = 50.min(area.width.saturating_sub(4));
    let popup_height = 16.min(area.height.saturating_sub(4));
    let popup_x = (area.width.saturating_sub(popup_width)) / 2;
    let popup_y = (area.height.saturating_sub(popup_height)) / 2;
    let popup_area = Rect::new(popup_x, popup_y, popup_width, popup_height);

    // Clear the popup area
    frame.render_widget(Clear, popup_area);

    // Build help content
    let help_items = [
        (UserEvent::NavigateDown, "Move down"),
        (UserEvent::NavigateUp, "Move up"),
        (UserEvent::HalfPageDown, "Half page down"),
        (UserEvent::HalfPageUp, "Half page up"),
        (UserEvent::PageDown, "Page down"),
        (UserEvent::PageUp, "Page up"),
        (UserEvent::GoToTop, "Go to top"),
        (UserEvent::GoToBottom, "Go to bottom"),
        (UserEvent::ScrollDown, "Scroll detail down"),
        (UserEvent::ScrollUp, "Scroll detail up"),
        (UserEvent::HelpToggle, "Toggle help"),
        (UserEvent::Quit, "Quit"),
    ];

    let mut lines: Vec<Line> = Vec::new();
    for (event, description) in help_items {
        let keys = keybind.keys_for_event(event);
        let key_str = if keys.is_empty() {
            "(unbound)".to_string()
        } else {
            keys.join(", ")
        };

        lines.push(Line::from(vec![
            Span::styled(
                format!("{:>15}", key_str),
                Style::default()
                    .fg(theme.help_key_fg)
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("  "),
            Span::raw(description),
        ]));
    }

    let help_paragraph = Paragraph::new(lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(" Help ")
                .title_style(Style::default().fg(theme.help_block_title_fg)),
        )
        .style(Style::default().fg(theme.fg).bg(theme.bg));

    frame.render_widget(help_paragraph, popup_area);
}