M4.2: Changes tool window with staging and commit

A Changes tab in the bottom panel (ui/src/components/vcs/changes/): the
project's changed files from git.status in Staged, Changes and Untracked
groups, re-read on start, project open, gitChanged and vcs.refresh
(serialised). A checkbox per file and per group stages or unstages through
git.stage / git.unstage (a staged rename passes both paths); Space stages,
Enter or a double-click runs vcs.showDiff when provided, else opens the
file. A message box with Amend and Commit (also Mod+Enter) runs flushDirty()
first, cancels when a save fails, then git.commit and toasts the short hash.
All git calls go through runWaiting.

UI commands vcs.openChanges (Mod+Alt+G), vcs.commit (Mod+K, focuses the
message box) and vcs.refresh in a new Git menu group; gitChanged added to
EngineEventPayload. 19 Vitest tests; palette, menu and catalog tests follow
the new commands. Docs: architecture, gaps G8, Git parity row 4% (est.),
ui/tooling checklists, roadmap M4 row, ROADMAP depth ~5.4% and log, README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-25 17:17:39 +01:00
parent 8701f50d37
commit f67f6b9f7c
18 changed files with 1792 additions and 23 deletions

View file

@ -64,7 +64,7 @@ claude mcp add lutra -- lutra mcp
## Status
**Pre-alpha (2026-10-22): M3 done, the MVP is feature-complete.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs with syntax highlighting for PHP (and HTML, CSS, JS/TS, JSON, YAML, Markdown), with every command in a palette (`Mod+Shift+P`) and settings and the light or dark theme in a settings dialog (`Mod+,`); unsaved text survives a crash and is offered back on the next open; M2 added find in files (`Mod+Alt+F`) and go to file, class or symbol (`Mod+P`, `Mod+Alt+C`, `Mod+T`); M3 added an integrated terminal (`Mod+Shift+T`) and PHP language features from Phpactor: errors underlined as you type (Problems tab `Mod+Alt+P`), code completion, documentation on hover and parameter info, go to definition (`F12` or Ctrl+click), find references (`Shift+F12`) and rename (`F2`), plus the `lutra` CLI, an MCP server (`lutra mcp`), an app menu and autosave. Git (M4) comes next on the way to alpha. [**ROADMAP.md**](ROADMAP.md) has the stage and what's next,
**Pre-alpha (2026-10-22): M3 done, the MVP is feature-complete.** You can open a folder, browse it in the project tree with live updates from disk, and edit and save files in tabs with syntax highlighting for PHP (and HTML, CSS, JS/TS, JSON, YAML, Markdown), with every command in a palette (`Mod+Shift+P`) and settings and the light or dark theme in a settings dialog (`Mod+,`); unsaved text survives a crash and is offered back on the next open; M2 added find in files (`Mod+Alt+F`) and go to file, class or symbol (`Mod+P`, `Mod+Alt+C`, `Mod+T`); M3 added an integrated terminal (`Mod+Shift+T`) and PHP language features from Phpactor: errors underlined as you type (Problems tab `Mod+Alt+P`), code completion, documentation on hover and parameter info, go to definition (`F12` or Ctrl+click), find references (`Shift+F12`) and rename (`F2`), plus the `lutra` CLI, an MCP server (`lutra mcp`), an app menu and autosave. Git (M4) has started: a Changes tab (`Mod+Alt+G`) stages files and commits them, on the way to alpha. [**ROADMAP.md**](ROADMAP.md) has the stage and what's next,
[`docs/target-app-parity.md`](docs/target-app-parity.md) the parity assessment and [`docs/gaps.md`](docs/gaps.md) the ranked work list.
**First target (MVP, M1–M3):** open a project, project tree, tabs, editor with highlighting, find in files,

View file

