trail-fm 1.13.0

A terminal-first workspace for navigating, inspecting and acting on the filesystem
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
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! Trail — a terminal file manager.
//!
//! Entry point: parses CLI arguments, initializes the terminal in raw mode
//! with an alternate screen, installs a panic hook that restores the terminal,
//! runs the event loop, and tears down cleanly on exit.
//!
//! Phase 4 extends the event loop with `select!` across terminal input, the
//! worker channel (`WorkerMsg`), and filesystem watch signals.

#![forbid(unsafe_code)]

mod actions;
mod app;
mod cli;
mod config;
mod input;
mod metafmt;
mod pathfmt;
mod paths;
mod plugin;
mod preview;
mod session;
mod terminal;
mod ui;
mod version;
mod window_title;
mod workers;

use std::io::{self, stdout};
use std::panic;
use std::path::PathBuf;
use std::time::{Duration, Instant};

use anyhow::Result;
use clap::Parser;
use crossterm::event::{self, Event, EventStream};
use crossterm::execute;
use crossterm::terminal::{self as tty, EnterAlternateScreen, LeaveAlternateScreen};
use futures::StreamExt;
use ratatui::backend::CrosstermBackend;
use ratatui::Terminal;
use tokio::sync::mpsc;

use crate::actions::shell_exec;
use crate::actions::Action;
use crate::app::state::AppState;
use crate::cli::Cli;
use crate::input::InputCtx;
use crate::preview::provider::{PreviewContent, PreviewCtx, PreviewOutcome, PreviewRegistry};
use crate::terminal::KeyOutcome;
use crate::window_title::{TitleMode, WindowTitle};
use crate::workers::fswatch::FsWatchHandle;
use crate::workers::{GitCache, WorkerMsg};

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // `--paths` is a report, not a session. Answer it and leave before the
    // panic hook, the logger or the terminal are touched, so the output is
    // ordinary stdout that can be piped, redirected or read by a script.
    if cli.paths {
        println!("{}", paths::report());
        return Ok(());
    }

    // Capture cwd_file path before consuming `cli` below.
    let cwd_file = cli.cwd_file.clone();

    // Install the panic hook BEFORE touching terminal state, so a panic at
    // any point during execution restores the terminal rather than leaving it
    // broken. This is a Phase 0 deliverable explicitly called out in the
    // implementation plan and coding standard (§5).
    let default_hook = panic::take_hook();
    panic::set_hook(Box::new(move |info| {
        // Best-effort terminal restoration — if this itself fails, there's
        // nothing more we can do.
        let _ = window_title::restore_to(&mut stdout());
        let _ = execute!(stdout(), LeaveAlternateScreen);
        let _ = tty::disable_raw_mode();
        default_hook(info);
    }));

    // Set up structured logging to a file (never stdout/stderr — we own the
    // alternate screen). Log files go to the system's tmp directory; Phase 9
    // can route them to a proper log dir.
    //
    // Failures here are non-fatal: the app works fine without logs.
    if let Ok(log_dir) = std::env::temp_dir().canonicalize() {
        let file_appender = tracing_appender::rolling::never(&log_dir, paths::LOG_FILE);
        let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
        let _ = tracing_subscriber::fmt()
            .with_writer(non_blocking)
            .with_env_filter(
                tracing_subscriber::EnvFilter::builder()
                    .with_default_directive(tracing_subscriber::filter::LevelFilter::INFO.into())
                    .from_env_lossy(),
            )
            .try_init();
        // _guard is intentionally leaked: it lives for the process lifetime.
        std::mem::forget(_guard);
    }

    // The data directory holds everything Trail persists between runs
    // (bookmarks, recent directories, the remembered --config path). Resolve
    // it before loading config, since the remembered path lives there.
    let data_dir = paths::data_dir();

    if let Err(e) = std::fs::create_dir_all(&data_dir) {
        tracing::debug!("failed to create data dir: {e}");
    }

    let config_state_file = data_dir.join(config::last_used::STATE_FILE_NAME);

    // Decide which config to load: an explicit --config, else the path
    // remembered from a previous run, else the built-in defaults.
    let config_source = config::last_used::resolve(
        cli.config.clone(),
        config::last_used::remembered(&config_state_file),
        cli.no_config,
    );

    // Build initial app state from the CLI start path before entering raw
    // mode so that a bad start path produces a normal error message rather
    // than a broken terminal.
    let (config, config_warning) = load_configured(&config_source)?;

    // Only record a path the user named explicitly, and only once it has
    // actually loaded — a file that fails to parse must never become the one
    // Trail reaches for on the next run.
    if let config::ConfigSource::Explicit(ref path) = config_source {
        if let Err(e) = config::last_used::remember(&config_state_file, path) {
            // Non-fatal: this session is fine, it just won't be recalled.
            tracing::debug!("failed to remember --config path: {e}");
        }
    }

    let mut state = AppState::with_config(cli.start_path, config)
        .map_err(|e| anyhow::anyhow!("failed to open start directory: {e}"))?;

    // The file `:config write` saves into: the one that loaded, if one did.
    // A remembered file that failed to load is not in use, so it is not it.
    state.settings.file = match &config_source {
        config::ConfigSource::Explicit(path) => Some(path.clone()),
        config::ConfigSource::Remembered(path) if config_warning.is_none() => Some(path.clone()),
        _ => None,
    };
    state.settings.remember_in = Some(config_state_file.clone());

    // Surface a degraded remembered config in the status bar. Trail owns the
    // alternate screen, so this is the only channel available.
    if let Some(warning) = config_warning {
        state.set_error(warning);
    }

    state.bookmark_store =
        match plugin::bookmarks::BookmarkStore::open(data_dir.join(paths::BOOKMARKS_FILE)) {
            Ok(store) => Some(store),
            Err(e) => {
                tracing::debug!("failed to load bookmarks: {e}");
                None
            }
        };

    state.recent_dirs = session::RecentDirs::load(&data_dir.join(paths::RECENT_DIRS_FILE));
    state.recent_dirs.visit(state.cwd.clone());

    let mut engine = plugin::PluginEngine::new()
        .map_err(|e| anyhow::anyhow!("failed to init plugin engine: {e}"))?;

    plugin::load_enabled_plugins(&mut engine, &state.config.plugins.enabled);
    state.plugin_engine = Some(engine);

    // Resolve the terminal's inline-image protocol before the first preview is
    // requested, so image decodes never race the detection.
    preview::graphics::configure(
        &state.config.preview.image_protocol,
        (
            state.config.preview.image_cell_width,
            state.config.preview.image_cell_height,
        ),
    );

    // Build the preview registry once at startup. All providers are registered
    // here; the main loop calls registry.preview_for on every selection change.
    let mut registry = PreviewRegistry::new();
    preview::register_defaults(&mut registry);

    // Set up the worker channel (single mpsc, drained once per UI tick).
    let (worker_tx, worker_rx) = workers::channel();
    // The terminal panel's shells report output and exit on the same channel.
    state.terminal.attach(worker_tx.clone());
    // Copies and moves run on the blocking pool and report here too.
    state.transfers.attach(worker_tx.clone());

    // Set up the git cache (shared between the UI thread and worker tasks).
    let git_cache = workers::git::new_cache();

    // Compute the initial preview for whatever is selected at startup.
    refresh_preview(&mut state, &registry, &worker_tx);

    // Spawn the initial git status worker for the starting directory.
    let initial_cwd = state.cwd.clone();
    if state.config.general.git_status_enabled {
        workers::git::spawn_git_status(initial_cwd.clone(), worker_tx.clone(), git_cache.clone());
    }

    // Start the filesystem watcher for the initial directory.
    let mut fs_watch_handle: Option<FsWatchHandle> = workers::fswatch::spawn_fswatch(
        initial_cwd,
        worker_tx.clone(),
        state.config.general.fs_watch_debounce_ms,
    );

    // Enter raw mode and the alternate screen. The suspend/resume sequence in
    // shell_exec::run_external reuses the same crossterm operations, so
    // establishing the enter/exit pair correctly here avoids rework later.
    tty::enable_raw_mode()?;
    execute!(stdout(), EnterAlternateScreen)?;

    let backend = CrosstermBackend::new(stdout());
    // expect: terminal init is a genuinely unrecoverable startup failure,
    // and the panic hook is already installed above, so the terminal will be
    // restored before the process exits.
    let mut terminal = Terminal::new(backend).expect("failed to initialize terminal");

    let mut title = WindowTitle::default();
    let run_result = run_event_loop(
        &mut terminal,
        &mut state,
        &registry,
        worker_rx,
        worker_tx.clone(),
        git_cache,
        &mut fs_watch_handle,
        &mut title,
    )
    .await;

    // Teardown: give the shell its title back, leave alternate screen and
    // restore cooked mode regardless of whether the event loop exited cleanly
    // or with an error.
    if let Err(e) = title.restore(&mut stdout()) {
        tracing::debug!("restoring the terminal title failed: {e}");
    }
    execute!(stdout(), LeaveAlternateScreen)?;
    tty::disable_raw_mode()?;

    // Phase 6: On normal exit, write the current directory to `--cwd-file`
    // so the shell wrapper can `cd` into it. On cancellation or error the
    // file is not written — the shell wrapper then does nothing.
    let cancelled = matches!(&run_result, Err(ref e) if e.to_string() == "cancelled");
    if run_result.is_ok() {
        if let Some(ref path) = cwd_file {
            if let Err(e) = session::write_cwd_file(&state.cwd, path) {
                // Non-fatal: log and continue. The user still exits cleanly;
                // they just won't be `cd`-ed to the right directory this time.
                // `warn`, not `debug`: the shell silently staying put is the
                // one failure the user is guaranteed to notice and have no
                // explanation for, and the alternate screen is already gone.
                tracing::warn!("failed to write cwd-file: {e}");
            }
        }

        state
            .recent_dirs
            .save(&data_dir.join(paths::RECENT_DIRS_FILE));
    } else if cancelled {
        // Cancelled (Ctrl+C): save recent dirs but do NOT write cwd-file.
        state
            .recent_dirs
            .save(&data_dir.join(paths::RECENT_DIRS_FILE));
    }

    // Re-surface real errors; treat "cancelled" as a clean exit.
    if cancelled {
        Ok(())
    } else {
        run_result
    }
}

