diff --git a/AGENTS-TASKS.md b/AGENTS-TASKS.md index 08d5ea1..9cc08f2 100644 --- a/AGENTS-TASKS.md +++ b/AGENTS-TASKS.md @@ -214,7 +214,8 @@ tests open it as a real repository and validate its map and world invariants. These require user approval and are not part of the current implementation: -- [ ] Previewed, confirmed TUI mutations over the exact same library operations. +- [x] Previewed TUI entity creation/editing and one-step undo through library + transactions (authorized in the entity-authoring request below). - [ ] Branching timelines with named branches and merge/conflict workflows. - [ ] Shell completions and man pages generated from the Clap command model. - [ ] JSON/JSONL output modes and stable query/filter expressions for scripts. @@ -292,3 +293,23 @@ These require user approval and are not part of the current implementation: visible without changing domain types or persistence. - Validation: 112 all-feature tests and 108 portable tests, formatting, strict Clippy, both release builds, and the PTY smoke check passed. + +## TUI entity authoring + +- [x] Add forms for all six entity collections, validation, save previews, and draft cancellation. +- [x] Save only the worktree through library transactions with locked stale-state checks. +- [x] Add previewed one-step undo preserving the exact prior entity, including unstaged edits. +- [x] Cover creation/edit/undo, lock/conflict/failure paths, modal input and terminal workflows. +- [x] Update browser-only scope and help; pass quality gates and commit. +- Decision: this request authorizes TUI entity writes. HEAD/index remain read-only; + staging, commits, relationship editing, and general deletion remain CLI operations. +- Save checks hold the writer lock from fresh-state validation through the + journalled worktree write. Undo retains its own save-time snapshot so reload + cannot accidentally permit overwriting later edits. Entity order is preserved. +- Forms edit name, description, exact position, duration, effect, bounds, and + absolute statistics; relationship metadata and UUID/type remain intact. +- Undo is one step and session-local. Commit valuable work for durable recovery; + an index restore is intentionally documented as discarding all unstaged edits. +- Validation: 120 all-feature tests, 116 portable tests, formatting, strict + Clippy, default/portable release builds, and Unix PTY create/edit/preview/undo/ + discard/multiline-paste/terminal-restoration checks passed. diff --git a/README.md b/README.md index c15b454..3e7f11f 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,9 @@ 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 searches entities across HEAD, staged, and working state. Custom fields and TUI write -workflows remain planned. There is no GUI or web interface. +TUI searches entities across HEAD, staged, and working state, and offers +previewed entity creation/editing with one-step undo. Custom fields and TUI +staging/commit workflows remain planned. There is no GUI or web interface. > Epoch Forge is not yet suitable as the only copy of important campaign data. > Keep the repository in Git or make a directory backup before destructive @@ -74,14 +75,16 @@ Run `efo --help`, `efo --help`, or see the | Timeline | Commit, advance, switch, log, tag, summarise, diff, restore, revert, and backed-up future pruning | Branching and merging | | Entities | Add, edit, list, inspect, diff, and delete six built-in types | Custom types and custom fields; bulk operations | | Generation | Generate names and deterministic seeded events, settlements, regions, or worlds from embedded/override configuration | Roads, diffusion, and setting template packs | -| Interfaces | Complete CLI; read-only `efo-tui` repository browser | TUI write workflows; GUI/web (out of scope) | +| Interfaces | Complete CLI; `efo-tui` browser and entity editor | TUI staging/commits; GUI/web (out of scope) | `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 (or use `--repository PATH`). Press `/` to search, `1`/`2`/`3` to browse HEAD/index/worktree, and `v` to toggle formatted -details and raw JSON. Narrow terminals show one +details and raw JSON. Use `a` to add to the current collection, `e` to edit, +`Ctrl-S` to preview, and `y` to save to the worktree. Press `u` to preview undo +of the last TUI save. 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. diff --git a/docs/architecture.md b/docs/architecture.md index 1f8f309..901dcfe 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -27,8 +27,10 @@ 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 [TUI browser contract](tui-design.md) adds a separate read-only -repository browser without creating another persistence path. +The [TUI contract](tui-design.md) covers browsing and previewed entity editing. +`EntityDraft` validates forms in the library; `Workspace::apply_entity_change` +checks the editor snapshot and writes the worktree under one transaction lock. +The TUI retains the prior entity for one-step, conflict-checked undo. Library tests cover parsing, statistics, display snapshots, entity/epoch behavior, and repository transactions. CLI behavior is covered by subprocess diff --git a/docs/roadmap.md b/docs/roadmap.md index 1d82b39..b838264 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -31,9 +31,10 @@ Organisation-agnostic custom fields and types follow, with unknown-field retention designed before that format change. 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. +layouts, and guarded terminal handling. Its entity editor supports previewed +worktree creation/edits and conflict-checked one-step undo through the library. +Interactive staging, commits, relationships, and general deletion remain later +workflows. The next implementation track is the [simulation and world-generation design](simulation-worldgen-design.md). Its first checkpoint is deterministic, @@ -44,7 +45,7 @@ rendering build on that validated foundation. 1. Shell completions and generated man pages. 2. Stable JSON/JSONL output and query/filter expressions. -3. Extend the first read-only TUI with previewed, recoverable write workflows. +3. Extend the TUI entity editor with previewed staging and commit workflows. 4. Named timeline branches with merge/conflict handling. 5. Setting templates for empires, companies, guilds, and nations. 6. Validation/simulation hooks before committing an epoch. diff --git a/docs/tui-design.md b/docs/tui-design.md index b1ee755..f8b8af6 100644 --- a/docs/tui-design.md +++ b/docs/tui-design.md @@ -1,9 +1,10 @@ -# TUI browser and release contract +# TUI browser, editor, and release contract -`efo-tui` is a separate, read-only terminal interface over `lib_efo`. It browses +`efo-tui` is a separate 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. +state and creates/edits entities in the worktree with explicit save previews. +The CLI remains the complete interface for staging, commits, history, +relationships, comparison, and recovery. No repository format changes are introduced by the browser. ## Running @@ -54,11 +55,13 @@ While editing, ordinary character keys enter text instead of invoking commands. | `Enter`, `Esc` during search | Keep filter / restore previous filter | | `1`, `2`, `3` | View HEAD / index / worktree | | `v` | Toggle formatted / raw JSON details | +| `a`, `e` | Add to the current collection / edit the selected entity (worktree only) | +| `u` | Preview undo of the last TUI save in this session | | `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 | +| `Ctrl-C` | Quit the browser/help/search; cancel a form or undo confirmation | 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 @@ -88,8 +91,11 @@ before raw mode is enabled. A writer lock is displayed, never broken. Use 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 +validation and entity-draft parsing. No command changes the process working +directory. `Workspace::apply_entity_change` holds the writer lock across a fresh +read, comparison of manifest/index/worktree with the editor snapshot, validation, +and the existing journalled write operation. It writes only the worktree and +updates the browser snapshot only after success. Ratatui's rendered-line measurement bounds wrapped scrolling; its `unstable-rendered-line-info` feature is enabled against the locked version. A terminal guard restores raw mode, cursor visibility, and the alternate screen @@ -108,19 +114,76 @@ cargo build -p efo-tui --locked python3 tui_efo/tests/terminal_smoke.py ``` -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. +The smoke check uses a temporary copy of the curated example. It verifies +read-only browsing, creation, multiline paste, save previews, editing, draft +cancellation, exact entity undo, unchanged HEAD/index, and terminal restoration +on `q` and Ctrl-C. -## Future interactive writes +## Creating and editing entities -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: +Select the collection (characters, towns, events, calamities, organisations, or +blockers), press `3` for the worktree, and press `a` to add. To edit, select an +entity and press `e`. HEAD and index browsing stays read-only: switch to the +worktree explicitly before opening a form. -- 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. +The form has seven fields: name, multiline description, exact position, duration, +effect mode, bounds, and absolute statistics. Wide terminals show a field list; +narrow terminals show the active field. Newly created entities have zero stats, +a new stable UUID, and type-specific duration/effect/bounds defaults (events +start with one turn and `todo` effects). UUID, type, and existing relationships +are preserved while editing; use the CLI for relationship changes. -These are additional workflows, not implied capabilities of the browser. +| Form key | Action | +| --- | --- | +| `Tab` / `Shift-Tab`, up/down | Next / previous field | +| left/right, `Home` / `End` | Move the text cursor | +| Backspace / Delete | Remove the previous / next character | +| `Ctrl-U` | Clear the active field | +| Enter | New line in description; next field elsewhere | +| Paste | Insert text; multiline descriptions supported | +| `Ctrl-S` | Validate and preview the exact worktree change | +| `y` in preview | Save the previewed change | +| `n` / `Esc` in preview | Return to the draft | +| `Esc` / `Ctrl-C` in form | Cancel; changed drafts require `y` to discard | + +Names must be non-empty and unique (case-insensitively) within their collection. +Position uses exact integer `x,y` coordinates, including negative coordinates. +Duration accepts `permanent`, `done`, or a non-negative number of turns. Effect +accepts `recurring`, `when-present`, `todo`, or `done`. Bounds use `min:max`, with +the minimum no greater than the maximum. Statistics use the full field names +shown in the form and whitespace-separated `field:value` pairs. These are +absolute integer values, including aggregates; omitted fields stay unchanged, +and no randomisation or automatic aggregate recalculation occurs. + +Preview shows the affected entity/type, worktree layer, and before/after values. +Scroll with arrows, PageUp/PageDown, or Home/End. Saving clears the browser search +so the saved entity remains visible. It does not stage or commit. Use +`efo diff`, `efo stage`, and `efo commit` for the rest of the workflow. + +A save failure retains the draft and gives a scrollable error. Locks are never +broken automatically; use `efo lock status`. Interrupted transactions require +`efo recover`; then inspect the worktree before retrying, since recovery can +complete an already-written save. If another process changed manifest, index, +or worktree while the form was open, the save is refused. Cancel the draft, +reload with `r`, and reopen the entity to edit the current state. + +## Undo and recovery scope + +After a successful save, `u` previews undo and `y` confirms it. Undo restores the +exact previous entity, including any edits that were already unstaged when the +form opened, or removes an entity just created by the TUI. Other entities, +HEAD, and index are unchanged. Any intervening repository change refuses undo; +reloading does not bypass this check. Use `efo status` / `efo diff` to review +such changes. + +Undo is **one step, in this TUI session only**. A later successful save replaces +the prior undo record; exiting loses it. For a durable recovery point, stage +and commit valuable work before continuing to edit. The CLI's +`efo restore --worktree --kind KIND @UUID` restores that entity from the index, +which discards all its unstaged edits and is not equivalent to TUI undo. +See [recovery](recovery.md). + +Stage/unstage, commit, relationship editing, general deletion, transaction +recovery, and future pruning remain CLI operations. Additional interactive +writes require explicit previews, recovery guidance, and tests through the +library transaction operations. diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index a7545ea..185454d 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -21,6 +21,7 @@ use crate::{ error::EpochError, stats::{self, EntityType, MetaStats, OverallStats, Symbols, TypedLink}, }; +pub mod edit; pub mod implementations; /// An entity that can be present in the game world. diff --git a/lib_efo/src/entity/edit.rs b/lib_efo/src/entity/edit.rs new file mode 100644 index 0000000..99bf269 --- /dev/null +++ b/lib_efo/src/entity/edit.rs @@ -0,0 +1,147 @@ +//! Validated text inputs for interactive entity authoring. +use super::{EffectApplication, EffectBounds, Entity, EntityDuration}; +use crate::stats::EntityType; + +/// Editable fields shared by entity forms. Unexposed metadata stays intact. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct EntityDraft { + /// Non-empty display name. + pub name: String, + /// Free-form, possibly multiline description. + pub description: String, + /// Exact coordinates as `x,y`. + pub position: String, + /// `permanent`, `done`, or a number of turns. + pub duration: String, + /// `recurring`, `when-present`, `todo`, or `done`. + pub effect: String, + /// Inclusive effect bounds in `min:max` form. + pub bounds: String, + /// Absolute statistic values as whitespace-separated `field:value` pairs. + pub statistics: String, +} + +impl EntityDraft { + /// Construct a zero-stat entity with a stable UUID and type-specific defaults. + pub fn new_entity(kind: EntityType) -> Entity { + let event = kind == EntityType::Event; + Entity { + id: uuid::Uuid::new_v4(), + entity_type: kind, + duration: if event { + EntityDuration::Duration(1) + } else { + EntityDuration::Permanent + }, + effect_nature: if event { + EffectApplication::PermanentEffectToApply + } else { + EffectApplication::WhenPresent + }, + effect_bounds: match kind { + EntityType::Character => EffectBounds { min: 20, max: 110 }, + EntityType::Town => EffectBounds { min: 20, max: 60 }, + EntityType::Calamity => EffectBounds { min: 20, max: 80 }, + EntityType::Event => EffectBounds { min: 10, max: 80 }, + _ => EffectBounds { min: 0, max: 120 }, + }, + ..Entity::default() + } + } + + /// Populate a form without losing relationships or other unexposed fields. + pub fn from_entity(entity: &Entity) -> Result { + let position = + serde_json::to_value(entity.position()).map_err(|error| error.to_string())?; + let statistics = + serde_json::to_value(entity.get_stats()).map_err(|error| error.to_string())?; + Ok(Self { + name: entity.name.clone(), + description: entity.description.clone(), + position: format!("{},{}", position[0], position[1]), + duration: match entity.duration { + EntityDuration::Permanent => "permanent".into(), + EntityDuration::Done => "done".into(), + EntityDuration::Duration(turns) => turns.to_string(), + }, + effect: match entity.effect_nature { + EffectApplication::Recurring => "recurring", + EffectApplication::WhenPresent => "when-present", + EffectApplication::PermanentEffectToApply => "todo", + EffectApplication::PermanentEffectApplied => "done", + } + .into(), + bounds: format!("{}:{}", entity.effect_bounds.min, entity.effect_bounds.max), + statistics: statistics + .as_object() + .ok_or("statistics are not an object")? + .iter() + .map(|(key, value)| format!("{key}:{value}")) + .collect::>() + .join(" "), + }) + } + + /// Validate inputs and produce a new entity without mutating the original. + /// Unlisted statistics and all relationships are preserved. + pub fn apply(&self, original: &Entity) -> Result { + let name = self.name.trim(); + if name.is_empty() || name.chars().any(char::is_control) { + return Err("Name: enter a non-empty name without control characters".into()); + } + let mut entity = original.clone(); + entity.name = name.into(); + entity.description = self.description.clone(); + let coordinates: Vec<_> = self.position.split(',').map(str::trim).collect(); + if coordinates.len() != 2 { + return Err("Position: use exact x,y coordinates (for example 12,-5)".into()); + } + let coordinates: Vec = coordinates + .iter() + .map(|value| value.parse::()) + .collect::>() + .map_err(|_| "Position: both coordinates must be integers")?; + entity.metadata.position = serde_json::from_value(serde_json::json!(coordinates)) + .map_err(|error| format!("Position: {error}"))?; + entity.duration = self.duration.parse().map_err(|error| { + format!("Duration: {error}; use permanent, done, or a number of turns") + })?; + entity.effect_nature = match self.effect.trim().to_lowercase().as_str() { + "recurring" => EffectApplication::Recurring, + "when-present" => EffectApplication::WhenPresent, + "todo" => EffectApplication::PermanentEffectToApply, + "done" => EffectApplication::PermanentEffectApplied, + _ => return Err("Effect: use recurring, when-present, todo, or done".into()), + }; + entity.effect_bounds = self + .bounds + .parse() + .map_err(|error| format!("Bounds: {error}; use min:max"))?; + if entity.effect_bounds.min > entity.effect_bounds.max { + return Err("Bounds: minimum must not exceed maximum".into()); + } + let mut statistics = + serde_json::to_value(&entity.stats).map_err(|error| error.to_string())?; + let fields = statistics + .as_object_mut() + .ok_or("statistics are not an object")?; + let mut seen = std::collections::BTreeSet::new(); + for pair in self.statistics.split_whitespace() { + let (key, value) = pair + .split_once(':') + .ok_or_else(|| format!("Statistics: `{pair}` must be field:value"))?; + if !fields.contains_key(key) || !seen.insert(key) { + return Err(format!( + "Statistics: unknown or repeated field `{key}`; use the full field names shown in the form" + )); + } + let value: isize = value + .parse() + .map_err(|_| format!("Statistics: `{key}` requires an integer"))?; + fields.insert(key.into(), serde_json::json!(value)); + } + entity.stats = + serde_json::from_value(statistics).map_err(|error| format!("Statistics: {error}"))?; + Ok(entity) + } +} diff --git a/lib_efo/src/transaction.rs b/lib_efo/src/transaction.rs index 681efb7..821fc85 100644 --- a/lib_efo/src/transaction.rs +++ b/lib_efo/src/transaction.rs @@ -198,7 +198,21 @@ pub fn replace_files( replacements: &[(PathBuf, Vec)], command: &str, ) -> Result<(), TransactionError> { - let _lock = RepositoryLock::acquire(root, command)?; + let lock = RepositoryLock::acquire(root, command)?; + replace_files_locked(root, replacements, &lock) +} + +/// Replace files while retaining the caller's lock across validation and writing. +pub(crate) fn replace_files_locked( + root: &Path, + replacements: &[(PathBuf, Vec)], + lock: &RepositoryLock, +) -> Result<(), TransactionError> { + if lock.path != root.join(".efo/lock") { + return Err(TransactionError::Ambiguous( + "writer lock belongs to another repository".into(), + )); + } recover_unlocked(root)?; let workspace = root.join(".efo"); let journal_path = workspace.join("transaction.json"); diff --git a/lib_efo/src/workspace.rs b/lib_efo/src/workspace.rs index cd2922c..a0c425c 100644 --- a/lib_efo/src/workspace.rs +++ b/lib_efo/src/workspace.rs @@ -272,6 +272,85 @@ impl Workspace { save(&self.root, ".efo/worktree.json", &self.worktree, command) } + /// Apply one previewed entity change, rejecting stale editor snapshots under + /// the writer lock. `None` means creation/deletion; swapping arguments undoes + /// a change. HEAD and index are never written. In-memory state changes only + /// after the transaction succeeds. + pub fn apply_entity_change( + &mut self, + before: Option<&crate::entity::Entity>, + after: Option<&crate::entity::Entity>, + ) -> Result<(), WorkspaceError> { + let lock = crate::transaction::RepositoryLock::acquire(&self.root, "entity editor")?; + let mut current = Self::open(&self.root)?; + if encode(&self.manifest, "manifest")? != encode(¤t.manifest, "manifest")? + || encode(&self.index, "index")? != encode(¤t.index, "index")? + || encode(&self.worktree, "worktree")? != encode(¤t.worktree, "worktree")? + { + return Err(WorkspaceError::Conflict( + "repository changed since this editor snapshot; cancel and reload with r before retrying".into(), + )); + } + let identity = before + .or(after) + .ok_or_else(|| WorkspaceError::Inconsistent("empty entity change".into()))?; + if let (Some(before), Some(after)) = (before, after) + && (before.id != after.id || before.entity_type != after.entity_type) + { + return Err(WorkspaceError::Inconsistent( + "editing cannot change an entity UUID or type".into(), + )); + } + let collection = current + .worktree + .world + .vec_entities_mut(&identity.entity_type); + let stored = collection.iter().find(|entity| entity.id == identity.id); + if !same_entity(stored, before) { + return Err(WorkspaceError::Conflict(format!( + "entity @{} differs from the preview", + identity.id + ))); + } + if let Some(after) = after { + if after.name.trim().is_empty() || after.name.chars().any(char::is_control) { + return Err(WorkspaceError::Inconsistent( + "entity name must be non-empty and contain no control characters".into(), + )); + } + if collection.iter().any(|entity| { + entity.id != after.id && entity.name.to_lowercase() == after.name.to_lowercase() + }) { + return Err(WorkspaceError::Conflict(format!( + "an entity named `{}` already exists in this collection", + after.name + ))); + } + } + let position = collection + .iter() + .position(|entity| entity.id == identity.id); + match (position, after) { + (Some(index), Some(after)) => collection[index] = after.clone(), + (Some(index), None) => { + collection.remove(index); + } + (None, Some(after)) => collection.push(after.clone()), + (None, None) => {} + } + validate_world("edited worktree", ¤t.worktree.world)?; + crate::transaction::replace_files_locked( + &self.root, + &[( + self.root.join(".efo/worktree.json"), + encode(¤t.worktree, "worktree")?, + )], + &lock, + )?; + *self = current; + Ok(()) + } + /// Persist a caller-modified index through the transaction layer. pub fn save_index(&self, command: &str) -> Result<(), WorkspaceError> { save(&self.root, ".efo/index.json", &self.index, command) diff --git a/lib_efo/tests/entity_editor.rs b/lib_efo/tests/entity_editor.rs new file mode 100644 index 0000000..e755882 --- /dev/null +++ b/lib_efo/tests/entity_editor.rs @@ -0,0 +1,212 @@ +use lib_efo::{ + entity::{Entity, edit::EntityDraft}, + stats::EntityType, + transaction::RepositoryLock, + workspace::Workspace, +}; +use std::fs; + +fn candidate(kind: EntityType, name: &str) -> Entity { + let base = EntityDraft::new_entity(kind); + let mut draft = EntityDraft::from_entity(&base).expect("draft"); + draft.name = name.into(); + draft.description = "Unicode town: Draän\nSecond line".into(); + draft.position = "12,-5".into(); + draft.statistics = "food:17 population:30".into(); + draft.apply(&base).expect("valid form") +} + +#[test] +fn all_six_types_support_create_edit_exact_undo_and_existing_restore() { + let temp = tempfile::tempdir().expect("temp"); + let mut workspace = Workspace::initialize(temp.path(), "test").expect("init"); + let manifest = fs::read(temp.path().join(".epoch")).expect("manifest"); + let index = fs::read(temp.path().join(".efo/index.json")).expect("index"); + for kind in [ + EntityType::Character, + EntityType::Town, + EntityType::Event, + EntityType::Calamity, + EntityType::Organization, + EntityType::Blocker, + ] { + let original = candidate(kind, "Original"); + workspace + .apply_entity_change(None, Some(&original)) + .expect("create"); + let other = candidate(kind, "Other"); + workspace + .apply_entity_change(None, Some(&other)) + .expect("create other"); + let prior = fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"); + let mut draft = EntityDraft::from_entity(&original).expect("draft"); + draft.name = "Renamed".into(); + draft.duration = "12".into(); + let edited = draft.apply(&original).expect("edit draft"); + workspace + .apply_entity_change(Some(&original), Some(&edited)) + .expect("edit"); + let opened = Workspace::open(temp.path()).expect("reopen"); + assert_eq!(opened.worktree.world.vec_entities(&kind)[0].name, "Renamed"); + workspace + .apply_entity_change(Some(&edited), Some(&original)) + .expect("undo edit"); + assert_eq!( + fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"), + prior + ); + workspace + .apply_entity_change(Some(&original), None) + .expect("undo creation"); + workspace + .restore_worktree_entities( + kind, + &[lib_efo::entity::EntityIdentifier::Id(other.id.to_string())], + ) + .expect("CLI restore operation"); + assert!(workspace.worktree.world.vec_entities(&kind).is_empty()); + } + assert_eq!( + fs::read(temp.path().join(".epoch")).expect("manifest"), + manifest + ); + assert_eq!( + fs::read(temp.path().join(".efo/index.json")).expect("index"), + index + ); + assert!(!workspace.has_staged_changes()); + assert!(!workspace.has_unstaged_changes()); +} + +#[test] +fn stale_worktree_or_index_lock_and_journal_refuse_without_losing_data() { + let temp = tempfile::tempdir().expect("temp"); + let mut workspace = Workspace::initialize(temp.path(), "test").expect("init"); + let entity = candidate(EntityType::Town, "Durn"); + let baseline = fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"); + let lock = RepositoryLock::acquire(workspace.root(), "other writer").expect("lock"); + assert!( + workspace + .apply_entity_change(None, Some(&entity)) + .expect_err("locked") + .to_string() + .contains("locked") + ); + assert!(workspace.worktree.world.towns.is_empty()); + drop(lock); + fs::write(temp.path().join(".efo/transaction.json"), "{}").expect("journal"); + assert!( + workspace + .apply_entity_change(None, Some(&entity)) + .expect_err("journal") + .to_string() + .contains("efo recover") + ); + assert_eq!( + fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"), + baseline + ); + fs::remove_file(temp.path().join(".efo/transaction.json")).expect("remove simulated journal"); + let mut external = Workspace::open(temp.path()).expect("open"); + external + .apply_entity_change(None, Some(&entity)) + .expect("external create"); + assert!( + workspace + .apply_entity_change(None, Some(&candidate(EntityType::Town, "Other"))) + .expect_err("stale") + .to_string() + .contains("repository changed") + ); + workspace = Workspace::open(temp.path()).expect("open"); + external.stage_all().expect("external stage"); + assert!( + workspace + .apply_entity_change(Some(&entity), None) + .expect_err("stale index") + .to_string() + .contains("repository changed") + ); + assert_eq!( + Workspace::open(temp.path()) + .expect("open") + .worktree + .world + .towns[0] + .name, + "Durn" + ); + assert!(!temp.path().join(".efo/lock").exists()); +} + +#[test] +fn validation_preserves_relationships_and_rejects_invalid_fields() { + let mut original = candidate(EntityType::Town, "Durn"); + original.change_governor(lib_efo::stats::CharacterId(uuid::Uuid::new_v4())); + let draft = EntityDraft::from_entity(&original).expect("draft"); + assert_eq!( + serde_json::to_value(draft.apply(&original).expect("unchanged")).expect("json"), + serde_json::to_value(&original).expect("json") + ); + let mut invalid = draft.clone(); + for name in ["", " \t", "bad\nname"] { + invalid.name = name.into(); + assert!(invalid.apply(&original).is_err()); + } + invalid = draft.clone(); + invalid.bounds = "80:10".into(); + assert!(invalid.apply(&original).is_err()); + invalid = draft.clone(); + invalid.position = "NaN,2".into(); + assert!(invalid.apply(&original).is_err()); + invalid = draft.clone(); + invalid.duration = "foreverish".into(); + assert!(invalid.apply(&original).is_err()); + invalid = draft.clone(); + invalid.effect = "bad".into(); + assert!(invalid.apply(&original).is_err()); + for statistics in [ + "missing:2", + "food:no", + "food:2 food:4", + "food", + "food:999999999999999999999999999999999", + ] { + invalid = draft.clone(); + invalid.statistics = statistics.into(); + assert!(invalid.apply(&original).is_err()); + } +} + +#[test] +fn duplicate_names_changed_identity_and_corrupt_state_are_not_saved() { + let temp = tempfile::tempdir().expect("temp"); + let mut workspace = Workspace::initialize(temp.path(), "test").expect("init"); + let entity = candidate(EntityType::Event, "Éclipse"); + workspace + .apply_entity_change(None, Some(&entity)) + .expect("create"); + let prior = fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"); + assert!( + workspace + .apply_entity_change(None, Some(&candidate(EntityType::Event, "éclipse"))) + .is_err() + ); + let mut changed = entity.clone(); + changed.id = uuid::Uuid::new_v4(); + assert!( + workspace + .apply_entity_change(Some(&entity), Some(&changed)) + .is_err() + ); + assert_eq!( + fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"), + prior + ); + fs::write(temp.path().join(".efo/worktree.json"), "invalid").expect("corrupt"); + assert!(workspace.apply_entity_change(Some(&entity), None).is_err()); + assert_eq!( + fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"), + b"invalid" + ); +} diff --git a/tui_efo/src/editor.rs b/tui_efo/src/editor.rs new file mode 100644 index 0000000..5a75046 --- /dev/null +++ b/tui_efo/src/editor.rs @@ -0,0 +1,401 @@ +//! Modal, in-memory entity forms. Persistence stays in `Workspace`. +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use lib_efo::entity::{Entity, edit::EntityDraft}; +use ratatui::{ + Frame, + layout::{Constraint, Layout}, + text::Text, + widgets::{Block, List, ListItem, Paragraph, Wrap}, +}; + +const LABELS: [&str; 7] = [ + "Name", + "Description", + "Position", + "Duration", + "Effect", + "Bounds", + "Statistics", +]; +const HINTS: [&str; 7] = [ + "Required; names must be unique within this collection", + "Free text; Enter inserts a new line", + "Exact x,y coordinates, for example 12,-5", + "permanent, done, or a number of turns", + "recurring, when-present, todo, or done", + "Minimum:maximum, for example 10:80", + "Absolute field:value pairs; full field names; unlisted values are preserved", +]; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Mode { + Form, + Preview, + Discard, +} + +pub enum Action { + None, + Cancel, + Save, +} + +pub struct Editor { + pub before: Option, + pub candidate: Option, + base: Entity, + values: Vec, + initial: Vec, + preview_values: Vec, + field: usize, + cursor: usize, + mode: Mode, + scroll: u16, + max_scroll: u16, + pub error: String, +} + +impl Editor { + pub fn open(base: Entity, creating: bool) -> Result { + let draft = EntityDraft::from_entity(&base)?; + let values = fields(draft); + let cursor = base.name.len(); + Ok(Self { + before: (!creating).then(|| base.clone()), + candidate: None, + base, + initial: values.clone(), + preview_values: values.clone(), + values, + field: 0, + cursor, + mode: Mode::Form, + scroll: 0, + max_scroll: 0, + error: String::new(), + }) + } + fn draft(&self) -> EntityDraft { + EntityDraft { + name: self.values[0].clone(), + description: self.values[1].clone(), + position: self.values[2].clone(), + duration: self.values[3].clone(), + effect: self.values[4].clone(), + bounds: self.values[5].clone(), + statistics: self.values[6].clone(), + } + } + fn focus(&mut self, index: usize) { + self.field = index; + self.cursor = self.values[index].len(); + } + pub fn paste(&mut self, text: &str) { + if self.mode != Mode::Form { + return; + } + let text: String = text + .chars() + .filter_map(|c| { + if c == '\n' { + Some(if self.field == 1 { '\n' } else { ' ' }) + } else if c.is_control() { + None + } else { + Some(c) + } + }) + .collect(); + self.values[self.field].insert_str(self.cursor, &text); + self.cursor += text.len(); + self.error.clear(); + } + pub fn handle(&mut self, key: KeyEvent) -> Action { + if self.mode == Mode::Discard { + return match key.code { + KeyCode::Char('y') => Action::Cancel, + KeyCode::Char('n') | KeyCode::Esc => { + self.mode = Mode::Form; + Action::None + } + _ => Action::None, + }; + } + if self.mode == Mode::Preview { + match key.code { + KeyCode::Char('y') => return Action::Save, + KeyCode::Esc | KeyCode::Char('n') => { + self.mode = Mode::Form; + self.error.clear(); + } + KeyCode::Up | KeyCode::Char('k') => self.scroll = self.scroll.saturating_sub(1), + KeyCode::Down | KeyCode::Char('j') => { + self.scroll = self.scroll.saturating_add(1).min(self.max_scroll) + } + KeyCode::PageUp => self.scroll = self.scroll.saturating_sub(10), + KeyCode::PageDown => { + self.scroll = self.scroll.saturating_add(10).min(self.max_scroll) + } + KeyCode::Home => self.scroll = 0, + KeyCode::End => self.scroll = self.max_scroll, + _ => {} + } + return Action::None; + } + if key.modifiers.contains(KeyModifiers::CONTROL) { + match key.code { + KeyCode::Char('s') => match self.draft().apply(&self.base).and_then(|entity| { + let values = fields(EntityDraft::from_entity(&entity)?); + Ok((entity, values)) + }) { + Ok((entity, values)) => { + self.preview_values = values; + self.candidate = Some(entity); + self.mode = Mode::Preview; + self.scroll = 0; + self.error.clear(); + } + Err(error) => self.error = error, + }, + KeyCode::Char('u') => { + self.values[self.field].clear(); + self.cursor = 0; + } + _ => {} + } + return Action::None; + } + match key.code { + KeyCode::Esc => { + if self.values == self.initial { + return Action::Cancel; + } + self.mode = Mode::Discard; + } + KeyCode::BackTab => self.focus((self.field + 6) % 7), + KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => { + self.focus((self.field + 6) % 7) + } + KeyCode::Tab | KeyCode::Down => self.focus((self.field + 1) % 7), + KeyCode::Up => self.focus((self.field + 6) % 7), + KeyCode::Home => self.cursor = 0, + KeyCode::End => self.cursor = self.values[self.field].len(), + KeyCode::Left => { + self.cursor = self.values[self.field][..self.cursor] + .char_indices() + .next_back() + .map_or(0, |(index, _)| index) + } + KeyCode::Right => { + if let Some(c) = self.values[self.field][self.cursor..].chars().next() { + self.cursor += c.len_utf8(); + } + } + KeyCode::Backspace => { + if let Some((index, _)) = self.values[self.field][..self.cursor] + .char_indices() + .next_back() + { + self.values[self.field].drain(index..self.cursor); + self.cursor = index; + } + } + KeyCode::Delete => { + if self.cursor < self.values[self.field].len() { + self.values[self.field].remove(self.cursor); + } + } + KeyCode::Enter if self.field == 1 => self.paste("\n"), + KeyCode::Enter => self.focus((self.field + 1) % 7), + KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::ALT) => { + self.paste(&c.to_string()) + } + _ => {} + } + Action::None + } + pub fn render(&mut self, frame: &mut Frame<'_>) { + let area = frame.area(); + let rows = Layout::vertical([ + Constraint::Length(if area.height < 14 { 2 } else { 3 }), + Constraint::Min(1), + Constraint::Length((area.height / 4).clamp(2, 5)), + ]) + .split(area); + let title = format!( + "{} {:?} · worktree only · @{}", + if self.before.is_none() { "Add" } else { "Edit" }, + self.base.entity_type, + self.base.id + ); + frame.render_widget( + Paragraph::new(title).block(Block::bordered().title(" Entity editor ")), + rows[0], + ); + let footer = if self.mode == Mode::Discard { + frame.render_widget(Paragraph::new("Discard this unsaved draft?\n\ny: discard n / Esc: continue editing\nNothing has been saved.").block(Block::bordered().title(" Confirm discard ")).wrap(Wrap { trim: false }), rows[1]); + String::new() + } else if self.mode == Mode::Preview { + let mut text = format!( + "Confirm {} in the WORKTREE only.\nHEAD and index stay unchanged.\nUndo this save with u; stage/commit with efo when ready.\n\n", + if self.before.is_none() { + "creation" + } else { + "edit" + } + ); + let changed = self + .preview_values + .iter() + .zip(&self.initial) + .enumerate() + .filter(|(_, (after, before))| self.before.is_none() || after != before); + for (index, (after, before)) in changed { + text.push_str(&format!( + "{}\n Before: {}\n After: {}\n\n", + LABELS[index], + if self.before.is_none() { + "(new entity)" + } else { + before + }, + after + )); + } + if !self.error.is_empty() { + text.push_str(&format!( + "Save failed: {}\nDraft retained. Esc returns to the form.\n", + self.error + )); + } + let paragraph = Paragraph::new(Text::from(text)).wrap(Wrap { trim: false }); + self.max_scroll = paragraph + .line_count(rows[1].width.saturating_sub(2)) + .saturating_sub(usize::from(rows[1].height.saturating_sub(2))) + .min(usize::from(u16::MAX)) as u16; + self.scroll = self.scroll.min(self.max_scroll); + frame.render_widget( + paragraph + .block(Block::bordered().title(" Save preview · ↑↓ / PgUp/PgDn scroll ")) + .scroll((self.scroll, 0)), + rows[1], + ); + format!( + "y save · n / Esc back to form\n{}", + if self.error.is_empty() { + "" + } else { + "SAVE FAILED · scroll preview to read error" + } + ) + } else { + let body = if area.width >= 90 { + let columns = + Layout::horizontal([Constraint::Length(24), Constraint::Min(1)]).split(rows[1]); + let items = LABELS.iter().enumerate().map(|(index, label)| { + ListItem::new(format!( + "{} {}", + if index == self.field { "›" } else { " " }, + label + )) + }); + frame.render_widget( + List::new(items).block(Block::bordered().title(" Fields · Tab / ↑↓ ")), + columns[0], + ); + columns[1] + } else { + rows[1] + }; + let value = &self.values[self.field]; + let displayed = format!("{}▏{}", &value[..self.cursor], &value[self.cursor..]); + let inner_width = body.width.saturating_sub(2); + let cursor_line = Paragraph::new(format!("{}▏", &value[..self.cursor])) + .wrap(Wrap { trim: false }) + .line_count(inner_width); + let offset = cursor_line + .saturating_sub(usize::from(body.height.saturating_sub(2))) + .min(usize::from(u16::MAX)) as u16; + frame.render_widget( + Paragraph::new(displayed) + .wrap(Wrap { trim: false }) + .scroll((offset, 0)) + .block(Block::bordered().title(format!( + " {} ({}/7) ", + LABELS[self.field], + self.field + 1 + ))), + body, + ); + if self.error.is_empty() { + format!( + "Tab/↑↓ field · ←→ cursor · Ctrl-U clear\nCtrl-S preview/save · Esc cancel\n{}", + HINTS[self.field] + ) + } else { + format!("{}\nCtrl-S retry · Esc cancel", self.error) + } + }; + frame.render_widget(Paragraph::new(footer).wrap(Wrap { trim: false }), rows[2]); + } +} + +fn fields(draft: EntityDraft) -> Vec { + vec![ + draft.name, + draft.description, + draft.position, + draft.duration, + draft.effect, + draft.bounds, + draft.statistics, + ] +} + +#[cfg(test)] +mod tests { + use super::*; + use lib_efo::stats::EntityType; + use ratatui::{Terminal, backend::TestBackend}; + fn key(editor: &mut Editor, code: KeyCode) { + editor.handle(KeyEvent::new(code, KeyModifiers::NONE)); + } + + #[test] + fn unicode_cursor_paste_multiline_and_modal_preview() { + let mut editor = + Editor::open(EntityDraft::new_entity(EntityType::Event), true).expect("editor"); + editor.paste("É日x"); + key(&mut editor, KeyCode::Left); + key(&mut editor, KeyCode::Backspace); + assert_eq!(editor.values[0], "Éx"); + key(&mut editor, KeyCode::Home); + key(&mut editor, KeyCode::Delete); + assert_eq!(editor.values[0], "x"); + key(&mut editor, KeyCode::Tab); + editor.paste("line one\nline two"); + key(&mut editor, KeyCode::Enter); + assert_eq!(editor.values[1], "line one\nline two\n"); + editor.handle(KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL)); + assert!(editor.mode == Mode::Preview); + let candidate = serde_json::to_value(editor.candidate.as_ref()).expect("json"); + editor.paste("must not change preview"); + assert_eq!( + serde_json::to_value(editor.candidate.as_ref()).expect("json"), + candidate + ); + for (width, height) in [(1, 1), (32, 10), (60, 16), (120, 30)] { + let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("terminal"); + editor.render_test(&mut terminal); + key(&mut editor, KeyCode::End); + editor.render_test(&mut terminal); + } + key(&mut editor, KeyCode::Esc); + assert!(editor.mode == Mode::Form); + } + impl Editor { + fn render_test(&mut self, terminal: &mut Terminal) { + terminal.draw(|frame| self.render(frame)).expect("render"); + } + } +} diff --git a/tui_efo/src/main.rs b/tui_efo/src/main.rs index 18c1850..b4a5d8b 100644 --- a/tui_efo/src/main.rs +++ b/tui_efo/src/main.rs @@ -1,7 +1,8 @@ -//! Interactive, read-only Epoch Forge repository browser. +//! Interactive Epoch Forge repository browser and entity editor. #![deny(clippy::unwrap_used)] mod details; +mod editor; use clap::Parser; use crossterm::{ @@ -34,7 +35,7 @@ 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 v Toggle formatted / JSON details\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." + after_long_help = "KEYS:\n Tab / Shift-Tab Move focus\n Arrows or h/j/k/l Navigate\n ? Toggle help\n v Toggle formatted / JSON details\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. Use a to add, e to edit, u to undo the last TUI save. Forms: Tab fields, Ctrl-S preview, y save. HEAD/index are read-only. Use `efo` for staging, commits, relationships, and recovery." )] struct Args { /// Disable colours (also respects NO_COLOR). @@ -136,6 +137,12 @@ impl Layer { } } +struct UndoChange { + workspace: Workspace, + before: Option, + after: Entity, +} + struct App { repository: PathBuf, workspace: Workspace, @@ -151,6 +158,9 @@ struct App { help_max: u16, message: String, writer: String, + editor: Option, + undo: Option, + undo_confirm: bool, layer: Layer, query: String, search: Option, @@ -179,8 +189,11 @@ impl App { help: false, help_offset: 0, help_max: 0, - message: "Read-only mode · press ? for help".into(), + message: "a add · e edit · u undo · ? help".into(), writer, + editor: None, + undo: None, + undo_confirm: false, layer: Layer::Worktree, query: String::new(), search: None, @@ -190,6 +203,92 @@ impl App { page_size: 10, }) } + fn open_editor(&mut self, creating: bool) { + if self.layer != Layer::Worktree { + self.message = "HEAD/index are read-only. Press 3 to edit the worktree.".into(); + return; + } + let base = if creating { + let kind = match Collection::ALL[self.collection] { + Collection::Characters => lib_efo::stats::EntityType::Character, + Collection::Towns => lib_efo::stats::EntityType::Town, + Collection::Events => lib_efo::stats::EntityType::Event, + Collection::Calamities => lib_efo::stats::EntityType::Calamity, + Collection::Organisations => lib_efo::stats::EntityType::Organization, + Collection::Blockers => lib_efo::stats::EntityType::Blocker, + }; + lib_efo::entity::edit::EntityDraft::new_entity(kind) + } else if let Some(entity) = self.selected_entity() { + entity.clone() + } else { + self.message = "Select an entity to edit, or press a to add one.".into(); + return; + }; + match editor::Editor::open(base, creating) { + Ok(editor) => self.editor = Some(editor), + Err(error) => self.message = error, + } + } + fn save_editor(&mut self) { + let Some(editor) = &mut self.editor else { + return; + }; + let Some(candidate) = &editor.candidate else { + return; + }; + match self + .workspace + .apply_entity_change(editor.before.as_ref(), Some(candidate)) + { + Ok(()) => { + let id = candidate.id; + self.undo = Some(UndoChange { + workspace: self.workspace.clone(), + before: editor.before.clone(), + after: candidate.clone(), + }); + self.editor = None; + self.diagnostic = None; + self.query.clear(); + self.select_id(Some(id)); + self.focus = Focus::Details; + self.writer = writer_status(self.workspace.root()); + self.message = + "Saved to worktree · u undo last save · use efo stage / commit when ready" + .into(); + } + Err(error) => { + editor.error = format!( + "{error}\nRun efo lock status for locks; efo recover for interrupted writes. Cancel and reload (r) if another writer changed the repository." + ) + } + } + } + fn undo_last_save(&mut self) { + if let Some(undo) = &mut self.undo { + match undo + .workspace + .apply_entity_change(Some(&undo.after), undo.before.as_ref()) + { + Ok(()) => { + self.workspace = undo.workspace.clone(); + self.undo = None; + self.layer = Layer::Worktree; + self.clamp_entity(); + self.message = + "Last TUI save undone; the exact prior entity state was restored.".into(); + self.diagnostic = None; + } + Err(error) => { + self.message = "Undo refused; nothing overwritten. Press ! for details.".into(); + self.diagnostic = Some(format!( + "{error}\nUse efo status / diff to review subsequent changes. Undo never overwrites a changed repository." + )); + } + } + } + self.undo_confirm = false; + } fn world(&self) -> &EpochInfo { match self.layer { Layer::Head => &self.workspace.head, @@ -286,6 +385,37 @@ impl App { if key.kind == KeyEventKind::Release { return false; } + if self.editor.is_some() { + let key = if key.modifiers.contains(KeyModifiers::CONTROL) + && key.code == KeyCode::Char('c') + { + KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE) + } else { + key + }; + let action = self.editor.as_mut().map(|editor| editor.handle(key)); + match action { + Some(editor::Action::Save) => self.save_editor(), + Some(editor::Action::Cancel) => { + self.editor = None; + self.message = "Draft cancelled; no changes saved.".into(); + } + _ => {} + } + return false; + } + if self.undo_confirm { + if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') { + self.undo_confirm = false; + return false; + } + match key.code { + KeyCode::Char('y') => self.undo_last_save(), + KeyCode::Char('n') | KeyCode::Esc => self.undo_confirm = false, + _ => {} + } + return false; + } if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') { return true; } @@ -382,6 +512,15 @@ impl App { } } KeyCode::Char('r') => self.reload(), + KeyCode::Char('a') => self.open_editor(true), + KeyCode::Char('e') => self.open_editor(false), + KeyCode::Char('u') => { + if self.undo.is_some() { + self.undo_confirm = true; + } else { + self.message = "No TUI save to undo in this session.".into(); + } + } KeyCode::Char('v') => { self.detail_view.toggle(); self.details_offset = 0; @@ -416,7 +555,7 @@ impl TerminalGuard { enable_raw_mode()?; TERMINAL_ACTIVE.store(true, Ordering::SeqCst); let mut stdout = io::stdout(); - if let Err(error) = execute!(stdout, EnterAlternateScreen) { + if let Err(error) = execute!(stdout, EnterAlternateScreen, event::EnableBracketedPaste) { Self::restore(); return Err(error); } @@ -431,7 +570,12 @@ impl TerminalGuard { fn restore() { if TERMINAL_ACTIVE.swap(false, Ordering::SeqCst) { let _ = disable_raw_mode(); - let _ = execute!(io::stdout(), crossterm::cursor::Show, LeaveAlternateScreen); + let _ = execute!( + io::stdout(), + event::DisableBracketedPaste, + crossterm::cursor::Show, + LeaveAlternateScreen + ); } } } @@ -473,12 +617,20 @@ fn run(args: Args) -> Result<(), AppError> { let mut terminal = TerminalGuard::enter()?; loop { terminal.terminal.draw(|frame| render(frame, &mut app))?; - if event::poll(Duration::from_millis(250))? - && let Event::Key(key) = event::read()? - && key.kind != KeyEventKind::Release - && app.handle_key(key) - { - break; + if event::poll(Duration::from_millis(250))? { + match event::read()? { + Event::Key(key) if key.kind != KeyEventKind::Release => { + if app.handle_key(key) { + break; + } + } + Event::Paste(text) => { + if let Some(editor) = &mut app.editor { + editor.paste(&text); + } + } + _ => {} + } } } Ok(()) @@ -486,6 +638,24 @@ fn run(args: Args) -> Result<(), AppError> { fn render(frame: &mut Frame<'_>, app: &mut App) { let area = frame.area(); + if let Some(editor) = &mut app.editor { + editor.render(frame); + return; + } + if app.undo_confirm { + let name = app + .undo + .as_ref() + .map(|undo| undo.after.name.as_str()) + .unwrap_or("entity"); + let action = if app.undo.as_ref().is_some_and(|undo| undo.before.is_none()) { + "Remove the entity created by the last TUI save" + } else { + "Restore the exact entity state before the last TUI save" + }; + frame.render_widget(Paragraph::new(format!("{action}: {name}\n\nWorktree only; HEAD and index stay unchanged.\nRefused if the repository has changed since that save.\n\ny confirm undo · n / Esc cancel")).block(Block::bordered().title(" Undo preview ")).wrap(Wrap { trim: false }), area); + return; + } 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; @@ -523,7 +693,7 @@ fn render(frame: &mut Frame<'_>, app: &mut App) { Paragraph::new(if app.search.is_some() { format!(" /{}▏ Enter apply · Esc cancel", app.query) } else { - format!(" {}\n Tab focus · / search · v view · 1 HEAD 2 index 3 worktree · r reload · ? help · q quit", app.message) + format!(" {}\n a add · e edit · u undo · Tab focus · / search · v view · 1 HEAD 2 index 3 worktree · r reload · ? help · q quit", app.message) }), rows[2], ); @@ -567,7 +737,7 @@ fn render_status(frame: &mut Frame<'_>, app: &App, area: Rect) { ); frame.render_widget( Paragraph::new(text).block(Block::bordered().title(format!( - " Epoch Forge · read-only · {} ", + " Epoch Forge · {} ", app.workspace.root().display() ))), area, @@ -655,7 +825,7 @@ fn render_help(frame: &mut Frame<'_>, app: &mut App, area: Rect) { let popup = centered_rect(88, area.height, area); frame.render_widget(Clear, 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\nv Toggle formatted / raw JSON details\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{}", + "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\nv Toggle formatted / raw JSON details\nr Reload, preserving selected UUID\n? or ! Help and last reload diagnostic\nq, Esc Close help; then quit\nCtrl-C Quit browser; cancel editor/undo\n\na / e Add / edit in the worktree\nu Preview undo of last TUI save\nForms: Tab fields, Ctrl-S preview, y save, Esc cancel.\nCtrl-C in a form cancels with a draft-discard prompt.\nUse efo for staging, commits, relationships, and recovery.\n\n{}", app.diagnostic.as_deref().unwrap_or("No reload errors.") ); let paragraph = Paragraph::new(text).wrap(Wrap { trim: true }); @@ -955,4 +1125,142 @@ mod tests { key(&mut app, KeyCode::Char('v')); assert_eq!(app.detail_view, DetailView::Formatted); } + fn control(app: &mut App, c: char) { + app.handle_key(KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL)); + } + #[test] + fn authoring_all_collections_previews_saves_edits_and_undoes() { + for collection in 0..Collection::ALL.len() { + let (temp, mut app) = app(); + app.collection = collection; + let head = fs::read(temp.path().join("epoch/0/epochinfo.json")).expect("head"); + let index = fs::read(temp.path().join(".efo/index.json")).expect("index"); + key(&mut app, KeyCode::Char('a')); + app.editor.as_mut().expect("editor").paste("Draän test"); + control(&mut app, 's'); + assert!( + Workspace::open(temp.path()) + .expect("open") + .worktree + .world + .vec_entities( + &app.editor + .as_ref() + .expect("editor") + .candidate + .as_ref() + .expect("preview") + .entity_type + ) + .is_empty() + ); + let mut terminal = Terminal::new(TestBackend::new(90, 24)).expect("terminal"); + terminal.draw(|f| render(f, &mut app)).expect("preview"); + assert!(terminal.backend().to_string().contains("WORKTREE")); + key(&mut app, KeyCode::Char('y')); + assert!(app.editor.is_none()); + assert_eq!(app.selected_entity().expect("created").name, "Draän test"); + let prior = fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"); + key(&mut app, KeyCode::Char('e')); + control(&mut app, 'u'); + app.editor.as_mut().expect("editor").paste("Renamed"); + control(&mut app, 's'); + key(&mut app, KeyCode::Char('y')); + assert_eq!(app.selected_entity().expect("renamed").name, "Renamed"); + key(&mut app, KeyCode::Char('u')); + key(&mut app, KeyCode::Char('n')); + assert_eq!(app.selected_entity().expect("not undone").name, "Renamed"); + key(&mut app, KeyCode::Char('u')); + key(&mut app, KeyCode::Char('y')); + assert_eq!( + fs::read(temp.path().join(".efo/worktree.json")).expect("worktree"), + prior + ); + assert_eq!( + fs::read(temp.path().join(".efo/index.json")).expect("index"), + index + ); + assert_eq!( + fs::read(temp.path().join("epoch/0/epochinfo.json")).expect("head"), + head + ); + } + } + #[test] + fn drafts_are_modal_cancellable_and_retained_on_save_failure() { + let (temp, mut app) = app(); + key(&mut app, KeyCode::Char('1')); + key(&mut app, KeyCode::Char('a')); + assert!(app.editor.is_none()); + key(&mut app, KeyCode::Char('3')); + key(&mut app, KeyCode::Char('a')); + control(&mut app, 's'); + assert!(app.editor.as_ref().expect("editor").error.contains("Name")); + app.editor.as_mut().expect("editor").paste("qrueav"); + assert!(app.editor.is_some()); + control(&mut app, 'c'); + key(&mut app, KeyCode::Char('n')); + assert!(app.editor.is_some()); + control(&mut app, 's'); + let lock = lib_efo::transaction::RepositoryLock::acquire(app.workspace.root(), "test") + .expect("lock"); + key(&mut app, KeyCode::Char('y')); + assert!( + app.editor + .as_ref() + .expect("draft retained") + .error + .contains("locked") + ); + drop(lock); + assert!( + Workspace::open(temp.path()) + .expect("open") + .worktree + .world + .characters + .is_empty() + ); + key(&mut app, KeyCode::Char('y')); + assert!(app.editor.is_none()); + key(&mut app, KeyCode::Char('u')); + key(&mut app, KeyCode::Char('y')); + assert!(app.workspace.worktree.world.characters.is_empty()); + key(&mut app, KeyCode::Char('a')); + app.editor.as_mut().expect("editor").paste("Discarded"); + key(&mut app, KeyCode::Esc); + key(&mut app, KeyCode::Char('y')); + assert!(app.editor.is_none()); + assert!( + Workspace::open(temp.path()) + .expect("open") + .worktree + .world + .characters + .is_empty() + ); + } + #[test] + fn undo_refuses_external_changes_even_after_reload() { + let (temp, mut app) = app(); + key(&mut app, KeyCode::Char('a')); + app.editor.as_mut().expect("editor").paste("Aria"); + control(&mut app, 's'); + key(&mut app, KeyCode::Char('y')); + let mut external = Workspace::open(temp.path()).expect("open"); + external.worktree.world.summary = "External change".into(); + external.save_worktree("external").expect("save"); + app.reload(); + key(&mut app, KeyCode::Char('u')); + key(&mut app, KeyCode::Char('y')); + assert!( + app.diagnostic + .as_ref() + .expect("diagnostic") + .contains("repository changed") + ); + let current = Workspace::open(temp.path()).expect("open"); + assert_eq!(current.worktree.world.summary, "External change"); + assert_eq!(current.worktree.world.characters.len(), 1); + } } diff --git a/tui_efo/tests/terminal_smoke.py b/tui_efo/tests/terminal_smoke.py index 0c956e4..7a1be24 100644 --- a/tui_efo/tests/terminal_smoke.py +++ b/tui_efo/tests/terminal_smoke.py @@ -2,7 +2,7 @@ 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 +import fcntl, hashlib, json, os, pathlib, pty, select, shutil, struct, subprocess, tempfile, termios, time binary = str(pathlib.Path('target/debug/efo-tui').resolve()) def snapshot(root): @@ -34,13 +34,39 @@ with tempfile.TemporaryDirectory() as directory: fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 16, 60, 0, 0)) os.write(master, b'\t') drain(0.1) + if exit_keys == b'\x03': + def send(*keys): + for key in keys: + os.write(master, key) + drain(0.08) + def world(): + return json.loads((root / '.efo/worktree.json').read_text()) + original_world = world() + send(b'a', b'\x1b[200~TUI smoke created\x1b[201~', b'\t', b'\x1b[200~Multiline\nDra\xc3\xa4n\x1b[201~', b'\x13') + assert world() == original_world, 'preview wrote state before confirmation' + send(b'y') + assert any(e['name'] == 'TUI smoke created' and e['description'] == 'Multiline\nDraän' for e in world()['world']['characters']), 'create/paste failed' + send(b'u', b'y') + assert world() == original_world, 'undo creation failed' + send(b'\x1b[Z', b'\x1b[H', b'e', b'\x15', b'TUI smoke renamed', b'\x13', b'y') + assert any(e['name'] == 'TUI smoke renamed' for e in world()['world']['characters']), 'edit failed' + send(b'u', b'n') + assert any(e['name'] == 'TUI smoke renamed' for e in world()['world']['characters']), 'cancel undo failed' + send(b'u', b'y') + assert world() == original_world, 'undo edit failed' + send(b'a', b'Discard draft', b'\x1b', b'y') + assert world() == original_world, 'discard changed state' + current = snapshot(root) + assert {k: v for k, v in current.items() if k != '.efo/worktree.json'} == {k: v for k, v in before.items() if k != '.efo/worktree.json'}, 'editor changed files outside worktree' + print('PTY authoring passed: create, multiline paste, preview, edit, discard, confirmed undo; HEAD/index unchanged') 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') + if exit_keys == b'q': + assert snapshot(root) == before, 'browsing modified repository' + print(f'PTY smoke passed: exit={exit_keys!r}, navigation/search/layers/help/resize, terminal restored') finally: if process.poll() is None: process.kill()