@ -2,7 +2,7 @@
**Stage: pre-alpha (M3 done: MVP feature-complete)** · next: hardening and Git (M4); alpha when the six core workflows work end to end (see [docs/roadmap.md › Alpha gate](docs/roadmap.md#alpha-gate))
> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-10-22 · **Change:** minor (C4 review: M3 done, breadth recounted, factor 0.17) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-10-25 · **Change:** minor (M4.2: Changes tool window, Git 4%) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only
Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue interface, targeting the PhpStorm workflow. Agents can drive all of it over MCP, the `lutra` CLI and a JSON control channel. This page is the summary; the evidence is in [`docs/target-app-parity.md`](docs/target-app-parity.md) and the work list in [`docs/gaps.md`](docs/gaps.md).
@ -13,7 +13,7 @@ Lutra is a clean-room, open-source PHP IDE with a Rust core and a Tauri + Vue in
| | Value | Kind |
|---|---|---|
| **Feature breadth** (PhpStorm's actions, tool windows, languages, integrations exist) | **~21%** (32 of 155 feature units of the public PhpStorm help have at least partial support) | estimated |
| **Feature depth** (weighted by use, scored by behaviour) | **~5.1%** (Editor core 11% × weight 12, Navigation 13% × weight 10, Code completion 5% × weight 10, Inspections 4% × weight 8, Refactoring 3% × weight 7, Project view 8% × weight 6, Search and replace 8% × weight 6, Terminal 15% × weight 3, Settings 7% × weight 1, of 101) | estimated |
| **Feature depth** (weighted by use, scored by behaviour) | **~5.4%** (Editor core 11% × weight 12, Navigation 13% × weight 10, Code completion 5% × weight 10, Inspections 4% × weight 8, Refactoring 3% × weight 7, Project view 8% × weight 6, Search and replace 8% × weight 6, Terminal 15% × weight 3, Git 4% × weight 8, Settings 7% × weight 1, of 101) | estimated |
| **MVP (M1–M3)** | **done** in ~26 h of agent time (M1 ~5.6 h, M2 ~6.1 h, M3 ~14 h, measured); was ~190 h before calibration | measured (factor per cycle: C1 0.07, C2 0.10, C3 0.14, C4 0.17) |
| **To full parity** | **~520 h** at the current factor of ~0.18 (range 300–3,300 h; the factor has risen each cycle, and deep areas such as type inference and inspections have no data yet) | estimated |
@ -49,7 +49,7 @@ Stability 8%: no-panic lints, the engine guard, a fuzzed control protocol and a
| Inspections and quick-fixes | 4% (est.) | ~290 |
| Refactoring | 3% (est.) | ~244 |
| Code style and formatting | 0% | ~120 |
| Version control (Git) | 0% | ~150 |
| Version control (Git) | 4% (est.) | ~138 |
| Terminal | 15% (est.) | ~26 |
| Run configurations | 0% | ~50 |
| Debugger (Xdebug) | 0% | ~120 |
@ -75,6 +75,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | What landed |
|---|---|
| 2026-10-25 | M4.2: a Changes tab for Git (`Mod+Alt+G`, menu Git › Changes) lists staged, changed and untracked files. Tick a file or a whole group to stage it, untick to unstage, write a message and press Commit (or Ctrl+Enter); Amend rewrites the last commit. Lutra saves your open files first, and the toast shows the new commit's short hash. Double-click opens the file (the diff viewer follows). |
| 2026-10-22 | M3.4: PHP code completes as you type. After `->`, `::`, `$` or a few letters Lutra shows Phpactor's suggestions with an icon per kind, and accepting one also adds its import. Resting the mouse on a class or method shows its documentation (`Mod+I` at the cursor), and typing `(` or `,` shows the parameters with the current one highlighted. A suggestion takes about 60–110 ms on Windows. |
| 2026-10-22 | M3.5: Jump to where a class or method is defined with F12 or Ctrl+click (a list when there are several), list every use of it with Shift+F12 in a References tab grouped by file, and rename it everywhere with F2: type the new name in a small field over the old one, which shows how many uses in how many files will change. Open files are changed but not saved, so Ctrl+Z takes it back; files that are not open are saved directly. |
| 2026-10-21 | M3.3: PHP errors show up while you type. Lutra starts Phpactor for the open project. Problems such as calling a method that does not exist or using an unknown class get a wavy underline, a dot in the gutter and their message on hover, and `Mod+Alt+P` opens a Problems tab that lists them by file; click one to jump there. |
@ -101,6 +102,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a
| Date | Change | Summary |
|---|---|---|
| 2026-10-25 | minor | M4.2: Changes tool window; Git 0% → 4% (est.), feature depth ~5.1% → ~5.4%, progress log |
| 2026-10-22 | minor | C4 review: M3 done (MVP feature-complete, ~14 h measured), breadth recounted 28 → 32 units (~21%), factor 0.17, full parity ~520 h at ×0.18 |
| 2026-10-22 | minor | M3.4: Code completion 0% → 5% (est.), feature depth ~4.1% → ~4.6%, breadth 24 → 26 units |
| 2026-10-22 | minor | M3.5: Navigation 10% → 13% (est.), Refactoring 0% → 3% (est.), feature depth ~4.6% → ~5.1%, breadth 26 → 28 units |

View file

@ -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); Git backend (M4.1) · **Last updated:** 2026-10-25
> **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); Git backend (M4.1), Changes tool window (M4.2) · **Last updated:** 2026-10-25
## Overview
@ -573,6 +573,18 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- A generated repository with 20,000 committed PHP files, 5 modified and 1 untracked: first `git.status` 1.5 s (cold file cache), then 90–98 ms.
- **Tests:** `crates/vcs/tests/repo.rs` (13 tests against real temp repositories: initial repository without HEAD, stage/unstage/commit, amend, modified/deleted/renamed, CRLF with `core.autocrlf`, Unicode and space paths, literal pathspecs and a non-UTF-8 name on Unix, detached HEAD, branches, remote tracking checkout from a clone, a refused checkout, a file over the cap, binary, BOM and Latin-1 files, a failing pre-commit hook, nothing staged, a project inside a repository, the watch); unit and property tests of the parsers; `crates/engine/tests/git.rs` (4 tests through `run_waiting`: the command shapes, `gitChanged` after changes and from outside changes, no repository, a missing git, no project). Tests skip with a message when git is not installed.
### Changes tool window (M4.2)
- **Where:** a Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): `changes.ts` is the Pinia store, `ChangesToolWindow.vue` the window. The main layout starts the store when it mounts, so the status is current before the tab opens, and supplies the UI commands.
- **Commands** (UI commands, menu group Git): `vcs.openChanges` `Mod+Alt+G` shows the tab; `vcs.commit` `Mod+K` shows it and focuses the message box; `vcs.refresh` re-reads the status (enabled while `git.status` is).
- **Status:** `git.status` through `runWaiting` on start, on `projectOpened`, on `gitChanged` and on `vcs.refresh`; calls are serialised and requests made during a round cause exactly one more round. `projectClosed` clears it. The result is untrusted: unknown states and malformed entries are dropped, at most 50,000 files. The event type `gitChanged` is now part of `EngineEventPayload` in `ui/src/ipc.ts`.
- **Groups:** Staged (the index side changed), Changes (the work tree side changed, or conflicted), Untracked. A partly staged file is in Staged and Changes. Names are coloured with `--lt-vcs-*` (renamed and modified use `modified`, copied uses `added`); a deleted file is struck through. A staged rename shows "from <old path>".
- **Staging:** a checkbox per file and per group header: checked in Staged (clearing it unstages), clear elsewhere (checking it stages). `git.stage {paths}` / `git.unstage {paths}`, both through `runWaiting`; unstaging a staged rename passes both paths, as M4.1 requires. Keyboard: Up/Down, Page Up/Down, Home, End move; Space stages or unstages; Enter opens. Failures toast git's message (`notification.command.failed`).
- **Opening:** Enter or a double-click runs the UI command `vcs.showDiff {path, staged}` when something provides it (the diff viewer, M4.3, registers and provides it); until then the file opens with `file.open`, and a deleted file does nothing.
- **Commit:** a message box, an Amend checkbox and Commit (`Mod+Enter` in the box as well). Commit is enabled with a non-blank message and staged files, or with Amend. It runs `flushDirty()` first; a failed save cancels the commit with a warning (`notification.vcs.commitNotSaved`) and changes nothing. Then `git.commit {message, amend}`; success toasts "Committed <short hash>: <summary>" (7 characters), clears the box and Amend; a refusal (a hook, nothing to commit) toasts git's message and keeps the box.
- **States without a repository:** git missing or too old shows git's reason and a hint to Settings › Git executable; a project outside a repository and a clean tree say so; the status line names the branch, or the short hash when detached, or "no commits yet".
- **Tests:** `ui/tests/vcs/ChangesToolWindow.test.ts` (19 Vitest tests against a fake engine: parsing and grouping, rename unstaging, refresh triggers and serialisation, staging per file and group, git's error as a toast, commit after `flushDirty` with the short hash, a commit cancelled by a failed save, amend without staged files, the window's status lines, checkboxes, keyboard, `vcs.showDiff` and the `file.open` fallback, the commands' shortcuts and menu paths in the layout).
## Decisions (M0)
| Question | Decision | Why |
@ -590,6 +602,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary |
|---|---|---|
| 2026-10-25 | minor | M4.2: Changes tool window (`vcs.openChanges`, `vcs.commit`, `vcs.refresh`, staging, commit after `flushDirty`) |
| 2026-10-25 | minor | M4.1: Git backend (`lutra-vcs`, `git.*` commands, `gitChanged`, `git.executable`) |
| 2026-10-24 | minor | H4: string and path controls in the settings dialog (`pick_file` IPC), assist settings (auto popup, completion delay, hover delay) read live |
| 2026-10-25 | minor | H5: banner-aligned light and dark palettes, `DIAGNOSTIC_TOKENS` and `VCS_TOKENS`, completion icon colours by kind, contrast test extended |

View file

@ -1,6 +1,6 @@
# 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); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1); G14 English UI catalog in place · **Last updated:** 2026-10-25
> **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); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2); G14 English UI catalog in place · **Last updated:** 2026-10-25
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.
@ -13,7 +13,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
| G6 | Language server: completion, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1; ~~engine wiring and diagnostics~~, M3.3; ~~completion, hover, signature help~~, M3.4; ~~definition, references, rename~~, M3.5) | M3 | ~15 h |
| G7 | ~~Terminal~~ (M3.6: PTY sessions, xterm.js sub-tabs in the bottom panel; settings, persistence, links and search still open), ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~16 h |
| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`; no UI yet), Changes window, gutter markers and status colours, diff viewer, branch popup, log, blame, conflicts, stash, remotes | M4 | ~148 h |
| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, no chunk staging), gutter markers and status colours, diff viewer, branch popup, log, blame, conflicts, stash, remotes | M4 | ~138 h |
| G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h |
| G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h |
| G11 | Stability: crash-free operation on real projects and machines (~~recovery journal~~, M1.7) | ongoing | ~95 h |
@ -52,6 +52,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin
| Date | Change | Summary |
|---|---|---|
| 2026-10-25 | minor | G8 shrunk: Changes window (M4.2) |
| 2026-10-25 | minor | G8 shrunk: Git backend (M4.1) |
| 2026-10-24 | patch | G3/G6: string and path settings in the dialog, completion and tooltip settings (H4) |
| 2026-10-25 | minor | G11 note: isolated data directory for dev and live-check instances (H6) |

View file

@ -1,6 +1,6 @@
# Milestones
> **Status:** M0–M3 done, M4 in progress (C5) · **Last updated:** 2026-10-24
> **Status:** M0–M3 done, M4 in progress (C5: Git backend, Changes window) · **Last updated:** 2026-10-25
Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, the rest estimated. Since cycle C1 (factor 0.07) M1–M3 were scaled ×0.1 to ×0.15 (measured factors: C1 0.07, C2 0.10, C3 0.14, C4 0.17; next cycle ×0.18); M4–M6 keep their first raw estimates (multiply by ~0.1 for the calibrated value).
@ -10,7 +10,7 @@ Hours are agent wall-clock hours for one agent; M0 and M1 so far are measured, t
| M1 | Editor and project: open folder, tree, tabs, editor, save, recovery, palette, settings, themes | done 2026-10-16 (M1.1 text, M1.2 VFS, M1.5 tree UI, M1.3 engine workspace, M1.4 desktop bridge, M1.6 tabs and editor, M1.11 message catalog, M1.9a settings backend, M1.10 themes, M1.7 recovery journal, M1.12 notifications, M1.13 C1 follow-ups, M1.8 command palette and keymap, M1.14 app icon, M1.9b settings dialog; C2 live checks pending, gaming mode) | ~5.6 (measured: C1 2.5, C2 3.1) |
| M2 | Syntax and search: highlighting, structure, find in files, go to file/class/symbol | done 2026-10-17 (C3: M2.1 tree-sitter syntax, M2.2 highlighting + `editor.reveal`, M2.3 search backend, M2.4 Find tool window, M2.5 symbol index + go-to commands, M2.6 go-to popup, M2.7 Structure tool window) | ~6.1 (measured) |
| M3 | LSP, terminal, CLI: completion, diagnostics, go to definition, hover, rename; terminal; `lutra` CLI and MCP — **MVP** | done 2026-10-22 (C4: M3.1 PHP detection and Phpactor download, M3.2 LSP client, M3.3 engine wiring and diagnostics, M3.4 completion, hover and signature help, M3.5 definition, references and rename, M3.6 integrated terminal, M3.7 CLI and single instance, M3.8 MCP server, M3.9 app menu, M3.10 autosave; live check with real key presses pending) | ~14 (measured) |
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend done) | ~148 |
| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend, M4.2 Changes window done) | ~138 |
| M5 | Debugger (Xdebug via DAP), PHPUnit/Pest runner, Composer, run configurations | not started | ~300 |
| M6 | Own indexer and inspections; Symfony, Laravel, Shopware, WordPress support | not started | ~1,100 |
| M7 | Workbench and tools: Deployment (FTP/SFTP/local mappings, upload/download, compare with server, save before deploy, optional upload on save per server), Local History, diff tool (files/folders), scratch files, macros, keymap editor, user themes, plug-in system, Database tools and SQL, HTTP Client, SSH/Docker/Vagrant/WSL, File Watchers, external tools, TODO view, tasks and contexts | not started | ~900 |
@ -34,6 +34,7 @@ By the raw estimates the alpha gate needs M1–M4 plus cross-platform verificati
| Date | Change | Summary |
|---|---|---|
| 2026-10-25 | minor | M4.2 Changes tool window |
| 2026-10-24 | minor | M4.1 Git backend; M4 in progress |
| 2026-10-22 | minor | C4 review: M3 done (~14 h measured) |
| 2026-10-22 | minor | M3.5 definition, references, rename |

View file

@ -1,6 +1,6 @@
# Target-app parity
> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal, go to definition, find references and rename through Phpactor · **Last updated:** 2026-10-25 · **Target:** PhpStorm 2026.x
> **Status:** M1 done (text buffer, VFS, engine workspace, project tree, tabs and a plain-text editor, recovery, palette, settings and themes in the app); M2 started: PHP syntax highlighting, find in files with its tool window, the symbol index and the go-to popup, the Structure tool window; M3 started: the integrated terminal, go to definition, find references and rename through Phpactor; M4 started: Git backend (M4.1), Changes tool window (M4.2) · **Last updated:** 2026-10-25 · **Target:** PhpStorm 2026.x
## How this is measured
@ -22,7 +22,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour
| Inspections and quick-fixes | 8 | 4% (est.) | Lutra's own inspections and their settings, severities per inspection, quick-fixes (LSP code actions), suppression, inspection profiles, running inspections on a scope, PHP lint syntax errors on Windows, the editor's problem counter and scrollbar marks, next/previous problem, a current-file Problems view and severity filters, external tools (PHPStan, Psalm, PHP_CodeSniffer) | ~290 (est.) | M3.3: diagnostics from Phpactor (worse reflection: missing members, unknown classes, …) as wavy underlines, gutter markers and hover messages in the editor (`ui/src/components/editor/lint.ts`, tokens only), and a Problems tab in the bottom panel grouped by file with click to reveal (`ui/src/components/problems/`, `problems.open` `Mod+Alt+P`); engine `diagnosticsChanged`, `diagnostics.list`, `lspStatus` (`crates/engine/src/lsp/`). Tests: 10 engine tests against a fake server incl. a sync proptest, a TCP test, 16 Vitest tests, an ignored test against the real PHAR. Checked in the app on Windows 11 with the real Phpactor (port 7933): five errors underlined and listed; first diagnostics 2.7 s after `file.open`, 2.7–2.9 s after an edit (debug build, measured, incl. Phpactor's 1 s debounce). Graded against `plan/phpstorm/11-problems.md`: the depth comes from Phpactor, Lutra has no inspections of its own |
| Refactoring | 7 | 3% (est.) | rename: preview of all changes, comments/strings and text occurrences, scope, renaming files with classes, one undo across files (closed files written on disk are not undone by the editor); extract variable/method/constant, inline, move, change signature, safe delete, pull up/push down, introduce parameter | ~244 (est.) | M3.5: Rename (`lsp.prepareRename` then `lsp.rename`, F2) through Phpactor with an inline field over the symbol that shows how many uses in how many files change. The workspace edit is checked completely first (inside the project, ranges fit, open buffers unchanged since the request, no file operations); then closed files are written atomically through the VFS (written ones restored if a later write fails), open buffers change through `buffer.edit` (dirty, one undo step each in the editor), Phpactor reindexes the written files (sent as `didOpen`/`didSave`/`didClose`; its index followed in 140 ms, measured) and a summary notification follows. Live: renaming a method used in 3 files took 28 ms (open buffer + 2 closed files, CRLF kept). Tests: `crates/engine/tests/lsp_nav.rs` (multi-file rename incl. a closed CRLF file, an edit outside the project refused, a bad range refused, a buffer edited meanwhile refused; ignored real-Phpactor rename and rename back), Vitest `ui/tests/nav/`. |
| Code style and formatting | 4 | 0% | everything | ~120 (est.) | — |
| Git | 8 | 1% (est.) | everything visible: Changes window, commit UI, gutter markers, status colours, diff viewer, branch widget (C5 wave 2/3); log, blame, conflicts, stash, remotes (C6); ignored files in the status; chunk staging | ~148 (est.) | M4.1 (backend only, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: nothing a user sees yet, so the score stays near zero. |
| Git | 8 | 4% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers, status colours, diff viewer, branch widget (C5 wave 2/3); log, blame, conflicts, stash, remotes (C6); ignored files in the status; chunk staging | ~138 (est.) | M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+G`, `vcs.commit` `Mod+K`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing and staging work from the UI; diff, gutter markers, status colours, branches, log, blame and remotes do not yet. |
| Terminal | 3 | 15% (est.) | renaming and splitting tabs, sessions kept across restarts, search in the output, clickable paths and links, drag and drop, command completion, terminal settings (shell path, start directory, environment, font, cursor shape, bell, copy on selection, middle-click paste), a key back to the editor, the PHP interpreter in `PATH`, a terminal in a file's directory, confirmation before killing a running process, moving a terminal into the editor | ~26 (est.) | M3.6: `crates/terminal` runs the shell in a pseudo terminal (`portable-pty`: ConPTY on Windows, Unix pty elsewhere) on its own reader, writer and waiter threads: UTF-8 split across reads joined, invalid bytes U+FFFD, a 1 MiB output buffer per session with backpressure (the shell waits, nothing is dropped while it runs), a non-blocking input queue, resize, kill, exit codes. Engine `terminal.create {cwd?, shell?, cols, rows}` / `terminal.input` / `terminal.resize` / `terminal.close`, events `terminalOutput` (≤ 64 KiB per terminal and 256 KiB per pump, round-robin) and `terminalExited {code}`; terminals close with the project and on `app.quit`. UI: a Terminal tab in the bottom panel (tabs next to Find), xterm.js with the fit addon, several terminals as sub-tabs (Local, Local (2)…) with close and new buttons, output replayed after collapsing the panel, copy (`Mod+Shift+C`, `Ctrl+C` with a selection) and paste (`Mod+Shift+V`, `Ctrl+V`), a focus rule that leaves plain Ctrl keys to the shell, Lutra's own ANSI colours (`--lt-terminal-*`, all text colours ≥ 4.5:1), `terminal.open` `Mod+Shift+T`. Tests: 8 session tests with real `cmd.exe` (echo, exit code, input, 6,000 multibyte characters without U+FFFD, 30,000 lines through a full buffer without losing a line, resize, kill, spawn errors) and UTF-8 proptests (`crates/terminal`), 3 engine tests (`crates/engine/tests/terminal.rs`), a TCP control test create → output → input → exit (`crates/control/tests/terminal.rs`), 20 Vitest tests with a mocked xterm (`ui/tests/terminal/`). Live check (Windows 11, debug build with bundled UI, control port 7936, temp project): `terminal.open` showed a pwsh prompt in the project root, first `terminalOutput` 0.2–0.5 s after the command; `php -v` printed PHP 8.4.24 within 0.5–1.5 s; `dir` listed the project; resizing the window changed the shell's width 144 → 190 → 105 → 142 columns (pwsh `WindowSize`); a second terminal as sub-tab "Local (2)"; Find and Terminal as bottom tabs; dark and light screenshots read; `exit 3` gave `terminalExited {code: 3}`; `app.quit` ended the app and its shells (measured). The live check found two bugs, fixed before the commit: xterm's own black viewport background showed as a bar under the last row, and programs printing ANSI white (PSReadLine) were unreadable on the light theme, so xterm now enforces a 4.5:1 minimum contrast. Typing, clicking and copy/paste were not driven in the app (the control channel has no input method); Vitest covers them. Graded against `plan/phpstorm/10-terminal.md` |
| Run configurations | 2 | 0% | everything | ~50 (est.) | — |
| Debugger | 5 | 0% | everything | ~120 (est.) | — |
@ -65,6 +65,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated);
| Date | Change | Summary |
|---|---|---|
| 2026-10-25 | minor | M4.2: Git 1% → 4% (est.), Changes tool window; hours 148 → 138 |
| 2026-10-25 | minor | M4.1: Git 0% → 1% (est.), Git backend without UI; hours 150 → 148 |
| 2026-10-25 | minor | H5: Settings row evidence (banner-aligned themes, diagnostic and VCS tokens); score unchanged |
| 2026-10-24 | minor | H4: Settings 7% → 8% (est.), string and path controls, completion and tooltip settings; hours 60 → 58 |