/// Loads the configuration named by `source`, applying the failure policy that
/// the source implies.
///
/// Returns the config plus an optional warning to show in the status bar.
///
/// # Errors
///
/// Returns an error only for [`config::ConfigSource::Explicit`]: the user named
/// that file on the command line, so a typo or a syntax error must fail loudly
/// rather than silently starting with different settings. A
/// [`config::ConfigSource::Remembered`] path that no longer loads is reported
/// as a warning and falls back to the built-in defaults instead — it was
/// recorded by an earlier run and may since have been moved, deleted or edited,
/// and refusing to start would leave the user with no obvious way back.
fn load_configured(source: &config::ConfigSource) -> Result<(config::TrailConfig, Option<String>)> {
    match source {
        config::ConfigSource::Defaults => {
            tracing::info!("using built-in default configuration");
            let config =
                config::load(None).map_err(|e| anyhow::anyhow!("failed to load config: {e}"))?;
            Ok((config, None))
        }

        config::ConfigSource::Explicit(path) => {
            tracing::info!(?path, "loading configuration from --config");
            let config = config::load(Some(path))
                .map_err(|e| anyhow::anyhow!("failed to load config: {e}"))?;
            Ok((config, None))
        }

        config::ConfigSource::Remembered(path) => match config::load(Some(path)) {
            Ok(config) => {
                tracing::info!(?path, "loading remembered configuration");
                Ok((config, None))
            }
            Err(e) => {
                tracing::warn!(
                    ?path,
                    "remembered config failed to load; falling back to defaults: {e}"
                );
                let config = config::load(None)
                    .map_err(|e| anyhow::anyhow!("failed to load config: {e}"))?;
                let warning = format!(
                    "remembered config {} failed to load ({e}); using defaults",
                    path.display()
                );
                Ok((config, Some(warning)))
            }
        },
    }
}

