diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index e846f40..99363df 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -125,6 +125,9 @@ pub struct History { next_id: u64, /// Most bytes the blobs may take: [`MAX_BYTES`], smaller in tests. max_bytes: u64, + /// A failed snapshot was reported and none has succeeded since, so + /// further failures stay quiet. + warned: bool, } /// Milliseconds since the Unix epoch; 0 before it. @@ -171,6 +174,7 @@ impl History { blobs: BTreeMap::new(), next_id: 1, max_bytes: MAX_BYTES, + warned: false, }; history.load()?; let dropped = history.prune(now); @@ -449,13 +453,20 @@ fn warn(state: &mut State, message: String) { /// Takes a snapshot of `text` for the project-relative `path`. Best /// effort: without a history nothing happens, and a failure is reported as /// a warning instead of failing the caller, because a save or a reload must -/// not stop for the history. +/// not stop for the history. Only the first failure after a success is +/// reported, so a full disk does not raise one warning per save. pub fn snapshot(state: &mut State, path: &Path, text: &str, bom: bool, reason: Reason) { let Some(history) = state.history.as_mut() else { return; }; - if let Err(message) = history.record(&path_string(path), text, bom, reason, SystemTime::now()) { - warn(state, message); + match history.record(&path_string(path), text, bom, reason, SystemTime::now()) { + Ok(_) => history.warned = false, + Err(message) => { + if !history.warned { + history.warned = true; + warn(state, message); + } + } } } diff --git a/docs/architecture.md b/docs/architecture.md index 94f8965..95330cc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5); remotes: fetch, pull, push, clone and remote management (M4.10); stash (M4.9) · **Last updated:** 2026-11-02 +> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5); remotes: fetch, pull, push, clone and remote management (M4.10); stash (M4.9); files changed on disk and Local History (C10 A2) · **Last updated:** 2026-11-08 ## Overview @@ -117,9 +117,9 @@ Theme tokens are defined in Rust (`lutra_engine::theme`) and rendered as CSS cus ### Events -`lutra_engine::Event`, serialised as `{"kind": "", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands), `recoveryResolved {paths}` (M1.15, see Recovery journal), `searchResults {searchId, path, matches}` and `searchDone {searchId, files, matches, truncated, cancelled, elapsedMs}` (M2.3, see Search), `terminalOutput {terminalId, data}` and `terminalExited {terminalId, code}` (M3.6, see Terminal). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab. +`lutra_engine::Event`, serialised as `{"kind": "", ...}`: `projectOpened {root, name}`, `projectClosed`, `treeChanged {dir}`, `bufferOpened {id, path}`, `bufferFocused {id}` (M1.13), `bufferChanged {id, version}`, `dirtyChanged {id, dirty}`, `bufferClosed {id}`, `fileChangedOnDisk {path, id, removed}`, `diskConflictResolved {id}` (C10 A2), `watchFailed {message}`, `recoveryAvailable {entries}` (M1.7, see Recovery journal), `uiCommand {id, params}` (M1.8, see UI commands), `recoveryResolved {paths}` (M1.15, see Recovery journal), `searchResults {searchId, path, matches}` and `searchDone {searchId, files, matches, truncated, cancelled, elapsedMs}` (M2.3, see Search), `terminalOutput {terminalId, data}` and `terminalExited {terminalId, code}` (M3.6, see Terminal). Events say what changed; clients fetch data with `project.children` and `buffer.get`. `file.open` on a file whose buffer is already open returns that buffer and emits `bufferFocused {id}` instead of `bufferOpened` (M1.13): a separate event, so that `bufferOpened` keeps meaning "a new buffer exists" (the host's `engine_ready` replay and other clients rely on that) while every client, including the editor, still learns that the user asked to see that buffer and activates its tab. -Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. At most 10,000 VFS events are handled per pump. +Changes on disk reach the engine through `Engine::pump_vfs()`, which hosts call regularly (the desktop's pump thread every 100 ms; tests call it directly). It maps VFS events to `treeChanged` for the parent directories, reloads a clean buffer whose file changed (unless the file already matches, as after our own save) with `bufferChanged`, and reports `fileChangedOnDisk` for a dirty buffer, which keeps its text, or for a removed file. C10 A2: every event for a path only means "look again", so a delete followed by a create (git checkout, atomic saves) reloads instead of reporting a removal; a removed file's buffer becomes dirty; a save checks the file's mtime and hash and fails with `disk_changed` over a newer file; Local History snapshots are taken on save, reload, deletion, rename and file-changing git commands. See `docs/local-history.md`. At most 10,000 VFS events are handled per pump. Watched directories: the VFS watcher is non-recursive, so `project.children` watches each directory it lists. At most 256 directories besides the root are watched natively and 32 when polling (each polled directory is rescanned every 100 ms); beyond that the least recently listed directory is unwatched, and listing it again re-watches it. Expanding a deep `vendor/` therefore costs at most 256 native watches; changes in directories that dropped out are not reported until they are listed again. `node_modules`, ignored and hidden directories are never watched. The parent directory of every open buffer is pinned (M1.13, `workspace::sync_buffer_dirs`, run by `Engine::execute` after every command): it is watched even if the tree never listed it, so reloads and `fileChangedOnDisk` arrive for files opened by path from never-expanded folders. Pinned directories count against the cap but are never evicted while a buffer in them is open (with more pinned directories than the cap, the watched set exceeds it); after the last buffer in a directory closes, it ages out like a listed one. A buffer inside an ignored or hidden directory is still not watched. @@ -133,7 +133,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat ### Tabs and editor (M1.6) -- `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged`, `fileChangedOnDisk` and project open/close update it; `bufferFocused` activates the tab and outranks adoptions still fetching, so the most recent open wins. The project tree ends a directory the engine listed only partly (`truncated`) with a note row (`project.tree.truncated`). `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them. +- `ui/src/stores/editor.ts` holds the tabs (buffer id, path, dirty, notice), the active tab and the close question. It adds a tab from the `file.open` result (opened from the tree) or, for a `bufferOpened` event it did not cause (control channel, replay after a reload), from `buffer.get`. `bufferClosed`, `dirtyChanged` and project open/close update it (files changed on disk: `ui/src/stores/diskConflicts.ts`, C10 A2); `bufferFocused` activates the tab and outranks adoptions still fetching, so the most recent open wins. The project tree ends a directory the engine listed only partly (`truncated`) with a note row (`project.tree.truncated`). `ui/src/components/editor/engineEvents.ts` checks event fields before the store sees them. - One `BufferSync` per tab (`ui/src/components/editor/bufferSync.ts`) owns the tab's CodeMirror `EditorState`; one `EditorView` shows the active tab's state, so undo history and selection survive tab switches. Every transaction goes through the sync. Local changes are sent with `buffer.edit` against the confirmed version, one call in flight, later keystrokes composed into the next call. On `stale_version`, or a `bufferChanged` with a newer version than ours, the sync fetches `buffer.get`, diffs it against the confirmed text, rebases unsent local changes over that diff (CodeMirror change-set mapping) and applies the remote part to the editor without adding it to undo history. A refused edit (other than stale) is reported and the editor returns to the engine text. - Line breaks: the engine keeps text as on disk and counts `\r\n` as two UTF-16 units; CodeMirror counts every break as one position. `EngineText` remembers which breaks are `\r\n` and converts positions when building edits; inserted breaks are sent with the buffer's line ending, so a CRLF file stays CRLF in memory. Text without `\r\n` (the common case) needs no table. - Save, save all and close run from the engine's default shortcuts (`file.save` `Mod+S`, `file.saveAll` `Mod+Alt+S`, `buffer.close` `Mod+W`), loaded with `listCommands` and matched by key code, with the active buffer as context; since M1.8 through the global keymap (see UI commands, palette and keymap). Saving and closing wait until the sync has no pending edits. diff --git a/docs/gaps.md b/docs/gaps.md index 0e8c9c8..5d22485 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,13 +1,13 @@ # Gaps -> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10; stash, M4.9; chunk staging, C8 C3); G14 English UI catalog in place · **Last updated:** 2026-11-06 +> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave, files changed on disk and Local History); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10; stash, M4.9; chunk staging, C8 C3); G14 English UI catalog in place · **Last updated:** 2026-11-08 Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated. | # | Gap | Milestone | Estimate (one agent) | |---|---|---|---| | G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) | -| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), ~~tab management (preview, pin, split, close others, reopen)~~ (C10 A1), conflict UI for files changed on disk, ~~autosave~~ (M3.10), local history | M1 | ~10 h | +| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), ~~tab management (preview, pin, split, close others, reopen)~~ (C10 A1), ~~conflict UI for files changed on disk~~ (C10 A2), ~~autosave~~ (M3.10), ~~local history~~ (C10 A2, v1) | M1 | ~10 h | | G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b; string and path controls: H4), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b; C9 T1: six built-in themes, picker with live preview, theme file import, editor font family and line height), ~~main menu~~ (M3.9: hamburger dropdown from `menuPath`s; native macOS menu bar: A1 adds the system menus (Lutra, Edit, Window; ⌘W and ⌘Q stay Lutra's), mirroring Lutra's own menus natively and display modes open) | M1 | ~24 h | | G4 | Syntax and structure: tree-sitter PHP, ~~Lezer highlighting~~ (M2.2: PHP with embedded HTML plus HTML, CSS, JS/TS, JSON, YAML, Markdown; `--lt-syntax-*` tokens; `editor.reveal`), ~~file structure~~ (M2.7: Structure tool window, `syntax.outline`), semantic highlighting, folding in the editor | M2 | ~8 h | | G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h | @@ -28,7 +28,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t | G20 | AI features (chat, inline prompts, commit messages); MCP server is G7/M3 | M9 | ~60 h | | G21 | Feature breadth: the full PhpStorm help inventory has 155 feature units; ~23 have at least partial support (2026-10-18, estimated). The list lives in `plan/phpstorm/00-feature-inventory.md` with public URLs | ongoing | — | -G2 progress: the engine text buffer landed (M1.1, `crates/text`: rope, UTF-16 and char positions, atomic edit batches, line ending policy). M1.3 added engine buffers with versions, the edit protocol, save and save all, and reloading on external changes. M1.6 added tabs and a CodeMirror 6 editor synced to engine buffers (version-based edits with resync, CRLF-aware offsets), save and save all by engine shortcuts, the Save / Don't Save / Cancel question and a notice for files changed on disk. M1.7 added the crash-recovery journal (debounced atomic entries per dirty buffer, `recovery.*` commands, restore dialog; not yet checked in the running app). M1.13 made re-opening an open file switch to its tab and keeps the folders of open files watched. M3.10 added autosave (window blur, tab switch, after 15 s idle; settings) and `flushDirty()`, the one "save all dirty and wait" entry point for later deployment and run features; autosave skips files in conflict with the disk. C10 A1 added tab management: preview tabs (and their setting), pinning, close others/all/left/right/unmodified with one question for every unsaved file, reopen closed tab with selection and scroll, a second editor group (split right/down, move, focus, unsplit) sharing one engine buffer and undo history, a tab context menu, `tabs.*` commands and the tab layout per project in Lutra's own state file. Left from tab management: drag to reorder or between groups, more than two groups, a tab limit, a recent-files switcher. Still open: a conflict UI (compare and merge with the disk version), local history, editor settings (soft wrap); estimate lowered to ~10 h. +G2 progress: the engine text buffer landed (M1.1, `crates/text`: rope, UTF-16 and char positions, atomic edit batches, line ending policy). M1.3 added engine buffers with versions, the edit protocol, save and save all, and reloading on external changes. M1.6 added tabs and a CodeMirror 6 editor synced to engine buffers (version-based edits with resync, CRLF-aware offsets), save and save all by engine shortcuts, the Save / Don't Save / Cancel question and a notice for files changed on disk. M1.7 added the crash-recovery journal (debounced atomic entries per dirty buffer, `recovery.*` commands, restore dialog; not yet checked in the running app). M1.13 made re-opening an open file switch to its tab and keeps the folders of open files watched. M3.10 added autosave (window blur, tab switch, after 15 s idle; settings) and `flushDirty()`, the one "save all dirty and wait" entry point for later deployment and run features; autosave skips files in conflict with the disk. C10 A1 added tab management: preview tabs (and their setting), pinning, close others/all/left/right/unmodified with one question for every unsaved file, reopen closed tab with selection and scroll, a second editor group (split right/down, move, focus, unsplit) sharing one engine buffer and undo history, a tab context menu, `tabs.*` commands and the tab layout per project in Lutra's own state file. Left from tab management: drag to reorder or between groups, more than two groups, a tab limit, a recent-files switcher. C10 A2 added the conflict UI and Local History v1 (`docs/local-history.md`): a banner in each editor pane for a dirty file changed (Reload (discard mine) / Keep mine / Compare with the disk text in the diff viewer) or deleted on disk (Keep as unsaved / Close); a delete followed by a create (git checkout) reloads instead of losing the buffer; a save never overwrites a newer file silently (mtime + hash check in the engine, `disk_changed`, Overwrite / Cancel); Local History in the data dir (content-addressed, 14 days / 200 MB per project, pruned on open) with snapshots on save, before reloads, on deletion, before rename and file-changing git operations; Show Local History (tree and tab menus, palette, File menu) with Show Diff and an undoable Revert to This. Still open: a merge view against the disk version, Local History labels, folder and project history, editor settings (soft wrap); estimate lowered to ~10 h. G4 progress: M2.1 added the structural half in `crates/syntax`: tree-sitter PHP parse and incremental reparse, outline (namespaces, class-likes, functions, members, promoted properties, enum cases; anonymous classes marked) and folding ranges, an 8 MiB parse cap, proptests and snapshots. M2.2 made highlighting visible. M2.7 added the Structure tool window: each open PHP buffer keeps a tree-sitter tree, reparsed incrementally on a worker thread off the engine lock (200 ms debounce), `syntax.outline` and `outlineChanged`, and the outline as a tree in the left tool window with jumps through `editor.reveal`. Open in G4: semantic highlighting, folding in the editor, Structure speed search, sorting and filters. Finding: a full parse of 1 MB takes 364–553 ms on the dev machine (target 50 ms; reparse 7–11 ms), so parsing must stay off the engine lock and the index must parse in parallel. @@ -55,6 +55,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin | Date | Change | Summary | |---|---|---| +| 2026-11-08 | minor | G2 shrunk: conflict UI for files changed on disk and Local History v1 (C10 A2) | | 2026-11-08 | minor | G2 shrunk: tab management (C10 A1) | | 2026-11-06 | patch | G17: deployment v2 (C9 D2): remote browser, compare, sync | | 2026-11-06 | patch | G17: deployment v1 (C9 D1); remote browser, compare and sync left for D2 | diff --git a/docs/local-history.md b/docs/local-history.md new file mode 100644 index 0000000..c7afbd7 --- /dev/null +++ b/docs/local-history.md @@ -0,0 +1,97 @@ +# Files changed on disk and Local History + +> **Status:** v1 (C10 A2, owner decision D29) · **Last updated:** 2026-11-08 + +Lutra never loses a text because another program, a git operation or Lutra itself changed a file. Two parts work together: + +- **Files changed on disk:** what an open editor does when its file changes or disappears outside Lutra, and how a save avoids overwriting a newer file. +- **Local History:** copies of file texts that Lutra keeps by itself, per project, so you can compare with and go back to an earlier text, also for files git does not track. + +Behaviour comes from Lutra's own design and the public documentation of the feature in other IDEs; wording, icons and shortcuts are Lutra's own (there is no default shortcut). + +## Files changed on disk + +Lutra watches the folders of every open file (`docs/architecture.md` › VFS). Every change to a file only means "look again": what counts is the file on disk when Lutra looks. + +| Situation | What Lutra does | +|---|---| +| The file changed, the tab has no unsaved changes | Reloads it silently. The editor moves onto the new text with the smallest change, so the caret and the scroll position stay where the text around them did not change. | +| The file changed, the tab has unsaved changes | Keeps your text and shows a banner in the editor: **Reload (discard mine)**, **Keep mine**, **Compare**. | +| The file was deleted or renamed away | Keeps the text, marks the tab as unsaved and shows a banner: **Keep as unsaved**, **Close**. Closing the tab later asks as for any unsaved file; saving writes the file again. | +| The file is deleted and created again (a git checkout, an editor that saves by replacing the file) | Treated as a change, not as a loss: the tab reloads (or shows the "changed" banner if it has unsaved changes). A tab that only became unsaved because its file was gone for a moment reloads like a clean one. | +| The file comes back with exactly your text | The banner goes away and the tab is clean again. | + +- **Reload (discard mine)** replaces your text with the file's (`file.reload`). Your text goes into the Local History first. +- **Keep mine** hides the banner. The next save asks once more before it overwrites the newer file. +- **Compare** opens a diff tab: the file on disk on the left, your text on the right (`file.readDisk`). You can edit the right side; it is the same buffer as the tab. +- **Close** closes the tab without saving; the text is in the Local History. + +### Saving never overwrites a newer file silently + +Before every save the engine compares the file's modification time and size with what it recorded when it last read or wrote the file. When they differ it reads the file and compares its hash. A different text means another program changed it: + +- `file.save` fails with `disk_changed`, and the editor asks "… was changed by another program since you opened it. Overwrite it with your text?" (**Overwrite** / **Cancel**, Cancel has the focus). Overwrite repeats the save with `overwrite: true`. +- `file.saveAll` saves the others and lists such files under `diskChanged`; the editor asks for each. +- Autosave (`file.saveAll {skipConflicts: true}`) never asks and never overwrites: it leaves these files unsaved. +- A file that was only touched (same text) saves without asking. A file that is gone is written again. + +## Local History + +### What is kept, and when + +| Reason in the list | When | +|---|---| +| Saved | Every save (also save all and autosave) keeps the saved text. | +| Before first save | The first save of a file in a session keeps the text it overwrites, unless the history already has it. | +| Changed by another program | When Lutra sees another program's text for an open file. | +| Before reload from disk | The tab's text before a reload replaces it (silent reload or "Reload (discard mine)"). | +| Deleted on disk | The tab's text when its file disappears. | +| Before refactoring | Every file a rename (`lsp.rename`) changes, before it changes. | +| Before git operation | Every open file before checkout, new branch with checkout, merge, abort merge, stash, apply stash, pull and revert chunk. | +| Before revert | The tab's text before "Revert to This" replaces it. | + +A text equal to the file's newest entry is not added again, so repeated saves of the same text cost nothing. Texts over 16 MiB are not kept. + +Files that are not open in Lutra are not watched for the history. git protects their local changes itself: checkout, merge and pull refuse to overwrite them, and stash keeps them. + +### Using it + +- **Show Local History**: in the project tree's context menu (Show Local History), the palette and File › Show Local History (`history.show {path?}`; without a path, the active tab's file). The dialog lists the file's entries newest first with date, time, reason and size. +- **Show Diff** (or Enter, or a double click) opens a diff tab: the entry on the left, the current text on the right. +- **Revert to This** (in the dialog and in the diff tab's caption) puts the entry's text into the editor as an ordinary unsaved change: Undo brings your text back, and nothing is written until you save. A closed file is opened first. + +### Storage and limits (D29) + +- In Lutra's data directory, per project: `/history//` (the project id is a hash of the project folder). Never inside the project; if the data directory lies inside the project, the Local History is off and Lutra says so. +- Content-addressed: each text is stored once as `blobs//`, however many entries refer to it. `index.jsonl` lists the entries. +- Kept for **14 days**, at most **200 MB per project**: when the project opens, older entries are dropped, then the oldest ones while the texts take more than 200 MB, and texts no entry refers to are deleted. A new entry that crosses 200 MB drops the oldest ones at once. +- A damaged index line is skipped; a text whose hash does not match is reported as damaged instead of shown. Failing to write the history never stops a save: Lutra shows one warning. + +## Commands + +| Command | What it does | +|---|---| +| `file.save {id, overwrite?}` | Saves; `disk_changed` when the file is newer, unless `overwrite`. | +| `file.saveAll {skipConflicts?}` | Saves every unsaved buffer; `diskChanged` lists the ones it left alone. | +| `file.reload {id}` | Replaces the buffer with the file ("Reload (discard mine)"). | +| `file.readDisk {path}` | The file's text on disk, answered like `git.show`. | +| `buffer.get {id}` | Includes `diskConflict`: `null`, `"changed"` or `"removed"`. | +| `history.list {path}` | The file's entries, newest first: `{id, time, reason, size}`. | +| `history.read {path, id}` | One entry's text, answered like `git.show`. | +| `history.revert {path, id}` | Puts an entry's text into the buffer (an undoable `buffer.edit`). | +| `history.show {path?}` | UI command: the dialog. | + +Events: `fileChangedOnDisk {path, id, removed}` sets the banner, `diskConflictResolved {id}` removes it. + +## Not yet + +- Labels (put a name on the current state), history of a folder or of the whole project, recently deleted files. +- History for files changed by tools while they are not open in Lutra. +- A merge view for a changed file (Compare shows both sides; you merge by editing the right side). +- Settings for the 14 days and 200 MB. + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-11-08 | major | First version (C10 A2) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2f97c63..218025f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity checklist -> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3), branch widget and popup (M4.5), fetch/pull/push progress, the clone and remotes dialogs (M4.10), four more themes, theme import and editor font settings (C9 T1) · **Last updated:** 2026-11-02 +> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3), branch widget and popup (M4.5), fetch/pull/push progress, the clone and remotes dialogs (M4.10), four more themes, theme import and editor font settings (C9 T1), files changed on disk and Local History (C10 A2) · **Last updated:** 2026-11-08 - [ ] Main window: tool window stripes, editor area, status bar, navigation bar - M2.7 (2026-10-17): a left stripe with one tab per left tool window (Project, Structure); the shown one is marked, clicking it again hides the window. Still missing: right docking, several bottom tool windows, drag to rearrange, navigation bar, layout persistence. @@ -15,6 +15,8 @@ - C10 A1 (2026-11-08): **preview tabs**: a single click in the project tree, a Find result or a Go-to choice opens a preview tab (italic title) that the next preview in its group replaces; editing it, opening it for good (double click in the tree), a double click on the tab or "Keep Tab Open" makes it permanent; setting `editor.tabs.preview` turns previews off. **Pinning** (Lucide `pin` icon): pinned tabs sit left and survive every bulk close. **Close actions**: close, close other tabs, close all, close to the left / right, close unmodified; the unsaved files of one action are asked about once with a list (Save All / Don't Save / Cancel). **Reopen Closed Tab**: a stack of the last 30 closed tabs per window, reopened at their place with selection and scroll position. **Split**: Split Right / Split Down add a second editor group (at most two) showing the active tab; Move Tab to Other Group, Focus Other Group, Unsplit; the same file in both groups is one engine buffer with one text, selection and undo history; the focused group is marked. A **tab context menu** (right click) runs all of these. Commands `tabs.*` in the registry (palette, a new Window menu group, agents); no default shortcuts. The layout of each project (groups, tabs, pins, previews, active tabs) is stored in Lutra's own state file (`layout.get` / `layout.set`, `/layout/`) and restored when the project opens. Vitest (model and area tests); live check over `--control` on Windows 11. Missing: reorder by drag, dragging tabs between groups, more than two groups, a tab limit, a recent-files switcher, duplicate-name disambiguation, diff tabs in the second group, per-group scroll for the same file (both groups share one selection). - [ ] Editor syntax highlighting (Lutra's own colours, no copied scheme) - M2.2 (2026-10-16): the language is picked from the file extension when a tab opens: PHP (with the HTML, CSS and JavaScript around ` { diff --git a/ui/src/commands/uiCommands.ts b/ui/src/commands/uiCommands.ts index 2ec51f7..2a971fc 100644 --- a/ui/src/commands/uiCommands.ts +++ b/ui/src/commands/uiCommands.ts @@ -36,6 +36,7 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [ { id: "editor.complete", labelKey: "command.editor.complete", menuPath: "Edit/Complete Code" }, { id: "editor.quickDocumentation", labelKey: "command.editor.quickDocumentation", menuPath: "Edit/Quick Documentation", defaultShortcut: "Mod+I" }, { id: "editor.parameterInfo", labelKey: "command.editor.parameterInfo", menuPath: "Edit/Parameter Info" }, + { id: "history.show", labelKey: "command.history.show", menuPath: "File/Show Local History" }, { id: "find.open", labelKey: "command.find.open", menuPath: "View/Find in Files…", defaultShortcut: "Mod+Alt+F" }, { id: "goto.classOpen", labelKey: "command.goto.classOpen", menuPath: "Go/Class…", defaultShortcut: "Mod+Alt+C" }, { id: "goto.fileOpen", labelKey: "command.goto.fileOpen", menuPath: "Go/File…", defaultShortcut: "Mod+P" }, diff --git a/ui/src/components/editor/DiskBanner.vue b/ui/src/components/editor/DiskBanner.vue new file mode 100644 index 0000000..4a393d3 --- /dev/null +++ b/ui/src/components/editor/DiskBanner.vue @@ -0,0 +1,142 @@ + + + + + diff --git a/ui/src/components/editor/EditorArea.vue b/ui/src/components/editor/EditorArea.vue index ad5bc1f..9bde581 100644 --- a/ui/src/components/editor/EditorArea.vue +++ b/ui/src/components/editor/EditorArea.vue @@ -11,15 +11,20 @@ * (`assist/commands.ts`) and the tab management commands * (`tabs/commands.ts`). Diff tabs (M4.3, `vcs/diff/`) share the first * group's tab bar; while one is active the diff view replaces that group's - * editor, and the area supplies the diff commands. + * editor, and the area supplies the diff commands. Files changed on disk + * (C10 A2): each pane shows its active tab's banner (`DiskBanner.vue`); + * the area shows the overwrite question (`OverwritePrompt.vue`), both from + * `stores/diskConflicts.ts`. */ import { onBeforeUnmount, onMounted } from "vue"; import { useCommandsStore } from "../../commands/store"; import { t } from "../../i18n"; import { useEditorStore } from "../../stores/editor"; +import { useDiskConflictsStore } from "../../stores/diskConflicts"; import ClosePrompt from "./ClosePrompt.vue"; import EditorPane from "./EditorPane.vue"; import { provideTabCommands } from "./tabs/commands"; +import OverwritePrompt from "./OverwritePrompt.vue"; import { reveal, REVEAL_COMMAND } from "./reveal"; import * as assist from "./assist/commands"; import { provideDiffCommands } from "../vcs/diff/commands"; @@ -28,12 +33,14 @@ import { useDiffStore } from "../vcs/diff/diff"; const editor = useEditorStore(); const commands = useCommandsStore(); const diff = useDiffStore(); +const disk = useDiskConflictsStore(); /** Withdraws the command handlers; filled while mounted. */ let withdraw: (() => void)[] = []; onMounted(() => { editor.start(); + disk.start(); const hasActive = (): boolean => editor.activeTab !== null; withdraw = [ commands.provide("file.save", { run: async () => { await editor.save(); }, enabled: hasActive }), @@ -53,6 +60,7 @@ onBeforeUnmount(() => { fn(); } withdraw = []; + disk.stop(); editor.stop(); }); @@ -96,6 +104,7 @@ onBeforeUnmount(() => { + diff --git a/ui/src/components/editor/EditorPane.vue b/ui/src/components/editor/EditorPane.vue index 53ee4ed..c1e0f3d 100644 --- a/ui/src/components/editor/EditorPane.vue +++ b/ui/src/components/editor/EditorPane.vue @@ -4,15 +4,15 @@ * tab and its editor. The first group also hosts the diff tabs; while a * diff is active there, the diff view replaces that group's editor. * - * Banners about the active tab (C10 A2's conflict banner) belong in this - * pane, between the tab bar and the editor, keyed by - * {@link activeTab}. + * The disk-conflict banner of the active tab (C10 A2, `DiskBanner.vue`) + * sits between the tab bar and the editor, keyed by {@link activeTab}. */ import { computed, defineAsyncComponent } from "vue"; import { t } from "../../i18n"; import { useEditorStore } from "../../stores/editor"; import { useDiffStore } from "../vcs/diff/diff"; import CodeEditor from "./CodeEditor.vue"; +import DiskBanner from "./DiskBanner.vue"; import EditorTabs from "./EditorTabs.vue"; /** The diff view, loaded on first use so `@codemirror/merge` stays out of the start bundle. */ @@ -45,6 +45,10 @@ const showsDiff = computed(() => props.group === 0 && diff.visible); data-test="editor-pane" > +
+/** + * The question before a save overwrites a file that another program + * changed (C10 A2): Overwrite or Cancel. Escape cancels; Cancel has the + * focus, so Enter never overwrites by accident. The questions come from + * the disk-conflict store (`stores/diskConflicts.ts`), one at a time. + */ +import { nextTick, ref, watch } from "vue"; +import { t } from "../../i18n"; +import { useDiskConflictsStore } from "../../stores/diskConflicts"; + +const disk = useDiskConflictsStore(); + +/** The Cancel button, focused when the question appears. */ +const cancelButton = ref(null); + +watch( + () => disk.prompt, + async (prompt) => { + if (prompt) { + await nextTick(); + cancelButton.value?.focus(); + } + }, + { immediate: true }, +); + +/** + * Cancels on Escape. + * + * @param event - the key event inside the dialog. + */ +function onKeydown(event: KeyboardEvent): void { + if (event.key === "Escape") { + event.preventDefault(); + void disk.resolveOverwrite(false); + } +} + + + + + diff --git a/ui/src/components/editor/engineEvents.ts b/ui/src/components/editor/engineEvents.ts index 5aa6f6f..4f1054e 100644 --- a/ui/src/components/editor/engineEvents.ts +++ b/ui/src/components/editor/engineEvents.ts @@ -18,7 +18,8 @@ export type EditorEvent = | { kind: "bufferChanged"; id: number; version: number } | { kind: "dirtyChanged"; id: number; dirty: boolean } | { kind: "bufferClosed"; id: number } - | { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean }; + | { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean } + | { kind: "diskConflictResolved"; id: number }; /** Callback receiving editor events. */ export type EditorEventHandler = (event: EditorEvent) => void; @@ -58,6 +59,8 @@ export function toEditorEvent(payload: EngineEventPayload): EditorEvent | null { return id !== null && typeof raw.path === "string" && typeof raw.removed === "boolean" ? { kind: "fileChangedOnDisk", id, path: raw.path, removed: raw.removed } : null; + case "diskConflictResolved": + return id !== null ? { kind: "diskConflictResolved", id } : null; default: return null; } diff --git a/ui/src/components/history/LocalHistoryDialog.vue b/ui/src/components/history/LocalHistoryDialog.vue new file mode 100644 index 0000000..aa77421 --- /dev/null +++ b/ui/src/components/history/LocalHistoryDialog.vue @@ -0,0 +1,413 @@ + + + + + diff --git a/ui/src/components/history/localHistory.ts b/ui/src/components/history/localHistory.ts new file mode 100644 index 0000000..c77dd22 --- /dev/null +++ b/ui/src/components/history/localHistory.ts @@ -0,0 +1,260 @@ +/** + * Local History (C10 A2): the "Show Local History" dialog's state and the + * revert action. The engine takes the snapshots (`crates/engine/src/ + * history.rs`); this store lists and applies them. + * + * - **Opening:** the UI command `history.show {path?}` (project tree and + * tab context menus with the file's path, the palette with the active + * tab's file). It lists `history.list {path}`, newest first, with time + * and reason. + * - **Show Diff:** opens a diff tab of the entry (left) against the + * current buffer (right), see `vcs/diff/diff.ts` › `openHistory`, and + * closes the dialog. The diff tab's caption has "Revert to This" too. + * - **Revert to This:** `history.revert {path, id}` replaces the buffer's + * text through the engine (an ordinary unsaved edit). For a file open in + * a tab, the change enters the editor's undo history + * (`BufferSync.beginUndoableRemote`), so Undo brings the text back. + * - **Untrusted input:** list entries are checked field by field. + */ +import { defineStore } from "pinia"; +import { computed, ref } from "vue"; +import { t } from "../../i18n"; +import { run, type JsonValue } from "../../ipc"; +import { useEditorStore } from "../../stores/editor"; +import { useDiffStore } from "../vcs/diff/diff"; + +/** Command id that opens the dialog. */ +export const SHOW_HISTORY_COMMAND = "history.show"; + +/** Why a snapshot was taken, as the engine names it. */ +export type HistoryReason = + | "save" + | "beforeSave" + | "externalChange" + | "beforeReload" + | "deleted" + | "refactoring" + | "git" + | "beforeRevert"; + +/** Every reason, for checking untrusted input. */ +const REASONS: readonly HistoryReason[] = [ + "save", + "beforeSave", + "externalChange", + "beforeReload", + "deleted", + "refactoring", + "git", + "beforeRevert", +]; + +/** One entry of `history.list`. */ +export interface HistoryEntry { + /** The entry's id. */ + id: number; + /** When it was taken, ms since the Unix epoch. */ + time: number; + /** Why it was taken. */ + reason: HistoryReason; + /** Size of the text in bytes. */ + size: number; +} + +/** + * Reads the entries of a `history.list` result; malformed entries are + * skipped, a malformed result gives null. + * + * @param raw - untrusted. + */ +export function toEntries(raw: unknown): HistoryEntry[] | null { + if (typeof raw !== "object" || raw === null || !Array.isArray((raw as { entries?: unknown }).entries)) { + return null; + } + const out: HistoryEntry[] = []; + for (const item of (raw as { entries: unknown[] }).entries) { + if (typeof item !== "object" || item === null) { + continue; + } + const e = item as Record; + const reason = REASONS.find((r) => r === e.reason); + if (typeof e.id === "number" && typeof e.time === "number" && typeof e.size === "number" && reason) { + out.push({ id: e.id, time: e.time, reason, size: e.size }); + } + } + return out; +} + +/** + * Reads the params of `history.show`; null when malformed. + * + * @param params - untrusted (`{}` from the palette and the keyboard). + * @returns the path, or `""` for the active tab's file. + */ +export function parseShowParams(params: unknown): string | null { + if (params === null || params === undefined) { + return ""; + } + if (typeof params !== "object" || Array.isArray(params)) { + return null; + } + const path = (params as Record).path; + if (path === undefined || path === null) { + return ""; + } + return typeof path === "string" && path !== "" ? path : null; +} + +/** The Local History store. */ +export const useLocalHistoryStore = defineStore("localHistory", () => { + const editor = useEditorStore(); + + /** Whether the dialog is open. */ + const open = ref(false); + /** The file whose history is shown. */ + const path = ref(""); + /** The entries, newest first; null while loading or after a failure. */ + const entries = ref(null); + /** Index of the selected entry. */ + const selected = ref(0); + /** Whether the list is loading. */ + const loading = ref(false); + /** Whether a revert runs. */ + const busy = ref(false); + /** Last failure, null if none. */ + const error = ref(null); + /** Bumped when the dialog wants the focus. */ + const focusRequest = ref(0); + /** Load generation, so only the newest load lands. */ + let generation = 0; + + /** The selected entry, or null. */ + const current = computed(() => entries.value?.[selected.value] ?? null); + + /** + * Opens the dialog for a file and lists its entries. + * + * @param file - project-relative path. + */ + async function show(file: string): Promise { + path.value = file; + open.value = true; + entries.value = null; + selected.value = 0; + error.value = null; + loading.value = true; + focusRequest.value += 1; + const mine = ++generation; + const result = await run("history.list", { path: file }); + if (mine !== generation) { + return; + } + loading.value = false; + if (!result.ok) { + error.value = result.error.message; + return; + } + const list = toEntries(result.value); + if (list === null) { + error.value = t("common.error.unexpectedResult", { command: "history.list" }); + return; + } + entries.value = list; + } + + /** Closes the dialog. */ + function hide(): void { + open.value = false; + generation += 1; + } + + /** + * Moves the selection. + * + * @param delta - rows to move; clamped to the list. + */ + function move(delta: number): void { + const count = entries.value?.length ?? 0; + if (count > 0) { + selected.value = Math.max(0, Math.min(count - 1, selected.value + delta)); + } + } + + /** + * Shows an entry against the current text in the diff viewer. + * + * @param entry - the entry. + */ + async function showDiff(entry: HistoryEntry): Promise { + const file = path.value; + hide(); + await useDiffStore().openHistory(file, entry.id, entry.time); + } + + /** + * Puts an entry's text into the file's buffer, undoably when the file is + * open in a tab, and closes the dialog. + * + * @param file - project-relative path. + * @param id - the entry's id. + * @returns whether it worked ({@link error} says why not). + */ + async function revert(file: string, id: number): Promise { + busy.value = true; + const tab = editor.tabOfPath(file); + const sync = tab ? editor.syncOf(tab.id) : undefined; + if (tab) { + await editor.settleAll(); + } + sync?.beginUndoableRemote(); + const result = await run<{ version?: unknown }>("history.revert", { path: file, id }); + busy.value = false; + if (!result.ok) { + sync?.endUndoableRemote(null); + error.value = result.error.message; + return false; + } + sync?.endUndoableRemote(typeof result.value.version === "number" ? result.value.version : null); + error.value = null; + hide(); + return true; + } + + /** + * Runs `history.show`: the given file, else the active diff's or editor + * tab's file. + * + * @param params - untrusted params. + * @throws Error with a catalog message when the params are malformed or + * there is no file. + */ + async function showCommand(params: JsonValue): Promise { + const parsed = parseShowParams(params); + if (parsed === null) { + throw new Error(t("history.invalidParams")); + } + const file = parsed !== "" ? parsed : (useDiffStore().activeTab?.path ?? editor.activeTab?.path ?? ""); + if (file === "") { + throw new Error(t("history.noFile")); + } + await show(file); + } + + return { + open, + path, + entries, + selected, + loading, + busy, + error, + focusRequest, + current, + show, + hide, + move, + showDiff, + revert, + showCommand, + }; +}); diff --git a/ui/src/components/layout/MainLayout.vue b/ui/src/components/layout/MainLayout.vue index 73bbdcc..d3f4eac 100644 --- a/ui/src/components/layout/MainLayout.vue +++ b/ui/src/components/layout/MainLayout.vue @@ -62,6 +62,7 @@ import { useChangesStore } from "../vcs/changes/changes"; import LogToolWindow from "../vcs/log/LogToolWindow.vue"; import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log"; import StashDialog from "../vcs/stash/StashDialog.vue"; +import LocalHistoryDialog from "../history/LocalHistoryDialog.vue"; import DeploymentLogToolWindow from "../deploy/DeploymentLogToolWindow.vue"; import RemoteBrowserToolWindow from "../deploy/RemoteBrowserToolWindow.vue"; import { useRemoteBrowserStore } from "../deploy/remoteBrowser"; @@ -417,6 +418,7 @@ onBeforeUnmount(() => { +
diff --git a/ui/src/components/menu/menu.ts b/ui/src/components/menu/menu.ts index 9789a4e..37843d8 100644 --- a/ui/src/components/menu/menu.ts +++ b/ui/src/components/menu/menu.ts @@ -46,6 +46,7 @@ const ITEM_ORDER = [ "project.openDialog", "file.save", "file.saveAll", + "history.show", "buffer.close", "project.close", "app.quit", diff --git a/ui/src/components/project/TreeContextMenu.vue b/ui/src/components/project/TreeContextMenu.vue index 4b0a093..f97c6bc 100644 --- a/ui/src/components/project/TreeContextMenu.vue +++ b/ui/src/components/project/TreeContextMenu.vue @@ -2,7 +2,7 @@ /** * The project tree's context menu (M4.3). For a file: Open, Show Diff * (`vcs.showDiff {path}`) and Show History (`vcs.showHistory {path}`, - * M4.6), the Git items dimmed while their command is disabled. For a file + * M4.6) and Show Local History (`history.show {path}`, C10 A2), the Git items dimmed while their command is disabled. For a file * and a folder: Upload to Server, Compare with Server (a diff for a file, * the sync preview for a folder, C9 D2) and Download from Server * (`deployment.upload` / `deployment.compare` / `deployment.download @@ -20,6 +20,7 @@ import { t } from "../../i18n"; import { useEditorStore } from "../../stores/editor"; import { SHOW_DIFF_COMMAND } from "../vcs/diff/diff"; import { SHOW_HISTORY_COMMAND } from "../vcs/log/log"; +import { SHOW_HISTORY_COMMAND as SHOW_LOCAL_HISTORY_COMMAND } from "../history/localHistory"; const props = defineProps<{ /** Project-relative path of the file. */ @@ -103,6 +104,12 @@ const fileItems = computed(() => [ enabled: commands.isEnabled(SHOW_HISTORY_COMMAND), run: () => commands.execute(SHOW_HISTORY_COMMAND, { path: props.path }), }, + { + id: "showLocalHistory", + label: t("project.tree.menu.showLocalHistory"), + enabled: commands.isEnabled(SHOW_LOCAL_HISTORY_COMMAND), + run: () => commands.execute(SHOW_LOCAL_HISTORY_COMMAND, { path: props.path }), + }, ]); /** The items, in order. */ diff --git a/ui/src/components/vcs/diff/DiffView.vue b/ui/src/components/vcs/diff/DiffView.vue index 148fe20..901c1ed 100644 --- a/ui/src/components/vcs/diff/DiffView.vue +++ b/ui/src/components/vcs/diff/DiffView.vue @@ -22,6 +22,9 @@ * buffer, so its Git gutter shows unstaged and staged markers; a click * opens the chunk popup with Stage, Unstage and Revert. A hint line says * so. + * - **Local tabs (C10 A2):** the disk text or a Local History entry on the + * left; a history tab's caption has "Revert to This" + * (`history.revert`, an undoable buffer edit). * - **Navigation:** a navigator over the merge view is registered for * `vcs.nextChange` / `vcs.previousChange` (`navigation.ts`): the focused * side, else the working copy, moves to the next or previous chunk. @@ -31,7 +34,8 @@ import { Annotation, EditorState, Transaction, type Extension } from "@codemirro import { EditorView } from "@codemirror/view"; import { basicSetup } from "codemirror"; import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue"; -import { t } from "../../../i18n"; +import { formatDateTime, t } from "../../../i18n"; +import { useLocalHistoryStore } from "../../history/localHistory"; import { onEngineEvent } from "../../../ipc"; import { useEditorStore } from "../../../stores/editor"; import type { BufferSync } from "../../editor/bufferSync"; @@ -44,6 +48,7 @@ import { setNavigator } from "./navigation"; const diff = useDiffStore(); const editor = useEditorStore(); +const history = useLocalHistoryStore(); /** Element the merge view is mounted in. */ const host = ref(null); @@ -102,6 +107,12 @@ const caption = computed(() => { if (tab.remote) { return t("vcs.diff.captionRemote", { path: tab.path, server: tab.remote.server }); } + if (tab.local?.kind === "disk") { + return t("history.diff.captionDisk", { path: tab.path }); + } + if (tab.local?.kind === "history") { + return t("history.diff.captionEntry", { path: tab.path, time: formatDateTime(tab.local.time) }); + } return refFor(tab.staged) === "HEAD" ? t("vcs.diff.captionHead", { path: tab.path }) : t("vcs.diff.captionIndex", { path: tab.path }); @@ -276,9 +287,19 @@ onBeforeUnmount(() => { data-test="diff-caption" > {{ caption }} +
@@ -318,6 +339,9 @@ onBeforeUnmount(() => { } .diff-view__caption { + display: flex; + align-items: center; + gap: 12px; flex-shrink: 0; padding: 3px 12px; color: var(--lt-fg-muted); @@ -328,6 +352,16 @@ onBeforeUnmount(() => { text-overflow: ellipsis; } +.diff-view__action { + margin-left: auto; + padding: 0 8px; + font: inherit; + color: var(--lt-fg); + background: transparent; + border: 1px solid var(--lt-border); + border-radius: 3px; +} + .diff-view__hint { flex-shrink: 0; padding: 2px 12px; diff --git a/ui/src/components/vcs/diff/diff.ts b/ui/src/components/vcs/diff/diff.ts index ab5f814..8cb9327 100644 --- a/ui/src/components/vcs/diff/diff.ts +++ b/ui/src/components/vcs/diff/diff.ts @@ -36,12 +36,17 @@ * which answers like `git.show`) with the working copy (right, the * ordinary buffer). Nothing is re-read on `gitChanged`; reopening the * tab reads the server again. + * - **Local tabs (C10 A2):** {@link openDisk} compares the file on disk + * (left, read-only, `file.readDisk {path}`) with the buffer: "Compare" in + * the disk-conflict banner. {@link openHistory} compares a Local History + * entry (left, `history.read {path, id}`) with the buffer. Both answer + * like `git.show`; nothing is re-read on `gitChanged`. * - **Untrusted input:** `git.show` results are checked field by field. */ import { defineStore } from "pinia"; import { computed, ref, shallowRef, watch } from "vue"; import { t } from "../../../i18n"; -import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc"; +import { onEngineEvent, run, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc"; import { baseName, useEditorStore } from "../../../stores/editor"; /** Command id that opens a diff. */ @@ -90,6 +95,33 @@ export interface DiffTab { commit?: DiffCommit; /** For a server tab: the deployment server compared with. */ remote?: DiffRemote; + /** For a local tab: the disk text or a Local History entry. */ + local?: DiffLocal; +} + +/** What a local tab compares the buffer with (C10 A2). */ +export type DiffLocal = + | { + /** The file as it is on disk now. */ + kind: "disk"; + } + | { + /** A Local History entry. */ + kind: "history"; + /** The entry's id from `history.list`. */ + id: number; + /** When it was taken, ms since the Unix epoch. */ + time: number; + }; + +/** + * The key of a local tab. + * + * @param path - project-relative path. + * @param local - what it compares with. + */ +export function localDiffKey(path: string, local: DiffLocal): string { + return local.kind === "disk" ? `disk:${path}` : `history:${String(local.id)}:${path}`; } /** The server a server tab compares the working copy with. */ @@ -307,6 +339,15 @@ export const useDiffStore = defineStore("diff", () => { * @returns the checked result, or the error text. */ async function readLeft(tab: DiffTab): Promise { + if (tab.local) { + const command = tab.local.kind === "disk" ? "file.readDisk" : "history.read"; + const params: Record = tab.local.kind === "disk" ? { path: tab.path } : { path: tab.path, id: tab.local.id }; + const local = await run(command, params); + if (!local.ok) { + return local.error.message; + } + return toShowResult(local.value) ?? t("common.error.unexpectedResult", { command }); + } if (tab.remote) { const params: Record = { path: tab.path }; if (tab.remote.serverId !== null) { @@ -502,6 +543,44 @@ export const useDiffStore = defineStore("diff", () => { await load(tab); } + /** + * Opens (or activates and reloads) the comparison of a file's buffer + * with the file on disk, or with a Local History entry. + * + * @param path - project-relative path. + * @param local - what to compare with. + */ + async function openLocal(path: string, local: DiffLocal): Promise { + const key = localDiffKey(path, local); + let tab = tabs.value.find((t) => t.key === key); + if (!tab) { + tab = { key, path, staged: false, name: baseName(path), local }; + tabs.value.push(tab); + } + activate(key); + await load(tab); + } + + /** + * Opens the comparison of a file's buffer with the file on disk. + * + * @param path - project-relative path. + */ + async function openDisk(path: string): Promise { + await openLocal(path, { kind: "disk" }); + } + + /** + * Opens the comparison of a file's buffer with a Local History entry. + * + * @param path - project-relative path. + * @param id - the entry's id. + * @param time - when it was taken, ms since the Unix epoch. + */ + async function openHistory(path: string, id: number, time: number): Promise { + await openLocal(path, { kind: "history", id, time }); + } + /** * Re-reads the left side of every loaded text tab; a changed text * replaces the left document (`gitChanged`). @@ -510,7 +589,7 @@ export const useDiffStore = defineStore("diff", () => { await Promise.all( tabs.value.map(async (tab) => { const before = contents.value[tab.key]; - if (before?.phase !== "ready" || tab.commit || tab.remote) { + if (before?.phase !== "ready" || tab.commit || tab.remote || tab.local) { return; } const generation = generations.get(tab.key); @@ -624,6 +703,8 @@ export const useDiffStore = defineStore("diff", () => { open, openAtCommit, openRemote, + openDisk, + openHistory, showDiff, refreshLeft, close, diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index 3cc7051..72b192a 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -17,6 +17,7 @@ "command.goto.classOpen": "Go to Class…", "command.goto.fileOpen": "Go to File…", "command.goto.symbolOpen": "Go to Symbol…", + "command.history.show": "Show Local History", "command.key.alt": "Alt", "command.key.cmd": "Cmd", "command.key.ctrl": "Ctrl", @@ -227,12 +228,18 @@ "editor.chunk.unstaged": "Not staged", "editor.closePrompt.question": "Save changes to {name} before closing?", "editor.closePrompt.questionMany": "Save changes to these {count} files before closing?", + "editor.disk.banner.changed": "{name} was changed by another program. You have unsaved changes.", + "editor.disk.banner.removed": "{name} was deleted on disk. Your text is still open.", + "editor.disk.compare": "Compare", + "editor.disk.keepMine": "Keep mine", + "editor.disk.keepUnsaved": "Keep as unsaved", + "editor.disk.overwrite.confirm": "Overwrite", + "editor.disk.overwrite.question": "{name} was changed by another program since you opened it. Overwrite it with your text?", + "editor.disk.reload": "Reload (discard mine)", "editor.gitGutter.added": "Added since the staged version", "editor.gitGutter.deleted": "Lines deleted here since the staged version", "editor.gitGutter.modified": "Changed since the staged version", "editor.gitGutter.staged": "Staged change (click for the chunk)", - "editor.notice.changedOnDisk": "{name} changed on disk. Your unsaved changes are kept; saving overwrites the file.", - "editor.notice.removedOnDisk": "{name} was deleted on disk. Your text is kept; saving writes it again.", "editor.reveal.invalidParams": "editor.reveal needs a path (string), line and column (numbers)", "editor.reveal.openFailed": "could not open {path}", "editor.saveFailed": "save failed", @@ -282,6 +289,26 @@ "goto.placeholder.file": "File name or path", "goto.placeholder.symbol": "Function, method, property or constant; Class::member", "goto.switchHint": "Tab switches", + "history.diff.captionDisk": "{path}: on disk (left) and your unsaved text (right)", + "history.diff.captionEntry": "{path}: Local History of {time} (left) and the current text (right)", + "history.empty": "No Local History for this file yet. Lutra keeps a copy on every save and before reloads, refactorings and git operations.", + "history.invalidParams": "Show Local History takes { path?: string }.", + "history.listLabel": "Local History entries", + "history.loading": "Loading…", + "history.noFile": "Open or select a file to show its Local History.", + "history.reason.beforeReload": "Before reload from disk", + "history.reason.beforeRevert": "Before revert", + "history.reason.beforeSave": "Before first save", + "history.reason.deleted": "Deleted on disk", + "history.reason.externalChange": "Changed by another program", + "history.reason.git": "Before git operation", + "history.reason.refactoring": "Before refactoring", + "history.reason.save": "Saved", + "history.revert": "Revert to This", + "history.showDiff": "Show Diff", + "history.sizeBytes": "{size} B", + "history.sizeKib": "{size} KiB", + "history.title": "Local History of {name}", "menu.button": "Main menu", "menu.group.edit": "Edit", "menu.group.file": "File", @@ -319,6 +346,7 @@ "notification.deploy.uploadFailed": "Upload failed: {reason}", "notification.deploy.uploadOnSaveFailed": "Upload on save to {server} failed: {error}", "notification.deploy.uploaded": "Uploaded {files} to {server}.", + "notification.history.failed": "Local History: {reason}", "notification.lsp.failed": "The PHP language server stopped: {reason}. Run Restart PHP Language Server to try again.", "notification.lsp.message": "PHP language server: {message}", "notification.lsp.renamed": "Renamed to {name}: {edits} changes in {files} files ({written} closed files saved)", @@ -408,6 +436,7 @@ "project.tree.menu.open": "Open", "project.tree.menu.showDiff": "Show Diff", "project.tree.menu.showHistory": "Show History", + "project.tree.menu.showLocalHistory": "Show Local History", "project.tree.menu.upload": "Upload to Server", "project.tree.truncated": "Listing truncated: more entries than can be shown", "recovery.dialog.changedOnDisk": "The file changed on disk since then", diff --git a/ui/src/ipc.ts b/ui/src/ipc.ts index c33e301..f7161dd 100644 --- a/ui/src/ipc.ts +++ b/ui/src/ipc.ts @@ -26,6 +26,7 @@ export type EngineEventPayload = | { kind: "dirtyChanged"; id: number; dirty: boolean } | { kind: "bufferClosed"; id: number } | { kind: "fileChangedOnDisk"; path: string; id: number; removed: boolean } + | { kind: "diskConflictResolved"; id: number } | { kind: "watchFailed"; message: string } | { kind: "themeChanged"; id: string; dark: boolean; tokens: Record } | { diff --git a/ui/src/stores/diskConflicts.ts b/ui/src/stores/diskConflicts.ts new file mode 100644 index 0000000..0deaff9 --- /dev/null +++ b/ui/src/stores/diskConflicts.ts @@ -0,0 +1,271 @@ +/** + * Files changed on disk (C10 A2): the banner of an editor tab whose file + * another program changed or deleted while the buffer had unsaved changes, + * and the question before a save overwrites a newer file. + * + * - **Banner, changed:** "Reload (discard mine)" runs `file.reload` (the + * engine keeps the discarded text in the Local History); "Keep mine" + * hides the banner, and the next save asks once more because the engine + * refuses it with `disk_changed`; "Compare" opens the diff viewer with + * the disk text on the left and the buffer on the right. + * - **Banner, removed:** "Keep as unsaved" hides the banner (the engine + * already made the buffer dirty, so closing asks and saving writes the + * file again); "Close" closes the tab without saving. + * - **Clean buffers** never get a banner: the engine reloads them silently. + * - **Overwrite question:** {@link askOverwrite} queues it, from a save or + * save-all the engine refused with `disk_changed`. "Overwrite" repeats the + * save with `overwrite: true`; "Cancel" leaves the file alone. + * - **Events:** `fileChangedOnDisk` sets a tab's banner (again, if the file + * changes once more after "Keep mine"); `diskConflictResolved` and + * `bufferClosed` drop it; a project open or close drops everything. + * + * Command failures are stored in {@link error} and shown, never thrown. + * Tabs are reached only through the editor store's public API (`tabOf`, + * `reloadBuffer`, C10 A1); each editor pane shows the banner of its own + * active tab ({@link bannerOf}). + */ +import { defineStore } from "pinia"; +import { computed, ref } from "vue"; +import { run } from "../ipc"; +import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents"; +import { useDiffStore } from "../components/vcs/diff/diff"; +import { baseName, useEditorStore } from "./editor"; + +/** What happened to a tab's file. */ +export type DiskConflictKind = "changed" | "removed"; + +/** The disk conflict of one buffer. */ +export interface DiskConflict { + /** Buffer id. */ + id: number; + /** Project-relative path. */ + path: string; + /** Changed by another program, or gone. */ + kind: DiskConflictKind; + /** The user chose "Keep mine" / "Keep as unsaved": no banner. */ + kept: boolean; +} + +/** A pending overwrite question. */ +export interface OverwritePrompt { + /** Buffer id. */ + id: number; + /** File name, for the question. */ + name: string; +} + +/** Store of disk conflicts and overwrite questions. */ +export const useDiskConflictsStore = defineStore("diskConflicts", () => { + const editor = useEditorStore(); + + /** Conflicts by buffer id; replaced as a whole on every change. */ + const conflicts = ref>({}); + /** Overwrite questions, oldest first; the first one is shown. */ + const prompts = ref([]); + /** Last failed action, null if none. */ + const error = ref(null); + /** Whether an action is running. */ + const busy = ref(false); + /** Ends the event subscription; set while started. */ + let unsubscribe: (() => void) | null = null; + + /** The overwrite question shown now, or null. */ + const prompt = computed(() => prompts.value[0] ?? null); + + /** The banner of the active editor tab, or null. */ + const activeBanner = computed(() => bannerOf(editor.activeId)); + + /** + * Replaces or removes one conflict. + * + * @param id - buffer id. + * @param next - the new conflict, or null to drop it. + */ + function put(id: number, next: DiskConflict | null): void { + const rest = Object.fromEntries(Object.entries(conflicts.value).filter(([key]) => Number(key) !== id)); + conflicts.value = next ? { ...rest, [id]: next } : rest; + } + + /** + * The banner of a buffer: its conflict unless the user kept the text. + * + * @param id - buffer id, or null. + */ + function bannerOf(id: number | null): DiskConflict | null { + const conflict = id === null ? undefined : conflicts.value[id]; + return conflict && !conflict.kept ? conflict : null; + } + + /** + * The conflict of a buffer. + * + * @param id - buffer id. + */ + function conflictOf(id: number): DiskConflict | null { + return conflicts.value[id] ?? null; + } + + /** + * Hides a buffer's banner ("Keep mine", "Keep as unsaved"). + * + * @param id - buffer id. + */ + function keep(id: number): void { + const conflict = conflicts.value[id]; + if (conflict) { + put(id, { ...conflict, kept: true }); + } + } + + /** + * "Reload (discard mine)": the buffer takes the file's text. + * + * @param id - buffer id. + */ + async function reload(id: number): Promise { + busy.value = true; + await editor.settleAll(); + const result = await run("file.reload", { id }); + busy.value = false; + if (result.ok) { + error.value = null; + put(id, null); + editor.reloadBuffer(id); + } else { + error.value = result.error.message; + } + } + + /** + * "Compare": the disk text against the buffer in the diff viewer. + * + * @param id - buffer id. + */ + async function compare(id: number): Promise { + const conflict = conflicts.value[id]; + if (conflict) { + await useDiffStore().openDisk(conflict.path); + } + } + + /** + * "Close": closes the tab without saving (the engine keeps the text in + * the Local History). + * + * @param id - buffer id. + */ + async function closeTab(id: number): Promise { + const result = await run("buffer.close", { id, force: true }); + if (result.ok) { + error.value = null; + put(id, null); + } else { + error.value = result.error.message; + } + } + + /** + * Queues the question whether to overwrite a newer file. + * + * @param id - buffer id whose save the engine refused with `disk_changed`. + */ + function askOverwrite(id: number): void { + if (prompts.value.some((p) => p.id === id)) { + return; + } + const tab = editor.tabOf(id); + const name = tab?.name ?? baseName(conflicts.value[id]?.path ?? String(id)); + prompts.value = [...prompts.value, { id, name }]; + } + + /** + * Answers the shown overwrite question. + * + * @param overwrite - write the buffer over the newer file, or leave it. + */ + async function resolveOverwrite(overwrite: boolean): Promise { + const current = prompts.value[0]; + if (!current) { + return; + } + prompts.value = prompts.value.slice(1); + if (!overwrite) { + return; + } + busy.value = true; + await editor.settleAll(); + const result = await run("file.save", { id: current.id, overwrite: true }); + busy.value = false; + if (result.ok) { + error.value = null; + put(current.id, null); + } else { + error.value = result.error.message; + } + } + + /** Drops every conflict and question. */ + function clear(): void { + conflicts.value = {}; + prompts.value = []; + error.value = null; + } + + /** + * Applies one editor event. + * + * @param event - the event. + */ + function handleEvent(event: EditorEvent): void { + switch (event.kind) { + case "projectOpened": + case "projectClosed": + clear(); + break; + case "fileChangedOnDisk": + put(event.id, { id: event.id, path: event.path, kind: event.removed ? "removed" : "changed", kept: false }); + break; + case "diskConflictResolved": + put(event.id, null); + break; + case "bufferClosed": + put(event.id, null); + prompts.value = prompts.value.filter((p) => p.id !== event.id); + break; + default: + break; + } + } + + /** Subscribes to engine events; calling it again has no effect. */ + function start(): void { + unsubscribe ??= onEditorEvent(handleEvent); + } + + /** Ends the subscription. */ + function stop(): void { + unsubscribe?.(); + unsubscribe = null; + } + + return { + conflicts, + prompts, + prompt, + error, + busy, + activeBanner, + bannerOf, + conflictOf, + keep, + reload, + compare, + closeTab, + askOverwrite, + resolveOverwrite, + clear, + handleEvent, + start, + stop, + }; +}); diff --git a/ui/src/stores/editor.ts b/ui/src/stores/editor.ts index e300a12..e26f63b 100644 --- a/ui/src/stores/editor.ts +++ b/ui/src/stores/editor.ts @@ -5,8 +5,10 @@ * Cancel question when tabs with unsaved changes close. * * Fed by engine events (`bufferOpened`, `bufferFocused`, `bufferChanged`, `dirtyChanged`, - * `bufferClosed`, `fileChangedOnDisk`, project open/close) and by command - * results. Text lives in the engine and in one {@link BufferSync} per + * `bufferClosed`, project open/close) and by command results. Files changed + * on disk are the disk-conflict store's (`diskConflicts.ts`, C10 A2): a save + * the engine refuses with `disk_changed` hands over to its overwrite + * question. Text lives in the engine and in one {@link BufferSync} per * buffer, kept outside reactive state; a buffer shown in both groups has * one sync, so both share the text and the undo history. Command failures * are stored and shown, never thrown. @@ -29,6 +31,7 @@ import { run, type EngineError, type RunResult } from "../ipc"; import { BufferSync, isBufferInfo, engineTransport, type BufferInfo, type SyncTransport } from "../components/editor/bufferSync"; import { onEditorEvent, type EditorEvent } from "../components/editor/engineEvents"; import { editorExtensions } from "../components/editor/extensions"; +import { useDiskConflictsStore } from "./diskConflicts"; import type { AssistBuffer } from "../components/editor/assist"; import * as model from "../components/editor/tabs/model"; import type { CloseAction, ClosedTab, SplitOrientation, TabLayout } from "../components/editor/tabs/model"; @@ -761,6 +764,11 @@ export const useEditorStore = defineStore("editor", () => { } await settled(id); const result = await run(EDITOR_COMMANDS.save, { id }); + if (!result.ok && result.error.code === "disk_changed") { + lastError.value = null; + useDiskConflictsStore().askOverwrite(id); + return false; + } lastError.value = result.ok ? null : result.error; if (result.ok) { const tab = tabOf(id); @@ -777,13 +785,19 @@ export const useEditorStore = defineStore("editor", () => { /** Saves every buffer after all local edits reached the engine. */ async function saveAll(): Promise { await Promise.all(records.value.map((t) => settled(t.id))); - const result = await run<{ failed?: { id?: unknown; message?: unknown }[] }>( + const result = await run<{ failed?: { id?: unknown; message?: unknown }[]; diskChanged?: unknown }>( EDITOR_COMMANDS.saveAll, ); if (!result.ok) { lastError.value = result.error; return; } + const diskChanged = Array.isArray(result.value.diskChanged) ? result.value.diskChanged : []; + for (const id of diskChanged) { + if (typeof id === "number") { + useDiskConflictsStore().askOverwrite(id); + } + } const failed = Array.isArray(result.value.failed) ? result.value.failed : []; lastError.value = failed.length > 0 @@ -1099,24 +1113,9 @@ export const useEditorStore = defineStore("editor", () => { removeTab(event.id); } break; - case "fileChangedOnDisk": { - const tab = tabOf(event.id); - if (!tab) { - break; - } - if (event.removed) { - tab.notice = { - kind: "removedOnDisk", - message: t("editor.notice.removedOnDisk", { name: tab.name }), - }; - } else { - tab.notice = { - kind: "changedOnDisk", - message: t("editor.notice.changedOnDisk", { name: tab.name }), - }; - } + case "fileChangedOnDisk": + case "diskConflictResolved": break; - } } } diff --git a/ui/tests/editor/EditorArea.test.ts b/ui/tests/editor/EditorArea.test.ts index 4cf406a..5899501 100644 --- a/ui/tests/editor/EditorArea.test.ts +++ b/ui/tests/editor/EditorArea.test.ts @@ -4,7 +4,7 @@ * `buffer.edit`, the dirty marker, closing (middle click, shortcut, the * Save / Don't Save / Cancel question), saving through the global keymap * (`commands/store.ts`) with shortcuts loaded from the engine's command - * list, the notice for files changed on disk, and the UI command + * list, the banner for files changed on disk, and the UI command * `editor.reveal` (open and closed files, CRLF text, bad params). * The engine is a fake behind the mocked Tauri `invoke`. */ @@ -482,16 +482,16 @@ describe("EditorArea", () => { expect(editor.activeId).toBe(1); }); - it("shows a notice when a dirty file changes on disk, and an open error", async () => { + it("shows the disk banner when a dirty file changes on disk, and an open error", async () => { const area = await mountArea(); const editor = useEditorStore(pinia); await editor.openFile("a.php"); await flushPromises(); emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "a.php", removed: false }); await flushPromises(); - expect(area.find("[data-test=editor-notice]").text()).toContain("changed on disk"); - await area.find("[data-test=notice-dismiss]").trigger("click"); - expect(area.find("[data-test=editor-notice]").exists()).toBe(false); + expect(area.find("[data-test=disk-banner]").text()).toContain("changed by another program"); + await area.find("[data-test=disk-keep]").trigger("click"); + expect(area.find("[data-test=disk-banner]").exists()).toBe(false); await editor.openFile("missing.php"); await flushPromises(); diff --git a/ui/tests/editor/diskConflicts.test.ts b/ui/tests/editor/diskConflicts.test.ts new file mode 100644 index 0000000..77533c0 --- /dev/null +++ b/ui/tests/editor/diskConflicts.test.ts @@ -0,0 +1,225 @@ +/** + * Tests for files changed on disk (C10 A2) in the editor area: the banner + * for a changed and a deleted file and its actions (Reload, Keep mine, + * Compare, Keep as unsaved, Close), the overwrite question after the + * engine refuses a save with `disk_changed`, and the diff tab against the + * disk. The engine is a fake behind the mocked Tauri `invoke`. + */ +import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; +import { createPinia, setActivePinia, type Pinia } from "pinia"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); + +import { useCommandsStore } from "../../src/commands/store"; +import EditorArea from "../../src/components/editor/EditorArea.vue"; +import { emitEditorEvent } from "../../src/components/editor/engineEvents"; +import { useDiffStore } from "../../src/components/vcs/diff/diff"; +import { useDiskConflictsStore } from "../../src/stores/diskConflicts"; +import { useEditorStore } from "../../src/stores/editor"; + +/** Every `engine_execute` call, in order. */ +let calls: { command: string; params: Record }[]; +/** The text the fake buffer holds. */ +let bufferText: string; +/** The text on the fake disk. */ +let diskText: string; +/** Whether the next plain `file.save` is refused with `disk_changed`. */ +let newerOnDisk: boolean; +/** Pinia of the current test. */ +let pinia: Pinia; +/** Mounted components. */ +let mounted: VueWrapper[] = []; + +/** The buffer as `file.open` and `buffer.get` describe it. */ +function info(): unknown { + return { id: 1, path: "src/a.php", text: bufferText, version: 1, dirty: true, lineEnding: "lf" }; +} + +/** + * Rejects like the shell does with an engine error. + * + * @param code - error code. + */ +function fail(code: string): Promise { + return Promise.reject(Object.assign(new Error(code), { code, message: `${code} message` })); +} + +/** + * The fake engine. + * + * @param command - command id. + * @param p - params. + */ +function execute(command: string, p: Record): Promise { + switch (command) { + case "file.open": + case "buffer.get": + return Promise.resolve(info()); + case "file.save": + if (newerOnDisk && p.overwrite !== true) { + return fail("disk_changed"); + } + diskText = bufferText; + return Promise.resolve({ id: 1, version: 1 }); + case "file.saveAll": + return Promise.resolve({ saved: [], failed: [], skipped: [], diskChanged: newerOnDisk ? [1] : [] }); + case "file.reload": + bufferText = diskText; + emitEditorEvent({ kind: "diskConflictResolved", id: 1 }); + return Promise.resolve({ id: 1, version: 2, dirty: false }); + case "file.readDisk": + return Promise.resolve({ text: diskText, binary: false, tooLarge: false }); + case "buffer.close": + emitEditorEvent({ kind: "bufferClosed", id: 1 }); + return Promise.resolve(null); + default: + return Promise.resolve(null); + } +} + +/** Mounts the editor area with `src/a.php` open. */ +async function mountWithFile(): Promise { + await useCommandsStore(pinia).start(); + const wrapper = mount(EditorArea, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(wrapper); + await useEditorStore(pinia).openFile("src/a.php"); + await flushPromises(); + return wrapper; +} + +/** + * The commands the fake engine received, without reads. + */ +function commandsRun(): string[] { + return calls.map((c) => c.command).filter((c) => c !== "buffer.get" && c !== "file.open"); +} + +beforeEach(() => { + pinia = createPinia(); + setActivePinia(pinia); + calls = []; + bufferText = "mine"; + diskText = "theirs"; + newerOnDisk = false; + invoke.mockReset(); + invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { + if (cmd === "engine_list_commands") { + return Promise.resolve([]); + } + if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) { + calls.push({ command: args.command, params: args.params }); + return execute(args.command, args.params); + } + return Promise.reject(new Error(`unexpected ${cmd}`)); + }); +}); + +afterEach(async () => { + await flushPromises(); + useCommandsStore(pinia).stop(); + for (const wrapper of mounted) { + wrapper.unmount(); + } + mounted = []; +}); + +describe("files changed on disk", () => { + it("offers Reload, Keep mine and Compare for a changed file", async () => { + const area = await mountWithFile(); + emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false }); + await flushPromises(); + const banner = area.find("[data-test=disk-banner]"); + expect(banner.attributes("data-kind")).toBe("changed"); + expect(banner.text()).toContain("a.php was changed by another program"); + expect(banner.findAll("button").map((b) => b.text())).toEqual(["Reload (discard mine)", "Keep mine", "Compare"]); + + await area.find("[data-test=disk-reload]").trigger("click"); + await flushPromises(); + expect(commandsRun()).toContain("file.reload"); + expect(area.find("[data-test=disk-banner]").exists()).toBe(false); + }); + + it("compares the disk text with the buffer in a diff tab", async () => { + const area = await mountWithFile(); + emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false }); + await flushPromises(); + await area.find("[data-test=disk-compare]").trigger("click"); + await flushPromises(); + const diff = useDiffStore(pinia); + expect(diff.activeTab?.key).toBe("disk:src/a.php"); + expect(diff.activeContent?.phase).toBe("ready"); + expect(diff.activeContent?.left).toBe("theirs"); + expect(diff.activeContent?.bufferId).toBe(1); + expect(calls.find((c) => c.command === "file.readDisk")?.params).toEqual({ path: "src/a.php" }); + }); + + it("asks once more when a kept buffer is saved over the newer file", async () => { + const area = await mountWithFile(); + const editor = useEditorStore(pinia); + emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false }); + await flushPromises(); + await area.find("[data-test=disk-keep]").trigger("click"); + expect(area.find("[data-test=disk-banner]").exists()).toBe(false); + + newerOnDisk = true; + expect(await editor.save(1)).toBe(false); + await flushPromises(); + expect(editor.lastError).toBeNull(); + const prompt = area.find("[data-test=overwrite-prompt]"); + expect(prompt.text()).toContain("a.php was changed by another program"); + expect(document.activeElement?.getAttribute("data-test")).toBe("overwrite-cancel"); + + await area.find("[data-test=overwrite-cancel]").trigger("click"); + await flushPromises(); + expect(diskText).toBe("theirs"); + expect(area.find("[data-test=overwrite-prompt]").exists()).toBe(false); + + await editor.save(1); + await flushPromises(); + await area.find("[data-test=overwrite-confirm]").trigger("click"); + await flushPromises(); + expect(calls.filter((c) => c.command === "file.save").map((c) => c.params)).toEqual([ + { id: 1 }, + { id: 1 }, + { id: 1, overwrite: true }, + ]); + expect(diskText).toBe("mine"); + }); + + it("asks for buffers that save all left unsaved because their file is newer", async () => { + const area = await mountWithFile(); + newerOnDisk = true; + await useEditorStore(pinia).saveAll(); + await flushPromises(); + expect(area.find("[data-test=overwrite-prompt]").exists()).toBe(true); + expect(useDiskConflictsStore(pinia).prompts).toHaveLength(1); + }); + + it("offers Keep as unsaved and Close for a deleted file", async () => { + const area = await mountWithFile(); + emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: true }); + await flushPromises(); + const banner = area.find("[data-test=disk-banner]"); + expect(banner.attributes("data-kind")).toBe("removed"); + expect(banner.findAll("button").map((b) => b.text())).toEqual(["Keep as unsaved", "Close"]); + await area.find("[data-test=disk-close]").trigger("click"); + await flushPromises(); + expect(calls.find((c) => c.command === "buffer.close")?.params).toEqual({ id: 1, force: true }); + expect(useEditorStore(pinia).tabs).toEqual([]); + }); + + it("drops the banner when the engine settles the conflict", async () => { + const area = await mountWithFile(); + emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: true }); + await flushPromises(); + await area.find("[data-test=disk-keep]").trigger("click"); + emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "src/a.php", removed: false }); + await flushPromises(); + expect(area.find("[data-test=disk-banner]").attributes("data-kind")).toBe("changed"); + emitEditorEvent({ kind: "diskConflictResolved", id: 1 }); + await flushPromises(); + expect(area.find("[data-test=disk-banner]").exists()).toBe(false); + }); +}); diff --git a/ui/tests/history/LocalHistory.test.ts b/ui/tests/history/LocalHistory.test.ts new file mode 100644 index 0000000..ea5d8d3 --- /dev/null +++ b/ui/tests/history/LocalHistory.test.ts @@ -0,0 +1,220 @@ +/** + * Tests for the Local History dialog (C10 A2): `history.show` from the + * palette (active tab) and with a path, the list with time and reason, + * keyboard selection, Show Diff (a diff tab of the entry against the + * buffer), Revert to This (`history.revert`, undoable in the editor), the + * empty and failed states, and the checks of untrusted input. The engine + * is a fake behind the mocked Tauri `invoke`. + */ +import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; +import { EditorView } from "@codemirror/view"; +import { createPinia, setActivePinia, type Pinia } from "pinia"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const invoke = vi.hoisted(() => vi.fn()); +vi.mock("@tauri-apps/api/core", () => ({ invoke })); + +import { useCommandsStore } from "../../src/commands/store"; +import EditorArea from "../../src/components/editor/EditorArea.vue"; +import { emitEditorEvent } from "../../src/components/editor/engineEvents"; +import LocalHistoryDialog from "../../src/components/history/LocalHistoryDialog.vue"; +import { parseShowParams, toEntries, useLocalHistoryStore } from "../../src/components/history/localHistory"; +import { useDiffStore } from "../../src/components/vcs/diff/diff"; +import { useEditorStore } from "../../src/stores/editor"; + +/** Every `engine_execute` call, in order. */ +let calls: { command: string; params: Record }[]; +/** The fake buffer. */ +let buffer: { text: string; version: number }; +/** Entries `history.list` returns. */ +let listed: unknown; +/** Pinia of the current test. */ +let pinia: Pinia; +/** Mounted components. */ +let mounted: VueWrapper[] = []; + +/** Snapshot texts by id. */ +const TEXTS: Record = { 2: "second", 1: "first" }; + +/** 2026-11-08 10:15 and 09:00 local time. */ +const T2 = new Date(2026, 10, 8, 10, 15).getTime(); +const T1 = new Date(2026, 10, 8, 9, 0).getTime(); + +/** + * The fake engine. + * + * @param command - command id. + * @param p - params. + */ +function execute(command: string, p: Record): Promise { + const describe = { id: 1, path: "src/a.php", text: buffer.text, version: buffer.version, dirty: false, lineEnding: "lf" }; + switch (command) { + case "file.open": + case "buffer.get": + return Promise.resolve(describe); + case "buffer.edit": { + let out = ""; + let pos = 0; + for (const e of p.edits as { from: number; to: number; insert: string }[]) { + out += buffer.text.slice(pos, e.from) + e.insert; + pos = e.to; + } + buffer.text = out + buffer.text.slice(pos); + buffer.version += 1; + return Promise.resolve({ id: 1, version: buffer.version, dirty: true }); + } + case "history.list": + return Promise.resolve(listed); + case "history.read": + return Promise.resolve({ text: TEXTS[Number(p.id)] ?? "", binary: false, tooLarge: false }); + case "history.revert": + buffer.text = TEXTS[Number(p.id)] ?? ""; + buffer.version += 1; + emitEditorEvent({ kind: "bufferChanged", id: 1, version: buffer.version }); + return Promise.resolve({ id: 1, version: buffer.version, dirty: true }); + default: + return Promise.resolve(null); + } +} + +/** Mounts the editor area (with `src/a.php` open) and the dialog. */ +async function mountAll(): Promise<{ area: VueWrapper; dialog: VueWrapper }> { + await useCommandsStore(pinia).start(); + const area = mount(EditorArea, { attachTo: document.body, global: { plugins: [pinia] } }); + const dialog = mount(LocalHistoryDialog, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(area, dialog); + await useEditorStore(pinia).openFile("src/a.php"); + await flushPromises(); + return { area, dialog }; +} + +beforeEach(() => { + pinia = createPinia(); + setActivePinia(pinia); + calls = []; + buffer = { text: "current", version: 1 }; + listed = { + path: "src/a.php", + entries: [ + { id: 2, time: T2, reason: "save", size: 6 }, + { id: 1, time: T1, reason: "externalChange", size: 2048 }, + ], + }; + invoke.mockReset(); + invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { + if (cmd === "engine_list_commands") { + return Promise.resolve([ + { id: "history.list", label: "List", menuPath: null, defaultShortcut: null, params: "", enabled: true }, + ]); + } + if ((cmd === "engine_execute" || cmd === "engine_execute_waiting") && args) { + calls.push({ command: args.command, params: args.params }); + return execute(args.command, args.params); + } + return Promise.reject(new Error(`unexpected ${cmd}`)); + }); +}); + +afterEach(async () => { + await flushPromises(); + useCommandsStore(pinia).stop(); + for (const wrapper of mounted) { + wrapper.unmount(); + } + mounted = []; +}); + +describe("Local History dialog", () => { + it("lists the active tab's entries with time, reason and size", async () => { + const { dialog } = await mountAll(); + await useCommandsStore(pinia).execute("history.show", {}); + await flushPromises(); + expect(calls.find((c) => c.command === "history.list")?.params).toEqual({ path: "src/a.php" }); + expect(dialog.find("#lt-history-title").text()).toBe("Local History of a.php"); + const rows = dialog.findAll("[data-test=history-row]"); + expect(rows.map((r) => r.text())).toEqual([ + "2026-11-08 10:15Saved6 B", + "2026-11-08 09:00Changed by another program2 KiB", + ]); + expect(document.activeElement?.getAttribute("data-test")).toBe("history-list"); + await dialog.find("[data-test=history-list]").trigger("keydown", { key: "ArrowDown" }); + expect(useLocalHistoryStore(pinia).current?.id).toBe(1); + }); + + it("opens an entry against the buffer in a diff tab", async () => { + const { dialog } = await mountAll(); + await useCommandsStore(pinia).execute("history.show", { path: "src/a.php" }); + await flushPromises(); + await dialog.find("[data-test=history-list]").trigger("keydown", { key: "Enter" }); + await flushPromises(); + expect(dialog.find("[data-test=local-history]").exists()).toBe(false); + const diff = useDiffStore(pinia); + expect(diff.activeTab?.key).toBe("history:2:src/a.php"); + expect(diff.activeContent?.left).toBe("second"); + expect(calls.find((c) => c.command === "history.read")?.params).toEqual({ path: "src/a.php", id: 2 }); + }); + + it("reverts through the engine, undoably in the editor", async () => { + const { area, dialog } = await mountAll(); + await useCommandsStore(pinia).execute("history.show", {}); + await flushPromises(); + await dialog.findAll("[data-test=history-row]")[1]?.trigger("click"); + await dialog.find("[data-test=history-revert]").trigger("click"); + await flushPromises(); + expect(calls.find((c) => c.command === "history.revert")?.params).toEqual({ path: "src/a.php", id: 1 }); + expect(dialog.find("[data-test=local-history]").exists()).toBe(false); + const view = EditorView.findFromDOM(area.find(".cm-editor").element as HTMLElement); + expect(view?.state.doc.toString()).toBe("first"); + view?.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: "z", ctrlKey: true, bubbles: true, cancelable: true })); + await flushPromises(); + expect(view?.state.doc.toString()).toBe("current"); + }); + + it("says when there are no entries or the list failed", async () => { + const { dialog } = await mountAll(); + listed = { path: "src/a.php", entries: [] }; + await useLocalHistoryStore(pinia).show("src/a.php"); + await flushPromises(); + expect(dialog.find("[data-test=history-hint]").text()).toContain("No Local History"); + expect(dialog.find("[data-test=history-diff]").attributes("disabled")).toBeDefined(); + listed = { nope: true }; + await useLocalHistoryStore(pinia).show("src/a.php"); + await flushPromises(); + expect(dialog.find("[data-test=history-error]").text()).toContain("history.list"); + await dialog.find("[data-test=history-cancel]").trigger("click"); + expect(dialog.find("[data-test=local-history]").exists()).toBe(false); + }); + + it("refuses bad params and runs without a file", async () => { + await mountAll(); + const history = useLocalHistoryStore(pinia); + await expect(history.showCommand({ path: 3 })).rejects.toThrow("Show Local History takes"); + useEditorStore(pinia).activeId = null; + await expect(history.showCommand({})).rejects.toThrow("Open or select a file"); + }); +}); + +describe("untrusted input", () => { + it("checks list entries field by field", () => { + expect(toEntries(null)).toBeNull(); + expect(toEntries({ entries: "x" })).toBeNull(); + expect( + toEntries({ + entries: [ + { id: 1, time: 2, reason: "save", size: 3 }, + { id: "1", time: 2, reason: "save", size: 3 }, + { id: 2, time: 2, reason: "unknown", size: 3 }, + null, + ], + }), + ).toEqual([{ id: 1, time: 2, reason: "save", size: 3 }]); + }); + + it("reads the params of history.show", () => { + expect(parseShowParams(null)).toBe(""); + expect(parseShowParams({})).toBe(""); + expect(parseShowParams({ path: "a.php" })).toBe("a.php"); + expect(parseShowParams({ path: "" })).toBeNull(); + expect(parseShowParams([])).toBeNull(); + }); +}); diff --git a/ui/tests/i18n/catalog.test.ts b/ui/tests/i18n/catalog.test.ts index ff482bc..c879589 100644 --- a/ui/tests/i18n/catalog.test.ts +++ b/ui/tests/i18n/catalog.test.ts @@ -178,7 +178,7 @@ describe("en.json", () => { it("uses flat dotted keys of known areas with string values", () => { for (const [key, value] of Object.entries(en)) { expect(key).toMatch( - /^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal|problems|nav|vcs|deploy)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/, + /^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu|terminal|problems|nav|vcs|deploy|history)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/, ); expect(typeof value).toBe("string"); expect(value.trim()).not.toBe(""); diff --git a/ui/tests/menu/AppMenu.test.ts b/ui/tests/menu/AppMenu.test.ts index 73bb32b..18eb7aa 100644 --- a/ui/tests/menu/AppMenu.test.ts +++ b/ui/tests/menu/AppMenu.test.ts @@ -272,6 +272,7 @@ describe("AppMenu", () => { "project.openDialog", "file.save", "file.saveAll", + "history.show", "buffer.close", "project.close", "app.quit", diff --git a/ui/tests/vcs/DiffView.test.ts b/ui/tests/vcs/DiffView.test.ts index 777f0e1..ddae97e 100644 --- a/ui/tests/vcs/DiffView.test.ts +++ b/ui/tests/vcs/DiffView.test.ts @@ -475,7 +475,7 @@ describe("project tree context menu", () => { await tree.find("[data-path='a.php']").trigger("contextmenu", { clientX: 40, clientY: 50 }); const menu = document.querySelector("[data-test=tree-menu]"); expect(menu).not.toBeNull(); - expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Upload to Server", "Compare with Server", "Download from Server"]); + expect([...document.querySelectorAll("[data-test=tree-menu-item]")].map((item) => item.textContent.trim())).toEqual(["Open", "Show Diff", "Show History", "Show Local History", "Upload to Server", "Compare with Server", "Download from Server"]); (document.querySelector("[data-item=showDiff]") as HTMLElement).click(); await flushPromises(); await flushPromises();