evault-tui 0.1.0

Terminal user interface for evault.
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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
//! Terminal lifecycle and event loop.

use std::io;
use std::panic::{self, AssertUnwindSafe};
use std::time::Duration;

use ratatui::crossterm::event::{self, Event};
use ratatui::DefaultTerminal;

use crate::app::{AppState, DispatchOutcome, View};
use crate::error::TuiError;
use crate::provider::{VarMutator, VarProvider};
use crate::theme::Theme;
use crate::views;

/// How long to block waiting for a key event before re-drawing.
///
/// Short enough that resize events feel snappy (50 ms ≈ 20 fps when
/// idle) but long enough that the runtime spends most of its time
/// asleep, not redrawing the same frame.
const POLL_INTERVAL: Duration = Duration::from_millis(50);

/// Run the TUI against `backend`.
///
/// The single `backend` argument implements both [`VarProvider`]
/// (read side: the dashboard refreshes from it) and [`VarMutator`]
/// (write side: the confirm-modal delete flow calls into it). Phase
/// 2c will extend [`VarMutator`] with create / update / link
/// without breaking this signature.
///
/// Owns the terminal lifecycle: enters raw mode + the alternate
/// screen, installs a panic hook that restores them on unwind, and
/// guarantees the restore happens whether the loop returns `Ok`,
/// returns `Err`, or panics.
///
/// `backend` is **consumed** for the duration of the session: the
/// TUI takes ownership and drops it on return, so callers cannot
/// reuse the same instance for a second session.
///
/// # Errors
/// Returns [`TuiError::Terminal`] if terminal I/O fails (raw-mode
/// toggling, drawing, event reading). Transient `ErrorKind::Interrupted`
/// errors (e.g. signal-interrupted `poll`) are retried internally and
/// do not surface. Returns [`TuiError::Provider`] only if the *initial*
/// refresh fails; subsequent refresh errors are surfaced as a sticky
/// error toast and the loop continues. Delete failures are surfaced
/// as a sticky error toast — they never propagate.
///
/// # Examples
///
/// ```no_run
/// use std::path::PathBuf;
/// use evault_core::model::VarId;
/// use evault_tui::{run_tui, ProviderError, VarDraft, VarMutator, VarProvider, VarSummary};
/// use secrecy::SecretString;
///
/// struct Empty;
/// impl VarProvider for Empty {
///     fn list(&self) -> Result<Vec<VarSummary>, ProviderError> { Ok(Vec::new()) }
///     fn get_value(&self, _id: VarId) -> Result<Option<SecretString>, ProviderError> {
///         Ok(None)
///     }
/// }
/// impl VarMutator for Empty {
///     fn delete(&self, _id: VarId) -> Result<(), ProviderError> { Ok(()) }
///     fn create(&self, _draft: VarDraft) -> Result<VarId, ProviderError> {
///         Ok(VarId::new_v4())
///     }
///     fn update_value(&self, _id: VarId, _value: SecretString) -> Result<(), ProviderError> {
///         Ok(())
///     }
///     fn link_to_project(
///         &self,
///         _var_id: VarId,
///         _var_name: String,
///         _project_path: PathBuf,
///         _profile: String,
///         _materialize: bool,
///     ) -> Result<(), ProviderError> { Ok(()) }
///     fn run_in_project(
///         &self,
///         _project_path: PathBuf,
///         _profile: String,
///         _program: String,
///         _args: Vec<String>,
///     ) -> Result<Option<i32>, ProviderError> { Ok(Some(0)) }
/// }
///
/// run_tui(Empty).unwrap();
/// ```
#[allow(clippy::needless_pass_by_value)]
pub fn run_tui<B>(backend: B) -> Result<(), TuiError>
where
    B: VarProvider + VarMutator,
{
    let mut terminal = ratatui::try_init()?;
    let loop_result = event_loop(&mut terminal, &backend);

    // ALWAYS attempt to restore. The restore-error precedence policy
    // is: if the loop succeeded, surface a restore failure; if the
    // loop already failed, log the restore failure to stderr (raw
    // mode is presumably broken anyway, so the print will reach the
    // user's reset shell) and propagate the *original* loop error so
    // the user sees the real cause.
    match (loop_result, ratatui::try_restore()) {
        (Ok(()), Ok(())) => Ok(()),
        (Ok(()), Err(restore_err)) => Err(TuiError::Terminal(restore_err)),
        (Err(loop_err), Ok(())) => Err(loop_err),
        (Err(loop_err), Err(restore_err)) => {
            // Best-effort visibility: the user's terminal may be in
            // an inconsistent state. We use stderr because logging
            // crates are not a dependency of this layer.
            #[allow(clippy::print_stderr)]
            {
                eprintln!("evault-tui: terminal restore failed after loop error: {restore_err}");
            }
            Err(loop_err)
        }
    }
}

