From 149a6c7049d1d25b067eb7f181a14d426c7efb0a Mon Sep 17 00:00:00 2001 From: danny Date: Mon, 26 Oct 2026 17:40:33 +0100 Subject: [PATCH] M4.5: branch status-bar item and branches popup The status bar shows the current branch (short hash when detached). Its popup lists local, then remote branches with a filter and New branch; checkout runs flushDirty first and toasts git's refusal. Commands vcs.branches, vcs.newBranch and vcs.checkout. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 8 +- docs/architecture.md | 13 +- docs/gaps.md | 5 +- docs/roadmap.md | 5 +- docs/target-app-parity.md | 5 +- docs/tooling-parity.md | 4 +- docs/ui-parity.md | 4 +- ui/src/commands/modals.ts | 4 +- ui/src/commands/uiCommands.ts | 3 + ui/src/components/StatusBar.vue | 4 +- .../components/vcs/branches/BranchPopup.vue | 536 ++++++++++++++++++ .../vcs/branches/BranchStatusItem.vue | 177 ++++++ ui/src/components/vcs/branches/branches.ts | 396 +++++++++++++ ui/src/i18n/en.json | 24 + ui/tests/i18n/catalog.test.ts | 8 +- ui/tests/menu/AppMenu.test.ts | 2 + ui/tests/palette/CommandPalette.test.ts | 5 +- ui/tests/vcs/Branches.test.ts | 399 +++++++++++++ 18 files changed, 1585 insertions(+), 17 deletions(-) create mode 100644 ui/src/components/vcs/branches/BranchPopup.vue create mode 100644 ui/src/components/vcs/branches/BranchStatusItem.vue create mode 100644 ui/src/components/vcs/branches/branches.ts create mode 100644 ui/tests/vcs/Branches.test.ts diff --git a/ROADMAP.md b/ROADMAP.md index 6d50eac..c8988e8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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-26 · **Change:** minor (M4.3: diff viewer, Git 8%) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only +> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-10-26 · **Change:** minor (M4.5: branch widget and popup, Git 9%) · **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.8%** (Editor core 11% × weight 12, Navigation 13% × weight 10, Code completion 5% × weight 10, Inspections 5% × weight 8, Refactoring 3% × weight 7, Project view 8% × weight 6, Search and replace 8% × weight 6, Terminal 15% × weight 3, Git 8% × weight 8, Settings 8% × weight 1, of 101 = 586/101) | estimated | +| **Feature depth** (weighted by use, scored by behaviour) | **~5.9%** (Editor core 11% × weight 12, Navigation 13% × weight 10, Code completion 5% × weight 10, Inspections 5% × weight 8, Refactoring 3% × weight 7, Project view 8% × weight 6, Search and replace 8% × weight 6, Terminal 15% × weight 3, Git 9% × weight 8, Settings 8% × weight 1, of 101 = 586/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) | 8% (est.) | ~128 | +| Version control (Git) | 9% (est.) | ~122 | | 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-26 | M4.5: the status bar shows the current Git branch (or the commit when HEAD is detached). Click it, or choose Git › Branches…, to see local and remote branches with a filter field; pick one to switch to it. Lutra saves your open files first, and if Git refuses (your changes would be overwritten) the message says so. "New branch…" creates a branch from where you are and switches to it. | | 2026-10-26 | M4.3: see what you changed side by side. Double-click a file in the Changes tab, right-click it in the project tree, or press `Mod+Alt+Shift+D`, and a "Diff: " tab shows the staged version (or the last commit) on the left and your file on the right, where you can keep editing. `Alt+Shift+]` and `Alt+Shift+[` jump between changes; binary and very large files get a short notice instead. | | 2026-10-25 | M4.4: Lutra shows what you changed. A coloured bar in the gutter marks lines you added or edited since the staged version, and a small notch marks deleted lines; it follows your typing. File names in the project tree and the tabs are coloured by their Git status: new, modified, deleted, untracked, conflicted and ignored. | | 2026-10-25 | M4.2: a Changes tab for Git (`Mod+Alt+Shift+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). | @@ -104,6 +105,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | M4.5: branch widget and popup; Git 8% → 9% (est.), hours ~128 → ~122, feature depth ~5.8% → ~5.9% (586 → 594 of 101), progress log | | 2026-10-26 | minor | M4.3: diff viewer; Git 6% → 8% (est.), hours ~136 → ~128, feature depth ~5.6% → ~5.8%, progress log | | 2026-10-25 | minor | M4.4: gutter change markers and status colours; Git 4% → 6% (est.), hours ~138 → ~136, feature depth ~5.4% → ~5.6%, progress log | | 2026-10-25 | minor | M4.2: Changes tool window; Git 0% → 4% (est.), feature depth ~5.1% → ~5.4%, progress log | diff --git a/docs/architecture.md b/docs/architecture.md index bca907c..2368d53 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3) · **Last updated:** 2026-10-26 +> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5) · **Last updated:** 2026-10-26 ## Overview @@ -622,6 +622,16 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - **Look:** both sides use the Lutra editor theme and the file's language; changed lines are tinted with `color-mix` of `--lt-vcs-deleted` (left) and `--lt-vcs-added` (right) into `--lt-editor-bg`, changed words more strongly, a change bar in each gutter, unchanged stretches over 8 lines collapse to a row (3 lines of context). No colour outside the tokens. - **Tests:** `ui/tests/vcs/DiffView.test.ts` (21 Vitest tests against a fake engine: params and `git.show` parsing, EOL normalisation, index and HEAD sides, one tab per side, the palette without a path, bad params and no file as toasts, disabled without a project, edits on the right reaching `buffer.edit`, engine changes reaching the right side, the left side refresh on `gitChanged`, closing with the buffer, binary / too large / git error / deleted / new file, switching between diff and file tabs, next/previous change with wrap-around, the tree context menu by right click and by Shift+F10 with Escape). +### Branches (M4.5) + +- **Where:** `ui/src/components/vcs/branches/`: `branches.ts` is the Pinia store, `BranchStatusItem.vue` the status-bar item (one line in `StatusBar.vue`, after H3's progress item), `BranchPopup.vue` the popup. The item supplies the UI commands, so they exist wherever the status bar is. +- **Status-bar item:** the current branch from the Changes store's `git.status` (no second query; it follows `gitChanged`), or the first 7 characters of HEAD when detached; hidden outside a repository, while git is missing and before the first status. A click runs `vcs.branches`. +- **Popup:** above the status bar's right end. A filter field (every word must occur in the name, ignoring case), "New branch…", then Local and Remote headings with their branches sorted by name; the current branch has a check and "current", a local branch shows its upstream. `git.branches` (through `runWaiting`) is read each time it opens; the first branch is selected once the list arrives. Up/Down/Page Up/Page Down move, Enter or a click chooses, Escape or a click outside closes and gives the focus back. Choosing the current branch only closes it. It is an exclusive modal (`ModalId` `branches`). The answer is untrusted: malformed entries are dropped, at most 10,000 per kind. +- **Checkout:** choosing a branch closes the popup and runs `vcs.checkout {branch}`: `flushDirty()` first; a failed save cancels with a warning (`notification.vcs.checkoutNotSaved`) and git is not called. Then `git.checkout`; git's refusal (local changes would be overwritten, an unknown branch) becomes an error toast `notification.vcs.checkoutFailed {branch, reason}` with git's text, success an info toast. A remote branch (`origin/x`) checks out its tracking branch (M4.1). Open buffers whose files changed reload through the watcher; the status follows `gitChanged`. +- **New branch:** "New branch…" (taking the filter text as a first name) or `vcs.newBranch` shows a name field and a "Check out" checkbox (on). Create runs `git.createBranch {name, checkout}` from HEAD; nothing is saved first because creating and switching from HEAD leaves the files alone. A blank name or git's refusal (invalid name, an existing branch) shows under the field (`role="alert"`) and the popup stays; Escape goes back to the list. +- **Commands** (UI commands, menu group Git, no default shortcuts): `vcs.branches` (Git › Branches…), `vcs.newBranch {name?, checkout?}` (Git › New Branch…; with a `name` it creates the branch without the popup, checked out unless `checkout: false`, and toasts a refusal), `vcs.checkout {branch}` (without `branch`, as from the palette, it opens the popup; a `branch` that is no non-blank string toasts an error). All are enabled while `git.branches` is (an open project). +- **Tests:** `ui/tests/vcs/Branches.test.ts` (16 Vitest tests against a fake engine: parsing, filter, head label, the item's states, popup order and marking, filtering, keyboard, checkout after `flushDirty` through `runWaiting`, a refusal toast, a cancelled checkout, creating with a blank name, a refusal and success, Escape back to the list, the commands' registration, params and enabled state). + ## Decisions (M0) | Question | Decision | Why | @@ -639,6 +649,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | M4.5: branches (status-bar item, popup, `vcs.branches`, `vcs.newBranch`, `vcs.checkout`) | | 2026-10-26 | minor | M4.3: diff viewer (`vcs.showDiff`, `vcs.nextChange`, `vcs.previousChange`, `@codemirror/merge` loaded lazily, the project tree's context menu) | | 2026-10-25 | minor | M4.4: `git.lineChanges` (index cache, `similar` line diff off the lock), gutter change markers, Git status colours in the tree and tabs | | 2026-10-25 | minor | M4.2: Changes tool window (`vcs.openChanges`, `vcs.commit`, `vcs.refresh`, staging, commit after `flushDirty`) | diff --git a/docs/gaps.md b/docs/gaps.md index cf441ff..4aada33 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -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, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3); G14 English UI catalog in place · **Last updated:** 2026-10-26 +> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5); G14 English UI catalog in place · **Last updated:** 2026-10-26 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`), ~~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~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), branch popup, log, blame, conflicts, stash, remotes | M4 | ~128 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~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), log, blame, conflicts, stash, remotes | M4 | ~122 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-26 | minor | G8 shrunk: branch widget and popup (M4.5) | | 2026-10-26 | minor | G8 shrunk: diff viewer (M4.3) | | 2026-10-25 | minor | G8 shrunk: gutter markers and status colours (M4.4) | | 2026-10-25 | minor | G8 shrunk: Changes window (M4.2) | diff --git a/docs/roadmap.md b/docs/roadmap.md index d34926d..da88df9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Milestones -> **Status:** M0–M3 done, M4 in progress (C5: Git backend, Changes window, gutter markers and status colours, diff viewer) · **Last updated:** 2026-10-26 +> **Status:** M0–M3 done, M4 in progress (C5: Git backend, Changes window, gutter markers and status colours, diff viewer, branches) · **Last updated:** 2026-10-26 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, M4.2 Changes window, M4.4 gutter markers and status colours, M4.3 diff viewer done) | ~128 | +| M4 | Git: status, diff, commit, branches, log, blame, conflicts | in progress (C5: M4.1 backend, M4.2 Changes window, M4.4 gutter markers and status colours, M4.3 diff viewer, M4.5 branches done) | ~122 | | 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-26 | minor | M4.5 branch widget and popup | | 2026-10-26 | minor | M4.3 diff viewer | | 2026-10-25 | minor | M4.4 gutter markers and status colours | | 2026-10-25 | minor | M4.2 Changes tool window | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9eae8ee..386e54a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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; M4 started: Git backend (M4.1), Changes tool window (M4.2), diff viewer (M4.3) · **Last updated:** 2026-10-26 · **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), diff viewer (M4.3), branches (M4.5) · **Last updated:** 2026-10-26 · **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 | 5% (est.) | Lutra's own inspections and their settings, severities per inspection, quick-fixes (LSP code actions), suppression, inspection profiles, running inspections on a scope, 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) | ~287 (est.) | H3: PHP syntax errors on Windows from Lutra's own `php -l` (on open and save, off the engine lock, killed with Lutra), merged into the editor underlines and the Problems tab with source `php -l`; the language server's messages as notifications and its log as `lsp.log`. Tests: `crates/engine/tests/lsp_ux.rs`, unit tests incl. a parser proptest. 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 | 8% (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: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branch widget (C5 wave 3); log, blame, conflicts, stash, remotes (C6); ignored files in the status | ~128 (est.) | M4.3: `vcs.showDiff {path, staged?}` (`Mod+Alt+Shift+D`, menu Git › Show Diff, double-click in Changes, the project tree's context menu, the palette) opens a "Diff: " tab in the editor area: `@codemirror/merge` side by side, the staged version (or the last commit for a staged row) read-only on the left, the working copy editable on the right through its normal engine buffer (saves, autosave, the journal), changed lines and words tinted with `--lt-vcs-*`, unchanged stretches collapsed, the left side re-read on `gitChanged`; next/previous change (`Alt+Shift+]` / `Alt+Shift+[`); notices for binary, too large, failed and deleted files (`ui/src/components/vcs/diff/`, 21 Vitest tests). 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+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.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, and changed lines and files are marked (read-only markers, no chunk actions); diff, branches, log, blame and remotes do not yet. | +| Git | 8 | 9% (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: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branches: merge, rebase, rename, delete, compare, favourites, incoming/outgoing markers, a branch from another start point; log, blame, conflicts, stash, remotes (C6); ignored files in the status | ~122 (est.) | M4.5: a status-bar item shows the current branch, or the short hash when detached (`ui/src/components/vcs/branches/`); clicking it or `vcs.branches` (menu Git › Branches…) opens a popup with a filter field, "New branch…", the local branches (current marked, upstream shown) and the remote branches, keyboard-driven; choosing one runs `vcs.checkout {branch}`, which saves dirty buffers through `flushDirty()` first, cancels when a save fails and toasts git's refusal with the branch name; a remote branch checks out its tracking branch. "New branch…" / `vcs.newBranch {name?, checkout?}` creates one from HEAD (checked out by default) and keeps git's refusal next to the name. Tests: 16 Vitest tests (`ui/tests/vcs/Branches.test.ts`). M4.3: `vcs.showDiff {path, staged?}` (`Mod+Alt+Shift+D`, menu Git › Show Diff, double-click in Changes, the project tree's context menu, the palette) opens a "Diff: " tab in the editor area: `@codemirror/merge` side by side, the staged version (or the last commit for a staged row) read-only on the left, the working copy editable on the right through its normal engine buffer (saves, autosave, the journal), changed lines and words tinted with `--lt-vcs-*`, unchanged stretches collapsed, the left side re-read on `gitChanged`; next/previous change (`Alt+Shift+]` / `Alt+Shift+[`); notices for binary, too large, failed and deleted files (`ui/src/components/vcs/diff/`, 21 Vitest tests). 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+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.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, staging and switching or creating branches work from the UI, and changed lines and files are marked (read-only markers, no chunk actions); diff, 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-26 | minor | M4.5: Git 8% → 9% (est.), branch widget and popup; hours 128 → 122 | | 2026-10-26 | minor | M4.3: Git 6% → 8% (est.), diff viewer; hours 136 → 128 | | 2026-10-25 | minor | M4.4: Git 4% → 6% (est.), gutter change markers and status colours; hours 138 → 136 | | 2026-10-25 | minor | H3: Inspections and quick-fixes 4% → 5% (est.), `php -l` on Windows; Code completion evidence (indexing ~3× faster), score unchanged; hours 290 → 287 and 240 → 238 | diff --git a/docs/tooling-parity.md b/docs/tooling-parity.md index 060d2be..190478b 100644 --- a/docs/tooling-parity.md +++ b/docs/tooling-parity.md @@ -1,12 +1,13 @@ # Tooling checklist -> **Status:** integrated terminal partial (M3.6), Git backend, Changes window and diff viewer partial (M4.1, M4.2, M4.3) · **Last updated:** 2026-10-26 +> **Status:** integrated terminal partial (M3.6), Git backend, Changes window, diff viewer and branches partial (M4.1, M4.2, M4.3, M4.5) · **Last updated:** 2026-10-26 - [ ] 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. - M4.3 (2026-10-26): a side-by-side diff of the working copy against the staged version or the last commit, editable on the right, with next/previous change. Missing: comparing with other revisions or branches, a unified view, three-way merge for conflicts. + - M4.5 (2026-10-26): current branch in the status bar, switch to a local or remote branch (saving open files first, git's refusal shown) and create a branch from HEAD in the branches popup. Missing: merge, rebase, rename, delete, push/pull, log, blame, conflicts, stash. - [ ] Composer: install, update, require, scripts - [ ] PHP interpreters: local, Docker - [ ] Xdebug via DAP: breakpoints, stepping, variables, watches @@ -20,6 +21,7 @@ | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Git: branch widget, checkout and new branch (M4.5) | | 2026-10-26 | minor | Git: diff viewer (M4.3) | | 2026-10-25 | minor | Git: status, staging and commit from the Changes tab (M4.2) | | 2026-10-18 | minor | Integrated terminal partial (M3.6) | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index c7f007e..1362a99 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity checklist -> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3) · **Last updated:** 2026-10-26 +> **Status:** main window layout (M1.5), project tree running against the engine (M1.4), editor tabs with a CodeMirror editor (M1.6), light and dark themes (M1.10), restore dialog for unsaved changes (M1.7), notification toasts (M1.12), command palette and global keymap (M1.8), settings dialog with search (M1.9b), syntax highlighting and `editor.reveal` (M2.2), Find tool window in the bottom panel (M2.4), go-to popup (M2.6), left stripe and Structure tool window (M2.7), app menu (M3.9), Terminal tool window and bottom panel tabs (M3.6), Problems tool window and editor diagnostics (M3.3), completion, quick documentation and parameter info (M3.4), string and path settings with completion and tooltip settings (H4), banner-aligned themes with diagnostic and VCS colours (H5), Changes tool window (M4.2), Git change markers and status colours (M4.4), diff viewer and the project tree's context menu (M4.3), branch widget and popup (M4.5) · **Last updated:** 2026-10-26 - [ ] 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. @@ -44,11 +44,13 @@ - M4.2 (2026-10-25): a Changes tab in the bottom panel (`vcs.openChanges` `Mod+Alt+Shift+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+Alt+Shift+M` 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`. - M4.4 (2026-10-25): the editor gutter shows a bar beside lines added or changed since the staged version and a notch where lines were deleted (tooltips from the catalog), updated 150 ms after typing and whenever Git changes; file names in the project tree and the tabs take the Git status colour (added, modified, deleted, untracked, conflicted; ignored entries inside a repository). Vitest. Missing: clicking a marker to see the old text, revert or stage the chunk, next/previous change, markers against HEAD, coloured directories. - M4.3 (2026-10-26): "Diff: " tabs in the editor area after the file tabs (`vcs.showDiff` `Mod+Alt+Shift+D`, menu Git › Show Diff; double-click or Enter in Changes; right click or Shift+F10 on a file in the project tree → Show Diff): the staged version or the last commit on the left, read-only, and the working copy on the right, editable like its own tab; a caption says what is compared; changed lines and words tinted with the VCS tokens, a change bar in each gutter, unchanged stretches collapsed to a clickable row; next/previous change `Alt+Shift+]` / `Alt+Shift+[` (wrapping); notices for binary, too large and deleted files and for git's errors. The project tree got its first context menu (Open, Show Diff; WAI-ARIA menu, keyboard). Vitest. Missing: unified view, revert/stage arrows between the sides, synchronised horizontal scrolling, whitespace and highlighting options, comparing with any revision, a diff window of its own, more tree context menu items. + - M4.5 (2026-10-26): the status bar shows the current branch (Lucide `git-branch`), or the short hash when detached, hidden outside a repository. A click or `vcs.branches` (menu Git › Branches…) opens a popup above it: a filter field, "New branch…", Local (current one checked, upstream beside it) and Remote headings; Up/Down/Page keys, Enter or a click checks out, Escape or a click outside closes and returns the focus. "New branch…" switches to a name field with a "Check out" checkbox; git's refusal shows under the field. An exclusive modal. Vitest (16 tests). Missing: merge, rebase, rename, delete, compare with current, favourites, recent branches first, incoming/outgoing markers, a submenu per branch. ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Branch widget and popup (M4.5) | | 2026-10-26 | minor | Diff viewer and the project tree's context menu (M4.3) | | 2026-10-25 | minor | Git change markers in the gutter, status colours in the tree and tabs (M4.4) | | 2026-10-25 | minor | Changes tool window (M4.2) | diff --git a/ui/src/commands/modals.ts b/ui/src/commands/modals.ts index 8ab9a36..0194f99 100644 --- a/ui/src/commands/modals.ts +++ b/ui/src/commands/modals.ts @@ -18,14 +18,14 @@ * but the go-to open commands closes it. So is the app menu (M3.9): any * command but `menu.open` closes it. * - **Navigation (M3.5):** the definition picker and the inline rename field - * are exclusive modals too. + * are exclusive modals too. So is the branches popup (M4.5). */ import { defineStore } from "pinia"; import { ref, watch } from "vue"; import { useEditorStore } from "../stores/editor"; /** The exclusive modals. */ -export type ModalId = "palette" | "goto" | "menu" | "settings" | "closePrompt" | "navPicker" | "rename"; +export type ModalId = "palette" | "goto" | "menu" | "settings" | "closePrompt" | "navPicker" | "rename" | "branches"; /** Store of the open exclusive modal. */ export const useModalsStore = defineStore("modals", () => { diff --git a/ui/src/commands/uiCommands.ts b/ui/src/commands/uiCommands.ts index 9429f64..d4fdf79 100644 --- a/ui/src/commands/uiCommands.ts +++ b/ui/src/commands/uiCommands.ts @@ -35,7 +35,10 @@ 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.branches", labelKey: "command.vcs.branches", menuPath: "Git/Branches…" }, + { id: "vcs.checkout", labelKey: "command.vcs.checkout" }, { id: "vcs.commit", labelKey: "command.vcs.commit", menuPath: "Git/Commit…", defaultShortcut: "Mod+Alt+Shift+M" }, + { id: "vcs.newBranch", labelKey: "command.vcs.newBranch", menuPath: "Git/New Branch…" }, { id: "vcs.openChanges", labelKey: "command.vcs.openChanges", menuPath: "Git/Changes", defaultShortcut: "Mod+Alt+Shift+G" }, { id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" }, { id: "vcs.showDiff", labelKey: "command.vcs.showDiff", menuPath: "Git/Show Diff", defaultShortcut: "Mod+Alt+Shift+D" }, diff --git a/ui/src/components/StatusBar.vue b/ui/src/components/StatusBar.vue index ee2b5bc..dbfc4f4 100644 --- a/ui/src/components/StatusBar.vue +++ b/ui/src/components/StatusBar.vue @@ -2,12 +2,13 @@ /** * Status bar along the bottom of the main window. Shows the product name and * version, or the last engine error, and on the right the language server's - * progress (H3). + * progress (H3) and the Git branch (M4.5). */ import { computed } from "vue"; import { t } from "../i18n"; import { useAppStore } from "../stores/app"; import LspProgressItem from "./problems/LspProgressItem.vue"; +import BranchStatusItem from "./vcs/branches/BranchStatusItem.vue"; const app = useAppStore(); @@ -28,6 +29,7 @@ const label = computed(() => { > {{ label }} + diff --git a/ui/src/components/vcs/branches/BranchPopup.vue b/ui/src/components/vcs/branches/BranchPopup.vue new file mode 100644 index 0000000..2d4feed --- /dev/null +++ b/ui/src/components/vcs/branches/BranchPopup.vue @@ -0,0 +1,536 @@ + + + + + diff --git a/ui/src/components/vcs/branches/BranchStatusItem.vue b/ui/src/components/vcs/branches/BranchStatusItem.vue new file mode 100644 index 0000000..e2265e7 --- /dev/null +++ b/ui/src/components/vcs/branches/BranchStatusItem.vue @@ -0,0 +1,177 @@ + + + + + diff --git a/ui/src/components/vcs/branches/branches.ts b/ui/src/components/vcs/branches/branches.ts new file mode 100644 index 0000000..04b51c2 --- /dev/null +++ b/ui/src/components/vcs/branches/branches.ts @@ -0,0 +1,396 @@ +/** + * The branches popup's state (M4.5): the repository's branches from + * `git.branches`, the filter, and switching to or creating a branch. + * + * - **Current branch:** the status-bar item reads it from the Changes + * store's `git.status` ({@link headLabel}), which already follows + * `gitChanged`, so there is no second status query. + * - **List:** `git.branches` (a pending outcome, so through `runWaiting`) + * each time the popup opens. Local branches come first, then remote + * ones; a filter keeps the names that contain every word of it, + * ignoring case. Malformed entries are dropped and the count capped + * ({@link MAX_BRANCHES}). + * - **Checkout:** `flushDirty()` first, so git sees what the editor shows + * and refuses instead of losing an unsaved edit; a save that failed + * cancels the checkout. git's own refusal (local changes would be + * overwritten, unknown branch) becomes an error toast that names the + * branch and quotes git. Buffers whose files changed reload through the + * file watcher. + * - **New branch:** `git.createBranch {name, checkout}` from HEAD. Creating + * and switching from HEAD leaves the files as they are, so nothing is + * saved first. A refusal stays in the popup next to the name. + */ +import { defineStore } from "pinia"; +import { computed, ref, shallowRef } from "vue"; +import { runWaiting, type JsonValue } from "../../../ipc"; +import { useAutosaveStore } from "../../../stores/autosave"; +import { useNotificationsStore } from "../../../stores/notifications"; +import { SHORT_HASH, type RepoSummary } from "../changes/changes"; + +/** Most branches kept per kind from one answer. */ +export const MAX_BRANCHES = 10_000; + +/** A branch as `git.branches` reports it. */ +export interface Branch { + /** Short name: `main`, or `origin/main` for a remote branch. */ + name: string; + /** Full hash of the commit it points to. */ + head: string; + /** The upstream of a local branch, such as `origin/main`. */ + upstream?: string; +} + +/** The result of `git.branches`, as the store keeps it. */ +export interface BranchList { + /** The checked-out branch; null when detached. */ + current: string | null; + /** Local branches, sorted by name. */ + local: Branch[]; + /** Remote-tracking branches, sorted by name. */ + remote: Branch[]; +} + +/** The value of `newError` when the name was blank. */ +export const EMPTY_NAME = "\u0000empty"; + +/** Which part of the popup shows. */ +export type BranchesMode = "list" | "new"; + +/** + * Reads the branches of one kind; malformed entries are dropped. + * + * @param raw - the untrusted `local` or `remote` field. + */ +function toBranchArray(raw: unknown): Branch[] { + if (!Array.isArray(raw)) { + return []; + } + const out: Branch[] = []; + for (const entry of raw as unknown[]) { + if (out.length >= MAX_BRANCHES) { + break; + } + if (typeof entry !== "object" || entry === null) { + continue; + } + const b = entry as Record; + if (typeof b.name !== "string" || b.name === "") { + continue; + } + const branch: Branch = { name: b.name, head: typeof b.head === "string" ? b.head : "" }; + if (typeof b.upstream === "string" && b.upstream !== "") { + branch.upstream = b.upstream; + } + out.push(branch); + } + return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); +} + +/** + * Reads the result of `git.branches`; null if it is not an object. + * + * @param raw - untrusted. + */ +export function toBranches(raw: unknown): BranchList | null { + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { + return null; + } + const r = raw as Record; + return { + current: typeof r.current === "string" && r.current !== "" ? r.current : null, + local: toBranchArray(r.local), + remote: toBranchArray(r.remote), + }; +} + +/** + * Keeps the branches whose name contains every word of the filter, + * ignoring case. + * + * @param branches - the branches. + * @param filter - the filter text; blank keeps everything. + */ +export function filterBranches(branches: Branch[], filter: string): Branch[] { + const words = filter.toLowerCase().split(/\s+/).filter((w) => w !== ""); + if (words.length === 0) { + return branches; + } + return branches.filter((b) => { + const name = b.name.toLowerCase(); + return words.every((w) => name.includes(w)); + }); +} + +/** + * What the status bar shows for HEAD: the branch, the short hash when + * detached, or null when there is nothing to name (no repository, no + * commit and no branch). + * + * @param repo - the repository summary of `git.status`. + */ +export function headLabel(repo: RepoSummary | null | undefined): string | null { + if (!repo) { + return null; + } + if (repo.branch !== undefined && !repo.detached) { + return repo.branch; + } + return repo.head ? repo.head.slice(0, SHORT_HASH) : (repo.branch ?? null); +} + +/** + * The text of an engine error for people: git's message as it is. + * + * @param message - the error message. + */ +function reasonOf(message: string): string { + return message.trim() === "" ? "?" : message.trim(); +} + +/** The Branches store. */ +export const useBranchesStore = defineStore("branches", () => { + const notifications = useNotificationsStore(); + + /** Whether the popup is open. */ + const open = ref(false); + /** Which part of the popup shows. */ + const mode = ref("list"); + /** The last list read; null before it arrived. */ + const list = shallowRef(null); + /** Whether `git.branches` runs. */ + const loading = ref(false); + /** Why the list could not be read. */ + const loadError = ref(null); + /** The filter text. */ + const filter = ref(""); + /** Index of the selected row of {@link rows}. */ + const selected = ref(0); + /** The name typed for a new branch. */ + const newName = ref(""); + /** Whether a new branch is checked out right away. */ + const newCheckout = ref(true); + /** Why the last new branch was refused. */ + const newError = ref(null); + /** Whether a checkout or a branch creation runs. */ + const busy = ref(false); + /** Bumped when the popup's field should take the focus. */ + const focusRequest = ref(0); + + /** Local branches that match the filter. */ + const local = computed(() => filterBranches(list.value?.local ?? [], filter.value)); + /** Remote branches that match the filter. */ + const remote = computed(() => filterBranches(list.value?.remote ?? [], filter.value)); + + /** + * The selectable rows in display order: "New branch…" (as null), then + * the local and the remote branches. + */ + const rows = computed<({ kind: "local" | "remote"; branch: Branch } | null)[]>(() => [ + null, + ...local.value.map((branch) => ({ kind: "local" as const, branch })), + ...remote.value.map((branch) => ({ kind: "remote" as const, branch })), + ]); + + /** Counts loads, so an older answer never replaces a newer one. */ + let loads = 0; + /** Whether the next list selects its first branch (set when the popup opens). */ + let pickFirst = false; + + /** Reads `git.branches`. */ + async function load(): Promise { + loads += 1; + const mine = loads; + loading.value = true; + const result = await runWaiting("git.branches"); + if (mine !== loads) { + return; + } + loading.value = false; + if (!result.ok) { + loadError.value = reasonOf(result.error.message); + return; + } + const next = toBranches(result.value); + loadError.value = next ? null : "unexpected result of git.branches"; + list.value = next; + if (pickFirst) { + pickFirst = false; + selected.value = rows.value.length > 1 ? 1 : 0; + } + clampSelection(); + } + + /** Keeps {@link selected} inside {@link rows}. */ + function clampSelection(): void { + selected.value = Math.min(Math.max(0, selected.value), rows.value.length - 1); + } + + /** + * Opens the popup and reads the branches. + * + * @param as - `list` for the branches, `new` for the name of a new one. + * @returns when the list arrived. + */ + function show(as: BranchesMode = "list"): Promise { + open.value = true; + mode.value = as; + filter.value = ""; + newError.value = null; + if (as === "new") { + newName.value = ""; + newCheckout.value = true; + } + selected.value = rows.value.length > 1 ? 1 : 0; + pickFirst = true; + focusRequest.value += 1; + return load(); + } + + /** Closes the popup. */ + function hide(): void { + open.value = false; + mode.value = "list"; + } + + /** Switches to entering a new branch's name. */ + function startNew(): void { + mode.value = "new"; + newName.value = filter.value.trim(); + newCheckout.value = true; + newError.value = null; + focusRequest.value += 1; + } + + /** Goes back from the new branch's name to the list. */ + function backToList(): void { + mode.value = "list"; + newError.value = null; + focusRequest.value += 1; + } + + /** + * Sets the filter and selects the first branch that matches. + * + * @param text - the filter. + */ + function setFilter(text: string): void { + filter.value = text; + pickFirst = false; + selected.value = rows.value.length > 1 ? 1 : 0; + } + + /** + * Moves the selection by `delta` rows, clamped. + * + * @param delta - rows to move; positive is down. + */ + function move(delta: number): void { + pickFirst = false; + selected.value += delta; + clampSelection(); + } + + /** + * Saves every dirty buffer, then checks out a branch. A remote branch + * (`origin/x`) checks out its local tracking branch `x`, created when + * missing. + * + * @param branch - the branch name. + * @returns whether git checked it out. + */ + async function checkout(branch: string): Promise { + if (busy.value) { + return false; + } + busy.value = true; + try { + const flushed = await useAutosaveStore().flushDirty(); + if (flushed.error !== null || flushed.failed.length > 0) { + notifications.notify({ + level: "warning", + messageKey: "notification.vcs.checkoutNotSaved", + params: { branch }, + }); + return false; + } + const result = await runWaiting("git.checkout", { branch }); + if (!result.ok) { + const reason = reasonOf(result.error.message); + notifications.notify({ + level: "error", + messageKey: "notification.vcs.checkoutFailed", + message: reason, + params: { branch, reason }, + }); + return false; + } + notifications.notify({ level: "info", messageKey: "notification.vcs.checkedOut", params: { branch } }); + return true; + } finally { + busy.value = false; + } + } + + /** + * Creates a branch at HEAD. + * + * @param name - its name; surrounding blanks are dropped. + * @param thenCheckout - whether to switch to it. + * @returns null when created, else why not (also kept in {@link newError}). + */ + async function create(name: string, thenCheckout: boolean): Promise { + const trimmed = name.trim(); + if (trimmed === "") { + newError.value = EMPTY_NAME; + return newError.value; + } + if (busy.value) { + return "busy"; + } + busy.value = true; + try { + const params: JsonValue = { name: trimmed, checkout: thenCheckout }; + const result = await runWaiting("git.createBranch", params); + if (!result.ok) { + newError.value = reasonOf(result.error.message); + return newError.value; + } + newError.value = null; + notifications.notify({ + level: "info", + messageKey: "notification.vcs.branchCreated", + params: { branch: trimmed }, + }); + return null; + } finally { + busy.value = false; + } + } + + return { + open, + mode, + list, + loading, + loadError, + filter, + selected, + newName, + newCheckout, + newError, + busy, + focusRequest, + local, + remote, + rows, + load, + show, + hide, + startNew, + backToList, + setFilter, + move, + checkout, + create, + }; +}); diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index 15a4323..aec494b 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -19,7 +19,10 @@ "command.settings.open": "Settings…", "command.terminal.open": "Terminal", "command.unavailable": "{command} cannot run right now", + "command.vcs.branches": "Branches…", + "command.vcs.checkout": "Check Out Branch", "command.vcs.commit": "Commit…", + "command.vcs.newBranch": "New Branch…", "command.vcs.nextChange": "Next Change", "command.vcs.openChanges": "Changes", "command.vcs.previousChange": "Previous Change", @@ -152,8 +155,13 @@ "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.branchCreated": "Created branch {branch}", + "notification.vcs.checkedOut": "Checked out {branch}", + "notification.vcs.checkoutFailed": "Git did not check out {branch}: {reason}", + "notification.vcs.checkoutNotSaved": "Checkout of {branch} cancelled: not every file could be saved first.", "notification.vcs.commitNotSaved": "Commit cancelled: not every file could be saved first.", "notification.vcs.committed": "Committed {hash}: {summary}", + "notification.vcs.newBranchFailed": "Branch {branch} was not created: {reason}", "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", @@ -273,6 +281,21 @@ "terminal.toolWindow.title": "Terminal", "theme.lutraDark": "Lutra Dark", "theme.lutraLight": "Lutra Light", + "vcs.branchItem.detached": "Detached HEAD at {hash}. Click for branches.", + "vcs.branchItem.label": "Git branch {branch}. Click for branches.", + "vcs.branches.create": "Create", + "vcs.branches.current": "current", + "vcs.branches.filter": "Filter branches", + "vcs.branches.label": "Branches", + "vcs.branches.loadFailed": "The branches cannot be read: {reason}", + "vcs.branches.loading": "Reading branches…", + "vcs.branches.local": "Local", + "vcs.branches.nameEmpty": "Enter a name for the branch.", + "vcs.branches.new": "New branch…", + "vcs.branches.newCheckout": "Check out", + "vcs.branches.newName": "Name of the new branch", + "vcs.branches.noMatches": "No branch matches", + "vcs.branches.remote": "Remote", "vcs.changes.clean": "{branch}: no changes", "vcs.changes.group.changes": "Changes", "vcs.changes.group.staged": "Staged", @@ -292,6 +315,7 @@ "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.checkout.invalidParams": "vcs.checkout needs a branch name (params: branch).", "vcs.commit.amend": "Amend", "vcs.commit.amendButton": "Amend Commit", "vcs.commit.button": "Commit", diff --git a/ui/tests/i18n/catalog.test.ts b/ui/tests/i18n/catalog.test.ts index 92b6767..7663cd5 100644 --- a/ui/tests/i18n/catalog.test.ts +++ b/ui/tests/i18n/catalog.test.ts @@ -45,7 +45,8 @@ const usedKeys = sourceFiles(SRC).flatMap((file) => * `settings.list`, the `messageKey` of * `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`. + * window's commit toasts (M4.2) and the branch toasts (M4.5), passed as + * `messageKey`. */ const RUNTIME_KEYS = new Set([ "notification.command.failed", @@ -59,8 +60,13 @@ const RUNTIME_KEYS = new Set([ "notification.recovery.unavailable", "notification.recovery.writeFailed", "notification.save.failed", + "notification.vcs.branchCreated", + "notification.vcs.checkedOut", + "notification.vcs.checkoutFailed", + "notification.vcs.checkoutNotSaved", "notification.vcs.commitNotSaved", "notification.vcs.committed", + "notification.vcs.newBranchFailed", "notification.settings.corrupt", "notification.settings.corruptNotMoved", "notification.settings.unavailable", diff --git a/ui/tests/menu/AppMenu.test.ts b/ui/tests/menu/AppMenu.test.ts index bc94c1f..bfc71f5 100644 --- a/ui/tests/menu/AppMenu.test.ts +++ b/ui/tests/menu/AppMenu.test.ts @@ -275,8 +275,10 @@ describe("AppMenu", () => { "goto.fileOpen", "goto.classOpen", "goto.symbolOpen", + "vcs.branches", "vcs.openChanges", "vcs.commit", + "vcs.newBranch", "vcs.nextChange", "vcs.previousChange", "vcs.refresh", diff --git a/ui/tests/palette/CommandPalette.test.ts b/ui/tests/palette/CommandPalette.test.ts index c587821..152ace8 100644 --- a/ui/tests/palette/CommandPalette.test.ts +++ b/ui/tests/palette/CommandPalette.test.ts @@ -258,7 +258,9 @@ 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.branches", "vcs.openChanges", + "vcs.checkout", "project.close", "palette.open", "vcs.commit", @@ -267,6 +269,7 @@ describe("CommandPalette", () => { "goto.classOpen", "goto.fileOpen", "goto.symbolOpen", + "vcs.newBranch", "vcs.nextChange", "project.openDialog", "menu.open", @@ -315,7 +318,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("vcs.openChanges"); + expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("vcs.branches"); }); it("dims disabled commands, which Enter and clicks do not run", async () => { diff --git a/ui/tests/vcs/Branches.test.ts b/ui/tests/vcs/Branches.test.ts new file mode 100644 index 0000000..c4c5afe --- /dev/null +++ b/ui/tests/vcs/Branches.test.ts @@ -0,0 +1,399 @@ +/** + * Tests of the branches feature (M4.5): reading an untrusted + * `git.branches`, the filter, the status-bar label (branch, short hash when + * detached, hidden outside a repository), the popup (local before remote, + * the current branch marked, filtering, keyboard, choosing the current + * branch), checkout with `flushDirty` first, git's refusal as a toast, a + * cancelled checkout when a save fails, creating a branch (in the popup and + * through `vcs.newBranch {name}`), and the registration of `vcs.branches`, + * `vcs.newBranch` and `vcs.checkout`. 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 { useModalsStore } from "../../src/commands/modals"; +import { useCommandsStore } from "../../src/commands/store"; +import { UI_COMMANDS } from "../../src/commands/uiCommands"; +import BranchStatusItem from "../../src/components/vcs/branches/BranchStatusItem.vue"; +import { + filterBranches, + headLabel, + toBranches, + useBranchesStore, +} from "../../src/components/vcs/branches/branches"; +import { useChangesStore } 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; +} + +/** Every engine call, in order. */ +let calls: Call[]; +/** What `git.status` answers. */ +let gitStatus: unknown; +/** What `git.branches` answers. */ +let gitBranches: unknown; +/** Errors to throw, by command id. */ +let failures: Record; +/** What `file.saveAll` answers. */ +let saveAll: unknown; +/** Pinia of the current test. */ +let pinia: Pinia; +/** Mounted components, unmounted after each test. */ +let mounted: VueWrapper[]; + +/** + * The calls of a command. + * + * @param command - the command id. + */ +function callsOf(command: string): Call[] { + return calls.filter((c) => c.command === command); +} + +/** Mounts the status-bar item with started stores. */ +async function mountItem(): Promise { + useChangesStore(pinia).start(); + const wrapper = mount(BranchStatusItem, { attachTo: document.body, global: { plugins: [pinia] } }); + mounted.push(wrapper); + await useCommandsStore(pinia).start(); + await flushPromises(); + return wrapper; +} + +/** + * Opens the popup by clicking the item. + * + * @param wrapper - the item. + */ +async function openPopup(wrapper: VueWrapper): Promise { + await wrapper.get("[data-test=branch-item]").trigger("click"); + await flushPromises(); +} + +/** + * The names of the rows of a kind. + * + * @param wrapper - the item. + * @param kind - `local` or `remote`. + */ +function names(wrapper: VueWrapper, kind: "local" | "remote"): string[] { + return wrapper.findAll(`[data-test=branches-${kind}]`).map((row) => row.attributes("data-branch") ?? ""); +} + +beforeEach(() => { + pinia = createPinia(); + setActivePinia(pinia); + calls = []; + mounted = []; + failures = {}; + gitStatus = { available: true, repo: { root: "C:/p", branch: "main", detached: false, head: "0123456789abcdef" }, files: [] }; + gitBranches = { + current: "main", + local: [ + { name: "main", head: "0123", upstream: "origin/main" }, + { name: "feature/login", head: "4567" }, + ], + remote: [ + { name: "origin/main", head: "0123" }, + { name: "origin/release", head: "89ab" }, + ], + }; + saveAll = { saved: [], failed: [], skipped: [] }; + Element.prototype.scrollIntoView = () => undefined; + invoke.mockReset(); + listen.mockReset(); + listen.mockImplementation(() => Promise.resolve(() => undefined)); + invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { + if (cmd === "engine_list_commands") { + return Promise.resolve([ + { id: "git.status", label: "Git Status", enabled: true }, + { id: "git.branches", label: "Git Branches", 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.branches": + return Promise.resolve(gitBranches); + case "file.saveAll": + return Promise.resolve(saveAll); + default: + return Promise.resolve({}); + } + }); +}); + +afterEach(() => { + for (const wrapper of mounted) { + wrapper.unmount(); + } + useChangesStore(pinia).stop(); + document.body.innerHTML = ""; +}); + +describe("reading git.branches", () => { + it("drops malformed entries and sorts by name", () => { + const list = toBranches({ + current: "", + local: [{ name: "z", head: "1" }, { name: "" }, "x", null, { name: "a", head: 5, upstream: "origin/a" }], + remote: "nope", + }); + expect(list).toEqual({ + current: null, + local: [ + { name: "a", head: "", upstream: "origin/a" }, + { name: "z", head: "1" }, + ], + remote: [], + }); + expect(toBranches(null)).toBeNull(); + expect(toBranches([1])).toBeNull(); + }); + + it("filters by every word, ignoring case", () => { + const all = [{ name: "feature/Login", head: "" }, { name: "main", head: "" }, { name: "fix/login-form", head: "" }]; + expect(filterBranches(all, "LOGIN").map((b) => b.name)).toEqual(["feature/Login", "fix/login-form"]); + expect(filterBranches(all, "login fix").map((b) => b.name)).toEqual(["fix/login-form"]); + expect(filterBranches(all, " ")).toHaveLength(3); + }); + + it("labels HEAD with the branch or the short hash", () => { + expect(headLabel({ root: "/r", branch: "main", detached: false, head: "abc" })).toBe("main"); + expect(headLabel({ root: "/r", detached: true, head: "0123456789" })).toBe("0123456"); + expect(headLabel({ root: "/r", branch: "main", detached: false })).toBe("main"); + expect(headLabel({ root: "/r", detached: false })).toBeNull(); + expect(headLabel(null)).toBeNull(); + }); +}); + +describe("the status-bar item", () => { + it("shows the branch, the short hash when detached, and hides outside a repository", async () => { + const wrapper = await mountItem(); + expect(wrapper.get("[data-test=branch-item]").text()).toBe("main"); + expect(wrapper.get("[data-test=branch-item]").attributes("aria-label")).toContain("main"); + gitStatus = { available: true, repo: { root: "C:/p", detached: true, head: "fedcba9876" }, files: [] }; + await useChangesStore(pinia).refresh(); + expect(wrapper.get("[data-test=branch-item]").text()).toBe("fedcba9"); + expect(wrapper.get("[data-test=branch-item]").attributes("aria-label")).toContain("Detached"); + gitStatus = { available: true, repo: null, files: [] }; + await useChangesStore(pinia).refresh(); + expect(wrapper.find("[data-test=branch-item]").exists()).toBe(false); + gitStatus = { available: false, error: "no git", repo: null, files: [] }; + await useChangesStore(pinia).refresh(); + expect(wrapper.find("[data-test=branch-item]").exists()).toBe(false); + }); +}); + +describe("the branches popup", () => { + it("lists local before remote branches, marks the current one and filters", async () => { + const wrapper = await mountItem(); + await openPopup(wrapper); + expect(callsOf("git.branches")[0]?.via).toBe("engine_execute_waiting"); + expect(names(wrapper, "local")).toEqual(["feature/login", "main"]); + expect(names(wrapper, "remote")).toEqual(["origin/main", "origin/release"]); + const main = wrapper.findAll("[data-test=branches-local]")[1]; + expect(main?.attributes("aria-current")).toBe("true"); + expect(main?.text()).toContain("current"); + expect(document.activeElement).toBe(wrapper.get("[data-test=branches-filter]").element); + expect(useModalsStore(pinia).current).toBe("branches"); + await wrapper.get("[data-test=branches-filter]").setValue("rel"); + expect(names(wrapper, "local")).toEqual([]); + expect(names(wrapper, "remote")).toEqual(["origin/release"]); + await wrapper.get("[data-test=branches-filter]").setValue("zzz"); + expect(wrapper.get("[data-test=branches-hint]").text()).toBe("No branch matches"); + }); + + it("checks out with Enter after saving dirty buffers", async () => { + const wrapper = await mountItem(); + await openPopup(wrapper); + const filter = wrapper.get("[data-test=branches-filter]"); + await filter.setValue("login"); + await filter.trigger("keydown", { key: "Enter" }); + await flushPromises(); + const order = calls.map((c) => c.command).filter((c) => c === "file.saveAll" || c === "git.checkout"); + expect(order).toEqual(["file.saveAll", "git.checkout"]); + expect(callsOf("git.checkout")[0]).toMatchObject({ via: "engine_execute_waiting", params: { branch: "feature/login" } }); + expect(wrapper.find("[data-test=branches]").exists()).toBe(false); + expect(useModalsStore(pinia).current).toBeNull(); + expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toBe("Checked out feature/login"); + }); + + it("checks out a remote branch from a click and only closes on the current branch", async () => { + const wrapper = await mountItem(); + await openPopup(wrapper); + await wrapper.findAll("[data-test=branches-local]")[1]?.trigger("click"); + await flushPromises(); + expect(callsOf("git.checkout")).toHaveLength(0); + expect(wrapper.find("[data-test=branches]").exists()).toBe(false); + await openPopup(wrapper); + await wrapper.findAll("[data-test=branches-remote]")[1]?.trigger("click"); + await flushPromises(); + expect(callsOf("git.checkout")[0]?.params).toEqual({ branch: "origin/release" }); + }); + + it("moves with the arrow keys and closes with Escape", async () => { + const wrapper = await mountItem(); + await openPopup(wrapper); + const branches = useBranchesStore(pinia); + expect(branches.selected).toBe(1); + const filter = wrapper.get("[data-test=branches-filter]"); + await filter.trigger("keydown", { key: "ArrowUp" }); + expect(branches.selected).toBe(0); + await filter.trigger("keydown", { key: "ArrowUp" }); + expect(branches.selected).toBe(0); + await filter.trigger("keydown", { key: "PageDown" }); + expect(branches.selected).toBe(4); + await filter.trigger("keydown", { key: "Escape" }); + await flushPromises(); + expect(wrapper.find("[data-test=branches]").exists()).toBe(false); + }); + + it("toasts git's refusal and names the branch", async () => { + failures["git.checkout"] = { + code: "failed", + message: "error: Your local changes to the following files would be overwritten by checkout:\n\tsrc/a.php", + }; + const wrapper = await mountItem(); + await openPopup(wrapper); + await wrapper.findAll("[data-test=branches-local]")[0]?.trigger("click"); + await flushPromises(); + const toast = useNotificationsStore(pinia).toasts.at(-1); + expect(toast?.level).toBe("error"); + expect(toast?.text).toContain("Git did not check out feature/login"); + expect(toast?.text).toContain("would be overwritten by checkout"); + expect(useBranchesStore(pinia).busy).toBe(false); + }); + + it("cancels the checkout when a buffer cannot be saved", async () => { + saveAll = { saved: [], failed: [{ id: 3, path: "src/a.php", message: "disk full" }], skipped: [] }; + const wrapper = await mountItem(); + await openPopup(wrapper); + await wrapper.findAll("[data-test=branches-local]")[0]?.trigger("click"); + await flushPromises(); + expect(callsOf("git.checkout")).toHaveLength(0); + const toast = useNotificationsStore(pinia).toasts.find((t) => t.text.includes("Checkout of feature/login cancelled")); + expect(toast?.level).toBe("warning"); + }); + + it("creates a branch from the popup and keeps git's refusal in place", async () => { + const wrapper = await mountItem(); + await openPopup(wrapper); + await wrapper.get("[data-test=branches-filter]").setValue("topic"); + await wrapper.get("[data-test=branches-new]").trigger("click"); + await flushPromises(); + const name = wrapper.get("[data-test=branches-new-name]"); + expect((name.element as HTMLInputElement).value).toBe("topic"); + expect(document.activeElement).toBe(name.element); + await name.setValue(" "); + await wrapper.get("[data-test=branches-new-form]").trigger("submit"); + await flushPromises(); + expect(wrapper.get("[data-test=branches-new-error]").text()).toBe("Enter a name for the branch."); + expect(callsOf("git.createBranch")).toHaveLength(0); + failures["git.createBranch"] = { code: "failed", message: "fatal: a branch named 'main' already exists" }; + await name.setValue("main"); + await wrapper.get("[data-test=branches-new-form]").trigger("submit"); + await flushPromises(); + expect(wrapper.get("[data-test=branches-new-error]").text()).toContain("already exists"); + expect(wrapper.find("[data-test=branches]").exists()).toBe(true); + delete failures["git.createBranch"]; + await name.setValue("topic/x"); + await wrapper.get("[data-test=branches-new-checkout]").setValue(false); + await wrapper.get("[data-test=branches-new-form]").trigger("submit"); + await flushPromises(); + expect(callsOf("git.createBranch").at(-1)).toMatchObject({ + via: "engine_execute_waiting", + params: { name: "topic/x", checkout: false }, + }); + expect(wrapper.find("[data-test=branches]").exists()).toBe(false); + expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toBe("Created branch topic/x"); + }); + + it("goes back from the new branch's name to the list with Escape", async () => { + const wrapper = await mountItem(); + await useCommandsStore(pinia).execute("vcs.newBranch"); + await flushPromises(); + expect(wrapper.find("[data-test=branches-new-form]").exists()).toBe(true); + await wrapper.get("[data-test=branches-new-name]").trigger("keydown", { key: "Escape" }); + await flushPromises(); + expect(wrapper.find("[data-test=branches-filter]").exists()).toBe(true); + }); +}); + +describe("the branch commands", () => { + it("are registered with menu paths and without shortcuts", () => { + const byId = new Map(UI_COMMANDS.map((c) => [c.id, c])); + expect(byId.get("vcs.branches")).toMatchObject({ menuPath: "Git/Branches…" }); + expect(byId.get("vcs.newBranch")).toMatchObject({ menuPath: "Git/New Branch…" }); + expect(byId.get("vcs.checkout")?.menuPath).toBeUndefined(); + expect(["vcs.branches", "vcs.newBranch", "vcs.checkout"].map((id) => byId.get(id)?.defaultShortcut)).toEqual([ + undefined, + undefined, + undefined, + ]); + }); + + it("vcs.checkout {branch} saves first, opens the popup without a branch and refuses a bad one", async () => { + const wrapper = await mountItem(); + const commands = useCommandsStore(pinia); + await commands.execute("vcs.checkout", { branch: "feature/login" }); + await flushPromises(); + expect(callsOf("file.saveAll")).toHaveLength(1); + expect(callsOf("git.checkout")[0]?.params).toEqual({ branch: "feature/login" }); + await commands.execute("vcs.checkout", { branch: 3 }); + await flushPromises(); + expect(callsOf("git.checkout")).toHaveLength(1); + expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toContain("vcs.checkout needs a branch name"); + await commands.execute("vcs.checkout"); + await flushPromises(); + expect(wrapper.find("[data-test=branches-filter]").exists()).toBe(true); + }); + + it("vcs.newBranch {name} creates and checks out without the popup", async () => { + const wrapper = await mountItem(); + const commands = useCommandsStore(pinia); + await commands.execute("vcs.newBranch", { name: "agent/work" }); + await flushPromises(); + expect(callsOf("git.createBranch")[0]?.params).toEqual({ name: "agent/work", checkout: true }); + expect(wrapper.find("[data-test=branches]").exists()).toBe(false); + failures["git.createBranch"] = { code: "invalid_params", message: "invalid branch name: -x" }; + await commands.execute("vcs.newBranch", { name: "-x", checkout: false }); + await flushPromises(); + const toast = useNotificationsStore(pinia).toasts.at(-1); + expect(toast?.level).toBe("error"); + expect(toast?.text).toContain("Branch -x was not created: invalid branch name: -x"); + }); + + it("are disabled without a project", async () => { + invoke.mockImplementation((cmd: string) => + Promise.resolve(cmd === "engine_list_commands" ? [{ id: "git.branches", label: "", enabled: false }] : null), + ); + await mountItem(); + const commands = useCommandsStore(pinia); + expect(commands.isEnabled("vcs.branches")).toBe(false); + expect(commands.isEnabled("vcs.newBranch")).toBe(false); + expect(commands.isEnabled("vcs.checkout")).toBe(false); + }); +});