clauth 0.5.0

Simple Claude Code account switcher and usage monitor
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Showcase — a fake-data TUI for taking README screenshots. Compiled ONLY
//! under `#[cfg(test)]` (included via `#[path]` into `crate::tui`), so none of
//! this ships in the `clauth` binary and it lives outside `src/`.
//!
//! Launch it in a real terminal (it takes over the screen; press q / ⎋ to quit):
//!
//! ```text
//! cargo test showcase -- --ignored --nocapture
//! ```
//!
//! It builds a believable [`AppConfig`] from hard-coded demo values, redirects
//! the home dir at a throwaway tempdir, and runs the **real, fully-interactive**
//! TUI loop. Every action works for real — switch, edit, toggle, reorder, set
//! threshold, delete — but `home_dir()` is overridden so all reads/writes land
//! in the sandbox, never the user's real `~/.clauth` / `~/.claude`. The sandbox
//! tempdir is removed when it drops at the end of the run.
//!
//! `reconcile_startup` is deliberately never called, so `on_tick` never spawns
//! the bootstrap/scheduler (gated on `reconcile_done`) — no background worker,
//! no network. The demo profiles carry no credentials, so even the manual
//! refresh / rotate paths have no token to use and stay inert.

use std::collections::BTreeMap;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};
use ratatui::crossterm::event::{
    self, Event, KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers,
};

use super::{TICK, Term, app, render, restore_terminal, setup_terminal};
use crate::profile::{AppConfig, AppState, Profile, home_dir, set_home_override};
use crate::usage::{ExtraUsage, FetchStatus, PlanInfo, UsageInfo, UsageWindow};

// ── Launch ──────────────────────────────────────────────────────────────────

#[test]
#[ignore = "interactive TUI; run with `cargo test showcase -- --ignored --nocapture` in a real terminal"]
fn showcase() {
    run(demo_config()).expect("showcase loop");
}

/// Same terminal setup/teardown as [`super::run`], but redirects the home dir
/// at a sandbox tempdir first so the real loop's writes never escape it.
fn run(config: AppConfig) -> Result<()> {
    let sandbox = tempfile::tempdir().context("create showcase sandbox dir")?;
    set_home_override(sandbox.path().to_path_buf());

    let mut terminal = setup_terminal()?;
    let outcome = showcase_loop(&mut terminal, config);
    let restore = restore_terminal(&mut terminal);
    // `sandbox` drops here → the tempdir and everything written to it is removed.
    outcome.and(restore)
}

/// The real event loop minus startup reconciliation: draw, dispatch keys
/// through the production `handle_key`, and run `on_tick` so worker results
/// (e.g. a switch) drain and spinners clear. No `reconcile_startup`, so no
/// bootstrap/scheduler ever spawns.
fn showcase_loop(terminal: &mut Term, config: AppConfig) -> Result<()> {
    let mut application = app::App::new(config);
    // Prime the usage stores so windows show simulated utilization, not `-`.
    seed_usage(&application);
    let mut last_tick = Instant::now();

    while !application.quit {
        terminal.draw(|frame| render::draw(frame, &application))?;

        let timeout = TICK.saturating_sub(last_tick.elapsed());
        if event::poll(timeout)? {
            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    app::handle_key(&mut application, key);
                }
                Event::Resize(_, _) => {}
                _ => {}
            }
        }

        if last_tick.elapsed() >= TICK {
            app::on_tick(&mut application);
            last_tick = Instant::now();
        }
    }

    Ok(())
}

// ── Time helper ───────────────────────────────────────────────────────────────

/// Returns an RFC3339-ish string (matching `iso_to_epoch_secs` expectations)
/// for `now + offset`.
fn future_iso(offset: Duration) -> String {
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
        + offset.as_secs();
    // Manual RFC3339 formatting — no chrono dep needed; matches the
    // `YYYY-MM-DDTHH:MM:SS+00:00` shape that `iso_to_epoch_secs` parses.
    let (y, mo, d, h, mi, sec) = epoch_to_parts(secs);
    format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{sec:02}+00:00")
}