#[allow(clippy::too_many_lines)]
fn event_loop<B>(terminal: &mut DefaultTerminal, backend: &B) -> Result<(), TuiError>
where
    B: VarProvider + VarMutator + ?Sized,
{
    let mut app = AppState::new();
    let theme = Theme::dark();

    // Initial load. A first-load failure is a hard error: the user
    // sees an empty TUI and has no way to recover.
    app.refresh(backend)?;

    while !app.quit_requested() {
        terminal.draw(|frame| views::render(frame, &mut app, &theme))?;

        let polled = match event::poll(POLL_INTERVAL) {
            Ok(b) => b,
            // EINTR is non-fatal: a signal arrived during `poll`
            // (SIGWINCH on resize, SIGCONT after a stop, debugger
            // attach). Treat the interruption as "no event"; the
            // outer loop will re-draw and try again.
            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(TuiError::Terminal(e)),
        };
        if !polled {
            continue;
        }
        let ev = match event::read() {
            Ok(ev) => ev,
            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(TuiError::Terminal(e)),
        };

        // We match all variants explicitly so the choice to ignore
        // resize / mouse / focus / paste is auditable rather than an
        // implicit drop via `if let Event::Key(_) = ...`.
        #[allow(clippy::match_same_arms)]
        match ev {
            Event::Key(key) => match app.dispatch_key(key) {
                DispatchOutcome::Continue => {}
                DispatchOutcome::RefreshRequested => {
                    // `dispatch_key` already cleared any toast. We
                    // re-fetch here so the side-effect lives at the
                    // boundary that owns the provider. On success
                    // surface a positive confirmation; on failure the
                    // error toast is sticky and survives further input.
                    match app.refresh(backend) {
                        Ok(()) => {
                            // When a filter is applied the dashboard
                            // title reads `vars (matched/total)`. The
                            // toast mirrors that format so a user with
                            // an active filter does not see two
                            // contradicting counts.
                            let total = app.rows().len();
                            let msg = if app.is_filter_active() {
                                let matched = app.visible_row_indices().len();
                                format!("refreshed ({matched}/{total} vars)")
                            } else {
                                format!("refreshed ({total} vars)")
                            };
                            app.set_info_toast(msg);
                        }
                        Err(e) => app.set_error_toast(e.to_string()),
                    }
                }
                DispatchOutcome::CreateRequested(draft) => {
                    let name = draft.name.clone();
                    let create_result =
                        panic::catch_unwind(AssertUnwindSafe(|| backend.create(draft)));
                    match create_result {
                        Err(_) => {
                            app.show_error_modal(
                                "create failed",
                                "backend panicked while creating the variable",
                                Some(
                                    "this is a bug in the backend; restart and \
                                     report the issue if it persists."
                                        .into(),
                                ),
                            );
                        }
                        Ok(Err(e)) => {
                            let msg = e.to_string();
                            let hint = create_hint(&msg);
                            app.show_error_modal("create failed", msg, hint);
                        }
                        Ok(Ok(_id)) => {
                            if let Err(e) = app.refresh(backend) {
                                app.set_error_toast(format!(
                                    "created `{name}` but refresh failed: {e}"
                                ));
                            } else {
                                app.set_info_toast(format!("created `{name}`"));
                            }
                        }
                    }
                }
                DispatchOutcome::UpdateValueRequested { id, value, name } => {
                    let update_result =
                        panic::catch_unwind(AssertUnwindSafe(|| backend.update_value(id, value)));
                    match update_result {
                        Err(_) => {
                            app.show_error_modal(
                                "update failed",
                                "backend panicked while updating the value",
                                Some(
                                    "this is a bug in the backend; restart \
                                     and report the issue if it persists."
                                        .into(),
                                ),
                            );
                        }
                        Ok(Err(e)) => {
                            let msg = e.to_string();
                            let hint = update_hint(&msg);
                            app.show_error_modal("update failed", msg, hint);
                        }
                        Ok(Ok(())) => {
                            if let Err(e) = app.refresh(backend) {
                                app.set_error_toast(format!(
                                    "updated `{name}` but refresh failed: {e}"
                                ));
                            } else {
                                app.set_info_toast(format!("updated `{name}`"));
                            }
                        }
                    }
                }
                DispatchOutcome::LinkRequested {
                    id,
                    name,
                    project_path,
                    profile,
                    materialize,
                } => {
                    let result = panic::catch_unwind(AssertUnwindSafe(|| {
                        backend.link_to_project(
                            id,
                            name.clone(),
                            project_path.clone(),
                            profile.clone(),
                            materialize,
                        )
                    }));
                    match result {
                        Err(_) => {
                            app.show_error_modal(
                                "link failed",
                                "backend panicked while linking the variable",
                                Some(
                                    "this is a bug in the backend; restart \
                                     and report the issue if it persists."
                                        .into(),
                                ),
                            );
                        }
                        Ok(Err(e)) => {
                            let msg = e.to_string();
                            let hint = link_hint(&msg);
                            app.show_error_modal("link failed", msg, hint);
                        }
                        Ok(Ok(())) => {
                            let suffix = if materialize { " + .env" } else { "" };
                            if let Err(e) = app.refresh(backend) {
                                app.set_error_toast(format!(
                                    "linked `{name}` to {}{suffix} but refresh failed: {e}",
                                    project_path.display()
                                ));
                            } else {
                                app.set_info_toast(format!(
                                    "linked `{name}` to {}{suffix}",
                                    project_path.display()
                                ));
                            }
                        }
                    }
                }
                DispatchOutcome::RunRequested {
                    project_path,
                    profile,
                    program,
                    args,
                } => {
                    // The child process must inherit a NORMAL terminal
                    // (no raw mode, no alternate screen). We tear the
                    // TUI down, spawn synchronously, and re-init when
                    // the child returns. `try_restore` failures are
                    // surfaced — without them, the child would print
                    // into the alternate buffer and never appear.
                    if let Err(e) = ratatui::try_restore() {
                        app.show_error_modal(
                            "run failed",
                            format!("could not restore the terminal before spawning: {e}"),
                            None,
                        );
                        continue;
                    }
                    let outcome = panic::catch_unwind(AssertUnwindSafe(|| {
                        backend.run_in_project(
                            project_path.clone(),
                            profile.clone(),
                            program.clone(),
                            args.clone(),
                        )
                    }));
                    // Re-enter raw mode + alternate screen regardless
                    // of the outcome below. Failing to re-init leaves
                    // the user stranded in a half-cooked terminal —
                    // bail out hard so the panic-restore path runs.
                    *terminal = ratatui::try_init().map_err(TuiError::Terminal)?;
                    match outcome {
                        Err(_) => {
                            app.show_error_modal(
                                "run failed",
                                "backend panicked while running the command",
                                Some(
                                    "this is a bug in the backend; restart \
                                     and report the issue if it persists."
                                        .into(),
                                ),
                            );
                        }
                        Ok(Err(e)) => {
                            let msg = e.to_string();
                            let hint = run_hint(&msg);
                            app.show_error_modal("run failed", msg, hint);
                        }
                        Ok(Ok(code)) => {
                            let cmd_repr = if args.is_empty() {
                                program.clone()
                            } else {
                                format!("{program} {}", args.join(" "))
                            };
                            let msg = match code {
                                Some(0) => format!("ran `{cmd_repr}` (exit 0)"),
                                Some(c) => format!("ran `{cmd_repr}` (exit {c})"),
                                None => format!("ran `{cmd_repr}` (killed by signal)"),
                            };
                            if let Err(e) = app.refresh(backend) {
                                app.set_error_toast(format!("{msg} but refresh failed: {e}"));
                            } else {
                                app.set_info_toast(msg);
                            }
                        }
                    }
                }
                DispatchOutcome::ViewValueRequested { id, name } => {
                    let result = panic::catch_unwind(AssertUnwindSafe(|| backend.get_value(id)));
                    match result {
                        Err(_) => {
                            app.set_error_toast("view value crashed: backend panicked");
                        }
                        Ok(Err(e)) => {
                            app.set_error_toast(format!("view value failed: {e}"));
                        }
                        Ok(Ok(None)) => {
                            app.set_error_toast(format!("value missing for `{name}`"));
                        }
                        Ok(Ok(Some(value))) => {
                            app.show_value_modal(name, value);
                        }
                    }
                }
                DispatchOutcome::DeleteRequested { id, name } => {
                    // Side-effect at the runtime boundary that owns
                    // the backend. We guard against three failure
                    // modes:
                    //
                    // 1. The backend's `delete` panics — without a
                    //    `catch_unwind` the panic hook would tear
                    //    the terminal down with no actionable toast
                    //    for the user. We wrap the call and surface
                    //    the panic as an error toast instead.
                    // 2. `delete` returns `Err` — surfaced verbatim.
                    // 3. `delete` succeeds but `refresh` fails:
                    //    locally splice the deleted row out so the
                    //    dashboard does not show a ghost entry that
                    //    would re-fire on a second `d` keypress.
                    //
                    // On the happy path we return to Dashboard *only*
                    // if the user was inspecting the deleted row;
                    // refresh's stale-target guard would otherwise
                    // surface "removed elsewhere" for a self-initiated
                    // delete (a lie).
                    let delete_result =
                        panic::catch_unwind(AssertUnwindSafe(|| backend.delete(id)));
                    match delete_result {
                        Err(_) => {
                            app.show_error_modal(
                                "delete failed",
                                "backend panicked while deleting the variable",
                                Some(
                                    "this is a bug in the backend; restart \
                                     and report the issue if it persists."
                                        .into(),
                                ),
                            );
                        }
                        Ok(Err(e)) => {
                            let msg = e.to_string();
                            app.show_error_modal("delete failed", msg, None);
                        }
                        Ok(Ok(())) => {
                            if matches!(app.current_view(), View::Detail) {
                                app.return_to_dashboard();
                            }
                            match app.refresh(backend) {
                                Ok(()) => {
                                    app.set_info_toast(format!("deleted `{name}`"));
                                }
                                Err(e) => {
                                    // Refresh failed — splice the
                                    // deleted row out so the user
                                    // doesn't see a ghost.
                                    app.splice_out_row(id);
                                    app.set_error_toast(format!(
                                        "deleted `{name}` but refresh failed: {e}"
                                    ));
                                }
                            }
                        }
                    }
                }
            },
            // Resize: the loop redraws on every iteration anyway, so
            // the new dimensions are picked up on the next `draw()`.
            Event::Resize(_, _) => {}
            // Mouse, focus, paste, etc. — not yet bound. Phase 2
            // will wire mouse selection and paste-into-editor.
            _ => {}
        }
    }

    Ok(())
}