/// Updates `state.preview` synchronously for the currently selected entry.
///
/// Called after every action that might change the selection or current
/// directory. Goes through [`crate::app::state::PreviewSlot::begin`], which
/// increments `state.preview.generation` on every call so that worker results
/// for a since-abandoned selection are discarded, and resets the preview's
/// scroll position only when the selected path actually changed.
///
/// The `tx` sender is passed through to `PreviewCtx` so providers can spawn
/// async worker tasks (highlight worker, image decode worker).
fn refresh_preview(state: &mut AppState, registry: &PreviewRegistry, tx: &mpsc::Sender<WorkerMsg>) {
    if let Some(entry) = state.selected_entry().cloned() {
        if let Some(engine) = &state.plugin_engine {
            engine.fire_on_select(&entry.path);
        }
        // Bumps the generation, and resets the scroll position only when this is
        // a different entry — a re-preview of the same path (filesystem watch,
        // `R`, hidden-file toggle) leaves the reader where they were.
        let generation = state.preview.begin(&entry.path);
        let ctx = PreviewCtx {
            show_hidden: state.show_hidden,
            worker_tx: tx.clone(),
            generation,
            text_sync_threshold_bytes: state.config.general.text_sync_threshold_kb * 1024,
            max_preview_lines: state.config.preview.max_lines,
        };
        match registry.preview_for(&entry, &ctx) {
            PreviewOutcome::Ready(content) => {
                state.preview.content = content;
            }
            PreviewOutcome::Deferred => {
                // A worker was spawned. Show loading placeholder until the
                // channel message arrives and merge() applies the content.
                state.preview.content = PreviewContent::Loading;
            }
        }
    } else {
        // No selection: still bump the generation, so a result for the entry
        // that was selected a moment ago cannot land in an empty pane.
        state.preview.begin(&PathBuf::new());
        state.preview.content = PreviewContent::Empty;
    }
    state.dirty = true;
}