fn epoch_to_parts(secs: u64) -> (u64, u64, u64, u64, u64, u64) {
    let s = secs % 60;
    let m = (secs / 60) % 60;
    let h = (secs / 3600) % 24;
    let days = secs / 86400;
    // Gregorian civil calendar (Howard Hinnant's algorithm, unsigned edition).
    let z = days + 719468;
    let era = z / 146097;
    let doe = z - era * 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let mo = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if mo <= 2 { y + 1 } else { y };
    (y, mo, d, h, m, s)
}

// ── Profile builders ──────────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn oauth_profile(
    name: &str,
    plan_type: &str,
    tier: &str,
    has_max: bool,
    has_pro: bool,
    auto_start: bool,
    fallback_threshold: Option<f64>,
    five_util: f64,
    five_resets_in: Option<Duration>,
    seven_sonnet: Option<(f64, Duration)>,
    seven_opus: Option<(f64, Duration)>,
    extra: Option<ExtraUsage>,
    fetch_status: Option<FetchStatus>,
) -> Profile {
    let five_hour = Some(UsageWindow {
        utilization: five_util,
        resets_at: five_resets_in.map(future_iso),
    });
    let seven_day_sonnet = seven_sonnet.map(|(u, reset)| UsageWindow {
        utilization: u,
        resets_at: Some(future_iso(reset)),
    });
    let seven_day_opus = seven_opus.map(|(u, reset)| UsageWindow {
        utilization: u,
        resets_at: Some(future_iso(reset)),
    });
    Profile {
        name: name.to_string(),
        base_url: None,
        api_key: None,
        auto_start,
        env: BTreeMap::new(),
        fallback_threshold,
        credentials: None,
        usage: Some(UsageInfo {
            plan: Some(PlanInfo {
                organization_type: Some(plan_type.to_string()),
                rate_limit_tier: Some(tier.to_string()),
                has_max,
                has_pro,
            }),
            five_hour,
            seven_day: None,
            seven_day_sonnet,
            seven_day_opus,
            extra_usage: extra,
        }),
        fetch_status,
    }
}

fn api_profile(name: &str) -> Profile {
    Profile {
        name: name.to_string(),
        base_url: Some("https://api.example.com".to_string()),
        api_key: Some(
            "sk-ant-api03-demo0000000000000000000000000000000000000000000000".to_string(),
        ),
        auto_start: false,
        env: BTreeMap::new(),
        fallback_threshold: None,
        credentials: None,
        usage: None,
        fetch_status: None,
    }
}

fn failed_profile(name: &str) -> Profile {
    Profile {
        name: name.to_string(),
        base_url: None,
        api_key: None,
        auto_start: false,
        env: BTreeMap::new(),
        fallback_threshold: Some(90.0),
        credentials: None,
        usage: None,
        fetch_status: Some(FetchStatus::Failed),
    }
}

// ── Demo config ───────────────────────────────────────────────────────────────

