From fc8ae6c2e3e7fb137941063669258f3488db67aa Mon Sep 17 00:00:00 2001 From: danny Date: Sun, 25 Oct 2026 17:36:59 +0100 Subject: [PATCH] M4.4: Git gutter change markers and status colours in tree and tabs - git.lineChanges {id} -> {ranges: [{kind, startLine, endLine}], version}: the buffer against its index blob, line diff with similar (Myers + Replace, no Compact) off the lock, CRLF-safe; index texts cached per path and dropped on gitChanged (State::emit -> git_lines::observe) - editor gutter markers for added, modified and deleted lines, queried 150 ms after edits, on show and on gitChanged, mapped through edits - vcsStatus store (git.status on projectOpened and gitChanged, no polling) colouring file names in the project tree and editor tabs with the --lt-vcs-* tokens; contrast also checked on the active tab - tests: unit and property tests, real-repo engine tests, Vitest - docs: architecture, parity, gaps, roadmap, ui-parity, ROADMAP Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 7 + ROADMAP.md | 10 +- crates/engine/Cargo.toml | 1 + crates/engine/src/cmd/git_lines.rs | 585 ++++++++++++++++++++++ crates/engine/src/cmd/mod.rs | 2 + crates/engine/src/engine.rs | 1 + crates/engine/src/state.rs | 3 + crates/engine/tests/git_lines.rs | 222 ++++++++ docs/architecture.md | 16 +- docs/gaps.md | 5 +- docs/roadmap.md | 5 +- docs/target-app-parity.md | 3 +- docs/ui-parity.md | 4 +- ui/src/App.vue | 7 +- ui/src/components/editor/EditorTabs.vue | 35 +- ui/src/components/editor/extensions.ts | 5 +- ui/src/components/editor/gitGutter.ts | 338 +++++++++++++ ui/src/components/project/ProjectTree.vue | 46 +- ui/src/i18n/en.json | 3 + ui/src/stores/vcsStatus.ts | 244 +++++++++ ui/tests/editor/gitGutter.test.ts | 253 ++++++++++ ui/tests/project/ProjectTree.test.ts | 29 +- ui/tests/theme/contrast.test.ts | 11 +- ui/tests/vcs/vcsStatus.test.ts | 155 ++++++ 24 files changed, 1970 insertions(+), 20 deletions(-) create mode 100644 crates/engine/src/cmd/git_lines.rs create mode 100644 crates/engine/tests/git_lines.rs create mode 100644 ui/src/components/editor/gitGutter.ts create mode 100644 ui/src/stores/vcsStatus.ts create mode 100644 ui/tests/editor/gitGutter.test.ts create mode 100644 ui/tests/vcs/vcsStatus.test.ts diff --git a/Cargo.lock b/Cargo.lock index 846f578..7355771 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2639,6 +2639,7 @@ dependencies = [ "proptest", "serde", "serde_json", + "similar", "tempfile", "thiserror 2.0.21", ] @@ -4429,6 +4430,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + [[package]] name = "siphasher" version = "1.0.4" diff --git a/ROADMAP.md b/ROADMAP.md index edd68d8..e58501d 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-25 · **Change:** minor (M4.2: Changes tool window, Git 4%) · **Target:** JetBrains PhpStorm 2026.x, described from public documentation only +> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-10-25 · **Change:** minor (M4.4: gutter markers and status colours, Git 6%) · **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.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 | +| **Feature depth** (weighted by use, scored by behaviour) | **~5.6%** (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 6% × 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 | @@ -25,7 +25,7 @@ Dimension hours overlap: language, framework and tooling hours are part of the f | Dimension | % | One agent (h) | Doc | |---|---:|---:|---| -| Features (depth) | ~5.1% | ~2,860 | [target-app-parity.md](docs/target-app-parity.md) | +| Features (depth) | ~5.6% | ~2,860 | [target-app-parity.md](docs/target-app-parity.md) | | UI/UX fidelity | 1% (est.) | ~150 on top of features | [ui-parity.md](docs/ui-parity.md) | | PHP language support | 0% | ~920 (in features) | [language-parity.md](docs/language-parity.md) | | Frameworks (Symfony, Laravel, Shopware, WordPress) | 0% | ~300 (in features) | [framework-parity.md](docs/framework-parity.md) | @@ -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) | 4% (est.) | ~138 | +| Version control (Git) | 6% (est.) | ~136 | | 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.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). | | 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. | @@ -102,6 +103,7 @@ All hours estimated. Weights, evidence and the missing items per area: [target-a | Date | Change | Summary | |---|---|---| +| 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 | | 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 | diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index f56f994..b2af5b4 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -22,6 +22,7 @@ lutra-vfs.workspace = true lutra-vcs.workspace = true serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" +similar = { version = "2.7.0", default-features = false } thiserror = "2.0.21" [lints] diff --git a/crates/engine/src/cmd/git_lines.rs b/crates/engine/src/cmd/git_lines.rs new file mode 100644 index 0000000..7fb751d --- /dev/null +++ b/crates/engine/src/cmd/git_lines.rs @@ -0,0 +1,585 @@ +//! `git.lineChanges` (M4.4): which lines of an open buffer were added, +//! modified or deleted against the file's version in the Git index, for +//! the editor's gutter markers. +//! +//! **Off the lock.** Under the lock the command only clones the buffer's +//! rope (cheap: ropes share their chunks) and takes the cached repository +//! and index text. A `lutra-git-lines` thread then finds git and the +//! repository if needed, reads the index text with `git show :0:` +//! if it is not cached, and diffs the lines with `similar` (Myers, with a +//! deadline). The finish, under the lock again, caches what the thread +//! found and returns the ranges. +//! +//! **Cache.** The index text of each path is cached (normalised to `\n` +//! line breaks), and so is the repository lookup. Every `gitChanged` +//! clears the index texts ([`observe`], called by [`State::emit`]); a +//! project change clears everything. A thread that started before a +//! `gitChanged` does not store what it read. "No repository" and "no +//! usable git" are cached for [`NEGATIVE_TTL`] only, since no `gitChanged` +//! arrives without a repository. +//! +//! **Lines.** Both texts are split at `\n`, `\r\n` and a lone `\r` (the +//! index holds the blob as stored, usually LF, while a buffer may be +//! CRLF), with no empty line after a final break. Lines are 0-based +//! (CodeMirror's line number minus one). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use lutra_text::Buffer; +use lutra_vcs::{Git, Repo, Rev}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use similar::DiffOp; +use similar::algorithms::{Capture, Replace, myers}; + +use super::params::parse; +use crate::buffers::BufferId; +use crate::workspace::path_string; +use crate::{Command, CommandSpec, EngineError, Event, Outcome, Pending, Registry, State}; + +/// How long "no repository" or "no usable git" is believed. +pub const NEGATIVE_TTL: Duration = Duration::from_secs(10); + +/// Longest the line diff may take before it settles for a coarser result. +const DIFF_DEADLINE: Duration = Duration::from_secs(1); + +/// Most ranges returned; a diff with more is cut. +pub const MAX_RANGES: usize = 10_000; + +/// Most index texts cached. +const MAX_CACHED: usize = 256; + +/// Most bytes of index text cached; the cache is cleared beyond it. +const MAX_CACHED_BYTES: usize = 64 * 1024 * 1024; + +/// Most calls running at once; more are refused. +const MAX_RUNNING: usize = 8; + +/// Longest wait for a call: git detection, opening and `show` each have +/// their own 30 s timeout in `lutra-vcs`; the runner kills git first. +const WAIT: Duration = Duration::from_secs(100); + +/// Registers `git.lineChanges`. +/// +/// # Errors +/// [`EngineError::Internal`] if the id is taken. +pub fn register(registry: &mut Registry) -> Result<(), EngineError> { + registry.register(Box::new(LineChanges)) +} + +/// The result of looking for the project's repository. +#[derive(Debug, Clone)] +struct Lookup { + /// The project root it was made for. + project: PathBuf, + /// The `git.executable` value it was made with. + setting: String, + /// The repository; `None` when there is none or git is unusable. + repo: Option>, + /// When it was made. + at: Instant, +} + +impl Lookup { + /// Whether the lookup still applies to `project` and `setting` at `now`. + fn applies(&self, project: &Path, setting: &str, now: Instant) -> bool { + self.project == project + && self.setting == setting + && (self.repo.is_some() || now.saturating_duration_since(self.at) < NEGATIVE_TTL) + } +} + +/// An index text; `None` when the path is not in the index, or the blob is +/// binary or too large. +type IndexText = Option>; + +/// Cached state of `git.lineChanges`. +#[derive(Debug, Default)] +pub struct GitLines { + /// The repository lookup. + lookup: Option, + /// Index texts by project-relative path. + index: HashMap, + /// Bytes held by `index`. + bytes: usize, + /// Incremented whenever the cache is cleared, so a thread that started + /// before does not store stale text. + generation: u64, + /// Calls running now. + running: Arc, +} + +impl GitLines { + /// Drops the cached index texts. + fn clear_index(&mut self) { + self.index.clear(); + self.bytes = 0; + self.generation = self.generation.wrapping_add(1); + } + + /// Stores the index text of `path`, clearing the cache first when it + /// would grow past its caps. + fn store(&mut self, path: String, text: IndexText) { + let size = text.as_ref().map_or(0, |t| t.len()); + if self.index.len() >= MAX_CACHED || self.bytes.saturating_add(size) > MAX_CACHED_BYTES { + self.index.clear(); + self.bytes = 0; + } + if size > MAX_CACHED_BYTES { + return; + } + if let Some(old) = self.index.insert(path, text) { + self.bytes = self + .bytes + .saturating_sub(old.as_ref().map_or(0, |t| t.len())); + } + self.bytes = self.bytes.saturating_add(size); + } +} + +/// Clears the cache for events that make it stale: `gitChanged` drops the +/// index texts, a project change everything. Called for every event by +/// [`State::emit`]. +pub fn observe(lines: &mut GitLines, event: &Event) { + match event { + Event::GitChanged(_) => lines.clear_index(), + Event::ProjectOpened { .. } | Event::ProjectClosed => { + lines.clear_index(); + lines.lookup = None; + } + _ => {} + } +} + +/// What a line changed: `added` lines are new, `modified` lines replace +/// others, and `deleted` marks where lines were removed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ChangeKind { + /// New lines. + Added, + /// Changed lines. + Modified, + /// Lines removed before `start_line`. + Deleted, +} + +/// One changed range of buffer lines. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LineRange { + /// What changed. + pub kind: ChangeKind, + /// The first line (0-based). + pub start_line: usize, + /// The line after the last one; equal to `start_line` for `deleted`, + /// where the removed lines were before `start_line` (which may be the + /// line count when they were at the end). + pub end_line: usize, +} + +/// Splits `text` into lines at `\n`, `\r\n` and a lone `\r`, without an +/// empty line after a final break. +fn split_lines(text: &str) -> Vec<&str> { + let mut lines = Vec::new(); + let mut rest = text; + while !rest.is_empty() { + match rest.find(['\n', '\r']) { + Some(at) => { + lines.push(rest.get(..at).unwrap_or_default()); + let skip = if rest.get(at..at + 2) == Some("\r\n") { + 2 + } else { + 1 + }; + rest = rest.get(at + skip..).unwrap_or_default(); + } + None => { + lines.push(rest); + rest = ""; + } + } + } + lines +} + +/// The changed ranges of `new` against `old`, at most [`MAX_RANGES`]; +/// the diff gives up refining after `deadline`. +/// +/// Myers' diff with adjacent deletes and inserts merged into replacements. +/// `similar`'s `Compact` step is left out on purpose: in 2.7.0 it can move +/// a delete to a wrong position in the new text (found by the property +/// test below). +pub fn line_changes(old: &str, new: &str, deadline: Option) -> Vec { + let old = split_lines(old); + let new = split_lines(new); + let mut hook = Replace::new(Capture::new()); + if myers::diff_deadline(&mut hook, &old, 0..old.len(), &new, 0..new.len(), deadline).is_err() { + return Vec::new(); + } + let ops = hook.into_inner().into_ops(); + ops.iter() + .filter_map(|op| match *op { + DiffOp::Equal { .. } => None, + DiffOp::Insert { + new_index, new_len, .. + } => Some(LineRange { + kind: ChangeKind::Added, + start_line: new_index, + end_line: new_index + new_len, + }), + DiffOp::Delete { new_index, .. } => Some(LineRange { + kind: ChangeKind::Deleted, + start_line: new_index, + end_line: new_index, + }), + DiffOp::Replace { + new_index, new_len, .. + } => Some(LineRange { + kind: ChangeKind::Modified, + start_line: new_index, + end_line: new_index + new_len, + }), + }) + .take(MAX_RANGES) + .collect() +} + +/// What the thread hands back to the finish. +struct Reply { + /// The repository lookup, when this call made one. + lookup: Option>>, + /// The index text, when this call read it. + index: Option, + /// The value or error. + value: Result, +} + +/// What the thread needs, taken under the lock. +struct Job { + /// The buffer's text. + buffer: Buffer, + /// Its version. + version: u64, + /// Its project-relative path. + path: String, + /// The project root. + project: PathBuf, + /// The `git.executable` setting. + setting: String, + /// The repository lookup, if one applies. + lookup: Option>>, + /// The cached index text, if any. + index: Option, +} + +/// The value for a buffer without index text to compare with. +fn unchanged(version: u64) -> Value { + json!({"ranges": [], "version": version}) +} + +/// The thread's work: find the repository and read the index text if they +/// are not cached, then diff. +fn work(job: Job) -> Reply { + let mut reply = Reply { + lookup: None, + index: None, + value: Ok(unchanged(job.version)), + }; + let repo = match job.lookup { + Some(repo) => repo, + None => { + let repo = Git::detect(&job.setting) + .ok() + .and_then(|git| git.open(&job.project).ok().flatten()) + .map(Arc::new); + reply.lookup = Some(repo.clone()); + repo + } + }; + let Some(repo) = repo else { + return reply; + }; + let index = match job.index { + Some(index) => index, + None => match repo.show(&job.path, Rev::Index) { + Ok(contents) => { + let text: IndexText = contents.text.map(Arc::from); + reply.index = Some(text.clone()); + text + } + Err(e) => { + reply.value = Err(EngineError::Failed(e.to_string())); + return reply; + } + }, + }; + let Some(index) = index else { + return reply; + }; + let text = job.buffer.text(); + let ranges = line_changes(&index, &text, Instant::now().checked_add(DIFF_DEADLINE)); + reply.value = Ok(json!({"ranges": ranges, "version": job.version})); + reply +} + +/// Params of `git.lineChanges`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct LineChangesParams { + /// Buffer id. + id: BufferId, +} + +/// `git.lineChanges`. +struct LineChanges; + +impl Command for LineChanges { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "git.lineChanges", + label: "Git: Line Changes", + menu_path: None, + default_shortcut: None, + params: "{ id: buffer id }; returns { ranges: [{ kind: \"added\"|\"modified\"|\"deleted\", startLine, endLine }], version } against the file in the Git index (lines 0-based, endLine exclusive; a deleted range has startLine = endLine, the removed lines were before it); no ranges when the project has no repository, git is unusable or the file is not in the index (untracked, binary, too large); the buffer version the ranges are for", + } + } + + fn enabled(&self, state: &State) -> bool { + state.has_project() + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let command = self.spec().id; + let p: LineChangesParams = parse(command, params)?; + let project = state + .project + .as_ref() + .ok_or_else(|| EngineError::Disabled(command.to_string()))? + .project + .root() + .to_path_buf(); + let open = state + .buffers + .get(p.id) + .ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {}", p.id)))?; + let path = path_string(&open.path); + let buffer = open.buffer.clone(); + let version = open.version; + let setting = state + .settings + .get(super::git::EXECUTABLE_SETTING) + .and_then(|v| v.as_str().map(str::to_string)) + .unwrap_or_default(); + let lines = &mut state.git_lines; + let now = Instant::now(); + if lines + .lookup + .as_ref() + .is_some_and(|l| !l.applies(&project, &setting, now)) + { + lines.lookup = None; + lines.clear_index(); + } + let lookup = lines.lookup.as_ref().map(|l| l.repo.clone()); + let index = lines.index.get(&path).cloned(); + let generation = lines.generation; + let running = Arc::clone(&lines.running); + if running.fetch_add(1, Ordering::SeqCst) >= MAX_RUNNING { + running.fetch_sub(1, Ordering::SeqCst); + return Err(EngineError::Failed( + "too many line change queries are running".into(), + )); + } + let job = Job { + buffer, + version, + path: path.clone(), + project: project.clone(), + setting: setting.clone(), + lookup, + index, + }; + let slot: Arc>> = Arc::new(Mutex::new(None)); + let (tx, rx) = mpsc::channel(); + let filled = Arc::clone(&slot); + let spawned = std::thread::Builder::new() + .name("lutra-git-lines".into()) + .spawn(move || { + let reply = work(job); + *filled.lock().unwrap_or_else(PoisonError::into_inner) = Some(reply); + running.fetch_sub(1, Ordering::SeqCst); + let _ = tx.send(Ok(Value::Null)); + }); + if let Err(e) = spawned { + state.git_lines.running.fetch_sub(1, Ordering::SeqCst); + return Err(EngineError::Failed(format!("cannot start git: {e}"))); + } + Ok(Outcome::pending(Pending::new(rx, WAIT, move |state, _| { + let reply = slot + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take() + .ok_or_else(|| EngineError::Failed("git did not answer in time".into()))?; + let current = state + .project + .as_ref() + .map(|w| w.project.root().to_path_buf()); + let lines = &mut state.git_lines; + if current.as_deref() == Some(project.as_path()) && lines.generation == generation { + if let Some(repo) = reply.lookup { + lines.lookup = Some(Lookup { + project, + setting, + repo, + at: Instant::now(), + }); + } + if let Some(text) = reply.index { + lines.store(path, text); + } + } + reply.value + }))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn range(kind: ChangeKind, start_line: usize, end_line: usize) -> LineRange { + LineRange { + kind, + start_line, + end_line, + } + } + + #[test] + fn splits_every_line_break_without_a_trailing_empty_line() { + assert_eq!(split_lines(""), Vec::<&str>::new()); + assert_eq!(split_lines("a"), vec!["a"]); + assert_eq!(split_lines("a\n"), vec!["a"]); + assert_eq!(split_lines("a\r\nb\rc\n\n"), vec!["a", "b", "c", ""]); + } + + #[test] + fn finds_added_modified_and_deleted_lines() { + let old = "a\nb\nc\nd\ne\n"; + assert_eq!(line_changes(old, old, None), vec![]); + assert_eq!( + line_changes(old, "a\nb\nx\ny\nc\nd\ne\n", None), + vec![range(ChangeKind::Added, 2, 4)] + ); + assert_eq!( + line_changes(old, "a\nB\nc\nd\ne\n", None), + vec![range(ChangeKind::Modified, 1, 2)] + ); + assert_eq!( + line_changes(old, "a\nd\ne\n", None), + vec![range(ChangeKind::Deleted, 1, 1)] + ); + assert_eq!( + line_changes(old, "a\nb\nc\n", None), + vec![range(ChangeKind::Deleted, 3, 3)] + ); + assert_eq!( + line_changes(old, "X\nb\nc\nd\n", None), + vec![ + range(ChangeKind::Modified, 0, 1), + range(ChangeKind::Deleted, 4, 4) + ] + ); + } + + #[test] + fn ranges_are_in_order_where_compaction_would_misplace_a_delete() { + let old = "aa\n\nb\ra\n\n\nb\n\nb\n\r"; + let new = "\n\na\n\ra\na\ra\r\r\ra\n\na\r\ra"; + let ranges = line_changes(old, new, None); + assert!(!ranges.is_empty()); + assert!( + ranges.windows(2).all(|w| w[0].end_line <= w[1].start_line), + "{ranges:?}" + ); + } + + #[test] + fn line_endings_do_not_count_as_changes() { + assert_eq!(line_changes("a\nb\n", "a\r\nb\r\n", None), vec![]); + assert_eq!(line_changes("a\nb", "a\nb\n", None), vec![]); + assert_eq!( + line_changes("a\r\nb\r\n", "a\r\nb\r\nc\r\n", None), + vec![range(ChangeKind::Added, 2, 3)] + ); + } + + #[test] + fn an_empty_index_file_makes_every_line_added() { + assert_eq!( + line_changes("", "a\nb\n", None), + vec![range(ChangeKind::Added, 0, 2)] + ); + assert_eq!( + line_changes("a\nb\n", "", None), + vec![range(ChangeKind::Deleted, 0, 0)] + ); + } + + #[test] + fn the_cache_respects_its_caps_and_generation() { + let mut lines = GitLines::default(); + lines.store("a".into(), Some(Arc::from("abc"))); + lines.store("a".into(), Some(Arc::from("abcd"))); + lines.store("b".into(), None); + assert_eq!(lines.bytes, 4); + let before = lines.generation; + observe( + &mut lines, + &Event::GitChanged(crate::cmd::git::GitChanged { + available: true, + repo: None, + files_changed: true, + }), + ); + assert!(lines.index.is_empty()); + assert_eq!(lines.bytes, 0); + assert_ne!(lines.generation, before); + for i in 0..=MAX_CACHED { + lines.store(i.to_string(), None); + } + assert!(lines.index.len() <= MAX_CACHED); + } + + proptest::proptest! { + #[test] + fn ranges_stay_inside_the_buffer( + old in "[ab\r\n]{0,40}", + new in "[ab\r\n]{0,40}", + ) { + let count = split_lines(&new).len(); + let ranges = line_changes(&old, &new, None); + let mut last = 0; + for r in &ranges { + proptest::prop_assert!(r.start_line <= r.end_line); + proptest::prop_assert!(r.end_line <= count); + proptest::prop_assert!(r.start_line >= last); + if r.kind == ChangeKind::Deleted { + proptest::prop_assert_eq!(r.start_line, r.end_line); + } else { + proptest::prop_assert!(r.start_line < r.end_line); + } + last = r.end_line; + } + if split_lines(&old) == split_lines(&new) { + proptest::prop_assert!(ranges.is_empty()); + } + } + } +} diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 5668357..110735e 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -4,6 +4,7 @@ mod app; mod buffer; mod file; pub mod git; +pub mod git_lines; pub mod goto; mod lsp_assist; mod lsp_diagnostics; @@ -66,5 +67,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> { lsp_assist::register(registry)?; lsp_nav::register(registry)?; git::register(registry)?; + git_lines::register(registry)?; Ok(()) } diff --git a/crates/engine/src/engine.rs b/crates/engine/src/engine.rs index ffa3af3..60b3a90 100644 --- a/crates/engine/src/engine.rs +++ b/crates/engine/src/engine.rs @@ -477,6 +477,7 @@ mod tests { "git.checkout", "git.commit", "git.createBranch", + "git.lineChanges", "git.show", "git.stage", "git.status", diff --git a/crates/engine/src/state.rs b/crates/engine/src/state.rs index 7575e38..7a02175 100644 --- a/crates/engine/src/state.rs +++ b/crates/engine/src/state.rs @@ -49,6 +49,8 @@ pub struct State { pub lsp: crate::lsp::Lsp, /// git and the project's repository (`git.*`, M4.1). pub git: crate::cmd::git::GitState, + /// Cached index texts for `git.lineChanges` (M4.4). + pub git_lines: crate::cmd::git_lines::GitLines, /// Number of notifications emitted, for their ids. notifications: u64, /// Events queued for the host, oldest first. @@ -58,6 +60,7 @@ pub struct State { impl State { /// Queues an event for the host. pub fn emit(&mut self, event: Event) { + crate::cmd::git_lines::observe(&mut self.git_lines, &event); self.events.push(event); } diff --git a/crates/engine/tests/git_lines.rs b/crates/engine/tests/git_lines.rs new file mode 100644 index 0000000..e2c820a --- /dev/null +++ b/crates/engine/tests/git_lines.rs @@ -0,0 +1,222 @@ +//! `git.lineChanges` through the engine against real temp repositories: +//! added, modified and deleted lines of an edited buffer, a CRLF buffer +//! against an LF index blob, an untracked file, the cache dropped by +//! `gitChanged` after staging, a project outside any repository, and an +//! unknown buffer. Skips with a message when git is not installed. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::indexing_slicing +)] + +use std::path::Path; +use std::process::Command; +use std::sync::Mutex; + +use lutra_engine::{Engine, EngineError, run_waiting}; +use serde_json::{Value, json}; + +/// Whether git is installed; prints why a test is skipped. +fn have_git() -> bool { + let ok = Command::new("git") + .arg("--version") + .output() + .is_ok_and(|o| o.status.success()); + if !ok { + eprintln!("skipped: git is not installed"); + } + ok +} + +/// Runs git for test setup. +fn git(dir: &Path, args: &[&str]) { + let out = Command::new("git") + .args(args) + .current_dir(dir) + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); +} + +/// A repository with `files` committed; `autocrlf` sets `core.autocrlf`. +fn repo(dir: &Path, autocrlf: &str, files: &[(&str, &str)]) { + git(dir, &["init", "-q", "-b", "main"]); + for (key, value) in [ + ("user.name", "Lutra Test"), + ("user.email", "test@lutra.invalid"), + ("commit.gpgsign", "false"), + ("core.autocrlf", autocrlf), + ("core.hooksPath", ".git/hooks"), + ] { + git(dir, &["config", key, value]); + } + for (name, text) in files { + std::fs::write(dir.join(name), text).unwrap(); + } + git(dir, &["add", "-A"]); + git(dir, &["commit", "-q", "-m", "base"]); +} + +/// An engine behind a lock, like a host. +struct Host { + /// The engine. + engine: Mutex, +} + +impl Host { + /// An engine with `root` open as the project. + fn open(root: &Path) -> Self { + let host = Self { + engine: Mutex::new(Engine::new().unwrap()), + }; + host.run("project.open", json!({"path": root})).unwrap(); + host + } + + /// Runs a command the way hosts do, waiting without the lock. + fn run(&self, command: &str, params: Value) -> Result { + run_waiting(|| self.engine.lock().unwrap(), command, params, |_| {}).map(|o| o.value) + } + + /// Opens `path` and returns its buffer id. + fn open_file(&self, path: &str) -> u64 { + self.run("file.open", json!({"path": path})).unwrap()["id"] + .as_u64() + .unwrap() + } + + /// Replaces the whole text of buffer `id`. + fn set_text(&self, id: u64, text: &str) { + let current = self.run("buffer.get", json!({"id": id})).unwrap(); + let len = current["text"].as_str().unwrap().encode_utf16().count(); + self.run( + "buffer.edit", + json!({ + "id": id, + "baseVersion": current["version"], + "edits": [{"from": 0, "to": len, "insert": text}], + }), + ) + .unwrap(); + } + + /// The ranges of `git.lineChanges` for buffer `id`. + fn ranges(&self, id: u64) -> Value { + self.run("git.lineChanges", json!({"id": id})).unwrap()["ranges"].clone() + } +} + +#[test] +fn reports_added_modified_and_deleted_lines() { + if !have_git() { + return; + } + let dir = tempfile::tempdir().unwrap(); + repo( + dir.path(), + "false", + &[("a.php", " **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 +> **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); line changes, gutter markers and status colours (M4.4) · **Last updated:** 2026-10-25 ## Overview @@ -585,6 +585,19 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat - **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). +### Line changes, gutter markers and status colours (M4.4) + +- **`git.lineChanges {id}`** (`crates/engine/src/cmd/git_lines.rs`, a pending outcome) → `{ranges: [{kind: added|modified|deleted, startLine, endLine}], version}`: the buffer's lines against the file's blob in the index. Lines are 0-based, `endLine` exclusive; a `deleted` range has `startLine = endLine`, the removed lines were before it (at the line count when they were at the end). `version` is the buffer version the ranges are for (an addition to the C5 contract). No ranges, not an error, when the project has no repository, git is unusable or the file is not in the index (untracked, binary, over 32 MiB, conflicted); an unknown buffer is `failed`. +- **Off the lock:** under the lock the command clones the buffer's rope (shared chunks, no copy) and takes the cached lookups; a `lutra-git-lines` thread detects git and opens the repository through `lutra-vcs` when needed, reads the blob with `Repo::show(path, Rev::Index)` when it is not cached, and diffs. At most 8 calls run at once. It keeps its own repository lookup instead of reaching into `cmd::git`'s state (no change to M4.1's file). +- **Line endings:** both texts are split at `\n`, `\r\n` and a lone `\r`, without an empty line after a final break, so a CRLF buffer equals its LF index blob (autocrlf) and a missing final newline is not a change. The lines match CodeMirror's. +- **Diff:** `similar` 2.7.0 (Apache-2.0, no default features, no dependencies), Myers with a 1 s deadline, adjacent deletes and inserts merged into replacements (`Replace` hook), at most 10,000 ranges. Its `Compact` step is not used: in 2.7.0 it moved a delete to a wrong position in the new text (found by the property test, kept as a unit test). +- **Cache:** index texts per path (at most 256 files or 64 MiB, cleared when full), dropped on every `gitChanged`: `State::emit` calls `git_lines::observe` for each event (one line in `state.rs`), and a generation counter keeps a thread that started before from storing stale text. A project change drops everything. "No repository" and "no usable git" are kept for 10 s only, because no `gitChanged` arrives without a repository. +- **Gutter** (`ui/src/components/editor/gitGutter.ts`, appended to `editorExtensions` for buffers): a 4 px gutter beside the code with a bar on added (`--lt-vcs-added`) and modified (`--lt-vcs-modified`) lines and a 3 px notch at the top of the line after deleted ones (`--lt-vcs-deleted`; at the bottom of the last line for deletions at the end), each with a catalog tooltip. A view plugin asks with `runWaiting` when the view shows the state, 150 ms after the last edit, and on `refreshGitGutters()` (every `gitChanged`); it waits for the buffer sync's `idle()` and drops answers for a document that changed meanwhile. Between answers the markers are mapped through the edits. A failure keeps the markers. Background tabs refresh when shown again. +- **Status colours** (`ui/src/stores/vcsStatus.ts`, Pinia `vcsStatus`, started by `App.vue`): `git.status` through `runWaiting` on start, `projectOpened` and every `gitChanged` (never polled), one query at a time plus one more for requests made meanwhile, answers for a closed project dropped. A file's two states fold into one token: conflicted, untracked, ignored, added (unless deleted again in the work tree), deleted, otherwise modified. The project tree and the editor tabs colour file names with `--lt-vcs-*` classes; inside a repository the tree also gives ignored entries `--lt-vcs-ignored` (`git.status` does not list them). Directories are not coloured. The contrast test also checks the status colours on the active tab. +- **Not shared yet:** the Changes window (M4.2) queries `git.status` itself, so a `gitChanged` costs two status calls (~100 ms each, off the lock). One shared store is a C6 follow-up. +- **Measured** (debug build with the bundled UI, Windows 11, git 2.47.1, control port 7944, a temp repository with the owner's global `core.autocrlf`; each number includes the control round trip and the pending wait): the first `git.lineChanges` 332 ms (git detection, opening the repository, reading the blob), then 0.4–1.4 ms with the index text cached; after `git.stage` (158 ms) the next call reads the blob again and returns no ranges. Screenshots read in both themes: a modified bar, a deleted notch and an added bar where expected, no markers after staging, tabs in the modified and untracked colours, no markers for the untracked file. No keys were sent (owner at the PC). +- **Tests:** `cmd::git_lines` unit and property tests (line splitting, kinds, line endings, empty files, cache caps and generation, ranges in order and inside the buffer); `crates/engine/tests/git_lines.rs` (4 tests against real temp repositories: added/modified/deleted, a CRLF buffer against an autocrlf LF blob, staging drops the cache, an untracked file and no repository, bad params); Vitest `ui/tests/editor/gitGutter.test.ts` (12: reading, building, query on show, debounce, stale answers, failures, refresh, mapping), `ui/tests/vcs/vcsStatus.test.ts` (colours, reading, coalescing, events, tabs) and one tree test in `ui/tests/project/ProjectTree.test.ts`. + ## Decisions (M0) | Question | Decision | Why | @@ -602,6 +615,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Date | Change | Summary | |---|---|---| +| 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`) | | 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 | diff --git a/docs/gaps.md b/docs/gaps.md index 4ca7ec8..bc4bb86 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); 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 +> **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; gutter markers and status colours, M4.4); 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`), ~~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 | +| 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, branch popup, log, blame, conflicts, stash, remotes | M4 | ~136 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: gutter markers and status colours (M4.4) | | 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) | diff --git a/docs/roadmap.md b/docs/roadmap.md index 818455e..62015c5 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) · **Last updated:** 2026-10-25 +> **Status:** M0–M3 done, M4 in progress (C5: Git backend, Changes window, gutter markers and status colours) · **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, M4.2 Changes window done) | ~138 | +| 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 done) | ~136 | | 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.4 gutter markers and status colours | | 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) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5386f35..b2905b1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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 | 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+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `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. | +| Git | 8 | 6% (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, branch widget (C5 wave 3); log, blame, conflicts, stash, remotes (C6); ignored files in the status | ~136 (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+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. | | 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.4: Git 4% → 6% (est.), gutter change markers and status colours; hours 138 → 136 | | 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 | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e1bc782..c00f79c 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) · **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), Git change markers and status colours (M4.4) · **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. @@ -42,11 +42,13 @@ - 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+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. ## Revision history | Date | Change | Summary | |---|---|---| +| 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) | | 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) | diff --git a/ui/src/App.vue b/ui/src/App.vue index c7fa45c..cf36e82 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -8,7 +8,8 @@ * `theme.ts`; a failed theme report raises an error toast) and the global * keymap with the UI commands (see `commands/store.ts`), and loads the settings so the * editor font size applies from the start (see `stores/settings.ts`). - * Starts autosave (see `stores/autosave.ts`). + * Starts autosave (see `stores/autosave.ts`) and the Git status colours + * (see `stores/vcsStatus.ts`). */ import { onMounted, onUnmounted } from "vue"; import { useCommandsStore } from "./commands/store"; @@ -24,6 +25,7 @@ import { useAppStore } from "./stores/app"; import { useAutosaveStore } from "./stores/autosave"; import { useNotificationsStore } from "./stores/notifications"; import { useSettingsStore } from "./stores/settings"; +import { useVcsStatusStore } from "./stores/vcsStatus"; import { startTheme } from "./theme"; const app = useAppStore(); @@ -31,6 +33,7 @@ const notifications = useNotificationsStore(); const commands = useCommandsStore(); const settings = useSettingsStore(); const autosave = useAutosaveStore(); +const vcsStatus = useVcsStatusStore(); /** Stops following the theme; set while mounted. */ let stopTheme: (() => void) | null = null; @@ -41,6 +44,7 @@ onMounted(() => { void commands.start(); void settings.start(); autosave.start(); + vcsStatus.start(); void app.loadAbout(); }); @@ -49,6 +53,7 @@ onUnmounted(() => { stopTheme = null; commands.stop(); autosave.stop(); + vcsStatus.stop(); settings.stop(); notifications.stop(); }); diff --git a/ui/src/components/editor/EditorTabs.vue b/ui/src/components/editor/EditorTabs.vue index 4e0a494..e0e343e 100644 --- a/ui/src/components/editor/EditorTabs.vue +++ b/ui/src/components/editor/EditorTabs.vue @@ -4,13 +4,16 @@ * * A click activates a tab, a middle click or the close button closes it, * Left/Right move between tabs. A dot marks unsaved changes. Closing a - * dirty tab asks first (see the editor store). + * dirty tab asks first (see the editor store). Names are coloured by their + * Git status (`--lt-vcs-*`, M4.4). */ import { X } from "@lucide/vue"; import { t } from "../../i18n"; import { useEditorStore } from "../../stores/editor"; +import { useVcsStatusStore } from "../../stores/vcsStatus"; const editor = useEditorStore(); +const vcs = useVcsStatusStore(); /** * Closes a tab on a middle click. @@ -67,7 +70,11 @@ function onKeydown(event: KeyboardEvent): void { @mousedown.middle.prevent @auxclick="onAuxClick($event, tab.id)" > - {{ tab.name }} + {{ tab.name }} ; +} + +/** The transport through the engine IPC, off the shell's main thread. */ +export const engineGitGutterTransport: GitGutterTransport = { + query: (command, params) => runWaiting(command, params), +}; + +/** Whether a value is a non-negative integer. */ +function isLine(value: unknown): value is number { + return typeof value === "number" && Number.isInteger(value) && value >= 0; +} + +/** + * Reads the ranges of a `git.lineChanges` result; malformed ranges are + * skipped. + * + * @param value - the untrusted result. + * @returns the ranges, or null when the result has no list. + */ +export function readLineChanges(value: unknown): LineChange[] | null { + if (typeof value !== "object" || value === null) { + return null; + } + const ranges = (value as Record).ranges; + if (!Array.isArray(ranges)) { + return null; + } + const out: LineChange[] = []; + for (const range of ranges as unknown[]) { + if (typeof range !== "object" || range === null) { + continue; + } + const { kind, startLine, endLine } = range as Record; + if ((kind === "added" || kind === "modified" || kind === "deleted") && isLine(startLine) && isLine(endLine) && endLine >= startLine) { + out.push({ kind, startLine, endLine }); + } + } + return out; +} + +/** A marker class: the three kinds, plus deleted lines below the last line. */ +type MarkerClass = LineChangeKind | "deleted-end"; + +/** The tooltip of each marker class, from the catalog. */ +const TITLES: Record string> = { + added: () => t("editor.gitGutter.added"), + modified: () => t("editor.gitGutter.modified"), + deleted: () => t("editor.gitGutter.deleted"), + "deleted-end": () => t("editor.gitGutter.deleted"), +}; + +/** One gutter marker; equal markers share their DOM. */ +class GitMarker extends GutterMarker { + /** + * @param kind - what it marks. + */ + constructor(readonly kind: MarkerClass) { + super(); + } + + override eq(other: GutterMarker): boolean { + return other instanceof GitMarker && other.kind === this.kind; + } + + override toDOM(): Node { + const element = document.createElement("div"); + element.className = `lt-git-marker lt-git-marker--${this.kind}`; + element.title = TITLES[this.kind](); + element.dataset.test = "git-marker"; + element.dataset.kind = this.kind; + return element; + } +} + +/** One marker instance per class. */ +const MARKERS: Record = { + added: new GitMarker("added"), + modified: new GitMarker("modified"), + deleted: new GitMarker("deleted"), + "deleted-end": new GitMarker("deleted-end"), +}; + +/** + * Builds the markers of `ranges` in `doc`: one per line of an added or + * modified range, one on the line after a deletion (on the last line when + * the deletion was at the end). Lines past the document are ignored; a + * line takes the first marker that reaches it. + * + * @param doc - the document the ranges were computed for. + * @param ranges - the ranges, in line order. + */ +export function buildMarkers(doc: Text, ranges: readonly LineChange[]): RangeSet { + const builder = new RangeSetBuilder(); + let next = 1; + for (const range of ranges) { + if (range.kind === "deleted") { + const atEnd = range.startLine >= doc.lines; + const number = atEnd ? doc.lines : range.startLine + 1; + if (number >= next) { + const line = doc.line(number); + builder.add(line.from, line.from, MARKERS[atEnd ? "deleted-end" : "deleted"]); + next = number + 1; + } + continue; + } + const first = Math.max(range.startLine + 1, next); + const last = Math.min(range.endLine, doc.lines); + for (let number = first; number <= last; number += 1) { + const line = doc.line(number); + builder.add(line.from, line.from, MARKERS[range.kind]); + } + next = Math.max(next, last + 1); + } + return builder.finish(); +} + +/** Replaces the markers of a state. */ +const setGitMarkers = StateEffect.define>(); + +/** The markers of a state, mapped through edits between answers. */ +const gitMarkers = StateField.define>({ + create: () => RangeSet.empty, + update(value, tr) { + let next = value.map(tr.changes); + for (const effect of tr.effects) { + if (effect.is(setGitMarkers)) { + next = effect.value; + } + } + return next; + }, +}); + +/** + * The markers a state carries, for tests and inspection. + * + * @param state - an editor state built with {@link gitGutterExtensions}. + * @returns the marker kind by 1-based line number; empty without the + * extension. + */ +export function gitMarkerLines(state: EditorState): Record { + const out: Record = {}; + const set = state.field(gitMarkers, false); + if (set === undefined) { + return out; + } + const cursor = set.iter(); + while (cursor.value !== null) { + if (cursor.value instanceof GitMarker) { + out[state.doc.lineAt(cursor.from).number] = cursor.value.kind; + } + cursor.next(); + } + return out; +} + +/** Live plugins, refreshed by {@link refreshGitGutters}. */ +const live = new Set<{ schedule(delay: number): void }>(); + +/** Asks every editor shown now to query its markers again (`gitChanged`). */ +export function refreshGitGutters(): void { + for (const plugin of live) { + plugin.schedule(0); + } +} + +/** + * The plugin that queries the markers of one view's state. + * + * @param buffer - the engine buffer the state shows. + * @param transport - how to reach the engine. + */ +function gitGutterPlugin(buffer: AssistBuffer, transport: GitGutterTransport): Extension { + return ViewPlugin.define((view): PluginValue => { + const life = { alive: true }; + let timer: ReturnType | null = null; + let asked = 0; + + /** + * Whether the plugin still lives and the view still shows `doc`. + * + * @param doc - the document a query was made for. + */ + function current(doc: Text): boolean { + return life.alive && view.state.doc === doc; + } + + /** Queries the markers for the current document and applies them. */ + async function run(): Promise { + const doc = view.state.doc; + await buffer.idle(); + if (!current(doc)) { + return; + } + asked += 1; + const mine = asked; + const result = await transport.query("git.lineChanges", { id: buffer.id }); + if (!current(doc) || mine !== asked || !result.ok) { + return; + } + const ranges = readLineChanges(result.value); + if (ranges !== null) { + view.dispatch({ effects: setGitMarkers.of(buildMarkers(doc, ranges)) }); + } + } + + const handle = { + schedule(delay: number): void { + if (!life.alive) { + return; + } + if (timer !== null) { + clearTimeout(timer); + } + timer = setTimeout(() => { + timer = null; + void run(); + }, delay); + }, + }; + live.add(handle); + handle.schedule(0); + return { + update(update: ViewUpdate): void { + if (update.docChanged) { + handle.schedule(GIT_GUTTER_DEBOUNCE_MS); + } + }, + destroy(): void { + life.alive = false; + live.delete(handle); + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + }, + }; + }); +} + +/** Marker styles from the status tokens. */ +const gitGutterTheme: Extension = EditorView.theme({ + ".lt-git-gutter .cm-gutterElement": { + width: "4px", + padding: "0", + }, + ".lt-git-marker": { + height: "100%", + }, + ".lt-git-marker--added": { + backgroundColor: "var(--lt-vcs-added)", + }, + ".lt-git-marker--modified": { + backgroundColor: "var(--lt-vcs-modified)", + }, + ".lt-git-marker--deleted": { + background: "linear-gradient(to bottom, var(--lt-vcs-deleted) 0 3px, transparent 3px)", + }, + ".lt-git-marker--deleted-end": { + background: "linear-gradient(to top, var(--lt-vcs-deleted) 0 3px, transparent 3px)", + }, +}); + +/** + * The Git change marker extensions of an editor state. + * + * @param buffer - the buffer it shows; none for states without one. + * @param transport - how to reach the engine. + * @returns the extensions; empty without a buffer. + */ +export function gitGutterExtensions( + buffer: AssistBuffer | undefined, + transport: GitGutterTransport = engineGitGutterTransport, +): Extension { + if (buffer === undefined) { + return []; + } + return [ + gitMarkers, + gutter({ + class: "lt-git-gutter", + markers: (view) => view.state.field(gitMarkers), + initialSpacer: () => MARKERS.added, + }), + gitGutterTheme, + gitGutterPlugin(buffer, transport), + ]; +} diff --git a/ui/src/components/project/ProjectTree.vue b/ui/src/components/project/ProjectTree.vue index 742166a..b80ef79 100644 --- a/ui/src/components/project/ProjectTree.vue +++ b/ui/src/components/project/ProjectTree.vue @@ -8,16 +8,20 @@ * to the parent, Enter opens a file or toggles a folder. Double-click does * the same as Enter. Ignored and excluded entries are dimmed. A directory * the engine listed only partly ends with a "listing truncated" note. + * File names are coloured by their Git status (`--lt-vcs-*`, M4.4); inside + * a repository, ignored entries take the ignored colour. */ import { ChevronDown, ChevronRight, File, FileCode, Folder, FolderOpen } from "@lucide/vue"; import { computed, nextTick, ref } from "vue"; import { t } from "../../i18n"; import { parentOf, useProjectStore, type TreeRow } from "../../stores/project"; import { useEditorStore } from "../../stores/editor"; +import { useVcsStatusStore, type VcsColour } from "../../stores/vcsStatus"; import type { TreeEntry } from "./engineEvents"; const project = useProjectStore(); const editor = useEditorStore(); +const vcs = useVcsStatusStore(); /** The tree element, for keeping the selected row in view. */ const treeEl = ref(null); @@ -64,6 +68,18 @@ function isDimmed(entry: TreeEntry): boolean { return entry.ignored || entry.excluded === true; } +/** + * The Git status colour of an entry's name: a file's status, else the + * ignored colour for an ignored entry inside a repository. + * + * @param entry - the entry. + * @returns the token name, or null for the normal colour. + */ +function vcsColour(entry: TreeEntry): VcsColour | null { + const colour = entry.kind === "file" ? vcs.colourOf(entry.path) : null; + return colour ?? (vcs.repo && entry.ignored ? "ignored" : null); +} + /** * Whether a file name looks like PHP source, for the code icon. * @@ -277,7 +293,11 @@ function onFocus(): void { :size="16" /> - {{ row.entry.name }} + {{ row.entry.name }}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index 97899c7..cafcb6d 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -64,6 +64,9 @@ "editor.assist.kind.variable": "Variable", "editor.assist.signature.count": "{index} of {count}", "editor.closePrompt.question": "Save changes to {name} before closing?", + "editor.gitGutter.added": "Added since the staged version", + "editor.gitGutter.deleted": "Lines deleted here since the staged version", + "editor.gitGutter.modified": "Changed since the staged version", "editor.notice.changedOnDisk": "{name} changed on disk. Your unsaved changes are kept; saving overwrites the file.", "editor.notice.removedOnDisk": "{name} was deleted on disk. Your text is kept; saving writes it again.", "editor.reveal.invalidParams": "editor.reveal needs a path (string), line and column (numbers)", diff --git a/ui/src/stores/vcsStatus.ts b/ui/src/stores/vcsStatus.ts new file mode 100644 index 0000000..89be3b9 --- /dev/null +++ b/ui/src/stores/vcsStatus.ts @@ -0,0 +1,244 @@ +/** + * Git status of the project's files for colouring file names in the + * project tree and the editor tabs (M4.4). + * + * - **Source:** `git.status` (a pending outcome, so through `runWaiting`) + * on start, when a project opens and on every `gitChanged`; never + * polled. One query runs at a time; requests made while it runs share + * one more query after it. + * - **Colour:** {@link statusColour} folds a file's index and work tree + * states into one of the `--lt-vcs-*` tokens. Ignored files are not in + * `git.status`; the tree colours its ignored entries itself while a + * repository is open. + * - **Gutters:** every `gitChanged` also asks the editors' change markers + * to refresh (`refreshGitGutters`), since the index may have changed. + * + * Results are untrusted: malformed files are skipped, a failed query + * keeps the last state and shows nothing (the Changes window reports git + * problems). + */ +import { defineStore } from "pinia"; +import { shallowRef } from "vue"; +import { onEngineEvent, runWaiting, type EngineEventPayload } from "../ipc"; +import { refreshGitGutters } from "../components/editor/gitGutter"; + +/** A file state as `git.status` names it. */ +export type GitFileState = + | "unmodified" + | "modified" + | "added" + | "deleted" + | "renamed" + | "copied" + | "untracked" + | "ignored" + | "conflicted"; + +/** The status token names (`--lt-vcs-`). */ +export type VcsColour = "added" | "modified" | "deleted" | "untracked" | "ignored" | "conflicted"; + +/** Every state `git.status` may report. */ +const STATES = new Set([ + "unmodified", + "modified", + "added", + "deleted", + "renamed", + "copied", + "untracked", + "ignored", + "conflicted", +]); + +/** Whether a value is a file state. */ +function isState(value: unknown): value is GitFileState { + return typeof value === "string" && STATES.has(value); +} + +/** + * The colour of a file from its two states: conflicts first, then + * untracked, ignored, added, deleted, and any other change as modified. + * + * @param index - the staged side. + * @param worktree - the work tree side. + * @returns the token name, or null for an unchanged file. + */ +export function statusColour(index: GitFileState, worktree: GitFileState): VcsColour | null { + const sides = [index, worktree]; + if (sides.includes("conflicted")) { + return "conflicted"; + } + if (sides.includes("untracked")) { + return "untracked"; + } + if (sides.includes("ignored")) { + return "ignored"; + } + if (index === "added") { + return worktree === "deleted" ? null : "added"; + } + if (sides.includes("deleted")) { + return "deleted"; + } + if (sides.some((side) => side !== "unmodified")) { + return "modified"; + } + return null; +} + +/** + * Reads the colours of a `git.status` result. + * + * @param value - the untrusted result. + * @returns colour by project-relative path, and whether a repository is + * open; null when the result is not an object. + */ +export function readStatus(value: unknown): { colours: Map; repo: boolean } | null { + if (typeof value !== "object" || value === null || Array.isArray(value)) { + return null; + } + const record = value as Record; + const colours = new Map(); + const files = Array.isArray(record.files) ? (record.files as unknown[]) : []; + for (const file of files) { + if (typeof file !== "object" || file === null) { + continue; + } + const { path, index, worktree } = file as Record; + if (typeof path !== "string" || !isState(index) || !isState(worktree)) { + continue; + } + const colour = statusColour(index, worktree); + if (colour !== null) { + colours.set(path, colour); + } + } + const repo = record.available === true && typeof record.repo === "object" && record.repo !== null; + return { colours, repo }; +} + +/** How the store reaches the engine; replaced in tests. */ +export interface VcsStatusTransport { + /** Runs `git.status`. */ + status(): Promise<{ ok: true; value: unknown } | { ok: false }>; +} + +/** The transport through the engine IPC. */ +const engineTransport: VcsStatusTransport = { + status: () => runWaiting("git.status", {}), +}; + +export const useVcsStatusStore = defineStore("vcsStatus", () => { + /** Colour by project-relative path, for changed files only. */ + const colours = shallowRef>(new Map()); + /** Whether the project is inside a repository with a usable git. */ + const repo = shallowRef(false); + + let transport: VcsStatusTransport = engineTransport; + let running: Promise | null = null; + const queued = { again: false }; + let generation = 0; + let unsubscribe: (() => void) | null = null; + + /** + * Replaces the transport (tests). + * + * @param next - the transport. + */ + function configure(next: VcsStatusTransport): void { + transport = next; + } + + /** Runs `git.status` once and applies it unless the project changed. */ + async function query(): Promise { + const asked = generation; + const result = await transport.status(); + if (!result.ok || asked !== generation) { + return; + } + const read = readStatus(result.value); + if (read !== null) { + colours.value = read.colours; + repo.value = read.repo; + } + } + + /** Whether a refresh was asked for while the last query ran. */ + function wantsAgain(): boolean { + return queued.again; + } + + /** + * Refreshes the status: starts a query, or, while one runs, makes sure + * one more runs after it. + * + * @returns resolves when the status is current. + */ + function refresh(): Promise { + if (running !== null) { + queued.again = true; + return running; + } + running = (async () => { + do { + queued.again = false; + await query(); + } while (wantsAgain()); + running = null; + })(); + return running; + } + + /** Forgets everything (project closed). */ + function clear(): void { + generation += 1; + colours.value = new Map(); + repo.value = false; + } + + /** + * The colour of a file name. + * + * @param path - project-relative path with `/`. + * @returns the token name, or null when unchanged or unknown. + */ + function colourOf(path: string): VcsColour | null { + return colours.value.get(path) ?? null; + } + + /** Handles one engine event. */ + function handle(event: EngineEventPayload): void { + switch (event.kind) { + case "projectOpened": + clear(); + void refresh(); + break; + case "projectClosed": + clear(); + break; + case "gitChanged": + void refresh(); + refreshGitGutters(); + break; + default: + break; + } + } + + /** Starts following the engine and queries once; repeated calls do nothing. */ + function start(): void { + if (unsubscribe !== null) { + return; + } + unsubscribe = onEngineEvent(handle); + void refresh(); + } + + /** Stops following the engine. */ + function stop(): void { + unsubscribe?.(); + unsubscribe = null; + } + + return { colours, repo, configure, refresh, clear, colourOf, handle, start, stop }; +}); diff --git a/ui/tests/editor/gitGutter.test.ts b/ui/tests/editor/gitGutter.test.ts new file mode 100644 index 0000000..dc1f314 --- /dev/null +++ b/ui/tests/editor/gitGutter.test.ts @@ -0,0 +1,253 @@ +/** + * Tests of the Git change markers (M4.4, `gitGutter.ts`): reading + * `git.lineChanges`, building markers (deleted at the end, clamping, + * overlaps), the query when a view shows the state, the 150 ms debounce + * after edits, dropping answers for an old document, `refreshGitGutters`, + * markers mapped through edits, and colours from tokens only. + */ +import { EditorState, Text } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + GIT_GUTTER_DEBOUNCE_MS, + buildMarkers, + gitGutterExtensions, + gitMarkerLines, + readLineChanges, + refreshGitGutters, + type GitGutterTransport, + type LineChange, +} from "../../src/components/editor/gitGutter"; +import type { JsonValue } from "../../src/ipc"; + +/** Views created by a test, destroyed after it. */ +let views: EditorView[] = []; + +/** A fake engine answering `git.lineChanges` with `answer`. */ +class FakeEngine implements GitGutterTransport { + /** The params of every query, in order. */ + readonly calls: JsonValue[] = []; + /** What the next queries answer. */ + answer: unknown = { ranges: [], version: 1 }; + /** Whether queries fail. */ + fail = false; + /** Queries waiting to be answered, when held. */ + held: (() => void)[] = []; + /** Whether to hold answers until released. */ + hold = false; + + query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }> { + expect(command).toBe("git.lineChanges"); + this.calls.push(params); + const answer = this.answer; + const result = this.fail ? ({ ok: false } as const) : ({ ok: true, value: answer } as const); + if (!this.hold) { + return Promise.resolve(result); + } + return new Promise((resolve) => { + this.held.push(() => { + resolve(result); + }); + }); + } +} + +/** The kinds of the markers a view shows, by 1-based line number. */ +function markers(view: EditorView): Record { + return gitMarkerLines(view.state); +} + +/** Kinds of the markers in a range set, by 1-based line. */ +function markerLines(doc: Text, ranges: LineChange[]): Record { + const out: Record = {}; + const set = buildMarkers(doc, ranges); + const cursor = set.iter(); + while (cursor.value !== null) { + out[doc.lineAt(cursor.from).number] = (cursor.value as unknown as { kind: string }).kind; + cursor.next(); + } + return out; +} + +/** + * A view of buffer 7 showing `doc`. + * + * @param doc - the text. + * @param engine - the fake engine. + */ +function viewOf(doc: string, engine: FakeEngine): EditorView { + const view = new EditorView({ + state: EditorState.create({ + doc, + extensions: gitGutterExtensions({ id: 7, idle: () => Promise.resolve() }, engine), + }), + parent: document.body, + }); + views.push(view); + return view; +} + +/** Lets timers and promises run. */ +async function flush(ms = 0): Promise { + await vi.advanceTimersByTimeAsync(ms); + for (let i = 0; i < 5; i += 1) { + await Promise.resolve(); + } +} + +beforeEach(() => { + vi.useFakeTimers(); +}); + +afterEach(() => { + for (const view of views) { + view.destroy(); + } + views = []; + vi.useRealTimers(); +}); + +describe("readLineChanges", () => { + it("keeps well-formed ranges and drops the rest", () => { + expect( + readLineChanges({ + ranges: [ + { kind: "added", startLine: 0, endLine: 2 }, + { kind: "moved", startLine: 0, endLine: 1 }, + { kind: "modified", startLine: 3, endLine: 2 }, + { kind: "deleted", startLine: -1, endLine: -1 }, + { kind: "deleted", startLine: 4, endLine: 4 }, + "x", + null, + ], + }), + ).toEqual([ + { kind: "added", startLine: 0, endLine: 2 }, + { kind: "deleted", startLine: 4, endLine: 4 }, + ]); + expect(readLineChanges({})).toBeNull(); + expect(readLineChanges(null)).toBeNull(); + }); +}); + +describe("buildMarkers", () => { + const doc = Text.of(["a", "b", "c", "d"]); + + it("marks every line of a range and the line after a deletion", () => { + expect( + markerLines(doc, [ + { kind: "modified", startLine: 0, endLine: 1 }, + { kind: "deleted", startLine: 2, endLine: 2 }, + { kind: "added", startLine: 3, endLine: 4 }, + ]), + ).toEqual({ 1: "modified", 3: "deleted", 4: "added" }); + }); + + it("puts a deletion at the end on the last line and clamps past the document", () => { + expect(markerLines(doc, [{ kind: "deleted", startLine: 4, endLine: 4 }])).toEqual({ 4: "deleted-end" }); + expect(markerLines(doc, [{ kind: "added", startLine: 2, endLine: 99 }])).toEqual({ 3: "added", 4: "added" }); + }); + + it("gives a line to the first marker that reaches it", () => { + expect( + markerLines(doc, [ + { kind: "added", startLine: 0, endLine: 2 }, + { kind: "modified", startLine: 1, endLine: 3 }, + ]), + ).toEqual({ 1: "added", 2: "added", 3: "modified" }); + }); +}); + +describe("the gutter", () => { + it("queries when the view shows the state and draws the markers", async () => { + const engine = new FakeEngine(); + engine.answer = { ranges: [{ kind: "added", startLine: 1, endLine: 2 }], version: 1 }; + const view = viewOf("a\nb\nc", engine); + await flush(); + expect(engine.calls).toEqual([{ id: 7 }]); + expect(markers(view)).toEqual({ 2: "added" }); + expect(view.dom.querySelector("[data-kind='added']")?.getAttribute("title")).toBe("Added since the staged version"); + }); + + it("asks again 150 ms after the last edit, once", async () => { + const engine = new FakeEngine(); + const view = viewOf("a\nb", engine); + await flush(); + expect(engine.calls).toHaveLength(1); + view.dispatch({ changes: { from: 0, insert: "x" } }); + await flush(GIT_GUTTER_DEBOUNCE_MS - 50); + view.dispatch({ changes: { from: 0, insert: "y" } }); + await flush(GIT_GUTTER_DEBOUNCE_MS - 1); + expect(engine.calls).toHaveLength(1); + engine.answer = { ranges: [{ kind: "modified", startLine: 0, endLine: 1 }], version: 3 }; + await flush(1); + expect(engine.calls).toHaveLength(2); + expect(markers(view)).toEqual({ 1: "modified" }); + }); + + it("drops an answer for a document that changed meanwhile", async () => { + const engine = new FakeEngine(); + engine.hold = true; + engine.answer = { ranges: [{ kind: "added", startLine: 0, endLine: 1 }], version: 1 }; + const view = viewOf("a\nb", engine); + await flush(); + expect(engine.held).toHaveLength(1); + view.dispatch({ changes: { from: 0, insert: "x" } }); + engine.held.shift()?.(); + await flush(); + expect(markers(view)).toEqual({}); + }); + + it("keeps the markers when a query fails", async () => { + const engine = new FakeEngine(); + engine.answer = { ranges: [{ kind: "added", startLine: 0, endLine: 1 }], version: 1 }; + const view = viewOf("a\nb", engine); + await flush(); + engine.fail = true; + refreshGitGutters(); + await flush(); + expect(engine.calls).toHaveLength(2); + expect(markers(view)).toEqual({ 1: "added" }); + }); + + it("refreshes on refreshGitGutters and maps markers through edits", async () => { + const engine = new FakeEngine(); + engine.answer = { ranges: [{ kind: "modified", startLine: 1, endLine: 2 }], version: 1 }; + const view = viewOf("a\nb\nc", engine); + await flush(); + expect(markers(view)).toEqual({ 2: "modified" }); + view.dispatch({ changes: { from: 0, insert: "new\n" } }); + expect(markers(view)).toEqual({ 3: "modified" }); + engine.answer = { ranges: [], version: 2 }; + refreshGitGutters(); + await flush(); + expect(markers(view)).toEqual({}); + }); + + it("stops asking once the view is gone", async () => { + const engine = new FakeEngine(); + const view = viewOf("a", engine); + await flush(); + view.destroy(); + views = []; + refreshGitGutters(); + await flush(GIT_GUTTER_DEBOUNCE_MS); + expect(engine.calls).toHaveLength(1); + }); + + it("adds nothing without a buffer", () => { + expect(gitGutterExtensions(undefined)).toEqual([]); + }); +}); + +describe("colours", () => { + it("come from the status tokens only", () => { + const source = readFileSync(join(__dirname, "../../src/components/editor/gitGutter.ts"), "utf8"); + expect(source).toContain("var(--lt-vcs-added)"); + expect(source).toContain("var(--lt-vcs-modified)"); + expect(source).toContain("var(--lt-vcs-deleted)"); + expect(source).not.toMatch(/#[0-9a-fA-F]{3,8}\b|rgb\(/); + }); +}); diff --git a/ui/tests/project/ProjectTree.test.ts b/ui/tests/project/ProjectTree.test.ts index e29e458..f1f7200 100644 --- a/ui/tests/project/ProjectTree.test.ts +++ b/ui/tests/project/ProjectTree.test.ts @@ -1,7 +1,7 @@ /** * Tests for the Project tool window: empty state, lazy expansion, keyboard - * navigation, refresh on `TreeChanged`, error display and the truncated - * listing note. The engine is + * navigation, refresh on `TreeChanged`, error display, the truncated + * listing note and Git status colours (M4.4). The engine is * mocked: `invoke` answers `project.children` from an in-memory folder and * events go through the local dispatcher in `engineEvents.ts`. */ @@ -15,6 +15,7 @@ vi.mock("@tauri-apps/api/core", () => ({ invoke })); import { emitEngineEvent } from "../../src/components/project/engineEvents"; import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue"; import { useProjectStore } from "../../src/stores/project"; +import { useVcsStatusStore } from "../../src/stores/vcsStatus"; import { t } from "../../src/i18n"; /** An entry as the engine's `project.children` returns it. */ @@ -267,4 +268,28 @@ describe("ProjectToolWindow", () => { emitEngineEvent({ kind: "projectOpened", root: "/tmp/other", name: "other" }); expect(useProjectStore().root).toBeNull(); }); + + it("colours file names by Git status, and ignored entries inside a repository", async () => { + const vcs = useVcsStatusStore(); + vcs.configure({ + status: () => + Promise.resolve({ + ok: true, + value: { + available: true, + repo: { root: "/tmp/demo", detached: false }, + files: [{ path: "index.php", index: "unmodified", worktree: "modified" }], + }, + }), + }); + const mounted = await mountOpen(); + wrapper = mounted; + await vcs.refresh(); + await flushPromises(); + const name = (path: string) => mounted.get(`[data-test=tree-row][data-path="${path}"] .tree__name`); + expect(name("index.php").attributes("data-vcs")).toBe("modified"); + expect(name("index.php").classes()).toContain("tree__name--vcs-modified"); + expect(name("node_modules").attributes("data-vcs")).toBe("ignored"); + expect(name("src").attributes("data-vcs")).toBeUndefined(); + }); }); diff --git a/ui/tests/theme/contrast.test.ts b/ui/tests/theme/contrast.test.ts index d1906a9..a226212 100644 --- a/ui/tests/theme/contrast.test.ts +++ b/ui/tests/theme/contrast.test.ts @@ -9,7 +9,7 @@ * meant to vanish into it is exempt per theme (`TERMINAL_EXEMPT`). Every * diagnostic severity (`--lt-diag-*`) and version-control status * (`--lt-vcs-*`) colour reaches 4.5:1 on the editor background, the active - * line and the window background, and every completion kind icon colour + * line and the window background (and on the active tab, M4.4), and every completion kind icon colour * reaches 3:1 on the popup and its selected row (H5). The * themes come from * `themes.json`, a snapshot that the Rust test `ui_snapshot_is_current` @@ -88,6 +88,13 @@ const STATUS_PAIRS: [string, string, number][] = [ ...VCS.map((name) => `vcs-${name}`), ].flatMap((fg) => STATUS_BACKGROUNDS.map((bg): [string, string, number] => [fg, bg, TEXT])); +/** Status colours as tab names on the active tab (M4.4). */ +const TAB_STATUS_PAIRS: [string, string, number][] = VCS.map((name): [string, string, number] => [ + `vcs-${name}`, + "tab-active-bg", + TEXT, +]); + /** Every completion kind icon colour on the popup and its selected row. */ const KIND_PAIRS: [string, string, number][] = [...new Set(Object.values(KIND_COLOURS))].flatMap( (fg): [string, string, number][] => [ @@ -196,7 +203,7 @@ describe.each(themes)("theme $id", (theme) => { expect(defined).toHaveLength(ANSI.length * 2); }); - it.each([...PAIRS, ...SYNTAX_PAIRS, ...STATUS_PAIRS, ...KIND_PAIRS, ...terminalPairs(theme.id)])("%s on %s reaches %d:1", (fg, bg, min) => { + it.each([...PAIRS, ...SYNTAX_PAIRS, ...STATUS_PAIRS, ...TAB_STATUS_PAIRS, ...KIND_PAIRS, ...terminalPairs(theme.id)])("%s on %s reaches %d:1", (fg, bg, min) => { expect(contrast(token(fg), token(bg))).toBeGreaterThanOrEqual(min); }); }); diff --git a/ui/tests/vcs/vcsStatus.test.ts b/ui/tests/vcs/vcsStatus.test.ts new file mode 100644 index 0000000..ca73cae --- /dev/null +++ b/ui/tests/vcs/vcsStatus.test.ts @@ -0,0 +1,155 @@ +/** + * Tests of the Git status colours (M4.4, `stores/vcsStatus.ts`): folding + * index and work tree states into a colour, reading untrusted + * `git.status` results, one query at a time with one more after it, + * reacting to `projectOpened`, `projectClosed` and `gitChanged` (which + * also refreshes the gutters), and coloured tab names. + */ +import { flushPromises, mount } from "@vue/test-utils"; +import { createPinia, setActivePinia } from "pinia"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const refreshGitGutters = vi.hoisted(() => vi.fn()); +vi.mock("../../src/components/editor/gitGutter", () => ({ refreshGitGutters })); + +import EditorTabs from "../../src/components/editor/EditorTabs.vue"; +import { useEditorStore } from "../../src/stores/editor"; +import { readStatus, statusColour, useVcsStatusStore, type VcsStatusTransport } from "../../src/stores/vcsStatus"; + +/** A `git.status` result with `files`. */ +function status(files: unknown[]): unknown { + return { available: true, repo: { root: "/r", branch: "main", detached: false }, files }; +} + +/** A transport whose answers the test releases one by one. */ +class HeldTransport implements VcsStatusTransport { + /** Queries waiting for an answer. */ + readonly waiting: ((value: unknown) => void)[] = []; + + status(): Promise<{ ok: true; value: unknown }> { + return new Promise((resolve) => { + this.waiting.push((value) => { + resolve({ ok: true, value }); + }); + }); + } +} + +beforeEach(() => { + setActivePinia(createPinia()); + refreshGitGutters.mockReset(); +}); + +describe("statusColour", () => { + it("puts conflicts first, then untracked, added, deleted and other changes", () => { + expect(statusColour("conflicted", "conflicted")).toBe("conflicted"); + expect(statusColour("untracked", "untracked")).toBe("untracked"); + expect(statusColour("added", "unmodified")).toBe("added"); + expect(statusColour("added", "modified")).toBe("added"); + expect(statusColour("added", "deleted")).toBeNull(); + expect(statusColour("deleted", "unmodified")).toBe("deleted"); + expect(statusColour("unmodified", "deleted")).toBe("deleted"); + expect(statusColour("modified", "unmodified")).toBe("modified"); + expect(statusColour("renamed", "modified")).toBe("modified"); + expect(statusColour("unmodified", "unmodified")).toBeNull(); + }); +}); + +describe("readStatus", () => { + it("skips malformed files and notes whether a repository is open", () => { + const read = readStatus( + status([ + { path: "a.php", index: "unmodified", worktree: "modified" }, + { path: "b.php", index: "bogus", worktree: "modified" }, + { path: 3, index: "added", worktree: "unmodified" }, + "x", + ]), + ); + expect(read?.repo).toBe(true); + expect([...(read?.colours ?? [])]).toEqual([["a.php", "modified"]]); + expect(readStatus({ available: true, repo: null, files: [] })?.repo).toBe(false); + expect(readStatus({ available: false, repo: null, files: [] })?.repo).toBe(false); + expect(readStatus("nope")).toBeNull(); + }); +}); + +describe("the store", () => { + it("runs one query at a time and one more for requests made meanwhile", async () => { + const transport = new HeldTransport(); + const store = useVcsStatusStore(); + store.configure(transport); + const first = store.refresh(); + void store.refresh(); + void store.refresh(); + expect(transport.waiting).toHaveLength(1); + transport.waiting.shift()?.(status([{ path: "a.php", index: "unmodified", worktree: "modified" }])); + await flushPromises(); + expect(store.colourOf("a.php")).toBe("modified"); + expect(transport.waiting).toHaveLength(1); + transport.waiting.shift()?.(status([])); + await first; + expect(store.colourOf("a.php")).toBeNull(); + expect(transport.waiting).toHaveLength(0); + }); + + it("refreshes on projectOpened and gitChanged, clears on projectClosed", async () => { + let answer = status([{ path: "n.php", index: "untracked", worktree: "untracked" }]); + const store = useVcsStatusStore(); + const calls = vi.fn(() => Promise.resolve({ ok: true as const, value: answer })); + store.configure({ status: calls }); + store.handle({ kind: "projectOpened", root: "/r", name: "r" }); + await flushPromises(); + expect(store.colourOf("n.php")).toBe("untracked"); + expect(store.repo).toBe(true); + + answer = status([{ path: "n.php", index: "added", worktree: "unmodified" }]); + store.handle({ kind: "gitChanged", available: true, repo: {}, filesChanged: true }); + await flushPromises(); + expect(store.colourOf("n.php")).toBe("added"); + expect(refreshGitGutters).toHaveBeenCalledTimes(1); + + store.handle({ kind: "projectClosed" }); + expect(store.colourOf("n.php")).toBeNull(); + expect(store.repo).toBe(false); + expect(calls).toHaveBeenCalledTimes(2); + }); + + it("ignores an answer for a project that closed meanwhile and keeps the state on failure", async () => { + const transport = new HeldTransport(); + const store = useVcsStatusStore(); + store.configure(transport); + void store.refresh(); + store.clear(); + transport.waiting.shift()?.(status([{ path: "a.php", index: "modified", worktree: "unmodified" }])); + await flushPromises(); + expect(store.colourOf("a.php")).toBeNull(); + + store.configure({ status: () => Promise.resolve({ ok: true, value: status([{ path: "b.php", index: "deleted", worktree: "unmodified" }]) }) }); + await store.refresh(); + store.configure({ status: () => Promise.resolve({ ok: false }) }); + await store.refresh(); + expect(store.colourOf("b.php")).toBe("deleted"); + }); +}); + +describe("tabs", () => { + it("colour the names of changed files", async () => { + const store = useVcsStatusStore(); + store.configure({ + status: () => Promise.resolve({ ok: true, value: status([{ path: "src/A.php", index: "unmodified", worktree: "modified" }]) }), + }); + await store.refresh(); + const editor = useEditorStore(); + editor.tabs = [ + { id: 1, path: "src/A.php", name: "A.php", dirty: false, notice: null }, + { id: 2, path: "src/B.php", name: "B.php", dirty: false, notice: null }, + ]; + const wrapper = mount(EditorTabs); + await flushPromises(); + const names = wrapper.findAll(".tabs__name"); + expect(names[0]?.attributes("data-vcs")).toBe("modified"); + expect(names[0]?.classes()).toContain("tabs__name--vcs-modified"); + expect(names[1]?.attributes("data-vcs")).toBeUndefined(); + wrapper.unmount(); + }); +});