/// Re-subscribes the filesystem watcher to `new_cwd`, replacing the previous
/// handle. The old handle is dropped, which cancels the old watch task.
fn resubscribe_fswatch(
    new_cwd: PathBuf,
    tx: &mpsc::Sender<WorkerMsg>,
    handle: &mut Option<FsWatchHandle>,
    debounce_ms: u64,
) {
    // Drop the current handle, which cancels the old watch task.
    *handle = None;
    *handle = workers::fswatch::spawn_fswatch(new_cwd, tx.clone(), debounce_ms);
}

/// The shortest interval between two frames drawn because a terminal panel
/// shell produced output — about 60 a second. Without a cap, a build or a
/// `cat` of a large file would redraw the whole screen for every read, and the
/// keys typed meanwhile would wait behind those frames.
const TERMINAL_FRAME: Duration = Duration::from_millis(16);

/// Sleeps for `wait`, or forever when there is nothing to wait for — so a
/// `select!` arm built from it fires only when terminal output is pending.
async fn frame_timer(wait: Option<Duration>) {
    match wait {
        Some(wait) => tokio::time::sleep(wait).await,
        None => std::future::pending().await,
    }
}

/// Runs the main event loop until the user quits.
///
/// Phase 4: `select!`s across three event sources:
///  1. Terminal key events (via `crossterm::event::EventStream`).
///  2. `WorkerMsg` messages from the async worker pool.
///  3. (No dedicated fs-signal channel: the watcher sends `FsChanged` over the
///     same `worker_rx` channel, matching the single-enum decision in the plan.)
///
/// On each iteration, after processing events, re-renders only when
/// `state.dirty` is set.
#[allow(clippy::too_many_arguments)]
async fn run_event_loop(
    terminal: &mut ratatui::Terminal<CrosstermBackend<io::Stdout>>,
    state: &mut AppState,
    registry: &PreviewRegistry,
    mut worker_rx: mpsc::Receiver<WorkerMsg>,
    worker_tx: mpsc::Sender<WorkerMsg>,
    git_cache: GitCache,
    fs_watch_handle: &mut Option<FsWatchHandle>,
    title: &mut WindowTitle,
) -> Result<()> {
    let mut ctx = InputCtx::default();
    let mut should_quit = false;
    let mut cancelled = false;

    // Initial render.
    ui::render(terminal, state)?;
    update_title(terminal, state, title);
    state.dirty = false;
    let mut last_render = Instant::now();

    // Use crossterm's async EventStream for non-blocking terminal input.
    let mut event_stream = EventStream::new();

    while !should_quit {
        // Drain any worker messages that are already queued, then wait for
        // either a terminal event or the next worker message.
        //
        // Priority: worker messages are drained first (they may be many in a
        // burst), then the select handles whichever arrives next.
        let mut worker_drained = false;
        // Track whether a non-preview worker message (Git, FsChanged) made the
        // state dirty. Preview/ImageMeta results are applied directly by
        // merge() and must NOT trigger another refresh_preview call — doing so
        // would overwrite the just-merged content with `Loading` again.
        let mut needs_preview_refresh = false;
        while let Ok(msg) = worker_rx.try_recv() {
            // A finished transfer re-lists the directory, so it can move the
            // selection the same way a filesystem change can.
            let is_listing_change = matches!(
                &msg,
                WorkerMsg::Git { .. }
                    | WorkerMsg::FsChanged { .. }
                    | WorkerMsg::TransferDone { .. }
            );
            let prev_cwd = state.cwd.clone();
            handle_worker_msg(
                msg,
                state,
                &worker_tx,
                &git_cache,
                fs_watch_handle,
                &prev_cwd,
            );
            worker_drained = true;
            if is_listing_change && state.dirty {
                needs_preview_refresh = true;
            }
        }

        // Refresh preview only when a listing-level change (FsChanged / Git)
        // dirtied the state — e.g. FsChanged triggered a directory refresh and
        // the selected entry may have changed. Preview/ImageMeta results are
        // already applied by merge() and must not be re-requested here.
        if needs_preview_refresh {
            refresh_preview(state, registry, &worker_tx);
        }

        // Terminal output waits for the next frame slot rather than drawing at
        // once; `frame_wait` is how long until that slot, if output is waiting.
        let frame_wait = state
            .terminal
            .output_pending()
            .then(|| TERMINAL_FRAME.saturating_sub(last_render.elapsed()));

        if !worker_drained && frame_wait != Some(Duration::ZERO) {
            // Block until either a terminal event or worker message arrives.
            tokio::select! {
                // Terminal input.
                maybe_event = event_stream.next() => {
                    match maybe_event {
                        Some(Ok(event)) => {
                            match event {
                                Event::Key(key) => {
                                    handle_key_event(
                                        key,
                                        terminal,
                                        state,
                                        registry,
                                        &worker_tx,
                                        &git_cache,
                                        fs_watch_handle,
                                        &mut ctx,
                                        &mut should_quit,
                                        &mut cancelled,
                                        title,
                                    );
                                }
                                Event::Resize(_, _) => {
                                    // A terminal resize desynchronises ratatui's
                                    // internal double-buffer from the physical
                                    // terminal. Call terminal.clear() to reset
                                    // ratatui's previous buffer so the next
                                    // draw() performs a complete redraw of every
                                    // cell, eliminating ghost content from the
                                    // old frame.
                                    if let Err(e) = terminal.clear() {
                                        tracing::debug!("terminal clear after resize failed: {e}");
                                    }
                                    state.dirty = true;
                                }
                                _ => {}
                            }
                        }
                        Some(Err(e)) => {
                            tracing::debug!("terminal event error: {e}");
                        }
                        None => {
                            // EventStream exhausted — terminal was closed.
                            should_quit = true;
                        }
                    }
                }

                // Worker messages (git, FsChanged, Preview, ImageMeta, and the
                // terminal panel's output and exits).
                Some(msg) = worker_rx.recv() => {
                    let prev_cwd = state.cwd.clone();
                    handle_worker_msg(
                        msg,
                        state,
                        &worker_tx,
                        &git_cache,
                        fs_watch_handle,
                        &prev_cwd,
                    );
                }

                // The frame slot for pending terminal output.
                () = frame_timer(frame_wait) => {}
            }
        }

        if state.terminal.output_pending() && last_render.elapsed() >= TERMINAL_FRAME {
            state.dirty = true;
        }

        // Re-render only when something changed.
        if state.dirty {
            ui::render(terminal, state)?;
            update_title(terminal, state, title);
            state.dirty = false;
            last_render = Instant::now();
            state.terminal.frame_drawn();
        }
    }

    if cancelled {
        Err(anyhow::anyhow!("cancelled"))
    } else {
        Ok(())
    }
}