fn demo_config() -> AppConfig {
    let max20 = oauth_profile(
        "personal",
        "claude_max",
        "default_claude_max_20x",
        true,
        false,
        true,
        Some(80.0),
        64.3,
        Some(Duration::from_secs(2 * 3600 + 17 * 60)), // resets in ~2h17m
        Some((22.1, Duration::from_secs(5 * 86400 + 6 * 3600))), // 7d sonnet ~5d
        Some((8.4, Duration::from_secs(6 * 86400 + 2 * 3600))), // 7d opus ~6d
        None,
        None, // live / fresh, no underline
    );

    let extra = ExtraUsage {
        is_enabled: true,
        monthly_limit: Some(100.00),
        used_credits: Some(42.50),
        utilization: Some(42.5),
        currency: Some("USD".to_string()),
    };
    let max5 = oauth_profile(
        "work",
        "claude_max",
        "default_claude_max_5x",
        true,
        false,
        true,
        Some(90.0),
        88.7,
        Some(Duration::from_secs(45 * 60)), // resets in ~45m
        Some((61.2, Duration::from_secs(3 * 86400 + 9 * 3600))), // 7d sonnet ~3d
        Some((33.9, Duration::from_secs(6 * 86400 + 3600))), // 7d opus ~6d
        Some(extra),
        Some(FetchStatus::Cached), // warning underline
    );

    let pro = oauth_profile(
        "side-project",
        "claude_pro",
        "default_claude_pro",
        false,
        true,
        false,
        Some(100.0),
        12.0,
        Some(Duration::from_secs(4 * 3600 + 5 * 60)),
        None,
        None,
        None,
        None,
    );

    let api = api_profile("bedrock-dev");

    let stale = failed_profile("research");

    let names: Vec<String> = [
        "personal",
        "work",
        "side-project",
        "bedrock-dev",
        "research",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();

    AppConfig {
        state: AppState {
            active_profile: Some("personal".to_string()),
            profiles: names,
            fallback_chain: vec![
                "personal".to_string(),
                "work".to_string(),
                "side-project".to_string(),
            ],
            ..AppState::default()
        },
        profiles: vec![max20, max5, pro, api, stale],
    }
}

// ── Usage simulation ───────────────────────────────────────────────────────────

/// Seed the live usage stores from the demo profiles' baked-in usage, exactly
/// as a real fetch worker would. Without this the first `on_tick` → `apply_usage`
/// reads an empty `usage_store` and blanks every window to `-`; with it the demo
/// utilization, reset timers and fetch-status underlines render — and survive
/// every subsequent tick, since `apply_usage` now finds the values it expects.
///
/// Reads the config and drops its guard before touching the usage locks, so no
/// lock is held across another (rank order: `usage_store` → `usage_status` are
/// both inner of `config`).
fn seed_usage(application: &app::App) {
    let snapshot: Vec<(String, Option<UsageInfo>, Option<FetchStatus>)> = {
        let cfg = application.config();
        cfg.profiles
            .iter()
            .map(|p| (p.name.clone(), p.usage.clone(), p.fetch_status))
            .collect()
    };
    if let Ok(mut store) = application.usage_store.lock() {
        for (name, usage, _) in &snapshot {
            if let Some(u) = usage {
                store.insert(name.clone(), u.clone());
            }
        }
    }
    if let Ok(mut status) = application.usage_status.lock() {
        for (name, _, fetch_status) in &snapshot {
            if let Some(s) = fetch_status {
                status.insert(name.clone(), *s);
            }
        }
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[test]
fn demo_config_has_expected_profiles() {
    let cfg = demo_config();
    assert_eq!(cfg.profiles.len(), 5);
    assert_eq!(cfg.state.active_profile.as_deref(), Some("personal"));
    assert_eq!(cfg.state.fallback_chain.len(), 3);

    let personal = cfg.profiles.iter().find(|p| p.name == "personal");
    assert!(personal.is_some_and(|p| p.auto_start && p.base_url.is_none()));

    let work = cfg.profiles.iter().find(|p| p.name == "work");
    assert!(work.is_some_and(|p| {
        p.fetch_status == Some(FetchStatus::Cached)
            && p.usage
                .as_ref()
                .and_then(|u| u.extra_usage.as_ref())
                .is_some_and(|e| e.is_enabled)
    }));

    let api = cfg.profiles.iter().find(|p| p.name == "bedrock-dev");
    assert!(api.is_some_and(|p| !p.is_oauth()));

    let failed = cfg.profiles.iter().find(|p| p.name == "research");
    assert!(
        failed.is_some_and(|p| p.fetch_status == Some(FetchStatus::Failed) && p.usage.is_none())
    );
}

#[test]
fn future_iso_parses() {
    use crate::usage::iso_to_epoch_secs;
    let s = future_iso(Duration::from_secs(3600));
    assert!(iso_to_epoch_secs(&s).is_some());
}

// ── Non-interactive driver ──────────────────────────────────────────────────
//
// The `showcase` test above is the human-driven version: it takes over a real
// terminal and waits for keypresses. This one runs the *same* `App` against the
// *same* demo data, but feeds synthetic key events through the production
// `handle_key` / `on_tick` so CI can prove every action works — switch, edit,
// toggle, reorder, set threshold (stepper + inline editor), delete — without a
// TTY and without ever touching the real `~/.clauth` / `~/.claude`.

/// Clears the home override when it drops, so a redirect can't leak past this
/// test and shadow `$HOME` for whatever runs next — even on a panic.
struct HomeOverrideReset;
impl Drop for HomeOverrideReset {
    fn drop(&mut self) {
        crate::profile::clear_home_override();
    }
}

fn key(code: KeyCode) -> KeyEvent {
    KeyEvent {
        code,
        modifiers: KeyModifiers::NONE,
        kind: KeyEventKind::Press,
        state: KeyEventState::NONE,
    }
}

fn key_shift(code: KeyCode) -> KeyEvent {
    KeyEvent {
        code,
        modifiers: KeyModifiers::SHIFT,
        kind: KeyEventKind::Press,
        state: KeyEventState::NONE,
    }
}

/// Press a bare key through the real dispatcher.
fn press(app: &mut app::App, code: KeyCode) {
    app::handle_key(app, key(code));
}

/// Type a string one `Char` event at a time, exactly as a terminal would.
fn type_str(app: &mut app::App, s: &str) {
    for c in s.chars() {
        app::handle_key(app, key(KeyCode::Char(c)));
    }
}

/// Drive `on_tick` until `pred` holds (worker results land asynchronously) or a
/// generous budget is exhausted. Mirrors the real loop's draw→tick cadence.
fn settle(app: &mut app::App, what: &str, mut pred: impl FnMut(&app::App) -> bool) {
    for _ in 0..400 {
        app::on_tick(app);
        if pred(app) {
            return;
        }
        std::thread::sleep(Duration::from_millis(5));
    }
    panic!("'{what}' never settled after draining ticks");
}

/// Read a profile's `auto_start` / `base_url` / `fallback_threshold` without
/// holding the config guard across a later `handle_key` (which re-locks it).
fn base_url_of(app: &app::App, name: &str) -> Option<String> {
    app.config().find(name).and_then(|p| p.base_url.clone())
}

fn auto_start_of(app: &app::App, name: &str) -> bool {
    app.config()
        .find(name)
        .map(|p| p.auto_start)
        .unwrap_or(false)
}

fn threshold_of(app: &app::App, name: &str) -> Option<f64> {
    app.config().find(name).and_then(|p| p.fallback_threshold)
}

#[test]
fn demo_data_drives_all_actions() {
    // Hold the shared home lock for the whole test and reset the override on
    // exit, so no $HOME-based test races us or sees our (dead) sandbox.
    let _guard = crate::profile::HOME_TEST_LOCK
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    let _reset = HomeOverrideReset;
    let sandbox = tempfile::tempdir().expect("create driver sandbox");
    set_home_override(sandbox.path().to_path_buf());

    // Every read/write the App makes from here on resolves under the sandbox.
    assert_eq!(
        home_dir().expect("home dir"),
        sandbox.path(),
        "home override must redirect every FS access into the sandbox"
    );

    let mut app = app::App::new(demo_config());
    seed_usage(&app); // simulate a fetch so usage windows aren't blanked to `-`

    // reconcile_startup is never called → no bootstrap, no scheduler, no fetch.
    assert!(!app.reconcile_done && !app.bootstrap_started);

    // ── Tab navigation: ⇥ walks forward and wraps, ⇧⇥ walks back. ──
    use app::Tab;
    assert_eq!(app.tab, Tab::Overview);
    press(&mut app, KeyCode::Tab);
    assert_eq!(app.tab, Tab::Usage);
    press(&mut app, KeyCode::Tab);
    assert_eq!(app.tab, Tab::Config);
    press(&mut app, KeyCode::Tab);
    assert_eq!(app.tab, Tab::Fallback);
    press(&mut app, KeyCode::Tab);
    assert_eq!(app.tab, Tab::Overview, "Tab wraps back to Overview");
    press(&mut app, KeyCode::BackTab);
    assert_eq!(app.tab, Tab::Fallback, "BackTab wraps to the last tab");
    press(&mut app, KeyCode::BackTab);
    press(&mut app, KeyCode::BackTab);
    press(&mut app, KeyCode::BackTab);
    assert_eq!(app.tab, Tab::Overview);

    // ── Switch: Overview → highlight "work" → ⏎ raises confirm → ⏎ commits. ──
    assert_eq!(
        app.config().state.active_profile.as_deref(),
        Some("personal")
    );
    press(&mut app, KeyCode::Down); // cursor 0 (personal) → 1 (work)
    press(&mut app, KeyCode::Enter); // request switch → confirm modal
    assert_eq!(app.modals.len(), 1, "switch raises a confirm modal");
    press(&mut app, KeyCode::Enter); // accept (choice defaults to yes)
    assert!(app.modals.is_empty(), "confirming pops the modal");
    settle(&mut app, "switch to work", |a| {
        a.config().state.active_profile.as_deref() == Some("work")
    });

    // Usage is simulated: on_tick ran apply_usage during the switch, and the
    // seeded windows survived instead of blanking to `-`.
    {
        let cfg = app.config();
        let util = cfg
            .find("personal")
            .and_then(|p| p.usage.as_ref())
            .and_then(|u| u.five_hour.as_ref())
            .map(|w| w.utilization);
        assert_eq!(
            util,
            Some(64.3),
            "seeded 5h utilization must survive on_tick → apply_usage"
        );
    }

    // The switch persisted into the sandbox, never the real config.
    let state_file = sandbox.path().join(".clauth").join("profiles.toml");
    assert!(
        state_file.exists(),
        "switch must write profiles.toml inside the sandbox"
    );

    // ── Edit: Config → "side-project" → BaseUrl row → type a URL → ⏎ saves. ──
    press(&mut app, KeyCode::Tab); // Overview → Usage
    press(&mut app, KeyCode::Tab); // Usage → Config
    assert_eq!(app.tab, Tab::Config);
    press(&mut app, KeyCode::Down); // 0 → 1
    press(&mut app, KeyCode::Down); // 1 → 2 (side-project)
    press(&mut app, KeyCode::Enter); // focus the detail pane
    assert_eq!(app.config_focus, app::ConfigFocus::Actions);
    assert!(app.config_draft.is_some());
    press(&mut app, KeyCode::Down); // Name → BaseUrl
    press(&mut app, KeyCode::Enter); // start capturing the field
    assert_eq!(
        app.config_draft.as_ref().and_then(|d| d.active),
        Some(app::ConfigRow::BaseUrl)
    );
    type_str(&mut app, "https://proxy.test");
    press(&mut app, KeyCode::Enter); // commit the field
    assert_eq!(
        base_url_of(&app, "side-project").as_deref(),
        Some("https://proxy.test"),
        "editing the BaseUrl field must persist it"
    );
    press(&mut app, KeyCode::Esc); // back out of the detail pane
    assert_eq!(app.config_focus, app::ConfigFocus::Profiles);

    // ── Toggle: "personal" auto-start ON → OFF (no worker spawns when off). ──
    assert!(auto_start_of(&app, "personal"), "demo seeds personal ON");
    press(&mut app, KeyCode::Up); // cursor 2 (side-project) → 1 (work)
    press(&mut app, KeyCode::Up); // → 0 (personal)
    press(&mut app, KeyCode::Enter); // focus detail for personal
    press(&mut app, KeyCode::Down); // Name → BaseUrl
    press(&mut app, KeyCode::Down); // → ApiKey
    press(&mut app, KeyCode::Down); // → AutoStart
    press(&mut app, KeyCode::Enter); // flip it
    assert!(
        !auto_start_of(&app, "personal"),
        "auto-start must toggle off"
    );
    press(&mut app, KeyCode::Esc);

    // ── Reorder: Fallback chain [personal, work, side-project] → ⇧↓ on head. ──
    press(&mut app, KeyCode::Tab); // Config → Fallback
    assert_eq!(app.tab, Tab::Fallback);
    {
        let cfg = app.config();
        assert_eq!(
            cfg.state.fallback_chain,
            vec!["personal", "work", "side-project"]
        );
    }
    app::handle_key(&mut app, key_shift(KeyCode::Down)); // move head down one
    {
        let cfg = app.config();
        assert_eq!(
            cfg.state.fallback_chain,
            vec!["work", "personal", "side-project"],
            "⇧↓ reorders the chain"
        );
    }
    assert_eq!(app.chain_cursor, 1, "cursor follows the moved member");

    // ── Set threshold (stepper): "personal" is now chain index 1, 80% → 85%. ──
    assert_eq!(threshold_of(&app, "personal"), Some(80.0));
    press(&mut app, KeyCode::Enter); // enter the member detail pane
    assert_eq!(app.fallback_focus, app::FallbackFocus::Detail);
    press(&mut app, KeyCode::Char('+')); // +5 step
    assert_eq!(
        threshold_of(&app, "personal"),
        Some(85.0),
        "the + stepper bumps the threshold by 5"
    );

    // ── Set threshold (inline editor): ⏎ opens it, retype 50, ⏎ commits. ──
    press(&mut app, KeyCode::Enter); // open the inline editor on the Threshold row
    assert!(app.fallback_threshold_draft.is_some());
    press(&mut app, KeyCode::Backspace); // clear "85"
    press(&mut app, KeyCode::Backspace);
    type_str(&mut app, "50");
    press(&mut app, KeyCode::Enter); // commit
    assert!(app.fallback_threshold_draft.is_none());
    assert_eq!(
        threshold_of(&app, "personal"),
        Some(50.0),
        "the inline editor sets an absolute threshold"
    );
    press(&mut app, KeyCode::Esc); // leave the detail pane
    assert_eq!(app.fallback_focus, app::FallbackFocus::Chain);

    // ── Delete: Config → "research" → Delete row → ⏎ arms, ⏎ confirms. ──
    let before = app.profile_count();
    press(&mut app, KeyCode::BackTab); // Fallback → Config
    assert_eq!(app.tab, Tab::Config);
    for _ in 0..4 {
        press(&mut app, KeyCode::Down); // 0 → 4 (research, the last profile)
    }
    press(&mut app, KeyCode::Enter); // focus detail
    for _ in 0..4 {
        press(&mut app, KeyCode::Down); // Name → … → Delete (last row)
    }
    press(&mut app, KeyCode::Enter); // arm
    assert!(
        app.config_draft
            .as_ref()
            .map(|d| d.armed_delete)
            .unwrap_or(false),
        "first ⏎ arms the delete row"
    );
    press(&mut app, KeyCode::Enter); // confirm
    assert_eq!(app.profile_count(), before - 1, "delete drops one profile");
    assert!(
        app.config().find("research").is_none(),
        "the deleted profile is gone from the config"
    );

    // ── Quit. ──
    press(&mut app, KeyCode::Char('q'));
    assert!(app.quit, "q quits");

    // Nothing escaped the sandbox: home_dir still points there and the real
    // tree is untouched (the override is the only path the App ever resolved).
    assert_eq!(home_dir().expect("home dir"), sandbox.path());
}