View file

@ -1,10 +1,11 @@
# Tooling checklist
> **Status:** integrated terminal partial (M3.6) · **Last updated:** 2026-10-18
> **Status:** integrated terminal partial (M3.6), Git backend and Changes window partial (M4.1, M4.2) · **Last updated:** 2026-10-25
- [ ] Integrated terminal with tabs
- M3.6 (2026-10-18): PTY sessions (pwsh → powershell → cmd on Windows, `$SHELL` or `/bin/sh` on Unix; cwd = project root) in the bottom panel's Terminal tab, several terminals as sub-tabs, xterm.js rendering with Lutra's colours, copy/paste, resize, exit codes; closed with the project. Missing: settings, persistence across restarts, split tabs, search, links, the PHP interpreter in `PATH`.
- [ ] Git: status, diff, commit, push/pull, branches, log, blame, conflict resolution
- M4.2 (2026-10-25): status, stage/unstage and commit (with amend) from the Changes tab, saving open files first. Missing: diff, gutter markers, branches UI, push/pull, log, blame, conflicts, stash.
- [ ] Composer: install, update, require, scripts
- [ ] PHP interpreters: local, Docker
- [ ] Xdebug via DAP: breakpoints, stepping, variables, watches
@ -18,5 +19,6 @@
| Date | Change | Summary |
|---|---|---|
| 2026-10-25 | minor | Git: status, staging and commit from the Changes tab (M4.2) |
| 2026-10-18 | minor | Integrated terminal partial (M3.6) |
| 2026-10-13 | major | Baseline |

View file

@ -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) · **Last updated:** 2026-10-25
> **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) · **Last updated:** 2026-10-25
- [ ] 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.
@ -41,11 +41,13 @@
- [ ] Terminal tool window
- M3.6 (2026-10-18): a Terminal tab in the bottom panel (the panel shows Find and Terminal as tabs while both are open; Left/Right switch); xterm.js with the fit addon follows the panel size; several terminals as sub-tabs (Local, Local (2)…) with a close button each and a new-terminal button, Left/Right/Home/End/Delete on a sub-tab, an ended shell dims its tab and prints its exit code; output survives collapsing the panel; copy with `Mod+Shift+C` or `Ctrl+C` on a selection, paste with `Mod+Shift+V` or `Ctrl+V`; while a terminal has the focus plain Ctrl keys go to the shell and only Mod+Shift / Mod+Alt shortcuts reach Lutra; Lutra's own ANSI palette in both themes (text colours ≥ 4.5:1). `terminal.open` `Mod+Shift+T`. Missing: renaming and splitting tabs, a context menu, search, clickable links and paths, drag and drop, a key back to the editor, a confirmation before killing a running process, terminal settings.
- [ ] Git tool window
- M4.2 (2026-10-25): a Changes tab in the bottom panel (`vcs.openChanges` `Mod+Alt+G`, menu Git › Changes): Staged, Changes and Untracked groups with counts, file names coloured by status (`--lt-vcs-*`, deleted struck through, a staged rename shows its old path), a checkbox per file and per group to stage or unstage, Up/Down/Page/Home/End and Space in the list, double-click or Enter opens the diff (M4.3) or the file; a commit message box with Amend and Commit (`Mod+Enter`; `vcs.commit` `Mod+K` focuses it), saving open files first; a refresh button (`vcs.refresh`); hints when git is missing or the folder is not a repository. Vitest (19 tests). Missing: a tree view and grouping by directory or module, changelists, chunk staging, a context menu (rollback, delete, add to .gitignore), recent commit messages, commit options (sign-off, author, skip hooks), commit and push, a commit preview of the diff. Behaviour notes: `plan/phpstorm/16-vcs-basics.md`.
## Revision history
| Date | Change | Summary |
|---|---|---|
| 2026-10-25 | minor | Changes tool window (M4.2) |
| 2026-10-25 | minor | Themes: banner-aligned palettes, diagnostic and VCS colours, completion icon colours (H5) |
| 2026-10-24 | minor | Settings dialog: string and path controls, completion and tooltip settings (H4) |
| 2026-10-22 | minor | Completion popup, quick documentation and parameter info partial (M3.4) |

View file

@ -35,5 +35,8 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "settings.open", labelKey: "command.settings.open", menuPath: "View/Settings…", defaultShortcut: "Mod+," },
{ id: "terminal.open", labelKey: "command.terminal.open", menuPath: "View/Terminal", defaultShortcut: "Mod+Shift+T" },
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", menuPath: "View/Project", defaultShortcut: "Mod+1" },
{ id: "vcs.commit", labelKey: "command.vcs.commit", menuPath: "Git/Commit…", defaultShortcut: "Mod+K" },
{ id: "vcs.openChanges", labelKey: "command.vcs.openChanges", menuPath: "Git/Changes", defaultShortcut: "Mod+Alt+G" },
{ id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" },
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" },
];

View file