/// Contextual hint for a failed `create` action.
///
/// Inspects the backend's error message and returns a plain-English
/// explanation. Multi-line hints use `\n` between bullets — the
/// error modal renders each line separately.
fn create_hint(msg: &str) -> Option<String> {
    let lower = msg.to_ascii_lowercase();
    if lower.contains("invalid character") || lower.contains("invalid name") {
        return Some(
            "Variable names have these rules:\n\
             \u{2022} Start with a letter (A-Z or a-z) or an underscore (_)\n\
             \u{2022} After the first character, use only letters, digits, \
             or underscores\n\
             \u{2022} Maximum 64 characters\n\
             \u{2022} Not allowed: dashes, spaces, dots, accents, or other \
             punctuation\n\
             \n\
             Try a name like API_KEY, DATABASE_URL, or my_token."
                .to_owned(),
        );
    }
    if lower.contains("duplicate") || lower.contains("already exists") {
        return Some(
            "A variable with that name already exists. Pick a different \
             name, or press e on the existing row to update its value."
                .to_owned(),
        );
    }
    if lower.contains("empty") {
        return Some("The value field cannot be empty.".to_owned());
    }
    if lower.contains("too long") {
        return Some(
            "Names are limited to 64 characters. Values typically cap \
             around 1 MB depending on the storage backend."
                .to_owned(),
        );
    }
    None
}

