From e7241a3874073fe65c9cf0e63c170db24b4e99bd Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 21 Sep 2026 19:03:15 +0200 Subject: [PATCH] feat: mature the read-only TUI browser for release --- AGENTS-TASKS.md | 20 ++ README.md | 9 +- docs/architecture.md | 2 +- docs/roadmap.md | 4 +- docs/tui-design.md | 178 ++++++----- tui_efo/Cargo.toml | 4 +- tui_efo/src/main.rs | 543 +++++++++++++++++++++++++++----- tui_efo/tests/startup.rs | 56 ++++ tui_efo/tests/terminal_smoke.py | 49 +++ 9 files changed, 699 insertions(+), 166 deletions(-) create mode 100644 tui_efo/tests/startup.rs create mode 100644 tui_efo/tests/terminal_smoke.py diff --git a/AGENTS-TASKS.md b/AGENTS-TASKS.md index 9b1b09b..f34d7e3 100644 --- a/AGENTS-TASKS.md +++ b/AGENTS-TASKS.md @@ -262,3 +262,23 @@ These require user approval and are not part of the current implementation: position tests; document and provide a runnable `lib_efo` repository example. - [x] Configure Tarpaulin around its subprocess-attribution limitation and refresh `rust_autobadges` at a directly measured coverage level above 70%. + +## TUI release-readiness pass + +- [x] Add searchable, sorted entity lists and HEAD/index/worktree browsing. +- [x] Improve detail rendering, bounded scrolling, paging, and compact layouts. +- [x] Preserve selection on reload and expose full reload diagnostics. +- [x] Harden terminal lifecycle, Ctrl-C, non-terminal startup, and no-colour output. +- [x] Add rendering, navigation, failure, and binary workflow coverage; update docs. +- Decision: this pass matures the read-only browser; interactive writes retain + the preview/recovery design requirements in `docs/tui-design.md`. + +- Fixed multiline JSON details, stale reload selection, help clipping, blank + overscroll, and list-window jumps when navigating upward. +- The browser uses Ratatui's locked rendered-line measurement feature for exact + wrapped scroll bounds. Persisted repository data is unchanged. +- Validation: 109 all-feature tests and 105 portable tests, formatting, strict + Clippy, both release builds, and Unix PTY navigation/resize/restoration checks. + TUI coverage includes nine state/render tests and three binary startup tests. +- Release boundary: write workflows and history comparison stay in the CLI; + cross-terminal visual review remains useful before publishing a final release. diff --git a/README.md b/README.md index 5463c98..61f96ed 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ The current release manages organisations, characters, towns, events, calamities, and blockers with statistics and relationships. Repository format 1.0 provides worktree/index staging, immutable commits, restore, conflict-safe revert, switching, and recoverable future pruning from initialisation. A separate -read-only TUI browses repository status and entities. Custom fields and TUI write +read-only TUI searches entities across HEAD, staged, and working state. Custom fields and TUI write workflows remain planned. There is no GUI or web interface. > Epoch Forge is not yet suitable as the only copy of important campaign data. @@ -79,9 +79,10 @@ Run `efo --help`, `efo --help`, or see the `efo show all` gives a world overview; per-type commands such as `efo chr show Aria` provide targeted or detailed inspection. -Run `efo-tui` in a repository root. The TUI -uses ordinary Unicode and text labels, so no meaning depends on Nerd Font -glyphs. Press `?` for its complete keyboard reference. +Run `efo-tui` in a repository root (or use `--repository PATH`). Press `/` to +search and `1`/`2`/`3` to browse HEAD/index/worktree. Narrow terminals show one +focused panel; Tab cycles panels. Use `--no-color` for monochrome output and +`?` for the scrollable keyboard reference. No Nerd Font is required. ## Documentation diff --git a/docs/architecture.md b/docs/architecture.md index 2440729..1f8f309 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -27,7 +27,7 @@ the index, and the editable worktree, and defines the atomic transaction rules that implementation must preserve. The sole pre-release repository format is version 1.0; its structured major/minor discriminator leaves room for explicit 1.x migrations without retaining an unreleased prototype reader. -The approved [first-pass TUI contract](tui-design.md) adds a separate read-only +The approved [TUI browser contract](tui-design.md) adds a separate read-only repository browser without creating another persistence path. Library tests cover parsing, statistics, display snapshots, entity/epoch diff --git a/docs/roadmap.md b/docs/roadmap.md index 41e11b4..1d82b39 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -30,8 +30,8 @@ changes use 1.x versions and regain explicit migration tooling when needed. Organisation-agnostic custom fields and types follow, with unknown-field retention designed before that format change. -The first [TUI checkpoint](tui-design.md) is now approved: a separate, -read-only `efo-tui` binary browses repository status and entities through the +The [TUI browser](tui-design.md) now includes search, layer browsing, responsive +layouts, and guarded terminal handling. The read-only `efo-tui` uses the same library API. Interactive mutations remain a later, separately reviewed checkpoint. diff --git a/docs/tui-design.md b/docs/tui-design.md index 5a5ab53..7eb44e6 100644 --- a/docs/tui-design.md +++ b/docs/tui-design.md @@ -1,105 +1,119 @@ -# TUI first-pass design +# TUI browser and release contract -The terminal user interface is a separate `efo-tui` binary over `lib_efo`. It -does not replace the `efo` CLI, invent another persistence path, or make the -library depend on terminal rendering. The CLI remains the complete, -scriptable interface and the reference recovery surface. +`efo-tui` is a separate, read-only terminal interface over `lib_efo`. It browses +all six entity collections in HEAD, index (staged), and worktree (editable) +state. The CLI remains the complete interface for changes, history, comparison, +and recovery. No repository format changes are introduced by the browser. -## First checkpoint +## Running -The first checkpoint is deliberately read-only. It must make a repository -repository easy to understand before interactive mutations are introduced: +```bash +cargo install --locked --path tui_efo +efo-tui --repository /path/to/world +# From a repository root: +efo-tui +# Monochrome (NO_COLOR also works): +efo-tui --no-color +``` -- open the repository rooted at the current directory; -- show HEAD, staged state, worktree state, and entity totals without relying - on colour or icons; -- browse every entity collection and inspect an entity's stable UUID, - description, and serialized details; -- explain all active keys in an in-application help overlay; -- reload state from disk without restarting; and -- leave the terminal usable after normal exit, an application error, or a - panic. +The path must identify a repository root; parent-directory discovery is not +performed. Both stdin and stdout must be interactive terminals. `--help` and +`--version` also work when redirected. For scripts use `efo status` and +`efo show`. -Unsupported repository versions receive an actionable error. Repository -discovery above the current directory and mutating actions are explicitly -outside this checkpoint. +## Browsing -## Interaction contract +The header reports HEAD, staged and unstaged changes, writer-lock state, the +viewed layer, and its world summary. Start in the worktree. Press `1`, `2`, or +`3` to browse HEAD, index, or worktree. Collection counts reflect the viewed +layer. Entities sort by lowercase name, then stable UUID, and show a shortened +UUID beside their name; details include the full UUID and serialized fields. +Switch to an earlier layer to inspect an entity removed from the worktree. +Use `efo diff` or `efo diff --staged` for a complete change comparison. -The application has three focus areas: collection list, entity list, and -details. The focused area is named in text and visually emphasized. +Search applies to the current collection in every layer. It matches name and +description using Unicode lowercase matching, or any substring of the UUID +(with or without `@`). This is literal substring matching, not a query language +or accent-insensitive search. Press `/`, edit the query, and press Enter to +keep it. An empty query clears the filter; Escape restores the previous query. +While editing, ordinary character keys enter text instead of invoking commands. | Key | Action | | --- | --- | -| `Tab`, `Shift-Tab` | Move focus forward or backward | -| arrows, `h`/`j`/`k`/`l` | Navigate focus and selected rows | -| `?` | Toggle contextual help | -| `r` | Reload repository state | -| `q`, `Esc` | Close help first, then quit | +| `Tab`, `Shift-Tab`, `h`/`l`, left/right | Cycle focus: collections, entities, details | +| up/down, `j`/`k` | Select a row or scroll details/help | +| `Home`, `End` | First/last row or start/end of details/help | +| `PageUp`, `PageDown` | Move by approximately one visible page | +| `/` | Edit the search filter; Backspace removes a character | +| `Enter`, `Esc` during search | Keep filter / restore previous filter | +| `1`, `2`, `3` | View HEAD / index / worktree | +| `r` | Reload from disk, preserving selection by UUID when present | +| `?`, `!` | Open help and the last reload diagnostic | +| `?`, `!`, `q`, `Esc` in help | Close help | +| `q`, `Esc` outside help/search | Quit | +| `Ctrl-C` | Quit from any view, including help and search | -Every essential state is expressed in words. Colour may reinforce meaning but -is never the only signal. Borders and ordinary Unicode are the baseline; Nerd -Font glyphs are optional decoration, never controls or status vocabulary. -Layouts must degrade to a useful compact message in small terminals, and text -must be clipped safely rather than wrapped into neighbouring panels. +At widths of 100 columns and above, the browser shows three panels. Narrower +terminals show the focused panel at full width; Tab cycles between them. The +minimum usable size is 32×10. Smaller sizes show resize advice. Details wrap +within their panel and scrolling stops at the last page, including after a +resize. Help and diagnostics scroll independently. -## Architecture +Focus, selection, and repository state use text and reverse video as well as +optional colour. No Nerd Font is required. `--no-color` or the presence of +`NO_COLOR` disables application colours while retaining these selection cues. -```text -efo-tui input/render loop - │ - ▼ -pure application state and navigation - │ - ▼ -lib_efo::workspace::Workspace -``` +## Snapshot and failure behavior -The binary owns terminal setup, key mapping, view state, and rendering. Pure -state transitions and rendering through Ratatui's test backend are unit tested. -`lib_efo` continues to own repository validation and all future mutations. +The browser reads a snapshot on startup and refreshes only on `r`; external +changes never silently move the selection. Successful reload and layer changes +keep the selected UUID when it remains in the filtered collection, otherwise +clamp to an available row. A failed reload keeps the last loaded snapshot and +sets a visible stale-data message. Press `!` and scroll to read the full error, +including its path and recovery advice; fix the problem and retry with `r`. -A terminal guard must enter raw mode and the alternate screen only after setup -succeeds, and undo both in `Drop`. A panic hook restores the terminal before -delegating to the previous hook. No command changes the process working -directory. +Unsupported versions, corrupt data, and unfinished transactions fail startup +before raw mode is enabled. A writer lock is displayed, never broken. Use +`efo lock status`, `efo status`, or `efo recover` when appropriate. See +[recovery](recovery.md) for the CLI safety workflows. -## Later interactive mutations +## Architecture and verification -Write operations require a second design checkpoint. The first candidates are -stage/unstage, restore, and commit because Phase 4 already makes them atomic -and reversible. Before exposure, each action needs: +The binary owns argument parsing, terminal setup, key mapping, view state, and +Ratatui rendering. `lib_efo::workspace::Workspace` owns repository loading and +validation. No command changes the process working directory or writes world +state. Ratatui's rendered-line measurement bounds wrapped scrolling; its +`unstable-rendered-line-info` feature is enabled against the locked version. -- an explicit preview of the affected layer and entities; -- confirmation for discarding or history-changing operations; -- success text naming the recovery command; -- lock and interrupted-transaction guidance; and -- integration tests proving the TUI invokes the same library operation as the - CLI. +A terminal guard restores raw mode, cursor visibility, and the alternate screen +on normal exit and application errors. The panic hook restores an active +terminal before printing the panic, and does not emit terminal controls before +terminal setup. Ctrl-C takes the same guarded exit path. Forced process kills +cannot run cleanup. -Entity editing, recovery, and future pruning remain CLI-only until -their interactive failure and recovery flows are equally clear. - -## Acceptance gate - -The checkpoint is complete when `efo-tui --help` is self-documenting, startup -and repository failures are actionable, navigation and rendering have tests, -the terminal lifecycle is guarded, and the full workspace passes formatting, -tests, strict Clippy, and release builds with default and portable features. - -## Running the first checkpoint - -Install both interfaces, then start the browser from a repository or name its -path explicitly: +Tests cover search, navigation, layer/reload identity, corrupt reload recovery, +scrolling, responsive layouts, monochrome rendering, and noninteractive startup. +The release gate includes workspace formatting, tests, strict Clippy, default +and portable builds, plus a pseudo-terminal navigation/restoration smoke test. On Unix, run it with: ```bash -cargo install --locked --path bin_efo -cargo install --locked --path tui_efo -efo-tui -# or: efo-tui --repository /path/to/world +cargo build -p efo-tui --locked +python3 tui_efo/tests/terminal_smoke.py ``` -The header reports HEAD, staged and unstaged state, and any active writer lock. -The browser reloads only when `r` is pressed; it never writes or silently -refreshes underneath a selection. Use `efo status`, `efo lock status`, or -`efo recover` when its diagnostic recommends that CLI recovery path. +The smoke check uses a temporary copy of the curated example, verifies that its +files remain byte-identical, and checks terminal restoration on `q` and Ctrl-C. + +## Future interactive writes + +The current release scope is a read-only browser. Stage/unstage, restore, +commit, entity editing, recovery, and future pruning remain CLI operations. +Before adding an interactive write, provide: + +- a preview naming the affected layer and entities; +- confirmation for discarding or history-changing actions; +- success text naming the recovery command; +- lock and interrupted-transaction guidance; and +- integration tests proving use of the same library operations as the CLI. + +These are additional workflows, not implied capabilities of the browser. diff --git a/tui_efo/Cargo.toml b/tui_efo/Cargo.toml index 41f19ef..3b57b87 100644 --- a/tui_efo/Cargo.toml +++ b/tui_efo/Cargo.toml @@ -8,10 +8,10 @@ repository = "https://proxy.dandaedre.com/gitea/idle-org/epoch_forge" clap = { workspace = true } crossterm = { workspace = true } lib_efo = { path = "../lib_efo", default-features = false } -ratatui = { workspace = true } +ratatui = { workspace = true, features = ["unstable-rendered-line-info"] } serde_json = { workspace = true } thiserror = { workspace = true } +uuid = { workspace = true } [dev-dependencies] tempfile = "3.23.0" -uuid = { workspace = true } diff --git a/tui_efo/src/main.rs b/tui_efo/src/main.rs index 4db424c..a4359d0 100644 --- a/tui_efo/src/main.rs +++ b/tui_efo/src/main.rs @@ -17,9 +17,10 @@ use ratatui::{ widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}, }; use std::{ - io::{self, Stdout}, + io::{self, IsTerminal, Stdout}, path::PathBuf, process::ExitCode, + sync::atomic::{AtomicBool, Ordering}, time::Duration, }; @@ -30,9 +31,12 @@ use std::{ about = "Browse an Epoch Forge repository interactively" )] #[command( - after_long_help = "KEYS:\n Tab / Shift-Tab Move focus\n Arrows or h/j/k/l Navigate\n ? Toggle help\n r Reload repository\n q or Esc Quit\n\nThis first release is read-only. Use `efo` for mutations and recovery." + after_long_help = "KEYS:\n Tab / Shift-Tab Move focus\n Arrows or h/j/k/l Navigate\n ? Toggle help\n r Reload repository\n q or Esc Quit\n\nSearch with /; select HEAD/index/worktree with 1/2/3. Home/End and PageUp/PageDown navigate. Ctrl-C exits. This browser is read-only. Use `efo` for mutations and recovery." )] struct Args { + /// Disable colours (also respects NO_COLOR). + #[arg(long)] + no_color: bool, /// Repository directory to browse. #[arg(short, long, default_value = ".", value_name = "PATH")] repository: PathBuf, @@ -112,16 +116,44 @@ impl Collection { } } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Layer { + Head, + Index, + #[default] + Worktree, +} +impl Layer { + fn name(self) -> &'static str { + match self { + Self::Head => "HEAD", + Self::Index => "index", + Self::Worktree => "worktree", + } + } +} + struct App { repository: PathBuf, workspace: Workspace, focus: Focus, collection: usize, entity: usize, + entity_list: ListState, + collection_list: ListState, details_offset: u16, help: bool, + help_offset: u16, + help_max: u16, message: String, writer: String, + layer: Layer, + query: String, + search: Option, + diagnostic: Option, + no_color: bool, + details_max: u16, + page_size: u16, } impl App { fn open(repository: PathBuf) -> Result { @@ -136,30 +168,81 @@ impl App { focus: Focus::Collections, collection: 0, entity: 0, + entity_list: ListState::default(), + collection_list: ListState::default(), details_offset: 0, help: false, + help_offset: 0, + help_max: 0, message: "Read-only mode · press ? for help".into(), writer, + layer: Layer::Worktree, + query: String::new(), + search: None, + diagnostic: None, + no_color: false, + details_max: 0, + page_size: 10, }) } fn world(&self) -> &EpochInfo { - &self.workspace.worktree.world + match self.layer { + Layer::Head => &self.workspace.head, + Layer::Index => &self.workspace.index.world, + Layer::Worktree => &self.workspace.worktree.world, + } } - fn entities(&self) -> &[Entity] { - Collection::ALL[self.collection].entities(self.world()) + fn entities(&self) -> Vec<&Entity> { + let query = self.query.to_lowercase(); + let mut entities: Vec<_> = Collection::ALL[self.collection] + .entities(self.world()) + .iter() + .filter(|entity| { + query.is_empty() + || entity.name.to_lowercase().contains(&query) + || entity.description.to_lowercase().contains(&query) + || format!("@{}", entity.id).contains(&query) + }) + .collect(); + entities.sort_by_cached_key(|entity| (entity.name.to_lowercase(), entity.id)); + entities } fn selected_entity(&self) -> Option<&Entity> { - self.entities().get(self.entity) + self.entities().get(self.entity).copied() + } + fn select_id(&mut self, id: Option) { + if let Some(index) = self + .entities() + .iter() + .position(|entity| Some(entity.id) == id) + { + self.entity = index; + } + self.clamp_entity(); + } + fn set_layer(&mut self, layer: Layer) { + let id = self.selected_entity().map(|entity| entity.id); + self.layer = layer; + self.select_id(id); } fn reload(&mut self) { + let id = self.selected_entity().map(|entity| entity.id); match Workspace::open(&self.repository) { Ok(workspace) => { self.writer = writer_status(workspace.root()); self.workspace = workspace; - self.clamp_entity(); + self.select_id(id); + self.diagnostic = None; self.message = "Repository reloaded from disk".into(); } - Err(error) => self.message = format!("Reload failed: {error}"), + Err(error) => { + self.message = + "Reload failed; showing the last loaded snapshot. Press ! for details.".into(); + self.diagnostic = Some(format!( + "Could not reload {}:\n{error}\n\nThe last loaded snapshot is still displayed. Fix the problem, then press r to retry.", + self.repository.display() + )); + } } } fn clamp_entity(&mut self) { @@ -187,7 +270,7 @@ impl App { } Focus::Details => { self.details_offset = if down { - self.details_offset.saturating_add(1) + self.details_offset.saturating_add(1).min(self.details_max) } else { self.details_offset.saturating_sub(1) } @@ -195,18 +278,104 @@ impl App { } } fn handle_key(&mut self, key: KeyEvent) -> bool { + if key.kind == KeyEventKind::Release { + return false; + } + if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') { + return true; + } + if let Some(previous) = self.search.clone() { + match key.code { + KeyCode::Enter => self.search = None, + KeyCode::Esc => { + self.query = previous; + self.search = None; + } + KeyCode::Backspace => { + self.query.pop(); + } + KeyCode::Char(c) + if !key + .modifiers + .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) => + { + self.query.push(c) + } + _ => {} + } + self.entity = 0; + self.details_offset = 0; + return false; + } if self.help { - if matches!( - key.code, - KeyCode::Char('?') | KeyCode::Esc | KeyCode::Char('q') - ) { - self.help = false; + match key.code { + KeyCode::Char('?') | KeyCode::Char('!') | KeyCode::Esc | KeyCode::Char('q') => { + self.help = false; + self.help_offset = 0; + } + KeyCode::Down | KeyCode::Char('j') => { + self.help_offset = self.help_offset.saturating_add(1).min(self.help_max) + } + KeyCode::Up | KeyCode::Char('k') => { + self.help_offset = self.help_offset.saturating_sub(1) + } + KeyCode::PageDown => { + self.help_offset = self + .help_offset + .saturating_add(self.page_size) + .min(self.help_max) + } + KeyCode::PageUp => { + self.help_offset = self.help_offset.saturating_sub(self.page_size) + } + KeyCode::Home => self.help_offset = 0, + KeyCode::End => self.help_offset = self.help_max, + _ => {} } return false; } match key.code { KeyCode::Char('q') | KeyCode::Esc => return true, KeyCode::Char('?') => self.help = true, + KeyCode::Char('!') => { + self.help = true; + } + KeyCode::Char('/') => { + self.search = Some(self.query.clone()); + self.focus = Focus::Entities; + } + KeyCode::Char('1') => self.set_layer(Layer::Head), + KeyCode::Char('2') => self.set_layer(Layer::Index), + KeyCode::Char('3') => self.set_layer(Layer::Worktree), + KeyCode::Home => match self.focus { + Focus::Collections => { + self.collection = 0; + self.entity = 0; + self.details_offset = 0; + } + Focus::Entities => { + self.entity = 0; + self.details_offset = 0; + } + Focus::Details => self.details_offset = 0, + }, + KeyCode::End => match self.focus { + Focus::Collections => { + self.collection = Collection::ALL.len() - 1; + self.entity = 0; + self.details_offset = 0; + } + Focus::Entities => { + self.entity = self.entities().len().saturating_sub(1); + self.details_offset = 0; + } + Focus::Details => self.details_offset = self.details_max, + }, + KeyCode::PageDown | KeyCode::PageUp => { + for _ in 0..self.page_size { + self.move_selection(key.code == KeyCode::PageDown); + } + } KeyCode::Char('r') => self.reload(), KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => { self.focus = self.focus.previous() @@ -222,15 +391,23 @@ impl App { } } +static TERMINAL_ACTIVE: AtomicBool = AtomicBool::new(false); + struct TerminalGuard { terminal: Terminal>, } impl TerminalGuard { fn enter() -> io::Result { + if !io::stdin().is_terminal() || !io::stdout().is_terminal() { + return Err(io::Error::other( + "stdin and stdout must be interactive terminals; use `efo status` for redirected output", + )); + } enable_raw_mode()?; + TERMINAL_ACTIVE.store(true, Ordering::SeqCst); let mut stdout = io::stdout(); if let Err(error) = execute!(stdout, EnterAlternateScreen) { - let _ = disable_raw_mode(); + Self::restore(); return Err(error); } match Terminal::new(CrosstermBackend::new(stdout)) { @@ -242,14 +419,15 @@ impl TerminalGuard { } } fn restore() { - let _ = disable_raw_mode(); - let _ = execute!(io::stdout(), LeaveAlternateScreen); + if TERMINAL_ACTIVE.swap(false, Ordering::SeqCst) { + let _ = disable_raw_mode(); + let _ = execute!(io::stdout(), crossterm::cursor::Show, LeaveAlternateScreen); + } } } impl Drop for TerminalGuard { fn drop(&mut self) { Self::restore(); - let _ = self.terminal.show_cursor(); } } @@ -261,8 +439,7 @@ fn main() -> ExitCode { Err(error) => { eprintln!("error: {error}"); match &error { - AppError::Repository { source, .. } => { - eprintln!("help: {source}"); + AppError::Repository { .. } => { eprintln!("help: run `efo status` for the scriptable repository view"); } AppError::Terminal(_) => { @@ -282,12 +459,13 @@ fn install_panic_hook() { } fn run(args: Args) -> Result<(), AppError> { let mut app = App::open(args.repository)?; + app.no_color = args.no_color || std::env::var_os("NO_COLOR").is_some(); let mut terminal = TerminalGuard::enter()?; loop { - terminal.terminal.draw(|frame| render(frame, &app))?; + terminal.terminal.draw(|frame| render(frame, &mut app))?; if event::poll(Duration::from_millis(250))? && let Event::Key(key) = event::read()? - && key.kind == KeyEventKind::Press + && key.kind != KeyEventKind::Release && app.handle_key(key) { break; @@ -296,10 +474,10 @@ fn run(args: Args) -> Result<(), AppError> { Ok(()) } -fn render(frame: &mut Frame<'_>, app: &App) { +fn render(frame: &mut Frame<'_>, app: &mut App) { let area = frame.area(); - if area.width < 54 || area.height < 14 { - frame.render_widget(Paragraph::new(format!("Epoch Forge needs at least 54×14 cells.\nCurrent terminal: {}×{}\n\nPress q to quit.", area.width, area.height)).block(Block::bordered().title(" Terminal too small ")).wrap(Wrap { trim: true }), area); + if area.width < 32 || area.height < 10 { + frame.render_widget(Paragraph::new(format!("Epoch Forge needs at least 32×10 cells.\nCurrent terminal: {}×{}\n\nPress q to quit.", area.width, area.height)).block(Block::bordered().title(" Terminal too small ")).wrap(Wrap { trim: true }), area); return; } let rows = Layout::default() @@ -311,29 +489,42 @@ fn render(frame: &mut Frame<'_>, app: &App) { ]) .split(area); render_status(frame, app, rows[0]); - let columns = Layout::default() - .direction(Direction::Horizontal) - .constraints([ - Constraint::Percentage(25), - Constraint::Percentage(30), - Constraint::Percentage(45), - ]) - .split(rows[1]); - render_collections(frame, app, columns[0]); - render_entities(frame, app, columns[1]); - render_details(frame, app, columns[2]); + app.page_size = rows[1].height.saturating_sub(2).max(1); + if area.width < 100 { + match app.focus { + Focus::Collections => render_collections(frame, app, rows[1]), + Focus::Entities => render_entities(frame, app, rows[1]), + Focus::Details => render_details(frame, app, rows[1]), + } + } else { + let columns = Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Percentage(25), + Constraint::Percentage(30), + Constraint::Percentage(45), + ]) + .split(rows[1]); + render_collections(frame, app, columns[0]); + render_entities(frame, app, columns[1]); + render_details(frame, app, columns[2]); + } frame.render_widget( - Paragraph::new(format!(" {}", app.message)).style(Style::default().fg(Color::DarkGray)), + Paragraph::new(if app.search.is_some() { + format!(" /{}▏ Enter apply · Esc cancel", app.query) + } else { + format!(" {}\n Tab focus · / search · 1 HEAD 2 index 3 worktree · r reload · ? help · q quit", app.message) + }), rows[2], ); if app.help { - render_help(frame, area); + render_help(frame, app, area); } } -fn panel(title: &str, focused: bool) -> Block<'_> { +fn panel(title: &str, focused: bool, no_color: bool) -> Block<'_> { let style = if focused { Style::default() - .fg(Color::Cyan) + .fg(if no_color { Color::Reset } else { Color::Cyan }) .add_modifier(Modifier::BOLD) } else { Style::default() @@ -358,79 +549,134 @@ fn render_status(frame: &mut Frame<'_>, app: &App, area: Rect) { "clean" }; let text = format!( - "HEAD epoch {} · staged: {staged} · worktree: {worktree} · {}\nSummary: {}", + "HEAD epoch {} · staged: {staged} · worktree: {worktree} · {}\nViewing {} · {}", app.workspace.manifest.epoch_id, app.writer, + app.layer.name(), value_or_dash(&app.world().summary) ); frame.render_widget( - Paragraph::new(text).block(Block::bordered().title(" Epoch Forge · read-only browser ")), + Paragraph::new(text).block(Block::bordered().title(format!( + " Epoch Forge · read-only · {} ", + app.workspace.root().display() + ))), area, ); } -fn render_collections(frame: &mut Frame<'_>, app: &App, area: Rect) { - let items = Collection::ALL +fn render_collections(frame: &mut Frame<'_>, app: &mut App, area: Rect) { + let items: Vec<_> = Collection::ALL .iter() - .map(|c| ListItem::new(format!("{} ({})", c.name(), c.entities(app.world()).len()))); - let mut state = ListState::default().with_selected(Some(app.collection)); + .map(|c| ListItem::new(format!("{} ({})", c.name(), c.entities(app.world()).len()))) + .collect(); + app.collection_list.select(Some(app.collection)); frame.render_stateful_widget( List::new(items) - .block(panel("Collections", app.focus == Focus::Collections)) + .block(panel( + "Collections", + app.focus == Focus::Collections, + app.no_color, + )) .highlight_symbol("› ") .highlight_style(Style::default().add_modifier(Modifier::REVERSED)), area, - &mut state, + &mut app.collection_list, ); } -fn render_entities(frame: &mut Frame<'_>, app: &App, area: Rect) { +fn render_entities(frame: &mut Frame<'_>, app: &mut App, area: Rect) { let entities = app.entities(); let items: Vec> = if entities.is_empty() { - vec![ListItem::new("No entities")] + vec![ListItem::new(if app.query.is_empty() { + "No entities" + } else { + "No matches · / to change search" + })] } else { entities .iter() - .map(|e| ListItem::new(e.name.as_str())) + .map(|e| ListItem::new(format!("{} @{}", e.name, &e.id.to_string()[..8]))) .collect() }; - let mut state = - ListState::default().with_selected((!entities.is_empty()).then_some(app.entity)); + let title = format!( + "Entities {}/{} · {}", + if entities.is_empty() { + 0 + } else { + app.entity + 1 + }, + entities.len(), + app.query + ); + let selected = (!entities.is_empty()).then_some(app.entity); + app.entity_list.select(selected); frame.render_stateful_widget( List::new(items) - .block(panel("Entities", app.focus == Focus::Entities)) + .block(panel(&title, app.focus == Focus::Entities, app.no_color)) .highlight_symbol("› ") .highlight_style(Style::default().add_modifier(Modifier::REVERSED)), area, - &mut state, + &mut app.entity_list, ); } -fn render_details(frame: &mut Frame<'_>, app: &App, area: Rect) { +fn render_details(frame: &mut Frame<'_>, app: &mut App, area: Rect) { let text = app.selected_entity().map_or_else( || Text::from("No entity selected."), |entity| { let json = serde_json::to_string_pretty(entity) .unwrap_or_else(|error| format!("Could not display details: {error}")); - Text::from(vec![ + let mut lines = vec![ Line::from(entity.name.clone()).bold(), Line::from(format!("@{}", entity.id)), - Line::from(value_or_dash(&entity.description).to_owned()), - Line::from(""), - Line::from(json), - ]) + ]; + lines.extend( + entity + .description + .lines() + .map(|line| Line::from(line.to_owned())), + ); + lines.push(Line::from("")); + lines.extend(json.lines().map(|line| Line::from(line.to_owned()))); + Text::from(lines) }, ); + let paragraph = Paragraph::new(text).wrap(Wrap { trim: false }); + app.details_max = paragraph + .line_count(area.width.saturating_sub(2)) + .saturating_sub(usize::from(area.height.saturating_sub(2))) + .min(usize::from(u16::MAX)) as u16; + app.details_offset = app.details_offset.min(app.details_max); + let title = format!( + "Details · line {}/{}", + u32::from(app.details_offset) + 1, + u32::from(app.details_max) + 1 + ); frame.render_widget( - Paragraph::new(text) - .block(panel("Details", app.focus == Focus::Details)) - .scroll((app.details_offset, 0)) - .wrap(Wrap { trim: false }), + paragraph + .block(panel(&title, app.focus == Focus::Details, app.no_color)) + .scroll((app.details_offset, 0)), area, ); } -fn render_help(frame: &mut Frame<'_>, area: Rect) { - let popup = centered_rect(62, 14, area); +fn render_help(frame: &mut Frame<'_>, app: &mut App, area: Rect) { + let popup = centered_rect(88, area.height, area); frame.render_widget(Clear, popup); - frame.render_widget(Paragraph::new("Tab / Shift-Tab Move focus\narrows, h/j/k/l Navigate\nr Reload from disk\n? Close this help\nq, Esc Close help; then quit\n\nThis checkpoint is read-only. Use efo for changes,\nrecovery, and other repository operations.").block(Block::bordered().title(" Help ")).wrap(Wrap { trim: true }), popup); + let text = format!( + "Tab / Shift-Tab, h/l Move focus\nUp/Down, j/k Navigate or scroll details\nHome/End, PgUp/PgDn Jump or page in focused panel\n/ Search name, description, UUID\nEnter / Esc Apply / cancel search (empty clears)\n1 / 2 / 3 Browse HEAD / index / worktree\nr Reload, preserving selected UUID\n? or ! Help and last reload diagnostic\nq, Esc Close help; then quit\nCtrl-C Quit from any view\n\nRead-only. Use efo diff / diff --staged to compare layers.\nUse efo for changes and recovery.\n\n{}", + app.diagnostic.as_deref().unwrap_or("No reload errors.") + ); + let paragraph = Paragraph::new(text).wrap(Wrap { trim: true }); + app.help_max = paragraph + .line_count(popup.width.saturating_sub(2)) + .saturating_sub(usize::from(popup.height.saturating_sub(2))) + .min(usize::from(u16::MAX)) as u16; + app.help_offset = app.help_offset.min(app.help_max); + frame.render_widget( + paragraph + .block(Block::bordered().title(" Help · ↑↓ scroll · Esc close ")) + .scroll((app.help_offset, 0)), + popup, + ); } + fn centered_rect(width: u16, height: u16, area: Rect) -> Rect { let width = width.min(area.width); let height = height.min(area.height); @@ -513,9 +759,9 @@ mod tests { } #[test] fn empty_repository_render_has_semantic_labels() { - let mut terminal = Terminal::new(TestBackend::new(80, 20)).expect("test terminal"); - let (_temp, app) = app(); - terminal.draw(|f| render(f, &app)).expect("draw"); + let mut terminal = Terminal::new(TestBackend::new(120, 24)).expect("test terminal"); + let (_temp, mut app) = app(); + terminal.draw(|f| render(f, &mut app)).expect("draw"); let text = terminal.backend().to_string(); assert!(text.contains("HEAD epoch 0")); assert!(text.contains("staged: clean")); @@ -524,12 +770,159 @@ mod tests { } #[test] fn compact_terminal_explains_minimum_size() { - let mut terminal = Terminal::new(TestBackend::new(40, 10)).expect("test terminal"); - let (_temp, app) = app(); - terminal.draw(|f| render(f, &app)).expect("draw"); + let mut terminal = Terminal::new(TestBackend::new(30, 9)).expect("test terminal"); + let (_temp, mut app) = app(); + terminal.draw(|f| render(f, &mut app)).expect("draw"); let text = terminal.backend().to_string(); assert!(text.contains("needs at least")); - assert!(text.contains("54×14")); + assert!(text.contains("32×10")); assert!(text.contains("Press q to quit")); } + fn key(app: &mut App, code: KeyCode) -> bool { + app.handle_key(KeyEvent::new(code, KeyModifiers::NONE)) + } + fn entity(name: &str, id: u128) -> Entity { + let mut entity = Entity::default(); + entity.name = name.into(); + entity.entity_type = lib_efo::stats::EntityType::Character; + entity.id = Uuid::from_u128(id); + entity.description = "A traveller from Draän".into(); + entity + } + #[test] + fn search_is_unicode_aware_and_modal_and_can_be_cancelled() { + let (_temp, mut app) = app(); + app.workspace.worktree.world.characters = vec![entity("Zoe", 1), entity("Aria", 2)]; + assert_eq!(app.entities()[0].name, "Aria"); + key(&mut app, KeyCode::Char('/')); + for c in "DRAÄN".chars() { + assert!(!key(&mut app, KeyCode::Char(c))); + } + assert_eq!(app.entities().len(), 2); + key(&mut app, KeyCode::Enter); + key(&mut app, KeyCode::Char('/')); + key(&mut app, KeyCode::Char('q')); + assert!(app.entities().is_empty()); + key(&mut app, KeyCode::Esc); + assert_eq!(app.query, "DRAÄN"); + app.query = format!("@{}", Uuid::from_u128(2)); + assert_eq!(app.selected_entity().expect("UUID match").name, "Aria"); + } + #[test] + fn layers_and_reload_preserve_identity_and_failed_reload_keeps_snapshot() { + let (temp, mut app) = app(); + app.workspace.worktree.world.characters = vec![entity("Aria", 1), entity("Zoe", 2)]; + app.workspace.save_worktree("test").expect("save"); + app.workspace.stage_all().expect("stage"); + app.entity = 1; + key(&mut app, KeyCode::Char('2')); + assert_eq!( + app.selected_entity().expect("selection").id, + Uuid::from_u128(2) + ); + key(&mut app, KeyCode::Char('3')); + let mut external = Workspace::open(temp.path()).expect("open"); + external.worktree.world.characters[1].name = "Aaron".into(); + external.save_worktree("test").expect("save"); + app.reload(); + assert_eq!(app.entity, 0); + assert_eq!(app.selected_entity().expect("selection").name, "Aaron"); + fs::write(temp.path().join(".efo/worktree.json"), "broken").expect("corrupt"); + app.reload(); + assert!( + app.diagnostic + .as_deref() + .expect("diagnostic") + .contains("worktree.json") + ); + assert_eq!(app.selected_entity().expect("old snapshot").name, "Aaron"); + external.save_worktree("test").expect("repair"); + app.reload(); + assert!(app.diagnostic.is_none()); + key(&mut app, KeyCode::Char('1')); + assert!(app.selected_entity().is_none()); + } + #[test] + fn details_and_help_scroll_to_end_without_blank_overscroll() { + let (_temp, mut app) = app(); + app.workspace.worktree.world.characters = vec![entity("Aria", 1)]; + app.focus = Focus::Details; + let mut terminal = Terminal::new(TestBackend::new(60, 16)).expect("terminal"); + terminal.draw(|f| render(f, &mut app)).expect("draw"); + assert!(app.details_max > 0); + assert!(terminal.backend().to_string().contains("traveller")); + key(&mut app, KeyCode::End); + key(&mut app, KeyCode::Down); + assert_eq!(app.details_offset, app.details_max); + terminal.draw(|f| render(f, &mut app)).expect("draw"); + assert!(terminal.backend().to_string().contains('}')); + app.diagnostic = Some("Distinct final diagnostic".into()); + key(&mut app, KeyCode::Char('!')); + terminal.draw(|f| render(f, &mut app)).expect("draw"); + key(&mut app, KeyCode::End); + terminal.draw(|f| render(f, &mut app)).expect("draw"); + assert!( + terminal + .backend() + .to_string() + .contains("Distinct final diagnostic") + ); + } + #[test] + fn layouts_render_all_sizes_and_no_color_keeps_semantics() { + let (_temp, mut app) = app(); + app.no_color = true; + for (width, height) in [(1, 1), (32, 10), (60, 16), (100, 24), (160, 40)] { + for focus in [Focus::Collections, Focus::Entities, Focus::Details] { + app.focus = focus; + let mut terminal = + Terminal::new(TestBackend::new(width, height)).expect("terminal"); + terminal.draw(|f| render(f, &mut app)).expect("draw"); + for cell in terminal.backend().buffer().content() { + assert_eq!(cell.fg, Color::Reset); + assert_eq!(cell.bg, Color::Reset); + } + } + } + } + #[test] + fn paging_and_ctrl_c_work_and_release_events_are_ignored() { + let (_temp, mut app) = app(); + app.workspace.worktree.world.characters = (0..30) + .map(|i| entity(&format!("Person {i:02}"), i)) + .collect(); + app.focus = Focus::Entities; + key(&mut app, KeyCode::PageDown); + assert_eq!(app.entity, 10); + key(&mut app, KeyCode::End); + assert_eq!(app.entity, 29); + key(&mut app, KeyCode::Home); + assert_eq!(app.entity, 0); + assert!(!app.handle_key(KeyEvent::new_with_kind( + KeyCode::Char('q'), + KeyModifiers::NONE, + KeyEventKind::Release + ))); + for modal in ["help", "search"] { + app.help = modal == "help"; + app.search = (modal == "search").then(String::new); + assert!(app.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL))); + } + } + #[test] + fn scrolling_up_keeps_the_visible_list_window() { + let (_temp, mut app) = app(); + app.workspace.worktree.world.characters = (0..30) + .map(|i| entity(&format!("Person {i:02}"), i)) + .collect(); + app.focus = Focus::Entities; + app.entity = 20; + let mut terminal = Terminal::new(TestBackend::new(60, 16)).expect("terminal"); + terminal.draw(|f| render(f, &mut app)).expect("draw"); + let offset = app.entity_list.offset(); + assert!(offset > 0); + key(&mut app, KeyCode::Up); + terminal.draw(|f| render(f, &mut app)).expect("draw"); + assert_eq!(app.entity_list.offset(), offset); + } } diff --git a/tui_efo/tests/startup.rs b/tui_efo/tests/startup.rs new file mode 100644 index 0000000..041db75 --- /dev/null +++ b/tui_efo/tests/startup.rs @@ -0,0 +1,56 @@ +//! Startup contracts that must hold before entering terminal raw mode. +use std::process::{Command, Output}; + +fn run(args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_efo-tui")) + .args(args) + .output() + .expect("run efo-tui") +} + +#[test] +fn help_and_version_work_without_a_terminal() { + let help = run(&["--help"]); + assert!(help.status.success()); + let text = String::from_utf8_lossy(&help.stdout); + assert!(text.contains("--repository ")); + assert!(text.contains("--no-color")); + assert!(text.contains("read-only")); + assert!(text.contains("HEAD/index/worktree")); + assert!(run(&["--version"]).status.success()); +} + +#[test] +fn repository_failure_is_actionable_and_emits_no_terminal_controls() { + let temp = tempfile::tempdir().expect("tempdir"); + let output = run(&["--repository", temp.path().to_str().expect("path")]); + assert!(!output.status.success()); + let error = String::from_utf8_lossy(&output.stderr); + assert!(error.contains("could not open")); + assert!(error.contains("efo status")); + assert!(error.contains(temp.path().to_str().expect("path"))); + assert!(output.stdout.is_empty()); + assert!(!output.stderr.contains(&0x1b)); +} + +#[test] +fn redirected_startup_fails_cleanly_without_writing_repository() { + let temp = tempfile::tempdir().expect("tempdir"); + let workspace = lib_efo::workspace::Workspace::initialize(temp.path(), "test").expect("init"); + let manifest = std::fs::read(temp.path().join(".epoch")).expect("manifest"); + let worktree = std::fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"); + let output = run(&["--repository", workspace.root().to_str().expect("path")]); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("interactive terminal")); + assert!(output.stdout.is_empty()); + assert!(!output.stderr.contains(&0x1b)); + assert_eq!( + std::fs::read(temp.path().join(".epoch")).expect("manifest"), + manifest + ); + assert_eq!( + std::fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"), + worktree + ); + assert!(!temp.path().join(".efo/lock").exists()); +} diff --git a/tui_efo/tests/terminal_smoke.py b/tui_efo/tests/terminal_smoke.py new file mode 100644 index 0000000..abf8153 --- /dev/null +++ b/tui_efo/tests/terminal_smoke.py @@ -0,0 +1,49 @@ +"""Unix PTY release smoke check. Run from the repository root after cargo build. + +Uses only Python's standard library and a temporary copy of the example world. +""" +import fcntl, hashlib, os, pathlib, pty, select, shutil, struct, subprocess, tempfile, termios, time +binary = str(pathlib.Path('target/debug/efo-tui').resolve()) + +def snapshot(root): + return {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in root.rglob('*') if p.is_file()} + +with tempfile.TemporaryDirectory() as directory: + root = pathlib.Path(directory) / 'world' + shutil.copytree('examples/ravenous-draan', root) + before = snapshot(root) + for exit_keys in [b'q', b'\x03']: + master, slave = pty.openpty() + fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 28, 120, 0, 0)) + original = termios.tcgetattr(slave) + process = subprocess.Popen([binary, '--repository', str(root), '--no-color'], stdin=slave, stdout=slave, stderr=slave) + output = bytearray() + def drain(duration): + deadline = time.monotonic() + duration + while time.monotonic() < deadline: + if select.select([master], [], [], 0.02)[0]: + chunk = os.read(master, 65536) + output.extend(chunk) + if b'\x1b[6n' in chunk: + os.write(master, b'\x1b[1;1R') + try: + drain(0.3) + for keys in [b'\t', b'/dra', b'\r', b'2', b'3', b'\t', b'\x1b[F', b'?', b'\x1b[F', b'?', b'r']: + os.write(master, keys) + drain(0.06) + fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 16, 60, 0, 0)) + os.write(master, b'\t') + drain(0.1) + os.write(master, exit_keys) + drain(0.2) + assert process.wait(timeout=3) == 0, bytes(output[-2000:]) + assert termios.tcgetattr(slave) == original, 'terminal attributes were not restored' + assert b'\x1b[?1049h' in output and b'\x1b[?1049l' in output, 'alternate screen lifecycle missing' + assert snapshot(root) == before, 'repository was modified' + print(f'PTY smoke passed: exit={exit_keys!r}, navigation/search/layers/help/resize, terminal restored, repository unchanged') + finally: + if process.poll() is None: + process.kill() + process.wait() + os.close(master) + os.close(slave)