/// Points the terminal title at the current directory, as
/// `[general] terminal_title` asks. A failure is logged and otherwise
/// ignored: the title is a convenience, not worth ending a session over.
fn update_title(
    terminal: &mut ratatui::Terminal<CrosstermBackend<io::Stdout>>,
    state: &AppState,
    title: &mut WindowTitle,
) {
    // validate() and `:set` both reject anything else, so this is the default.
    let mode = TitleMode::parse(&state.config.general.terminal_title).unwrap_or(TitleMode::Dir);
    if let Err(e) = title.update(terminal.backend_mut(), mode, &state.cwd) {
        tracing::debug!("setting the terminal title failed: {e}");
    }
}

/// Handles a single terminal key event.
///
/// Updates selection/directory as needed, refreshes the preview, re-subscribes
/// the fs watcher and spawns a git worker if the directory changed.
/// Phase 6: also accepts `terminal` so it can call `terminal.clear()` after
/// returning from `shell_exec::run_external`.
#[allow(clippy::too_many_arguments)]
fn handle_key_event(
    key: event::KeyEvent,
    terminal: &mut ratatui::Terminal<CrosstermBackend<io::Stdout>>,
    state: &mut AppState,
    registry: &PreviewRegistry,
    worker_tx: &mpsc::Sender<WorkerMsg>,
    git_cache: &GitCache,
    fs_watch_handle: &mut Option<FsWatchHandle>,
    ctx: &mut InputCtx,
    should_quit: &mut bool,
    cancelled: &mut bool,
    title: &mut WindowTitle,
) {
    let old_selected = state.selected;
    // The index alone misses a change of entry: while searching, every keystroke
    // re-filters and selects match 0, which is a different entry from before.
    let old_selected_path = state.selected_entry().map(|e| e.path.clone());
    let old_cwd = state.cwd.clone();

    // A notice lasts until the user does the next thing. Dismissing it here —
    // before the keystroke's own action runs, and only for a real press — is
    // what keeps "yanked: …" from following the user into directories it has
    // nothing to do with, while still leaving the action free to post a new
    // one that this frame will draw.
    if key.kind == crossterm::event::KeyEventKind::Press {
        state.clear_notice();
    }

    // The terminal panel sees every key first: its toggle and focus keys work
    // from anywhere, and while a shell has the keyboard everything else is the
    // shell's.
    match terminal::handle_key(state, &key) {
        KeyOutcome::NotMine => {}
        KeyOutcome::Handled => return,
        KeyOutcome::Quit { cancel } => {
            *should_quit = true;
            *cancelled = cancel;
            return;
        }
    }

    if let Some(action) = input::dispatch(key, state, ctx) {
        // Quitting ends the panel's shells, so it may have to ask first; the
        // answer comes back through `terminal::handle_key` above.
        if action == Action::Quit || action == Action::Cancel {
            let cancel = action == Action::Cancel;
            if terminal::allow_quit(state, cancel) {
                *should_quit = true;
                *cancelled = cancel;
            }
            return;
        }

        // Track whether this action sets the pending prefix so we can
        // conditionally clear it on the next non-prefix key.
        let is_prefix = matches!(action, Action::SetPendingNavKey(_));
        // Track whether the action may change the listing content without
        // changing the selected index or cwd (e.g. Refresh, ToggleHidden).
        let forces_preview_refresh = matches!(action, Action::Refresh | Action::ToggleHidden);

        // Report the failure and continue rather than crashing — a bad
        // directory is inconvenient, not fatal. `set_error` puts it in the
        // status bar and in the log, where it used to be `debug`-only and
        // therefore below the default filter.
        if let Err(e) = actions::apply(action, state) {
            state.set_error(e.to_string());
        }

        if !is_prefix && state.pending_nav_key.is_some() {
            state.pending_nav_key = None;
            state.dirty = true;
        }

        // Refresh preview whenever the selection or directory changed, or the
        // action explicitly requires it (Refresh, ToggleHidden).
        let selected_path = state.selected_entry().map(|e| &e.path);
        if state.selected != old_selected
            || selected_path != old_selected_path.as_ref()
            || state.cwd != old_cwd
            || forces_preview_refresh
        {
            refresh_preview(state, registry, worker_tx);
        }
    } else if key.kind == crossterm::event::KeyEventKind::Press && state.pending_nav_key.is_some() {
        // A keypress while a prefix was pending but produced no action —
        // cancel the sequence. Release/Repeat events are intentionally
        // excluded: crossterm fires both Press *and* Release on every
        // keystroke (especially on Windows), so allowing Release to clear
        // the pending key would prevent any two-character sequence from
        // ever completing.
        state.pending_nav_key = None;
        state.dirty = true;
    }

    // If the directory changed, re-subscribe the watcher and spawn git.
    if state.cwd != old_cwd {
        resubscribe_fswatch(
            state.cwd.clone(),
            worker_tx,
            fs_watch_handle,
            state.config.general.fs_watch_debounce_ms,
        );
        if state.config.general.git_status_enabled {
            workers::git::spawn_git_status(state.cwd.clone(), worker_tx.clone(), git_cache.clone());
        }
        // Clear stale git state immediately so the old branch doesn't linger.
        state.git = None;
    }

    // Phase 6: drain any pending external action (editor-open or !shell).
    // run_external is synchronous (blocks until the child exits) but we must
    // call it here on the UI thread because it manipulates terminal state.
    if let Some(Action::RunExternal {
        argv,
        cwd,
        pause,
        label,
    }) = state.pending_external.take()
    {
        let argv_refs: Vec<&str> = argv.iter().map(|s| s.as_str()).collect();
        match shell_exec::run_external(&argv_refs, &cwd, pause, label.as_deref()) {
            Ok(report) => actions::report_run(state, &report),
            Err(e) => state.set_error(format!("exec: {e}")),
        }
        // Force a full redraw: the child process may have overwritten the screen.
        // terminal.clear() resets ratatui's internal buffer so the next render
        // redraws every cell from scratch, preventing ghost characters.
        if let Err(e) = terminal.clear() {
            tracing::debug!("terminal clear after run_external failed: {e}");
        }
        // The child may have set a title of its own (an editor usually does).
        title.forget();
        // Refresh the listing and preview — the subprocess may have changed
        // the filesystem (e.g. saving a file in the editor).
        let _ = state.refresh();
        refresh_preview(state, registry, worker_tx);
        state.dirty = true;
    }
}