@ -26,7 +26,10 @@
* results, the Terminal store the running terminals and the Problems store
* the diagnostics while they are hidden. The References tab (M3.5) shows
* when Find References runs (`lsp.references`); the nav store keeps its
* results.
* results. The Changes tab (M4.2) appears with `vcs.openChanges`
* (`Mod+Alt+G`) and `vcs.commit` (`Mod+K`, which also focuses the commit
* message box); `vcs.refresh` re-reads the Git status. Its store reads the
* status from the start, so it is current when the tab opens.
*
* A slim header bar along the top (M3.9) holds the app menu
* ({@link AppMenu}); its `header` slot can replace it.
@ -43,6 +46,8 @@ import ProblemsToolWindow from "../problems/ProblemsToolWindow.vue";
import { useProblemsStore } from "../problems/problems";
import ReferencesToolWindow from "../editor/nav/ReferencesToolWindow.vue";
import { useNavStore } from "../editor/nav/nav";
import ChangesToolWindow from "../vcs/changes/ChangesToolWindow.vue";
import { useChangesStore } from "../vcs/changes/changes";
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
import StatusBar from "../StatusBar.vue";
import StructureToolWindow from "../structure/StructureToolWindow.vue";
@ -89,9 +94,10 @@ const find = useFindStore();
const terminal = useTerminalStore();
const problems = useProblemsStore();
const nav = useNavStore();
const changes = useChangesStore();
/** Tool windows of the bottom panel. */
type BottomTool = "find" | "terminal" | "problems" | "references";
type BottomTool = "find" | "terminal" | "problems" | "references" | "changes";
/** The bottom tool window last chosen. */
const bottomTool = ref<BottomTool>("find");
/** Bottom tool windows that are shown, in tab order. */
@ -101,6 +107,7 @@ const bottomTools = computed(() => {
if (terminal.visible) tools.push({ id: "terminal", title: t("terminal.toolWindow.title") });
if (problems.visible) tools.push({ id: "problems", title: t("problems.toolWindow.title") });
if (nav.visible) tools.push({ id: "references", title: t("nav.references.title") });
if (changes.visible) tools.push({ id: "changes", title: t("vcs.changes.toolWindow.title") });
return tools;
});
/** The active bottom tool window: the chosen one if shown, else the first. */
@ -116,7 +123,9 @@ const bottomStore = computed(() =>
? problems
: bottomActive.value === "references"
? nav
: find,
: bottomActive.value === "changes"
? changes
: find,
);
/** Expansion of the panel, kept per tool window by its store. */
const bottomOpen = computed({
@ -132,7 +141,7 @@ const bottomOpen = computed({
* @param id - the tool window id from the panel.
*/
function chooseBottom(id: string): void {
if (id === "find" || id === "terminal" || id === "problems" || id === "references") {
if (id === "find" || id === "terminal" || id === "problems" || id === "references" || id === "changes") {
bottomTool.value = id;
}
}
@ -149,6 +158,7 @@ onMounted(() => {
find.start();
terminal.start();
problems.start();
changes.start();
withdraw = [
commands.provide("view.toggleProjectTree", {
run: () => {
@ -174,6 +184,22 @@ onMounted(() => {
problems.open();
},
}),
commands.provide("vcs.openChanges", {
run: () => {
bottomTool.value = "changes";
changes.open();
},
}),
commands.provide("vcs.commit", {
run: () => {
bottomTool.value = "changes";
changes.focusMessage();
},
}),
commands.provide("vcs.refresh", {
run: () => changes.refresh(),
enabled: () => commands.isEnabled("git.status"),
}),
commands.provide("view.toggleStructure", {
run: () => {
toggleLeft("structure");
@ -190,6 +216,7 @@ onBeforeUnmount(() => {
find.stop();
terminal.stop();
problems.stop();
changes.stop();
});
</script>
@ -263,6 +290,7 @@ onBeforeUnmount(() => {
/>
<ProblemsToolWindow v-show="bottomActive === 'problems'" />
<ReferencesToolWindow v-show="bottomActive === 'references'" />
<ChangesToolWindow v-show="bottomActive === 'changes'" />
</BottomPanel>
<StatusBar />
</div>

View file

@ -0,0 +1,632 @@
<script setup lang="ts">
/**
* The Changes tool window (M4.2), shown in the bottom panel: the project's
* changed files from git in the groups Staged, Changes and Untracked, and
* a commit message box.
*
* - **Status line:** the branch (or the short hash when detached) and the
* counts, or why there is nothing to show: git missing or too old (with
* a hint to the setting `git.executable`), no repository, no changes.
* A refresh button runs `vcs.refresh`.
* - **Groups:** a header with a checkbox that stages (Changes, Untracked)
* or unstages (Staged) the whole group, then the files. Each file has a
* checkbox doing the same for itself, its name coloured by its state
* (`--lt-vcs-*`), its directory and its state. Up/Down, Page Up/Down,
* Home and End move the selection, Space stages or unstages it, Enter or
* a double-click opens it.
* - **Opening:** through the UI command `vcs.showDiff {path, staged}` when
* something provides it (the diff viewer, M4.3); until then the file
* opens in the editor (`file.open`), unless it was deleted.
* - **Commit box:** the message, an Amend checkbox and Commit. Commit
* saves dirty buffers first (`flushDirty`); `Mod+Enter` in the box
* commits too.
* - State lives in the Changes store (`changes.ts`), so the status and the
* message survive hiding the window. Icons are Lucide's; colours are
* tokens.
*/
import { RefreshCw } from "@lucide/vue";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useCommandsStore } from "../../../commands/store";
import { isMac } from "../../../commands/keymap";
import { t } from "../../../i18n";
import { run } from "../../../ipc";
import { baseName } from "../../../stores/editor";
import { useNotificationsStore } from "../../../stores/notifications";
import { SHORT_HASH, useChangesStore, type ChangeRow, type FileState, type GroupId } from "./changes";
const changes = useChangesStore();
const commands = useCommandsStore();
const notifications = useNotificationsStore();
/** The list element. */
const list = ref<HTMLElement | null>(null);
/** The commit message box. */
const messageBox = ref<HTMLTextAreaElement | null>(null);
/** Rows moved by Page Up and Page Down. */
const PAGE = 10;
/**
* The title of a group.
*
* @param group - the group.
*/
function groupTitle(group: GroupId): string {
const titles: Record<GroupId, () => string> = {
staged: () => t("vcs.changes.group.staged"),
changes: () => t("vcs.changes.group.changes"),
untracked: () => t("vcs.changes.group.untracked"),
};
return titles[group]();
}
/**
* The name of a state, for people.
*
* @param state - the state.
*/
function stateLabel(state: FileState): string {
const labels: Record<FileState, () => string> = {
unmodified: () => t("vcs.state.unmodified"),
modified: () => t("vcs.state.modified"),
added: () => t("vcs.state.added"),
deleted: () => t("vcs.state.deleted"),
renamed: () => t("vcs.state.renamed"),
copied: () => t("vcs.state.copied"),
untracked: () => t("vcs.state.untracked"),
ignored: () => t("vcs.state.ignored"),
conflicted: () => t("vcs.state.conflicted"),
};
return labels[state]();
}
/**
* The colour class suffix of a state (`changes__name--<suffix>`, which
* uses the token `--lt-vcs-<suffix>`).
*
* @param state - the state.
*/
function stateColor(state: FileState): string {
switch (state) {
case "added":
case "copied":
return "added";
case "deleted":
return "deleted";
case "untracked":
return "untracked";
case "ignored":
return "ignored";
case "conflicted":
return "conflicted";
default:
return "modified";
}
}
/** The line above the list. */
const statusLine = computed(() => {
const s = changes.status;
switch (changes.phase) {
case "idle":
return changes.loadError ?? t("vcs.changes.noProject");
case "loading":
return t("vcs.changes.loading");
case "unavailable":
return t("vcs.changes.unavailable", { reason: s?.error ?? "" });
case "noRepo":
return s?.error ? t("vcs.changes.repoError", { reason: s.error }) : t("vcs.changes.noRepo");
default:
break;
}
const repo = s?.repo;
const where = repo?.branch ?? (repo?.head ? repo.head.slice(0, SHORT_HASH) : t("vcs.changes.noCommits"));
const g = changes.groups;
if (changes.rows.length === 0) {
return t("vcs.changes.clean", { branch: where });
}
return t("vcs.changes.summary", {
branch: where,
staged: String(g.staged.length),
changes: String(g.changes.length),
untracked: String(g.untracked.length),
});
});
/** The groups with rows, in display order, with each row's flat index. */
const shownGroups = computed(() => {
let index = 0;
const out: { id: GroupId; rows: { row: ChangeRow; index: number }[] }[] = [];
for (const id of ["staged", "changes", "untracked"] as const) {
const rows = changes.groups[id].map((row) => ({ row, index: index++ }));
if (rows.length > 0) {
out.push({ id, rows });
}
}
return out;
});
/** Label of the commit button. */
const commitLabel = computed(() => (changes.amend ? t("vcs.commit.amendButton") : t("vcs.commit.button")));
/** The shortcut hint of the commit button. */
const commitHint = computed(() => t("vcs.commit.hint", { keys: isMac() ? "⌘↩" : "Ctrl+Enter" }));
/**
* The DOM id of a row.
*
* @param index - the row's index in the flat list.
*/
function optionId(index: number): string {
return `changes-row-${String(index)}`;
}
/**
* The directory part of a path, empty at the root.
*
* @param path - project-relative path.
*/
function dirName(path: string): string {
const slash = path.lastIndexOf("/");
return slash < 0 ? "" : path.slice(0, slash);
}
/**
* What a row shows after the name: the directory, and the old path of a
* rename or copy.
*
* @param row - the row.
*/
function detail(row: ChangeRow): string {
const dir = dirName(row.file.path);
const orig = row.file.origPath;
return orig !== undefined && row.group === "staged" ? t("vcs.changes.renamedFrom", { path: orig }) : dir;
}
/**
* The accessible name of a row's checkbox.
*
* @param row - the row.
*/
function toggleLabel(row: ChangeRow): string {
return row.group === "staged"
? t("vcs.changes.unstageFile", { path: row.file.path })
: t("vcs.changes.stageFile", { path: row.file.path });
}
/**
* The accessible name of a group's checkbox.
*
* @param group - the group.
*/
function groupToggleLabel(group: GroupId): string {
return group === "staged" ? t("vcs.changes.unstageAll") : t("vcs.changes.stageGroup", { group: groupTitle(group) });
}
/**
* Opens a row: the diff when `vcs.showDiff` is provided, else the file.
*
* @param row - the row.
*/
async function openRow(row: ChangeRow): Promise<void> {
changes.select(row.key);
const staged = row.group === "staged";
if (commands.isEnabled("vcs.showDiff")) {
await commands.execute("vcs.showDiff", { path: row.file.path, staged });
return;
}
if (row.state === "deleted") {
return;
}
const result = await run("file.open", { path: row.file.path });
if (!result.ok) {
notifications.notifyError("file.open", result.error);
}
}
/**
* Keyboard navigation in the list.
*
* @param event - the key event.
*/
function onListKey(event: KeyboardEvent): void {
const count = changes.rows.length;
const moves: Record<string, number> = {
ArrowDown: 1,
ArrowUp: -1,
PageDown: PAGE,
PageUp: -PAGE,
Home: -count,
End: count,
};
const delta = moves[event.key];
const row = changes.rows[changes.selectedIndex];
if (delta !== undefined) {
event.preventDefault();
changes.move(delta);
} else if (event.key === "Enter" && row) {
event.preventDefault();
void openRow(row);
} else if (event.key === " " && row) {
event.preventDefault();
void changes.toggle(row);
}
}
/**
* Commits on `Mod+Enter` in the message box.
*
* @param event - the key event.
*/
function onMessageKey(event: KeyboardEvent): void {
if (event.key === "Enter" && (isMac() ? event.metaKey : event.ctrlKey)) {
event.preventDefault();
void changes.commit();
}
}
/** Takes the focus `vcs.commit` asked for, once. */
async function takeFocus(): Promise<void> {
if (!changes.focusPending) {
return;
}
changes.focusPending = false;
await nextTick();
messageBox.value?.focus();
}
watch(() => changes.focusRequest, takeFocus);
onMounted(() => {
void takeFocus();
});
watch(
() => changes.selectedIndex,
async (index) => {
await nextTick();
const element = index < 0 ? null : document.getElementById(optionId(index));
if (element && typeof element.scrollIntoView === "function") {
element.scrollIntoView({ block: "nearest" });
}
},
);
</script>
<template>
<div
class="changes"
data-test="changes"
>
<div class="changes__bar">
<div
class="changes__status"
role="status"
data-test="changes-status"
>
{{ statusLine }}
</div>
<button
type="button"
class="changes__icon-button"
:title="t('command.vcs.refresh')"
:aria-label="t('command.vcs.refresh')"
:disabled="changes.loading"
data-test="changes-refresh"
@click="changes.refresh()"
>
<RefreshCw :size="14" />
</button>
</div>
<div
v-if="changes.phase === 'unavailable'"
class="changes__hint"
data-test="changes-hint"
>
{{ t("vcs.changes.unavailableHint") }}
</div>
<div
ref="list"
class="changes__list"
role="listbox"
tabindex="0"
:aria-label="t('vcs.changes.list.label')"
:aria-activedescendant="changes.selectedIndex >= 0 ? optionId(changes.selectedIndex) : undefined"
data-test="changes-list"
@keydown="onListKey"
>
<div
v-for="group in shownGroups"
:key="group.id"
role="group"
:aria-label="groupTitle(group.id)"
:data-test="`changes-group-${group.id}`"
>
<div class="changes__group">
<input
type="checkbox"
class="changes__check"
:checked="group.id === 'staged'"
:disabled="changes.busy"
:aria-label="groupToggleLabel(group.id)"
:title="groupToggleLabel(group.id)"
:data-test="`changes-group-toggle-${group.id}`"
@click.prevent="changes.toggleGroup(group.id)"
>
<span class="changes__group-title">{{ groupTitle(group.id) }}</span>
<span class="changes__group-count">{{ group.rows.length }}</span>
</div>
<div
v-for="{ row, index } in group.rows"
:id="optionId(index)"
:key="row.key"
role="option"
class="changes__row"
:class="{ 'changes__row--selected': changes.selectedKey === row.key }"
:aria-selected="changes.selectedKey === row.key"
:data-state="row.state"
data-test="changes-row"
@click="changes.select(row.key)"
@dblclick="openRow(row)"
>
<input
type="checkbox"
class="changes__check"
tabindex="-1"
:checked="row.group === 'staged'"
:disabled="changes.busy"
:aria-label="toggleLabel(row)"
:title="toggleLabel(row)"
data-test="changes-row-toggle"
@click.stop.prevent="changes.toggle(row)"
>
<span
class="changes__name"
:class="`changes__name--${stateColor(row.state)}`"
>{{ baseName(row.file.path) }}</span>
<span class="changes__dir">{{ detail(row) }}</span>
<span class="changes__state">{{ stateLabel(row.state) }}</span>
</div>
</div>
</div>
<form
class="changes__commit"
data-test="changes-commit"
@submit.prevent="changes.commit()"
>
<textarea
ref="messageBox"
v-model="changes.message"
class="changes__message"
rows="3"
:placeholder="t('vcs.commit.placeholder')"
:aria-label="t('vcs.commit.messageLabel')"
:disabled="changes.phase !== 'ready'"
data-test="changes-message"
@keydown="onMessageKey"
/>
<div class="changes__commit-row">
<label class="changes__amend">
<input
v-model="changes.amend"
type="checkbox"
:disabled="changes.phase !== 'ready' || changes.busy"
data-test="changes-amend"
>
{{ t("vcs.commit.amend") }}
</label>
<button
type="submit"
class="changes__commit-button"
:disabled="!changes.canCommit"
:title="commitHint"
data-test="changes-commit-button"
>
{{ commitLabel }}
</button>
</div>
</form>
</div>
</template>
<style scoped>
.changes {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.changes__bar {
display: flex;
align-items: center;
gap: var(--lt-space-s, 4px);
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
}
.changes__status {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--lt-fg-muted);
}
.changes__hint {
padding: 0 var(--lt-space-m, 8px) var(--lt-space-xs, 2px);
color: var(--lt-fg-muted);
}
.changes__icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
padding: var(--lt-space-xs, 2px);
color: var(--lt-fg-muted);
background: transparent;
border: none;
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.changes__icon-button:hover:not(:disabled) {
color: var(--lt-fg);
background: color-mix(in srgb, var(--lt-fg) 8%, transparent);
}
.changes__icon-button:focus-visible {
outline: 2px solid var(--lt-accent);
}
.changes__list {
flex: 1;
min-height: 0;
overflow: auto;
border-top: 1px solid var(--lt-border);
outline: none;
}
.changes__list:focus-visible {
box-shadow: inset 0 0 0 1px var(--lt-accent);
}
.changes__group {
display: flex;
align-items: center;
gap: var(--lt-space-s, 4px);
padding: var(--lt-space-xs, 2px) var(--lt-space-m, 8px);
white-space: nowrap;
}
.changes__group-title {
font-weight: 600;
}
.changes__group-count {
color: var(--lt-fg-muted);
}
.changes__check {
flex: none;
margin: 0;
accent-color: var(--lt-accent);
}
.changes__row {
display: flex;
align-items: center;
gap: var(--lt-space-m, 8px);
padding: 0 var(--lt-space-m, 8px) 0 var(--lt-space-l, 24px);
white-space: nowrap;
cursor: default;
}
.changes__row:hover {
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
}
.changes__row--selected,
.changes__row--selected:hover {
background: var(--lt-editor-selection-bg);
}
.changes__name--added {
color: var(--lt-vcs-added);
}
.changes__name--modified {
color: var(--lt-vcs-modified);
}
.changes__name--deleted {
color: var(--lt-vcs-deleted);
text-decoration: line-through;
}
.changes__name--untracked {
color: var(--lt-vcs-untracked);
}
.changes__name--ignored {
color: var(--lt-vcs-ignored);
}
.changes__name--conflicted {
color: var(--lt-vcs-conflicted);
}
.changes__dir {
overflow: hidden;
text-overflow: ellipsis;
color: var(--lt-fg-muted);
}
.changes__state {
flex: none;
margin-left: auto;
color: var(--lt-fg-muted);
}
.changes__row--selected .changes__dir,
.changes__row--selected .changes__state {
color: var(--lt-fg);
}
.changes__commit {
display: flex;
flex-direction: column;
gap: var(--lt-space-xs, 2px);
padding: var(--lt-space-s, 4px) var(--lt-space-m, 8px);
border-top: 1px solid var(--lt-border);
}
.changes__message {
resize: vertical;
min-height: 3em;
padding: var(--lt-space-xs, 2px) var(--lt-space-s, 4px);
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
}
.changes__message:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: -1px;
}
.changes__commit-row {
display: flex;
align-items: center;
gap: var(--lt-space-m, 8px);
}
.changes__amend {
display: inline-flex;
align-items: center;
gap: var(--lt-space-xs, 2px);
color: var(--lt-fg);
}
.changes__commit-button {
margin-left: auto;
padding: var(--lt-space-xs, 2px) var(--lt-space-l, 24px);
color: var(--lt-fg);
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
border: 1px solid var(--lt-accent);
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.changes__commit-button:disabled {
opacity: 0.5;
cursor: default;
}
.changes__commit-button:focus-visible {
outline: 2px solid var(--lt-fg);
outline-offset: 1px;
}
</style>

View file

@ -0,0 +1,581 @@
/**
* The Changes tool window's state (M4.2): the project's changed files from
* `git.status`, grouped as Staged, Changes and Untracked, plus staging,
* unstaging and committing.
*
* - **Source:** `git.status` (a pending outcome, so through `runWaiting`)
* on start, when a project opens, on `gitChanged` and on `vcs.refresh`.
* Calls are serialised; a refresh asked for while one runs runs once
* more afterwards. A project close clears everything.
* - **Groups:** a file is Staged when its index side changed, in Changes
* when its work tree side changed or it is conflicted, and Untracked when
* git does not track it. A partly staged file is in both Staged and
* Changes. Ignored files are not listed by the backend.
* - **Staging:** `git.stage` / `git.unstage` per file or per group.
* Unstaging a staged rename passes both paths, as the backend asks.
* - **Commit:** `flushDirty()` first, so the files on disk hold what the
* editor shows; a save that failed cancels the commit. Then `git.commit
* {message, amend}`; success toasts the short hash and clears the box.
* - **Untrusted input:** the status comes from the engine and, through it,
* from git; malformed entries are dropped and the count capped
* ({@link MAX_FILES}).
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave";
import { useNotificationsStore } from "../../../stores/notifications";
/** Most files kept from one status. */
export const MAX_FILES = 50_000;
/** Length of the short commit hash shown to people. */
export const SHORT_HASH = 7;
/** States of one side of a file, as `git.status` names them. */
export const FILE_STATES = [
"unmodified",
"modified",
"added",
"deleted",
"renamed",
"copied",
"untracked",
"ignored",
"conflicted",
] as const;
/** State of one side (index or work tree) of a file. */
export type FileState = (typeof FILE_STATES)[number];
/** A changed file as `git.status` reports it. */
export interface ChangedFile {
/** Project-relative path with `/`. */
path: string;
/** The old path of a rename or copy. */
origPath?: string;
/** State in the index against HEAD. */
index: FileState;
/** State in the work tree against the index. */
worktree: FileState;
}
/** The repository summary of `git.status`. */
export interface RepoSummary {
/** Work tree root, absolute with `/`. */
root: string;
/** Current branch; absent when detached or unborn without a name. */
branch?: string;
/** Whether HEAD is detached. */
detached: boolean;
/** Full hash of HEAD; absent before the first commit. */
head?: string;
}
/** The groups of the window, in display order. */
export const GROUPS = ["staged", "changes", "untracked"] as const;
/** A group of the window. */
export type GroupId = (typeof GROUPS)[number];
/** A file in a group: one row of the list. */
export interface ChangeRow {
/** Stable key: group and path. */
key: string;
/** The group it is shown in. */
group: GroupId;
/** The file. */
file: ChangedFile;
/** The state shown: the index side in Staged, the work tree side otherwise. */
state: FileState;
}
/** What the window shows above the groups. */
export type ChangesPhase = "idle" | "loading" | "unavailable" | "noRepo" | "ready";
/**
* Reads a state; null if unknown.
*
* @param raw - untrusted.
*/
function toState(raw: unknown): FileState | null {
return FILE_STATES.find((s) => s === raw) ?? null;
}
/**
* Reads one file of `git.status`; null if malformed.
*
* @param raw - an untrusted entry of `files`.
*/
export function toFile(raw: unknown): ChangedFile | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const f = raw as Record<string, unknown>;
const index = toState(f.index);
const worktree = toState(f.worktree);
if (typeof f.path !== "string" || f.path === "" || !index || !worktree) {
return null;
}
const file: ChangedFile = { path: f.path, index, worktree };
if (typeof f.origPath === "string" && f.origPath !== "") {
file.origPath = f.origPath;
}
return file;
}
/**
* Reads the repository summary; null when absent or malformed.
*
* @param raw - the untrusted `repo` field.
*/
export function toRepo(raw: unknown): RepoSummary | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const r = raw as Record<string, unknown>;
if (typeof r.root !== "string") {
return null;
}
const repo: RepoSummary = { root: r.root, detached: r.detached === true };
if (typeof r.branch === "string" && r.branch !== "") {
repo.branch = r.branch;
}
if (typeof r.head === "string" && r.head !== "") {
repo.head = r.head;
}
return repo;
}
/** A status as the store keeps it. */
export interface StatusSnapshot {
/** Whether a usable git was found. */
available: boolean;
/** Why git is unavailable or the repository could not be opened. */
error: string | null;
/** The repository, or null outside one. */
repo: RepoSummary | null;
/** Changed files sorted by path. */
files: ChangedFile[];
}
/**
* Reads the result of `git.status`; null if it is not an object.
*
* @param raw - untrusted.
*/
export function toStatus(raw: unknown): StatusSnapshot | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const s = raw as Record<string, unknown>;
const files: ChangedFile[] = [];
if (Array.isArray(s.files)) {
for (const entry of s.files as unknown[]) {
if (files.length >= MAX_FILES) {
break;
}
const file = toFile(entry);
if (file) {
files.push(file);
}
}
}
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
return {
available: s.available === true,
error: typeof s.error === "string" && s.error !== "" ? s.error : null,
repo: toRepo(s.repo),
files,
};
}
/**
* Whether a side's state means "changed".
*
* @param state - the state.
*/
function changed(state: FileState): boolean {
return state !== "unmodified" && state !== "untracked" && state !== "ignored";
}
/**
* Splits files into the three groups.
*
* @param files - the files sorted by path.
* @returns the rows of each group, in path order.
*/
export function groupFiles(files: ChangedFile[]): Record<GroupId, ChangeRow[]> {
const out: Record<GroupId, ChangeRow[]> = { staged: [], changes: [], untracked: [] };
const add = (group: GroupId, file: ChangedFile, state: FileState): void => {
out[group].push({ key: `${group}:${file.path}`, group, file, state });
};
for (const file of files) {
if (file.index === "untracked" || file.worktree === "untracked") {
add("untracked", file, "untracked");
continue;
}
if (file.index === "conflicted" || file.worktree === "conflicted") {
add("changes", file, "conflicted");
continue;
}
if (changed(file.index)) {
add("staged", file, file.index);
}
if (changed(file.worktree)) {
add("changes", file, file.worktree);
}
}
return out;
}
/**
* The paths to pass to `git.unstage` for some staged rows: a rename or
* copy also passes its old path.
*
* @param rows - staged rows.
*/
export function unstagePaths(rows: ChangeRow[]): string[] {
const paths: string[] = [];
for (const row of rows) {
paths.push(row.file.path);
if (row.file.origPath !== undefined && row.file.index === "renamed") {
paths.push(row.file.origPath);
}
}
return [...new Set(paths)];
}
/** The Changes store. */
export const useChangesStore = defineStore("changes", () => {
const notifications = useNotificationsStore();
/** Whether the tool window is shown in the bottom panel. */
const visible = ref(false);
/** Whether the panel is expanded while Changes is shown. */
const expanded = ref(true);
/** The last status read; null before the first one or without a project. */
const status = shallowRef<StatusSnapshot | null>(null);
/** Whether a `git.status` call runs. */
const loading = ref(false);
/** The error of the last `git.status` call itself (not git's state). */
const loadError = ref<string | null>(null);
/** Whether a stage, unstage or commit runs. */
const busy = ref(false);
/** The commit message being written. */
const message = ref("");
/** Whether the next commit amends HEAD. */
const amend = ref(false);
/** Key of the selected row. */
const selectedKey = ref<string | null>(null);
/** Bumped when the message box should take the keyboard focus. */
const focusRequest = ref(0);
/** Whether a focus request waits for the window (it may mount later). */
const focusPending = ref(false);
/** The rows of each group. */
const groups = computed(() => groupFiles(status.value?.files ?? []));
/** Every row in display order. */
const rows = computed<ChangeRow[]>(() => GROUPS.flatMap((group) => groups.value[group]));
/** Index of the selected row, -1 if none. */
const selectedIndex = computed(() => rows.value.findIndex((row) => row.key === selectedKey.value));
/** What the window shows above the groups. */
const phase = computed<ChangesPhase>(() => {
const s = status.value;
if (!s) {
return loading.value ? "loading" : "idle";
}
if (!s.available) {
return "unavailable";
}
return s.repo ? "ready" : "noRepo";
});
/** Whether Commit can run now. */
const canCommit = computed(
() =>
!busy.value &&
phase.value === "ready" &&
message.value.trim() !== "" &&
(amend.value || groups.value.staged.length > 0),
);
/** Counts refresh requests, so a round knows whether another came in. */
let requests = 0;
/** Reads `git.status` once. */
async function loadOnce(): Promise<void> {
const result = await runWaiting("git.status");
if (!result.ok) {
loadError.value = result.error.message;
if (result.error.code === "disabled") {
status.value = null;
}
return;
}
const next = toStatus(result.value);
loadError.value = next ? null : "unexpected result of git.status";
status.value = next;
if (selectedKey.value !== null && !rows.value.some((row) => row.key === selectedKey.value)) {
selectedKey.value = null;
}
}
/** The `git.status` round running now, shared by callers. */
let running: Promise<void> | null = null;
/**
* Re-reads the status from git: `vcs.refresh`, `gitChanged`, project
* open. Serialised: a call while one runs makes it read once more
* afterwards and shares its promise.
*/
function refresh(): Promise<void> {
requests += 1;
if (running) {
return running;
}
loading.value = true;
running = (async () => {
let seen: number;
do {
seen = requests;
await loadOnce();
} while (seen !== requests);
})().finally(() => {
running = null;
loading.value = false;
});
return running;
}
/** Drops the status and the selection (project closed). */
function clear(): void {
status.value = null;
loadError.value = null;
selectedKey.value = null;
}
/**
* Runs a mutating git command, toasting its failure.
*
* @param command - `git.stage`, `git.unstage` or `git.commit`.
* @param params - its params.
* @returns its value, or null when it failed.
*/
async function mutate(command: string, params: JsonValue): Promise<unknown> {
const result = await runWaiting(command, params);
if (!result.ok) {
notifications.notifyError(command, result.error);
return null;
}
return result.value;
}
/**
* Stages files.
*
* @param list - rows of Changes or Untracked; others are ignored.
*/
async function stage(list: ChangeRow[]): Promise<void> {
const paths = [...new Set(list.filter((row) => row.group !== "staged").map((row) => row.file.path))];
if (paths.length === 0 || busy.value) {
return;
}
busy.value = true;
try {
if ((await mutate("git.stage", { paths })) !== null) {
await refresh();
}
} finally {
busy.value = false;
}
}
/**
* Unstages files.
*
* @param list - rows of Staged; others are ignored.
*/
async function unstage(list: ChangeRow[]): Promise<void> {
const paths = unstagePaths(list.filter((row) => row.group === "staged"));
if (paths.length === 0 || busy.value) {
return;
}
busy.value = true;
try {
if ((await mutate("git.unstage", { paths })) !== null) {
await refresh();
}
} finally {
busy.value = false;
}
}
/**
* Stages a row outside Staged, unstages a staged one.
*
* @param row - the row.
*/
function toggle(row: ChangeRow): Promise<void> {
return row.group === "staged" ? unstage([row]) : stage([row]);
}
/**
* Stages or unstages a whole group.
*
* @param group - the group.
*/
function toggleGroup(group: GroupId): Promise<void> {
const list = groups.value[group];
return group === "staged" ? unstage(list) : stage(list);
}
/**
* Saves every dirty buffer, then commits the staged changes with the
* message (or amends HEAD). Does nothing while {@link canCommit} is
* false. A failed save cancels the commit with a warning; a failed commit
* toasts git's message and keeps the box as it was.
*
* @returns the new commit's hash, or null when nothing was committed.
*/
async function commit(): Promise<string | null> {
if (!canCommit.value) {
return null;
}
busy.value = true;
try {
const flushed = await useAutosaveStore().flushDirty();
if (flushed.error !== null || flushed.failed.length > 0) {
notifications.notify({ level: "warning", messageKey: "notification.vcs.commitNotSaved" });
return null;
}
const value = await mutate("git.commit", { message: message.value, amend: amend.value });
if (value === null) {
return null;
}
const v = typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
const hash = typeof v.commit === "string" ? v.commit : "";
const summary = typeof v.summary === "string" ? v.summary : "";
notifications.notify({
level: "info",
messageKey: "notification.vcs.committed",
params: { hash: hash.slice(0, SHORT_HASH), summary },
});
message.value = "";
amend.value = false;
await refresh();
return hash;
} finally {
busy.value = false;
}
}
/**
* Applies one engine event.
*
* @param event - the event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "gitChanged" || event.kind === "projectOpened") {
void refresh();
} else if (event.kind === "projectClosed") {
clear();
}
}
/** Ends the event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** Subscribes to engine events and reads the status once. */
function start(): void {
if (unsubscribe) {
return;
}
unsubscribe = onEngineEvent(onEvent);
void refresh();
}
/** Ends the subscription. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
/** Shows the tool window: `vcs.openChanges`. */
function open(): void {
visible.value = true;
expanded.value = true;
}
/** Shows the tool window and focuses the message box: `vcs.commit`. */
function focusMessage(): void {
open();
focusPending.value = true;
focusRequest.value += 1;
}
/** Hides the tool window; the status and the message stay. */
function hide(): void {
visible.value = false;
}
/**
* Selects a row.
*
* @param key - the row key, or null for none.
*/
function select(key: string | null): void {
selectedKey.value = key;
}
/**
* Moves the selection by `delta` rows, clamped to the list.
*
* @param delta - rows to move; positive is down.
*/
function move(delta: number): void {
const list = rows.value;
if (list.length === 0) {
return;
}
const from = selectedIndex.value < 0 ? (delta > 0 ? -1 : list.length) : selectedIndex.value;
const index = Math.min(list.length - 1, Math.max(0, from + delta));
selectedKey.value = list[index]?.key ?? null;
}
return {
visible,
expanded,
status,
loading,
loadError,
busy,
message,
amend,
selectedKey,
selectedIndex,
focusRequest,
focusPending,
groups,
rows,
phase,
canCommit,
refresh,
stage,
unstage,
toggle,
toggleGroup,
commit,
onEvent,
start,
stop,
open,
focusMessage,
hide,
select,
move,
};
});

View file

@ -19,6 +19,9 @@
"command.settings.open": "Settings…",
"command.terminal.open": "Terminal",
"command.unavailable": "{command} cannot run right now",
"command.vcs.commit": "Commit…",
"command.vcs.openChanges": "Changes",
"command.vcs.refresh": "Refresh Changes",
"command.view.toggleProjectTree": "Show or Hide Project",
"command.view.toggleStructure": "Show or Hide Structure",
"common.cancel": "Cancel",
@ -142,6 +145,8 @@
"notification.toolchain.downloadFailed": "Phpactor {version} could not be downloaded: {reason}",
"notification.toolchain.downloadStarted": "Downloading Phpactor {version} from GitHub for PHP language features…",
"notification.toolchain.phpMissing": "PHP language features need PHP {min} or newer: {reason}. Install PHP or set the PHP executable in Settings.",
"notification.vcs.commitNotSaved": "Commit cancelled: not every file could be saved first.",
"notification.vcs.committed": "Committed {hash}: {summary}",
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
"palette.label": "Command palette",
@ -254,5 +259,39 @@
"terminal.tabs.label": "Terminals",
"terminal.toolWindow.title": "Terminal",
"theme.lutraDark": "Lutra Dark",
"theme.lutraLight": "Lutra Light"
"theme.lutraLight": "Lutra Light",
"vcs.changes.clean": "{branch}: no changes",
"vcs.changes.group.changes": "Changes",
"vcs.changes.group.staged": "Staged",
"vcs.changes.group.untracked": "Untracked",
"vcs.changes.list.label": "Changed files",
"vcs.changes.loading": "Reading the Git status…",
"vcs.changes.noCommits": "no commits yet",
"vcs.changes.noProject": "Open a project to see its changes",
"vcs.changes.noRepo": "This project is not in a Git repository",
"vcs.changes.renamedFrom": "from {path}",
"vcs.changes.repoError": "The Git repository cannot be read: {reason}",
"vcs.changes.stageFile": "Stage {path}",
"vcs.changes.stageGroup": "Stage all in {group}",
"vcs.changes.summary": "{branch}: {staged} staged, {changes} changed, {untracked} untracked",
"vcs.changes.toolWindow.title": "Changes",
"vcs.changes.unavailable": "Git is not available: {reason}",
"vcs.changes.unavailableHint": "Install Git 2.30 or newer, or set the Git executable in Settings.",
"vcs.changes.unstageAll": "Unstage all",
"vcs.changes.unstageFile": "Unstage {path}",
"vcs.commit.amend": "Amend",
"vcs.commit.amendButton": "Amend Commit",
"vcs.commit.button": "Commit",
"vcs.commit.hint": "Commit the staged changes ({keys})",
"vcs.commit.messageLabel": "Commit message",
"vcs.commit.placeholder": "Commit message",
"vcs.state.added": "added",
"vcs.state.conflicted": "conflicted",
"vcs.state.copied": "copied",
"vcs.state.deleted": "deleted",
"vcs.state.ignored": "ignored",
"vcs.state.modified": "modified",
"vcs.state.renamed": "renamed",
"vcs.state.unmodified": "unmodified",
"vcs.state.untracked": "untracked"
}

View file

@ -134,6 +134,15 @@ export type EngineEventPayload =
path: unknown;
/** `[{range, severity, message, source?, code?}]`, empty when cleared; unchecked. */
items: unknown;
}
| {
kind: "gitChanged";
/** Whether a usable git was found; unchecked. */
available: unknown;
/** The repository summary of `git.status`, or null; unchecked. */
repo: unknown;
/** Always true: re-query `git.status`. */
filesChanged: unknown;
};
/** Callback receiving engine events. */

View file

@ -43,8 +43,9 @@ const usedKeys = sourceFiles(SRC).flatMap((file) =>
* runtime: theme labels from `theme.list`, the settings' `labelKey`,
* `descriptionKey`, section names and enum value names from
* `settings.list`, the `messageKey` of
* `notification` events (engine and desktop host), and the keys the
* notifications store passes through a constant.
* `notification` events (engine and desktop host), the keys the
* notifications store passes through a constant, and the Changes
* window's commit toasts (M4.2), passed as `messageKey`.
*/
const RUNTIME_KEYS = new Set([
"notification.command.failed",
@ -57,6 +58,8 @@ const RUNTIME_KEYS = new Set([
"notification.recovery.unavailable",
"notification.recovery.writeFailed",
"notification.save.failed",
"notification.vcs.commitNotSaved",
"notification.vcs.committed",
"notification.settings.corrupt",
"notification.settings.corruptNotMoved",
"notification.settings.unavailable",
@ -151,7 +154,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)\.[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)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
);
expect(typeof value).toBe("string");
expect(value.trim()).not.toBe("");

View file

@ -254,7 +254,7 @@ describe("AppMenu", () => {
expect(menuShown()).toBe(true);
expect(menu.find("[data-test=menu-button]").attributes("aria-expanded")).toBe("true");
const headings = [...document.querySelectorAll("[data-test=menu-group]")].map((g) => g.querySelector(".app-menu__heading")?.textContent.trim());
expect(headings).toEqual(["File", "Edit", "View", "Go", "Help"]);
expect(headings).toEqual(["File", "Edit", "View", "Go", "Git", "Help"]);
expect(itemIds()).toEqual([
"project.openDialog",
"file.save",
@ -275,6 +275,9 @@ describe("AppMenu", () => {
"goto.fileOpen",
"goto.classOpen",
"goto.symbolOpen",
"vcs.openChanges",
"vcs.commit",
"vcs.refresh",
"app.about",
]);
const close = document.querySelector("[data-command='buffer.close']");

View file

@ -258,8 +258,10 @@ describe("CommandPalette", () => {
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
expect(document.activeElement).toBe(wrapper.find("[data-test=palette-input]").element);
expect(rows(wrapper)).toEqual([
"vcs.openChanges",
"project.close",
"palette.open",
"vcs.commit",
"editor.complete",
"find.open",
"goto.classOpen",
@ -271,6 +273,7 @@ describe("CommandPalette", () => {
"problems.open",
"editor.quickDocumentation",
"app.quit",
"vcs.refresh",
"editor.reveal",
"settings.open",
"view.toggleProjectTree",
@ -309,7 +312,7 @@ describe("CommandPalette", () => {
await press({ key: "ArrowUp" });
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("terminal.open");
await press({ key: "ArrowDown" });
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("project.close");
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("vcs.openChanges");
});
it("dims disabled commands, which Enter and clicks do not run", async () => {

View file

@ -0,0 +1,446 @@
/**
* Tests of the Changes tool window (M4.2): the store (reading an untrusted
* `git.status`, grouping into Staged / Changes / Untracked, refresh on
* start, project open and `gitChanged`, serialised refreshes, staging and
* unstaging per file and per group, renames, commit with `flushDirty`
* first, a cancelled commit when a save fails, git's error as a toast),
* the window (status line, hints, checkboxes, keyboard, double-click
* through `vcs.showDiff` or `file.open`), and the commands `vcs.openChanges`,
* `vcs.commit` and `vcs.refresh` in the main layout. The engine is a fake
* behind the mocked Tauri `invoke` and `listen`.
*/
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());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
import { useCommandsStore } from "../../src/commands/store";
import MainLayout from "../../src/components/layout/MainLayout.vue";
import ChangesToolWindow from "../../src/components/vcs/changes/ChangesToolWindow.vue";
import {
groupFiles,
toStatus,
unstagePaths,
useChangesStore,
type ChangedFile,
} from "../../src/components/vcs/changes/changes";
import { useNotificationsStore } from "../../src/stores/notifications";
/** A recorded engine call. */
interface Call {
/** `engine_execute` or `engine_execute_waiting`. */
via: string;
/** Command id. */
command: string;
/** Its params. */
params: Record<string, unknown>;
}
/** Every engine call, in order. */
let calls: Call[];
/** Engine event callbacks of every subscription. */
let listeners: ((event: { payload: unknown }) => void)[];
/** What `git.status` answers. */
let gitStatus: unknown;
/** Errors to throw, by command id. */
let failures: Record<string, { code: string; message: string }>;
/** What `file.saveAll` answers. */
let saveAll: unknown;
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components, unmounted after each test. */
let mounted: VueWrapper[];
/**
* Sends an engine event to every subscription.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of [...listeners]) {
listener({ payload });
}
await flushPromises();
}
/**
* The calls of a command.
*
* @param command - the command id.
*/
function callsOf(command: string): Call[] {
return calls.filter((c) => c.command === command);
}
/** A status with a staged, a partly staged, a changed, a renamed and an untracked file. */
function sampleStatus(): Record<string, unknown> {
return {
available: true,
repo: { root: "C:/p", branch: "main", detached: false, head: "0123456789abcdef" },
files: [
{ path: "src/b.php", index: "modified", worktree: "unmodified" },
{ path: "src/a.php", index: "modified", worktree: "modified" },
{ path: "c.php", index: "unmodified", worktree: "deleted" },
{ path: "new/name.php", origPath: "old/name.php", index: "renamed", worktree: "unmodified" },
{ path: "tmp.txt", index: "untracked", worktree: "untracked" },
],
};
}
/** Mounts the window with a started store. */
async function mountChanges(): Promise<VueWrapper> {
useChangesStore(pinia).start();
const wrapper = mount(ChangesToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await flushPromises();
return wrapper;
}
/**
* The text of every row.
*
* @param wrapper - the window.
*/
function rowTexts(wrapper: VueWrapper): string[] {
return wrapper.findAll("[data-test=changes-row]").map((row) => row.text());
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
calls = [];
listeners = [];
mounted = [];
failures = {};
gitStatus = sampleStatus();
saveAll = { saved: [], failed: [], skipped: [] };
Element.prototype.scrollIntoView = () => undefined;
invoke.mockReset();
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push(callback);
return Promise.resolve(() => {
listeners = listeners.filter((l) => l !== callback);
});
});
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([{ id: "git.status", label: "Git Status", enabled: true }]);
}
if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) {
return Promise.resolve(null);
}
calls.push({ via: cmd, command: args.command, params: args.params });
const failure = failures[args.command];
if (failure) {
return Promise.reject(Object.assign(new Error(failure.message), failure));
}
switch (args.command) {
case "git.status":
return Promise.resolve(gitStatus);
case "git.commit":
return Promise.resolve({ commit: "fedcba9876543210", summary: String(args.params.message).split("\n")[0] });
case "file.saveAll":
return Promise.resolve(saveAll);
case "file.open":
return Promise.resolve({ id: 1, path: args.params.path, text: "", version: 0 });
default:
return Promise.resolve({});
}
});
});
afterEach(() => {
for (const wrapper of mounted) {
wrapper.unmount();
}
useChangesStore(pinia).stop();
document.body.innerHTML = "";
});
describe("reading git.status", () => {
it("drops malformed entries, keeps renames and sorts by path", () => {
const status = toStatus({
available: true,
repo: { root: "/r", detached: true, head: "abc" },
files: [
{ path: "z.php", index: "modified", worktree: "unmodified" },
{ path: "", index: "modified", worktree: "unmodified" },
{ path: "x.php", index: "weird", worktree: "unmodified" },
"nope",
null,
{ path: "a.php", origPath: "b.php", index: "renamed", worktree: "modified" },
],
});
expect(status?.files.map((f) => f.path)).toEqual(["a.php", "z.php"]);
expect(status?.files[0]?.origPath).toBe("b.php");
expect(status?.repo).toEqual({ root: "/r", detached: true, head: "abc" });
expect(toStatus(null)).toBeNull();
expect(toStatus([1, 2])).toBeNull();
expect(toStatus({ available: false, error: "git not found", repo: null, files: "x" })).toEqual({
available: false,
error: "git not found",
repo: null,
files: [],
});
});
it("groups files: partly staged in both, conflicts in Changes, untracked apart", () => {
const files: ChangedFile[] = [
{ path: "a", index: "modified", worktree: "modified" },
{ path: "b", index: "added", worktree: "unmodified" },
{ path: "c", index: "unmodified", worktree: "deleted" },
{ path: "d", index: "conflicted", worktree: "conflicted" },
{ path: "e", index: "untracked", worktree: "untracked" },
];
const groups = groupFiles(files);
expect(groups.staged.map((r) => `${r.file.path}:${r.state}`)).toEqual(["a:modified", "b:added"]);
expect(groups.changes.map((r) => `${r.file.path}:${r.state}`)).toEqual(["a:modified", "c:deleted", "d:conflicted"]);
expect(groups.untracked.map((r) => r.file.path)).toEqual(["e"]);
});
it("unstages a staged rename with both paths", () => {
const groups = groupFiles([
{ path: "new.php", origPath: "old.php", index: "renamed", worktree: "unmodified" },
{ path: "x.php", index: "modified", worktree: "unmodified" },
]);
expect(unstagePaths(groups.staged)).toEqual(["new.php", "old.php", "x.php"]);
});
});
describe("the Changes store", () => {
it("reads the status through runWaiting on start, project open and gitChanged", async () => {
const changes = useChangesStore(pinia);
changes.start();
await flushPromises();
expect(callsOf("git.status")).toHaveLength(1);
expect(callsOf("git.status")[0]?.via).toBe("engine_execute_waiting");
expect(changes.groups.staged.map((r) => r.file.path)).toEqual(["new/name.php", "src/a.php", "src/b.php"]);
await emit({ kind: "gitChanged", available: true, repo: null, filesChanged: true });
await emit({ kind: "projectOpened", root: "C:/p", name: "p" });
expect(callsOf("git.status")).toHaveLength(3);
await emit({ kind: "projectClosed" });
expect(changes.status).toBeNull();
expect(changes.rows).toHaveLength(0);
});
it("serialises refreshes: calls during a round cause one more round", async () => {
const changes = useChangesStore(pinia);
const first = changes.refresh();
void changes.refresh();
void changes.refresh();
await first;
await flushPromises();
expect(callsOf("git.status")).toHaveLength(2);
});
it("stages and unstages per file and per group, then re-reads", async () => {
const changes = useChangesStore(pinia);
await changes.refresh();
const untracked = changes.groups.untracked[0];
if (!untracked) throw new Error("no untracked row");
await changes.toggle(untracked);
expect(callsOf("git.stage").map((c) => c.params)).toEqual([{ paths: ["tmp.txt"] }]);
await changes.toggleGroup("changes");
expect(callsOf("git.stage")[1]?.params).toEqual({ paths: ["c.php", "src/a.php"] });
await changes.toggleGroup("staged");
expect(callsOf("git.unstage")[0]?.params).toEqual({
paths: ["new/name.php", "old/name.php", "src/a.php", "src/b.php"],
});
expect(callsOf("git.stage")[0]?.via).toBe("engine_execute_waiting");
expect(callsOf("git.status")).toHaveLength(4);
});
it("toasts git's message when staging fails", async () => {
const changes = useChangesStore(pinia);
await changes.refresh();
failures["git.stage"] = { code: "failed", message: "fatal: index.lock exists" };
await changes.toggleGroup("untracked");
const toasts = useNotificationsStore(pinia).toasts;
expect(toasts.at(-1)?.level).toBe("error");
expect(toasts.at(-1)?.text).toContain("fatal: index.lock exists");
expect(changes.busy).toBe(false);
});
it("saves dirty buffers before committing and toasts the short hash", async () => {
const changes = useChangesStore(pinia);
await changes.refresh();
changes.message = "Fix the parser\n\nDetails";
expect(changes.canCommit).toBe(true);
const hash = await changes.commit();
expect(hash).toBe("fedcba9876543210");
const order = calls.map((c) => c.command).filter((c) => c === "file.saveAll" || c === "git.commit");
expect(order).toEqual(["file.saveAll", "git.commit"]);
expect(callsOf("git.commit")[0]?.params).toEqual({ message: "Fix the parser\n\nDetails", amend: false });
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toBe("Committed fedcba9: Fix the parser");
expect(changes.message).toBe("");
});
it("cancels the commit when a buffer cannot be saved", async () => {
const changes = useChangesStore(pinia);
await changes.refresh();
saveAll = { saved: [], failed: [{ id: 3, path: "src/a.php", message: "disk full" }], skipped: [] };
changes.message = "msg";
expect(await changes.commit()).toBeNull();
expect(callsOf("git.commit")).toHaveLength(0);
expect(useNotificationsStore(pinia).toasts.some((t) => t.text.includes("Commit cancelled"))).toBe(true);
expect(changes.message).toBe("msg");
});
it("refuses an empty message and an empty commit, but allows an amend without staged files", async () => {
gitStatus = { ...sampleStatus(), files: [{ path: "a.php", index: "unmodified", worktree: "modified" }] };
const changes = useChangesStore(pinia);
await changes.refresh();
changes.message = " ";
expect(changes.canCommit).toBe(false);
changes.message = "reword";
expect(changes.canCommit).toBe(false);
changes.amend = true;
expect(changes.canCommit).toBe(true);
await changes.commit();
expect(callsOf("git.commit")[0]?.params).toEqual({ message: "reword", amend: true });
expect(changes.amend).toBe(false);
});
it("keeps the message when git refuses the commit", async () => {
const changes = useChangesStore(pinia);
await changes.refresh();
failures["git.commit"] = { code: "failed", message: "pre-commit hook failed: lint" };
changes.message = "keep me";
expect(await changes.commit()).toBeNull();
expect(changes.message).toBe("keep me");
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("pre-commit hook failed: lint");
});
});
describe("the Changes window", () => {
it("shows the branch, the counts and the three groups", async () => {
const wrapper = await mountChanges();
expect(wrapper.get("[data-test=changes-status]").text()).toBe("main: 3 staged, 2 changed, 1 untracked");
expect(wrapper.find("[data-test=changes-group-staged]").exists()).toBe(true);
expect(wrapper.find("[data-test=changes-group-changes]").exists()).toBe(true);
expect(wrapper.find("[data-test=changes-group-untracked]").exists()).toBe(true);
expect(rowTexts(wrapper)[0]).toContain("name.php");
expect(rowTexts(wrapper)[0]).toContain("from old/name.php");
});
it("explains a missing git, a folder without a repository and a clean tree", async () => {
gitStatus = { available: false, error: "git 2.20 is older than 2.30", repo: null, files: [] };
const wrapper = await mountChanges();
expect(wrapper.get("[data-test=changes-status]").text()).toContain("git 2.20 is older than 2.30");
expect(wrapper.find("[data-test=changes-hint]").exists()).toBe(true);
gitStatus = { available: true, repo: null, files: [] };
await useChangesStore(pinia).refresh();
expect(wrapper.get("[data-test=changes-status]").text()).toBe("This project is not in a Git repository");
gitStatus = { available: true, repo: { root: "/r", detached: true, head: "abcdef0123456" }, files: [] };
await useChangesStore(pinia).refresh();
expect(wrapper.get("[data-test=changes-status]").text()).toBe("abcdef0: no changes");
expect(wrapper.get("[data-test=changes-message]").attributes("disabled")).toBeUndefined();
});
it("stages and unstages through the checkboxes", async () => {
const wrapper = await mountChanges();
await wrapper.get("[data-test=changes-group-toggle-untracked]").trigger("click");
await flushPromises();
expect(callsOf("git.stage")[0]?.params).toEqual({ paths: ["tmp.txt"] });
const firstToggle = wrapper.findAll("[data-test=changes-row-toggle]")[0];
await firstToggle?.trigger("click");
await flushPromises();
expect(callsOf("git.unstage")[0]?.params).toEqual({ paths: ["new/name.php", "old/name.php"] });
});
it("moves with the arrow keys, toggles with Space and opens with Enter", async () => {
const wrapper = await mountChanges();
const list = wrapper.get("[data-test=changes-list]");
await list.trigger("keydown", { key: "End" });
expect(useChangesStore(pinia).selectedKey).toBe("untracked:tmp.txt");
await list.trigger("keydown", { key: " " });
await flushPromises();
expect(callsOf("git.stage")[0]?.params).toEqual({ paths: ["tmp.txt"] });
await list.trigger("keydown", { key: "ArrowUp" });
await list.trigger("keydown", { key: "Enter" });
await flushPromises();
expect(callsOf("file.open").map((c) => c.params)).toEqual([{ path: "src/a.php" }]);
});
it("opens through vcs.showDiff when it is provided, and never opens a deleted file", async () => {
const wrapper = await mountChanges();
const rows = wrapper.findAll("[data-test=changes-row]");
const deleted = rows.find((row) => row.text().includes("c.php"));
await deleted?.trigger("dblclick");
await flushPromises();
expect(callsOf("file.open")).toHaveLength(0);
const diffs: unknown[] = [];
useCommandsStore(pinia).provide("vcs.showDiff", { run: (params) => void diffs.push(params) });
await rows[0]?.trigger("dblclick");
await flushPromises();
expect(diffs).toEqual([{ path: "new/name.php", staged: true }]);
expect(callsOf("file.open")).toHaveLength(0);
});
it("commits from the button and with Ctrl+Enter in the box", async () => {
const wrapper = await mountChanges();
const button = wrapper.get("[data-test=changes-commit-button]");
expect(button.attributes("disabled")).toBeDefined();
await wrapper.get("[data-test=changes-message]").setValue("First");
expect(button.attributes("disabled")).toBeUndefined();
await wrapper.get("[data-test=changes-commit]").trigger("submit");
await flushPromises();
expect(callsOf("git.commit")).toHaveLength(1);
await wrapper.get("[data-test=changes-message]").setValue("Second");
await wrapper.get("[data-test=changes-amend]").setValue(true);
expect(button.text()).toBe("Amend Commit");
await wrapper.get("[data-test=changes-message]").trigger("keydown", { key: "Enter", ctrlKey: true });
await flushPromises();
expect(callsOf("git.commit")[1]?.params).toEqual({ message: "Second", amend: true });
});
});
describe("the vcs commands in the main layout", () => {
/** Mounts the layout and starts the commands store. */
async function mountLayout(): Promise<VueWrapper> {
const wrapper = mount(MainLayout, {
attachTo: document.body,
global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true } },
});
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await flushPromises();
return wrapper;
}
it("registers the commands with menu paths and shortcuts", async () => {
await mountLayout();
const registered = callsOf("ui.registerCommands")[0]?.params.commands as {
id: string;
defaultShortcut?: string;
menuPath?: string;
}[];
expect(registered.find((c) => c.id === "vcs.openChanges")).toMatchObject({ defaultShortcut: "Mod+Alt+G", menuPath: "Git/Changes" });
expect(registered.find((c) => c.id === "vcs.commit")).toMatchObject({ defaultShortcut: "Mod+K", menuPath: "Git/Commit…" });
expect(registered.find((c) => c.id === "vcs.refresh")?.menuPath).toBe("Git/Refresh Changes");
});
it("opens the tab with its shortcut, focuses the box with vcs.commit and refreshes", async () => {
const wrapper = await mountLayout();
expect(wrapper.find("[data-test=changes]").exists()).toBe(false);
window.dispatchEvent(new KeyboardEvent("keydown", { key: "g", code: "KeyG", ctrlKey: true, altKey: true, bubbles: true }));
await flushPromises();
expect(wrapper.get("[data-test=changes]").isVisible()).toBe(true);
const commands = useCommandsStore(pinia);
await commands.execute("vcs.commit");
await flushPromises();
expect(document.activeElement).toBe(wrapper.get("[data-test=changes-message]").element);
const before = callsOf("git.status").length;
await commands.execute("vcs.refresh");
await flushPromises();
expect(callsOf("git.status").length).toBe(before + 1);
await commands.execute("problems.open");
await flushPromises();
expect(wrapper.findAll("[data-test=bottom-panel] [role=tab]").length).toBeGreaterThanOrEqual(2);
});
});