/// Contextual hint for a failed `update_value` action.
fn update_hint(msg: &str) -> Option<String> {
    let lower = msg.to_ascii_lowercase();
    if lower.contains("empty") {
        return Some("The new value cannot be empty.".to_owned());
    }
    if lower.contains("not found") || lower.contains("no variable") {
        return Some(
            "The variable was deleted by another process before the \
             update could complete. Press r to refresh the dashboard."
                .to_owned(),
        );
    }
    None
}

/// Contextual hint for a failed `run_in_project` action.
fn run_hint(msg: &str) -> Option<String> {
    let lower = msg.to_ascii_lowercase();
    if lower.contains("manifest") || lower.contains("evault.toml") || lower.contains("no such file")
    {
        return Some(
            "The project must have an evault.toml manifest before \
             it can be run. Link a variable to the project first \
             (press l on a row), or run `evault link` from the \
             shell."
                .to_owned(),
        );
    }
    if lower.contains("program not found") || lower.contains("not found") {
        return Some(
            "The program was not found on PATH inside the project \
             directory. Check the spelling, or use an absolute path \
             (for example `./node_modules/.bin/jest` or \
             `C:\\Program Files\\app\\app.exe`)."
                .to_owned(),
        );
    }
    if lower.contains("permission") {
        return Some(
            "The OS refused to spawn the program. On Unix, mark the \
             file executable with `chmod +x`. On Windows, check that \
             the file is not blocked by `Unblock-File`."
                .to_owned(),
        );
    }
    None
}

/// Contextual hint for a failed `link_to_project` action.
fn link_hint(msg: &str) -> Option<String> {
    let lower = msg.to_ascii_lowercase();
    if lower.contains("create project dir") || lower.contains("permission") {
        return Some(
            "Could not create the project directory. Check that the \
             path is writable and try again with a different path."
                .to_owned(),
        );
    }
    if lower.contains("canonicalise") || lower.contains("canonicalize") {
        return Some(
            "Could not resolve the project path. Check that the path \
             syntax is valid for your platform (use forward slashes on \
             Linux/macOS, backslashes or forward slashes on Windows)."
                .to_owned(),
        );
    }
    if lower.contains("manifest") {
        return Some(
            "Could not read or write the project's evault.toml file. \
             Check filesystem permissions on the project directory."
                .to_owned(),
        );
    }
    if lower.contains("materialize") {
        return Some(
            "Linking succeeded but writing the .env file failed. The \
             binding is recorded; you can retry materialization later \
             with evault gen --project PATH from the shell."
                .to_owned(),
        );
    }
    None
}