/// Handles a single `WorkerMsg` received from the worker channel.
///
/// - `Git` and `Preview`/`ImageMeta` are dispatched to `workers::merge()`.
/// - `FsChanged` additionally triggers a directory refresh and re-spawns the
///   git worker (after invalidating the cache for the changed path).
fn handle_worker_msg(
    msg: WorkerMsg,
    state: &mut AppState,
    worker_tx: &mpsc::Sender<WorkerMsg>,
    git_cache: &GitCache,
    fs_watch_handle: &mut Option<FsWatchHandle>,
    _prev_cwd: &std::path::Path,
) {
    match &msg {
        WorkerMsg::FsChanged { path } => {
            let changed_path = path.clone();

            // Determine whether this change is relevant to what we're showing:
            // (a) the watched directory itself changed, or
            // (b) a .git/HEAD file inside the current repo changed (branch switch).
            let is_cwd_change = changed_path == state.cwd;
            let is_git_head_change = changed_path
                .file_name()
                .map(|n| n == "HEAD")
                .unwrap_or(false)
                && changed_path
                    .parent()
                    .and_then(|p| p.file_name())
                    .map(|n| n == ".git")
                    .unwrap_or(false);

            if is_cwd_change {
                // Invalidate the git cache so the next git worker gets fresh data.
                workers::git::invalidate(git_cache, &changed_path);

                // Refresh the directory listing.
                if let Err(e) = state.refresh() {
                    // The directory we are watching can no longer be listed —
                    // deleted, renamed, or a mount that went away. The watch is
                    // pointing at something that is not there any more, so this
                    // is the one case that has to re-arm it.
                    tracing::warn!("refresh after FsChanged failed: {e}");
                    resubscribe_fswatch(
                        state.cwd.clone(),
                        worker_tx,
                        fs_watch_handle,
                        state.config.general.fs_watch_debounce_ms,
                    );
                }

                // Re-spawn the git worker for the now-refreshed directory.
                if state.config.general.git_status_enabled {
                    workers::git::spawn_git_status(
                        changed_path.clone(),
                        worker_tx.clone(),
                        git_cache.clone(),
                    );
                }

                tracing::debug!(?changed_path, "refreshed after FsChanged");
            } else if is_git_head_change {
                // A branch switch occurred — invalidate cache and re-run git worker.
                workers::git::invalidate(git_cache, &state.cwd);
                if state.config.general.git_status_enabled {
                    workers::git::spawn_git_status(
                        state.cwd.clone(),
                        worker_tx.clone(),
                        git_cache.clone(),
                    );
                }
                state.dirty = true;
                tracing::debug!(?changed_path, "git branch change detected via .git/HEAD");
            }

            // The watch is *not* re-armed here. It used to be, on every event,
            // which meant tearing down and rebuilding a `notify` watcher — a
            // thread and a directory handle — for each debounced burst, on top
            // of a re-listing and a git worker. A build writing into the watched
            // directory therefore cost more in bookkeeping than in the work the
            // user asked for, and that is what made Trail stutter under load.
            //
            // A directory watch survives changes *inside* the directory, so the
            // only cases that need a fresh one are a change of `cwd` (handled
            // where the directory changes) and a directory that can no longer be
            // listed (handled above).
        }
        _ => {
            // All other messages go through the standard merge path.
            workers::merge(msg, state);
        }
    }
}