PM: merge F1 vcs fixes, git.lastMessage, shared git status store
Some checks are pending
ci / ci (macos-15) (push) Waiting to run
ci / ci (ubuntu-24.04) (push) Waiting to run
ci / ci (windows-2025) (push) Waiting to run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-27 17:18:01 +01:00
commit 89df12f408
14 changed files with 649 additions and 314 deletions

View file

@ -1,6 +1,6 @@
//! Git commands (M4.1, owner decision D20): status, stage, unstage, commit,
//! file contents at HEAD or in the index, branches, checkout and branch
//! creation, through the user's installed git (`lutra-vcs`).
//! the last commit message, file contents at HEAD or in the index,
//! branches, checkout and branch creation, through the user's installed git (`lutra-vcs`).
//!
//! **Off the lock.** git can take seconds (a big status, a commit hook), so
//! every command returns a pending outcome ([`crate::Pending`]): under the
@ -60,6 +60,7 @@ pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(Stage))?;
registry.register(Box::new(Unstage))?;
registry.register(Box::new(Commit))?;
registry.register(Box::new(LastMessage))?;
registry.register(Box::new(Show))?;
registry.register(Box::new(BranchesCommand))?;
registry.register(Box::new(Checkout))?;
@ -188,6 +189,8 @@ enum Op {
/// Amend the last commit.
amend: bool,
},
/// `git.lastMessage`.
LastMessage,
/// `git.show`.
Show(String, Rev),
/// `git.branches`.
@ -208,7 +211,10 @@ enum Op {
impl Op {
/// Whether the call changes the repository (and sends `gitChanged`).
fn mutates(&self) -> bool {
!matches!(self, Self::Status | Self::Show(..) | Self::Branches)
!matches!(
self,
Self::Status | Self::LastMessage | Self::Show(..) | Self::Branches
)
}
}
@ -406,6 +412,7 @@ fn run_op(repo: &Repo, op: &Op) -> Result<Value, VcsError> {
let info = repo.commit(message, *amend)?;
Ok(json!({"commit": info.commit, "summary": info.summary}))
}
Op::LastMessage => Ok(json!({"message": repo.last_message()?})),
Op::Show(path, rev) => {
let contents = repo.show(path, *rev)?;
Ok(json!({
@ -714,6 +721,31 @@ impl Command for Commit {
}
}
/// `git.lastMessage`.
struct LastMessage;
impl Command for LastMessage {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.lastMessage",
label: "Git: Last Commit Message",
menu_path: None,
default_shortcut: None,
params: "none; returns { message: string | null }: the full message of HEAD (trailing line breaks removed), null before the first commit; for prefilling an amend",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let _: serde_json::Map<String, Value> = parse(command, params)?;
start(state, command, Op::LastMessage)
}
}
/// Which version `git.show` returns.
#[derive(Debug, Clone, Copy, Deserialize)]
enum RefParam {

View file

@ -484,6 +484,7 @@ mod tests {
"git.checkout",
"git.commit",
"git.createBranch",
"git.lastMessage",
"git.lineChanges",
"git.show",
"git.stage",

View file

@ -180,6 +180,13 @@ fn status_stage_commit_show_and_branches() {
assert_eq!(commit["summary"], "second");
assert_eq!(commit["commit"], git(dir.path(), &["rev-parse", "HEAD"]));
assert_eq!(host.git_changes().len(), 1);
assert_eq!(
host.run("git.lastMessage", Value::Null).unwrap(),
json!({"message": "second\n\nbody"})
);
assert!(host.git_changes().is_empty());
let err = host.run("git.lastMessage", json!([1])).unwrap_err();
assert_eq!(err.code(), "invalid_params");
assert_eq!(
host.run("git.status", Value::Null).unwrap()["files"],
json!([])

View file

@ -290,6 +290,66 @@ pub fn parse_refs(bytes: &[u8]) -> Vec<RefEntry> {
.collect()
}
/// One `remote.<name>.fetch` refspec.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchSpec {
/// The remote's name (case kept, may hold dots).
pub remote: String,
/// The refspec as configured, e.g. `+refs/heads/*:refs/remotes/origin/*`.
pub spec: String,
}
/// Parses `git config -z --get-regexp ^remote\..*\.fetch$` output: entries
/// separated by NUL, each `remote.<name>.fetch`, a line break and the value.
/// Entries without a value or with another key shape are skipped.
pub fn parse_fetch_specs(bytes: &[u8]) -> Vec<FetchSpec> {
bytes
.split(|b| *b == 0)
.filter_map(|entry| {
let text = String::from_utf8_lossy(entry);
let (key, value) = text.split_once('\n')?;
let remote = key.strip_prefix("remote.")?.strip_suffix(".fetch")?;
if remote.is_empty() || value.is_empty() {
return None;
}
Some(FetchSpec {
remote: remote.to_string(),
spec: value.to_string(),
})
})
.collect()
}
/// The local branch name git derives for checking out the remote-tracking
/// ref `refname` (`refs/remotes/origin/x`) with `--track`: the part a
/// configured fetch refspec's destination matches (`*`), or the source
/// branch of an exact refspec.
///
/// # Returns
/// `None` when no configured refspec maps a branch to `refname`; git can
/// then not set up tracking for it. Negative refspecs (`^…`) are skipped.
pub fn tracking_name(specs: &[FetchSpec], refname: &str) -> Option<String> {
specs.iter().find_map(|fetch| {
let spec = fetch.spec.strip_prefix('+').unwrap_or(&fetch.spec);
if spec.starts_with('^') {
return None;
}
let (src, dst) = spec.split_once(':')?;
match dst.split_once('*') {
Some((before, after)) => {
let name = refname.strip_prefix(before)?.strip_suffix(after)?;
src.contains('*').then_some(())?;
(!name.is_empty()).then(|| name.to_string())
}
None => (dst == refname)
.then(|| src.strip_prefix("refs/heads/"))
.flatten()
.filter(|n| !n.is_empty())
.map(str::to_string),
}
})
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::indexing_slicing)]
@ -394,6 +454,26 @@ u UU N... 100644 100644 100644 100644 a b c conflict.php\0\
assert!(refs[1].symbolic);
}
#[test]
fn fetch_specs_and_tracking_names() {
let out = b"remote.origin.fetch\n+refs/heads/*:refs/remotes/origin/*\0\
remote.my.fork.fetch\nrefs/heads/main:refs/remotes/my.fork/main\0\
remote.neg.fetch\n^refs/heads/secret\0remote..fetch\nx\0junk\0";
let specs = parse_fetch_specs(out);
assert_eq!(specs.len(), 3);
assert_eq!(specs[1].remote, "my.fork");
let name = |r: &str| tracking_name(&specs, r);
assert_eq!(
name("refs/remotes/origin/feature/x").as_deref(),
Some("feature/x")
);
assert_eq!(name("refs/remotes/my.fork/main").as_deref(), Some("main"));
assert_eq!(name("refs/remotes/my.fork/other"), None);
assert_eq!(name("refs/remotes/foo/x"), None);
assert_eq!(name("refs/remotes/origin/"), None);
assert_eq!(tracking_name(&[], "refs/remotes/origin/x"), None);
}
proptest! {
#[test]
fn status_parser_never_panics(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
@ -425,6 +505,8 @@ u UU N... 100644 100644 100644 100644 a b c conflict.php\0\
fn version_and_ref_parsers_never_panic(bytes in proptest::collection::vec(any::<u8>(), 0..256)) {
let _ = parse_version(&String::from_utf8_lossy(&bytes));
let _ = parse_refs(&bytes);
let specs = parse_fetch_specs(&bytes);
let _ = tracking_name(&specs, &String::from_utf8_lossy(&bytes));
}
}
}

View file

@ -10,7 +10,7 @@ use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard, PoisonError};
use crate::VcsError;
use crate::porcelain::{self, FileStatus, Head, REF_FORMAT, Status, Version};
use crate::porcelain::{self, FetchSpec, FileStatus, Head, REF_FORMAT, Status, Version};
use crate::runner::{self, Call, HOOK_TIMEOUT};
/// Oldest supported git: 2.30 (porcelain v2 headers, `--pathspec-from-file`
@ -564,20 +564,55 @@ impl Repo {
.success())
}
/// Checks out a local branch, or creates a local branch tracking a
/// remote one (`origin/feature` → `feature`). Hooks run (120 s).
/// The configured `remote.<name>.fetch` refspecs.
///
/// # Errors
/// The runner's errors; no configured remote is an empty list.
fn fetch_specs(&self) -> Result<Vec<FetchSpec>, VcsError> {
let output = self.run(Call::read(
&self.root,
&["config", "-z", "--get-regexp", r"^remote\..*\.fetch$"],
SMALL_CAP,
))?;
if !output.success() {
return Ok(Vec::new());
}
Ok(porcelain::parse_fetch_specs(&output.stdout))
}
/// Checks out a local branch, or creates a local branch from a remote
/// one (`origin/feature` → `feature`). Hooks run (120 s).
///
/// The new branch tracks the remote one when a configured fetch refspec
/// maps a branch to it (the name comes from that refspec, as git
/// derives it). Without one (the remote was removed, or the ref was
/// created by hand) git could not set up tracking and would fail after
/// updating the work tree, so the branch is created with `--no-track`,
/// named after the part behind the first `/`.
///
/// # Errors
/// [`VcsError::InvalidName`], [`VcsError::Git`] for an unknown branch
/// or when git refuses (local changes would be overwritten); git's
/// message is passed on.
/// or when git refuses (local changes would be overwritten, the local
/// branch exists already); git's message is passed on.
pub fn checkout(&self, branch: &str) -> Result<(), VcsError> {
check_name(branch)?;
let _guard = self.lock();
let remote_ref = format!("refs/remotes/{branch}");
let local;
let args: Vec<&str> = if self.ref_exists(&format!("refs/heads/{branch}"))? {
vec!["switch", "-q", branch]
} else if self.ref_exists(&format!("refs/remotes/{branch}"))? {
vec!["switch", "-q", "--track", branch]
} else if self.ref_exists(&remote_ref)? {
let tracked = porcelain::tracking_name(&self.fetch_specs()?, &remote_ref);
let track = if tracked.is_some() {
"--track"
} else {
"--no-track"
};
local = tracked
.or_else(|| branch.split_once('/').map(|(_, rest)| rest.to_string()))
.unwrap_or_default();
check_name(&local)?;
vec!["switch", "-q", "-c", &local, track, branch]
} else {
return Err(VcsError::Git(format!("no branch named {branch}")));
};
@ -586,6 +621,29 @@ impl Repo {
Ok(())
}
/// The full message of the last commit, for prefilling an amend.
///
/// # Returns
/// `None` before the first commit; otherwise the raw message (`%B`)
/// with trailing line breaks removed.
///
/// # Errors
/// The runner's errors or git's refusal.
pub fn last_message(&self) -> Result<Option<String>, VcsError> {
if !self.has_head()? {
return Ok(None);
}
let output = self
.run(Call::read(
&self.root,
&["show", "-s", "--format=%B", "HEAD"],
SMALL_CAP,
))?
.checked()?;
let text = String::from_utf8_lossy(&output.stdout);
Ok(Some(text.trim_end_matches(['\n', '\r']).to_string()))
}
/// Creates a branch.
///
/// # Parameters

View file

@ -351,6 +351,60 @@ fn remote_branches_are_listed_and_checked_out_as_tracking_branches() {
repo.checkout("origin/remote-only").unwrap();
let branches = repo.branches().unwrap();
assert_eq!(branches.current.as_deref(), Some("remote-only"));
let local = branches.local.iter().find(|b| b.name == "remote-only");
assert_eq!(
local.and_then(|b| b.upstream.as_deref()),
Some("origin/remote-only")
);
}
#[test]
fn remote_branches_without_a_configured_remote_check_out_untracked_and_clean() {
let Some(cli) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
init(dir.path());
write(dir.path(), "a.php", "<?php\n");
git(dir.path(), &["add", "-A"]);
git(dir.path(), &["commit", "-q", "-m", "base"]);
git(dir.path(), &["checkout", "-q", "-b", "gone"]);
write(dir.path(), "b.php", "<?php // only on gone\n");
git(dir.path(), &["add", "-A"]);
git(dir.path(), &["commit", "-q", "-m", "gone"]);
git(dir.path(), &["checkout", "-q", "main"]);
git(dir.path(), &["update-ref", "refs/remotes/old/gone", "gone"]);
git(dir.path(), &["branch", "-q", "-D", "gone"]);
let repo = open(&cli, dir.path());
repo.checkout("old/gone").unwrap();
let status = repo.status().unwrap();
assert_eq!(status.head.branch.as_deref(), Some("gone"));
assert_eq!(status.head.upstream, None);
assert!(status.files.is_empty(), "{:?}", status.files);
assert!(dir.path().join("b.php").exists());
repo.checkout("main").unwrap();
let err = repo.checkout("old/gone").unwrap_err();
assert!(matches!(err, VcsError::Git(_)), "{err:?}");
let status = repo.status().unwrap();
assert_eq!(status.head.branch.as_deref(), Some("main"));
assert!(status.files.is_empty(), "{:?}", status.files);
}
#[test]
fn the_last_message_prefills_an_amend() {
let Some(cli) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
init(dir.path());
let repo = open(&cli, dir.path());
assert_eq!(repo.last_message().unwrap(), None);
write(dir.path(), "a.php", "<?php\n");
repo.stage(&["a.php".into()]).unwrap();
repo.commit("Subject line\n\n# kept\nBody ü\n\n", false)
.unwrap();
assert_eq!(
repo.last_message().unwrap().as_deref(),
Some("Subject line\n\n# kept\nBody ü")
);
}
#[test]

View file

@ -565,7 +565,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- Caps: status 64 MiB, one file 32 MiB, other reads 16 MiB, stderr 16 KiB (the error text, also a failing hook's output; stdout is used when stderr is empty).
- Output is read only from machine formats: `status --porcelain=v2 -z --branch`, `cat-file --batch-check`, `for-each-ref` with NUL-separated fields, `show -s --format=%H%x00%s`. The parsers are property-tested with random bytes. Paths git prints that are not UTF-8 (Unix only) become U+FFFD instead of failing the status.
- `Git::detect(setting)` runs `git --version`; `Git::open(dir)` runs `rev-parse --show-toplevel --absolute-git-dir --git-common-dir --show-prefix` and gives `None` outside a work tree (the repository containing the project root; a nested repository wins). Paths in and out of `Repo` are project-relative with `/`; the prefix maps them to the repository root, and files outside the project are left out of the status. Input paths are refused when empty, absolute, with `..`, NUL or line breaks; they go to git through `--pathspec-from-file=- --pathspec-file-nul`, so any count and any name works.
- Operations: `status` (untracked files one by one, ignored files not listed), `head` (branch information only, `--untracked-files=no`), `stage` (`add -A`), `unstage` (`reset -q HEAD`, or `rm --cached` before the first commit), `commit` (`-F -` from stdin, `--cleanup=whitespace` so lines starting with `#` stay), `show` (the blob as stored: no smudge filters, no line-ending conversion, so LFS stays a pointer and nothing reaches the network; binary when a NUL is in the first 8000 bytes, the text is not UTF-8, or the entry is a submodule; a UTF-8 BOM is dropped), `branches`, `checkout` (local branch: `switch`; remote branch `origin/x`: `switch --track`, a local tracking branch), `create_branch` (name checked with `check-ref-format --branch`, which must echo the name unchanged, so `@{-1}` is refused; `switch -c` or `branch --end-of-options`). Names and revisions starting with `-` are refused. Changes hold a per-repository mutex.
- Operations: `status` (untracked files one by one, ignored files not listed), `head` (branch information only, `--untracked-files=no`), `stage` (`add -A`), `unstage` (`reset -q HEAD`, or `rm --cached` before the first commit), `commit` (`-F -` from stdin, `--cleanup=whitespace` so lines starting with `#` stay), `show` (the blob as stored: no smudge filters, no line-ending conversion, so LFS stays a pointer and nothing reaches the network; binary when a NUL is in the first 8000 bytes, the text is not UTF-8, or the entry is a submodule; a UTF-8 BOM is dropped), `branches`, `checkout` (local branch: `switch`; remote branch `origin/x`: `switch -c x --track` when a configured `remote.<name>.fetch` refspec maps a branch to it, the local name taken from that refspec as git does; otherwise, such as a removed remote or a hand-made ref, `switch -c x --no-track`, because git would update the work tree before failing on the tracking setup and leave it dirty; C6 F1), `last_message` (`show -s --format=%B HEAD`, none before the first commit; C6 F1), `create_branch` (name checked with `check-ref-format --branch`, which must echo the name unchanged, so `@{-1}` is refused; `switch -c` or `branch --end-of-options`). Names and revisions starting with `-` are refused. Changes hold a per-repository mutex.
- `RepoWatch` polls `HEAD`, `index`, `MERGE_HEAD`, `ORIG_HEAD`, `packed-refs` and the files under `refs/heads` and `refs/remotes` (at most 4,096) every 250 ms on its own thread, comparing size and modification time. The project watcher never sees `.git`, and OS notifications on a directory whose object store churns on every commit would be noisier than a few `stat` calls. `rebase()` takes the current state as the baseline after Lutra's own change.
- **Engine (`crates/engine/src/cmd/git.rs`):** every `git.*` command returns a pending outcome (M3.5). Under the lock it parses its params and takes the setting, the cached git and the cached repository; a `lutra-git` thread detects git and opens the repository when they are not cached, runs the call and fills a reply slot (the `Pending` channel only signals). The finish caches git (per setting value) and the repository (per project root), starts the watch, and emits `gitChanged` after a change. At most 32 calls run at once. Hosts and the UI call these commands with `run_waiting` / `runWaiting`.
- **Commands** (all need a project):
@ -574,7 +574,8 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- `git.commit {message, amend?}` → `{commit, summary}`; a blank message is `invalid_params`.
- `git.show {path, ref: "HEAD"|"index"}` → `{text|null, binary, tooLarge}`.
- `git.branches` → `{current|null, local: [{name, head, upstream?}], remote: [{name, head}]}` sorted by name, without `origin/HEAD`.
- `git.checkout {branch}` → `{}`; git's refusal is the error text. Open buffers follow through the file watcher.
- `git.lastMessage` → `{message|null}`: the full message of HEAD without trailing line breaks, null before the first commit (C6 F1, for the Amend prefill). Read-only, no `gitChanged`.
- `git.checkout {branch}` → `{}`; git's refusal is the error text. A remote branch without a configured remote becomes an untracked local branch (C6 F1). Open buffers follow through the file watcher.
- `git.createBranch {name, from?, checkout}` → `{}`.
- Bad paths, names or messages are `invalid_params`; everything git refuses is `failed` with git's message; no project is `disabled`.
- **Event `gitChanged {available, repo, filesChanged: true}`:** after every successful change (in the same outcome), and 300 ms after the last change the `.git` watch or the project watcher reported (at most 2 s after the first), from a `head()` query on its own thread. The UI re-queries `git.status`.
@ -588,7 +589,8 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **Where:** a Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): `changes.ts` is the Pinia store, `ChangesToolWindow.vue` the window. The main layout starts the store when it mounts, so the status is current before the tab opens, and supplies the UI commands.
- **Commands** (UI commands, menu group Git): `vcs.openChanges` `Mod+Alt+Shift+G` shows the tab; `vcs.commit` `Mod+Alt+Shift+M` shows it and focuses the message box; `vcs.refresh` re-reads the status (enabled while `git.status` is). The shortcuts are Lutra's own: checked against the public default keymaps (Windows and macOS) so they copy no default there, and against Lutra's registered shortcuts and CodeMirror's `basicSetup` keys (`Mod+Alt+G` is its go to line, which the global listener would swallow).
- **Status:** `git.status` through `runWaiting` on start, on `projectOpened`, on `gitChanged` and on `vcs.refresh`; calls are serialised and requests made during a round cause exactly one more round. `projectClosed` clears it. The result is untrusted: unknown states and malformed entries are dropped, at most 50,000 files. The event type `gitChanged` is now part of `EngineEventPayload` in `ui/src/ipc.ts`.
- **Status:** read from the shared status store (`ui/src/stores/vcsStatus.ts`, since C6 F1), which runs `git.status` on start, on `projectOpened`, on `gitChanged` and on `vcs.refresh`; `projectClosed` clears it and with it the rows and the selection. The result is untrusted: unknown states and malformed entries are dropped, at most 50,000 files.
- **Amend prefill (C6 F1):** checking Amend with an empty message box fills it from `git.lastMessage`; clearing Amend empties a box that still holds exactly that text. A message already typed is never replaced. The event type `gitChanged` is now part of `EngineEventPayload` in `ui/src/ipc.ts`.
- **Groups:** Staged (the index side changed), Changes (the work tree side changed, or conflicted), Untracked. A partly staged file is in Staged and Changes. Names are coloured with `--lt-vcs-*` (renamed and modified use `modified`, copied uses `added`); a deleted file is struck through. A staged rename shows "from <old path>".
- **Staging:** a checkbox per file and per group header: checked in Staged (clearing it unstages), clear elsewhere (checking it stages). `git.stage {paths}` / `git.unstage {paths}`, both through `runWaiting`; unstaging a staged rename passes both paths, as M4.1 requires. Keyboard: Up/Down, Page Up/Down, Home, End move; Space stages or unstages; Enter opens. Failures toast git's message (`notification.command.failed`).
- **Opening:** Enter or a double-click runs the UI command `vcs.showDiff {path, staged}` when something provides it (the diff viewer, M4.3, registers and provides it); until then the file opens with `file.open`, and a deleted file does nothing.
@ -605,7 +607,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **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.
- **Shared status store (C6 F1):** `vcsStatus` is the only caller of `git.status` in the UI. It keeps the snapshot (`snapshot`, read by `toStatus`: files, `repo` with branch, head, upstream, ahead and behind), `loading`, `loadError` (a failure keeps the last snapshot; `disabled` drops it) and the colours. The Changes window, the tree and tab colours and the branch status-bar item (M4.5) all read it, so each `gitChanged` costs one `git.status`; one round at a time, requests during a round share one more. `start` / `stop` are counted (`App.vue` and the main layout both hold it). Later features read `snapshot` and call `refresh()`, never `git.status`.
- **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`.
@ -649,6 +651,7 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
| Date | Change | Summary |
|---|---|---|
| 2026-10-27 | minor | C6 F1: remote branch checkout without a configured remote (`--no-track`), `git.lastMessage` and the Amend prefill, one shared git status store |
| 2026-10-27 | minor | F2: `ui.screenshot` through WebView2 `CapturePreview` without focus; region fallback elsewhere; `--control` windows open unfocused |
| 2026-10-26 | minor | M4.5: branches (status-bar item, popup, `vcs.branches`, `vcs.newBranch`, `vcs.checkout`) |
| 2026-10-26 | minor | M4.3: diff viewer (`vcs.showDiff`, `vcs.nextChange`, `vcs.previousChange`, `@codemirror/merge` loaded lazily, the project tree's context menu) |

View file

@ -13,7 +13,7 @@ Every known shortfall, ranked. This is the work list: unless the owner gives a t
| G5 | Search and navigation: find in files, go to file/class/symbol, first index | M2 | ~35 h |
| G6 | Language server: completion, definition, hover, rename via Phpactor (~~PHP detection and Phpactor download~~, M3.1; ~~engine wiring and diagnostics~~, M3.3; ~~completion, hover, signature help~~, M3.4; ~~definition, references, rename~~, M3.5) | M3 | ~15 h |
| G7 | ~~Terminal~~ (M3.6: PTY sessions, xterm.js sub-tabs in the bottom panel; settings, persistence, links and search still open), ~~`lutra` CLI and single instance~~ (M3.7: open folders and files at a line, `--wait`, forwarding a second start, token-protected rendezvous), ~~MCP server~~ (M3.8: `lutra mcp` with list/execute every command, screenshot, read buffer, recent events, open buffers as resources; still missing: resource and tool change notifications, progress for long commands), files outside the open project (the CLI refuses them; needs out-of-project buffers or a second window), `lutra diff` | M3 | ~16 h |
| G8 | Git integration: ~~backend through the installed git~~ (M4.1: status, stage/unstage, commit and amend, file contents at HEAD/index, branches, checkout, branch creation, `gitChanged`), ~~Changes window~~ (M4.2: staged/changes/untracked groups, stage and unstage per file and group, commit and amend after saving, no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), log, blame, conflicts, stash, remotes | M4 | ~122 h |
| 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, amend prefilled with the last message (C6 F1), no chunk staging), ~~gutter markers and status colours~~ (M4.4: added/modified/deleted against the index, tree and tab colours; no chunk actions), ~~diff viewer~~ (M4.3: side by side against the index or HEAD, editable working copy, next/previous change; no unified view, chunk actions or other revisions), ~~branch popup~~ (M4.5: status-bar branch, popup with local and remote branches and a filter, checkout after saving, new branch from HEAD; no merge, rebase, rename or delete), log, blame, conflicts, stash, remotes | M4 | ~122 h |
| G9 | Debugger, test runner, Composer, run configurations | M5 | ~300 h |
| G10 | Own indexer, type inference, inspections, refactorings | M6 | ~800 h |
| G11 | Stability: crash-free operation on real projects and machines (~~recovery journal~~, M1.7) | ongoing | ~95 h |
@ -52,6 +52,7 @@ G6 progress: M3.2 landed the LSP client library in `crates/lsp`: JSON-RPC framin
| Date | Change | Summary |
|---|---|---|
| 2026-10-27 | patch | G8: amend prefill, remote checkout fix, shared status store (C6 F1) |
| 2026-10-27 | minor | Screenshot item shrunk: webview capture without focus on Windows (F2) |
| 2026-10-26 | minor | G8 shrunk: branch widget and popup (M4.5) |
| 2026-10-26 | minor | G8 shrunk: diff viewer (M4.3) |

View file

@ -22,7 +22,7 @@ Hours are the estimated agent wall-clock hours for one agent to reach behaviour
| Inspections and quick-fixes | 8 | 5% (est.) | Lutra's own inspections and their settings, severities per inspection, quick-fixes (LSP code actions), suppression, inspection profiles, running inspections on a scope, the editor's problem counter and scrollbar marks, next/previous problem, a current-file Problems view and severity filters, external tools (PHPStan, Psalm, PHP_CodeSniffer) | ~287 (est.) | H3: PHP syntax errors on Windows from Lutra's own `php -l` (on open and save, off the engine lock, killed with Lutra), merged into the editor underlines and the Problems tab with source `php -l`; the language server's messages as notifications and its log as `lsp.log`. Tests: `crates/engine/tests/lsp_ux.rs`, unit tests incl. a parser proptest. M3.3: diagnostics from Phpactor (worse reflection: missing members, unknown classes, …) as wavy underlines, gutter markers and hover messages in the editor (`ui/src/components/editor/lint.ts`, tokens only), and a Problems tab in the bottom panel grouped by file with click to reveal (`ui/src/components/problems/`, `problems.open` `Mod+Alt+P`); engine `diagnosticsChanged`, `diagnostics.list`, `lspStatus` (`crates/engine/src/lsp/`). Tests: 10 engine tests against a fake server incl. a sync proptest, a TCP test, 16 Vitest tests, an ignored test against the real PHAR. Checked in the app on Windows 11 with the real Phpactor (port 7933): five errors underlined and listed; first diagnostics 2.7 s after `file.open`, 2.7–2.9 s after an edit (debug build, measured, incl. Phpactor's 1 s debounce). Graded against `plan/phpstorm/11-problems.md`: the depth comes from Phpactor, Lutra has no inspections of its own |
| Refactoring | 7 | 3% (est.) | rename: preview of all changes, comments/strings and text occurrences, scope, renaming files with classes, one undo across files (closed files written on disk are not undone by the editor); extract variable/method/constant, inline, move, change signature, safe delete, pull up/push down, introduce parameter | ~244 (est.) | M3.5: Rename (`lsp.prepareRename` then `lsp.rename`, F2) through Phpactor with an inline field over the symbol that shows how many uses in how many files change. The workspace edit is checked completely first (inside the project, ranges fit, open buffers unchanged since the request, no file operations); then closed files are written atomically through the VFS (written ones restored if a later write fails), open buffers change through `buffer.edit` (dirty, one undo step each in the editor), Phpactor reindexes the written files (sent as `didOpen`/`didSave`/`didClose`; its index followed in 140 ms, measured) and a summary notification follows. Live: renaming a method used in 3 files took 28 ms (open buffer + 2 closed files, CRLF kept). Tests: `crates/engine/tests/lsp_nav.rs` (multi-file rename incl. a closed CRLF file, an edit outside the project refused, a bad range refused, a buffer edited meanwhile refused; ignored real-Phpactor rename and rename back), Vitest `ui/tests/nav/`. |
| Code style and formatting | 4 | 0% | everything | ~120 (est.) | — |
| Git | 8 | 9% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branches: merge, rebase, rename, delete, compare, favourites, incoming/outgoing markers, a branch from another start point; log, blame, conflicts, stash, remotes (C6); ignored files in the status | ~122 (est.) | M4.5: a status-bar item shows the current branch, or the short hash when detached (`ui/src/components/vcs/branches/`); clicking it or `vcs.branches` (menu Git › Branches…) opens a popup with a filter field, "New branch…", the local branches (current marked, upstream shown) and the remote branches, keyboard-driven; choosing one runs `vcs.checkout {branch}`, which saves dirty buffers through `flushDirty()` first, cancels when a save fails and toasts git's refusal with the branch name; a remote branch checks out its tracking branch. "New branch…" / `vcs.newBranch {name?, checkout?}` creates one from HEAD (checked out by default) and keeps git's refusal next to the name. Tests: 16 Vitest tests (`ui/tests/vcs/Branches.test.ts`). M4.3: `vcs.showDiff {path, staged?}` (`Mod+Alt+Shift+D`, menu Git › Show Diff, double-click in Changes, the project tree's context menu, the palette) opens a "Diff: <name>" tab in the editor area: `@codemirror/merge` side by side, the staged version (or the last commit for a staged row) read-only on the left, the working copy editable on the right through its normal engine buffer (saves, autosave, the journal), changed lines and words tinted with `--lt-vcs-*`, unchanged stretches collapsed, the left side re-read on `gitChanged`; next/previous change (`Alt+Shift+]` / `Alt+Shift+[`); notices for binary, too large, failed and deleted files (`ui/src/components/vcs/diff/`, 21 Vitest tests). M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing, staging and switching or creating branches work from the UI, and changed lines and files are marked (read-only markers, no chunk actions); diff, log, blame and remotes do not yet. |
| Git | 8 | 9% (est.) | Changes window: chunk and line staging, changelists, recent messages and a message template, pre-commit checks, skipping hooks, commit-and-push, a tree view and grouping, a context menu (rollback, delete, ignore); gutter markers: actions (show the old text, revert or stage a chunk, next/previous change), markers against HEAD; directory status colours; diff viewer: a unified view, three-way merge, revert or stage a chunk from the diff, comparing with any revision or branch, ignore-whitespace options, folders; branches: merge, rebase, rename, delete, compare, favourites, incoming/outgoing markers, a branch from another start point; log, blame, conflicts, stash, remotes (C6); ignored files in the status | ~122 (est.) | C6 F1: Amend fills an empty message box with the last commit message (`git.lastMessage`); checking out a remote branch whose remote is not configured gives an untracked local branch and a clean tree instead of a half-done checkout; one shared status store, so a `gitChanged` costs one `git.status` for the Changes window, the colours and the branch item. M4.5: a status-bar item shows the current branch, or the short hash when detached (`ui/src/components/vcs/branches/`); clicking it or `vcs.branches` (menu Git › Branches…) opens a popup with a filter field, "New branch…", the local branches (current marked, upstream shown) and the remote branches, keyboard-driven; choosing one runs `vcs.checkout {branch}`, which saves dirty buffers through `flushDirty()` first, cancels when a save fails and toasts git's refusal with the branch name; a remote branch checks out its tracking branch. "New branch…" / `vcs.newBranch {name?, checkout?}` creates one from HEAD (checked out by default) and keeps git's refusal next to the name. Tests: 16 Vitest tests (`ui/tests/vcs/Branches.test.ts`). M4.3: `vcs.showDiff {path, staged?}` (`Mod+Alt+Shift+D`, menu Git › Show Diff, double-click in Changes, the project tree's context menu, the palette) opens a "Diff: <name>" tab in the editor area: `@codemirror/merge` side by side, the staged version (or the last commit for a staged row) read-only on the left, the working copy editable on the right through its normal engine buffer (saves, autosave, the journal), changed lines and words tinted with `--lt-vcs-*`, unchanged stretches collapsed, the left side re-read on `gitChanged`; next/previous change (`Alt+Shift+]` / `Alt+Shift+[`); notices for binary, too large, failed and deleted files (`ui/src/components/vcs/diff/`, 21 Vitest tests). M4.2: Changes tab in the bottom panel (`ui/src/components/vcs/changes/`): Staged / Changes / Untracked groups from `git.status` (re-read on `gitChanged`), stage and unstage per file and per group with checkboxes (a staged rename passes both paths), keyboard navigation with Space to stage, double-click or Enter opens through `vcs.showDiff` when the diff viewer provides it, else the file; a commit message box with Amend and Commit (also `Mod+Enter`), which runs `flushDirty()` first, cancels when a save fails and toasts the short hash; hints for a missing git and a folder without a repository; `vcs.openChanges` `Mod+Alt+Shift+G`, `vcs.commit` `Mod+Alt+Shift+M`, `vcs.refresh`. Tests: 19 Vitest tests (`ui/tests/vcs/ChangesToolWindow.test.ts`). M4.4: change markers in the editor gutter (added, modified, deleted against the index, 150 ms after typing and on every `gitChanged`, CRLF-safe) through `git.lineChanges` (line diff in Rust off the lock, index text cached and dropped on `gitChanged`); file names in the project tree and the editor tabs coloured by Git status (`--lt-vcs-*`), ignored entries in the ignored colour inside a repository. Tests: `crates/engine/tests/git_lines.rs` (real temp repositories), unit and property tests, Vitest (`ui/tests/editor/gitGutter.test.ts`, `ui/tests/vcs/vcsStatus.test.ts`). M4.1 (backend, reachable through the palette, control channel and MCP): `git.status`, `git.stage`, `git.unstage` (also before the first commit), `git.commit {message, amend}` with hooks, `git.show` at HEAD or the index, `git.branches`, `git.checkout` (remote → tracking branch), `git.createBranch`; `gitChanged` after changes and from a `.git` poll plus the project watcher. Runs the installed git ≥ 2.30 (`git.executable`), porcelain v2 / `-z` only, no prompts, timeouts and caps, off the engine lock. Tests against real temp repositories (`crates/vcs/tests/repo.rs`, `crates/engine/tests/git.rs`). Graded against `plan/phpstorm/16-vcs-basics.md`: committing, staging and switching or creating branches work from the UI, and changed lines and files are marked (read-only markers, no chunk actions); diff, log, blame and remotes do not yet. |
| Terminal | 3 | 15% (est.) | renaming and splitting tabs, sessions kept across restarts, search in the output, clickable paths and links, drag and drop, command completion, terminal settings (shell path, start directory, environment, font, cursor shape, bell, copy on selection, middle-click paste), a key back to the editor, the PHP interpreter in `PATH`, a terminal in a file's directory, confirmation before killing a running process, moving a terminal into the editor | ~26 (est.) | M3.6: `crates/terminal` runs the shell in a pseudo terminal (`portable-pty`: ConPTY on Windows, Unix pty elsewhere) on its own reader, writer and waiter threads: UTF-8 split across reads joined, invalid bytes U+FFFD, a 1 MiB output buffer per session with backpressure (the shell waits, nothing is dropped while it runs), a non-blocking input queue, resize, kill, exit codes. Engine `terminal.create {cwd?, shell?, cols, rows}` / `terminal.input` / `terminal.resize` / `terminal.close`, events `terminalOutput` (≤ 64 KiB per terminal and 256 KiB per pump, round-robin) and `terminalExited {code}`; terminals close with the project and on `app.quit`. UI: a Terminal tab in the bottom panel (tabs next to Find), xterm.js with the fit addon, several terminals as sub-tabs (Local, Local (2)…) with close and new buttons, output replayed after collapsing the panel, copy (`Mod+Shift+C`, `Ctrl+C` with a selection) and paste (`Mod+Shift+V`, `Ctrl+V`), a focus rule that leaves plain Ctrl keys to the shell, Lutra's own ANSI colours (`--lt-terminal-*`, all text colours ≥ 4.5:1), `terminal.open` `Mod+Shift+T`. Tests: 8 session tests with real `cmd.exe` (echo, exit code, input, 6,000 multibyte characters without U+FFFD, 30,000 lines through a full buffer without losing a line, resize, kill, spawn errors) and UTF-8 proptests (`crates/terminal`), 3 engine tests (`crates/engine/tests/terminal.rs`), a TCP control test create → output → input → exit (`crates/control/tests/terminal.rs`), 20 Vitest tests with a mocked xterm (`ui/tests/terminal/`). Live check (Windows 11, debug build with bundled UI, control port 7936, temp project): `terminal.open` showed a pwsh prompt in the project root, first `terminalOutput` 0.2–0.5 s after the command; `php -v` printed PHP 8.4.24 within 0.5–1.5 s; `dir` listed the project; resizing the window changed the shell's width 144 → 190 → 105 → 142 columns (pwsh `WindowSize`); a second terminal as sub-tab "Local (2)"; Find and Terminal as bottom tabs; dark and light screenshots read; `exit 3` gave `terminalExited {code: 3}`; `app.quit` ended the app and its shells (measured). The live check found two bugs, fixed before the commit: xterm's own black viewport background showed as a bar under the last row, and programs printing ANSI white (PSReadLine) were unreadable on the light theme, so xterm now enforces a 4.5:1 minimum contrast. Typing, clicking and copy/paste were not driven in the app (the control channel has no input method); Vitest covers them. Graded against `plan/phpstorm/10-terminal.md` |
| Run configurations | 2 | 0% | everything | ~50 (est.) | — |
| Debugger | 5 | 0% | everything | ~120 (est.) | — |
@ -65,6 +65,7 @@ The project tree is the first user-visible feature (Project view 8%, estimated);
| Date | Change | Summary |
|---|---|---|
| 2026-10-27 | patch | C6 F1 evidence in the Git row (Amend prefill, remote checkout fix, shared status store) |
| 2026-10-26 | minor | C5 review: breadth 35/155 |
| 2026-10-26 | minor | M4.5: Git 8% → 9% (est.), branch widget and popup; hours 128 → 122 |
| 2026-10-26 | minor | M4.3: Git 6% → 8% (est.), diff viewer; hours 136 → 128 |

View file

@ -21,17 +21,17 @@ import { useCommandsStore } from "../../../commands/store";
import { t } from "../../../i18n";
import type { JsonValue } from "../../../ipc";
import { useNotificationsStore } from "../../../stores/notifications";
import { useChangesStore } from "../changes/changes";
import { useVcsStatusStore } from "../../../stores/vcsStatus";
import BranchPopup from "./BranchPopup.vue";
import { headLabel, useBranchesStore } from "./branches";
const changes = useChangesStore();
const vcs = useVcsStatusStore();
const branches = useBranchesStore();
const commands = useCommandsStore();
const notifications = useNotificationsStore();
/** The repository of the last status, if any. */
const repo = computed(() => (changes.status?.available ? changes.status.repo : null));
const repo = computed(() => (vcs.snapshot?.available ? vcs.snapshot.repo : null));
/** The text of the item, or null when it is hidden. */
const text = computed(() => headLabel(repo.value));

View file

@ -2,9 +2,9 @@
* The branches popup's state (M4.5): the repository's branches from
* `git.branches`, the filter, and switching to or creating a branch.
*
* - **Current branch:** the status-bar item reads it from the Changes
* store's `git.status` ({@link headLabel}), which already follows
* `gitChanged`, so there is no second status query.
* - **Current branch:** the status-bar item reads it from the shared
* status store (`stores/vcsStatus.ts`, {@link headLabel}), which already
* follows `gitChanged`, so there is no second status query.
* - **List:** `git.branches` (a pending outcome, so through `runWaiting`)
* each time the popup opens. Local branches come first, then remote
* ones; a filter keeps the names that contain every word of it,
@ -25,7 +25,8 @@ import { computed, ref, shallowRef } from "vue";
import { runWaiting, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave";
import { useNotificationsStore } from "../../../stores/notifications";
import { SHORT_HASH, type RepoSummary } from "../changes/changes";
import { type RepoSummary } from "../../../stores/vcsStatus";
import { SHORT_HASH } from "../changes/changes";
/** Most branches kept per kind from one answer. */
export const MAX_BRANCHES = 10_000;

View file

@ -3,10 +3,10 @@
* `git.status`, grouped as Staged, Changes and Untracked, plus staging,
* unstaging and committing.
*
* - **Source:** `git.status` (a pending outcome, so through `runWaiting`)
* on start, when a project opens, on `gitChanged` and on `vcs.refresh`.
* Calls are serialised; a refresh asked for while one runs runs once
* more afterwards. A project close clears everything.
* - **Source:** the shared status store (`stores/vcsStatus.ts`, the only
* caller of `git.status`), which re-reads on start, when a project
* opens, on `gitChanged` and on `vcs.refresh`. A project close clears
* it, and with it the rows and the selection.
* - **Groups:** a file is Staged when its index side changed, in Changes
* when its work tree side changed or it is conflicted, and Untracked when
* git does not track it. A partly staged file is in both Staged and
@ -16,61 +16,36 @@
* - **Commit:** `flushDirty()` first, so the files on disk hold what the
* editor shows; a save that failed cancels the commit. Then `git.commit
* {message, amend}`; success toasts the short hash and clears the box.
* - **Amend:** checking Amend with an empty box fills it with the last
* commit's message (`git.lastMessage`); clearing Amend again empties a
* box that still holds exactly that text.
* - **Untrusted input:** the status comes from the engine and, through it,
* from git; malformed entries are dropped and the count capped
* ({@link MAX_FILES}).
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { onEngineEvent, runWaiting, type EngineEventPayload, type JsonValue } from "../../../ipc";
import { computed, ref, watch } from "vue";
import { runWaiting, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave";
import { useNotificationsStore } from "../../../stores/notifications";
import { useVcsStatusStore, type ChangedFile, type GitFileState } from "../../../stores/vcsStatus";
/** Most files kept from one status. */
export const MAX_FILES = 50_000;
export {
FILE_STATES,
MAX_FILES,
toFile,
toRepo,
toStatus,
type ChangedFile,
type RepoSummary,
type StatusSnapshot,
} from "../../../stores/vcsStatus";
/** Length of the short commit hash shown to people. */
export const SHORT_HASH = 7;
/** States of one side of a file, as `git.status` names them. */
export const FILE_STATES = [
"unmodified",
"modified",
"added",
"deleted",
"renamed",
"copied",
"untracked",
"ignored",
"conflicted",
] as const;
/** State of one side (index or work tree) of a file. */
export type FileState = (typeof FILE_STATES)[number];
/** A changed file as `git.status` reports it. */
export interface ChangedFile {
/** Project-relative path with `/`. */
path: string;
/** The old path of a rename or copy. */
origPath?: string;
/** State in the index against HEAD. */
index: FileState;
/** State in the work tree against the index. */
worktree: FileState;
}
/** The repository summary of `git.status`. */
export interface RepoSummary {
/** Work tree root, absolute with `/`. */
root: string;
/** Current branch; absent when detached or unborn without a name. */
branch?: string;
/** Whether HEAD is detached. */
detached: boolean;
/** Full hash of HEAD; absent before the first commit. */
head?: string;
}
export type FileState = GitFileState;
/** The groups of the window, in display order. */
export const GROUPS = ["staged", "changes", "untracked"] as const;
@ -93,103 +68,6 @@ export interface ChangeRow {
/** What the window shows above the groups. */
export type ChangesPhase = "idle" | "loading" | "unavailable" | "noRepo" | "ready";
/**
* Reads a state; null if unknown.
*
* @param raw - untrusted.
*/
function toState(raw: unknown): FileState | null {
return FILE_STATES.find((s) => s === raw) ?? null;
}
/**
* Reads one file of `git.status`; null if malformed.
*
* @param raw - an untrusted entry of `files`.
*/
export function toFile(raw: unknown): ChangedFile | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const f = raw as Record<string, unknown>;
const index = toState(f.index);
const worktree = toState(f.worktree);
if (typeof f.path !== "string" || f.path === "" || !index || !worktree) {
return null;
}
const file: ChangedFile = { path: f.path, index, worktree };
if (typeof f.origPath === "string" && f.origPath !== "") {
file.origPath = f.origPath;
}
return file;
}
/**
* Reads the repository summary; null when absent or malformed.
*
* @param raw - the untrusted `repo` field.
*/
export function toRepo(raw: unknown): RepoSummary | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const r = raw as Record<string, unknown>;
if (typeof r.root !== "string") {
return null;
}
const repo: RepoSummary = { root: r.root, detached: r.detached === true };
if (typeof r.branch === "string" && r.branch !== "") {
repo.branch = r.branch;
}
if (typeof r.head === "string" && r.head !== "") {
repo.head = r.head;
}
return repo;
}
/** A status as the store keeps it. */
export interface StatusSnapshot {
/** Whether a usable git was found. */
available: boolean;
/** Why git is unavailable or the repository could not be opened. */
error: string | null;
/** The repository, or null outside one. */
repo: RepoSummary | null;
/** Changed files sorted by path. */
files: ChangedFile[];
}
/**
* Reads the result of `git.status`; null if it is not an object.
*
* @param raw - untrusted.
*/
export function toStatus(raw: unknown): StatusSnapshot | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const s = raw as Record<string, unknown>;
const files: ChangedFile[] = [];
if (Array.isArray(s.files)) {
for (const entry of s.files as unknown[]) {
if (files.length >= MAX_FILES) {
break;
}
const file = toFile(entry);
if (file) {
files.push(file);
}
}
}
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
return {
available: s.available === true,
error: typeof s.error === "string" && s.error !== "" ? s.error : null,
repo: toRepo(s.repo),
files,
};
}
/**
* Whether a side's state means "changed".
*
@ -249,17 +127,18 @@ export function unstagePaths(rows: ChangeRow[]): string[] {
/** The Changes store. */
export const useChangesStore = defineStore("changes", () => {
const notifications = useNotificationsStore();
const vcs = useVcsStatusStore();
/** Whether the tool window is shown in the bottom panel. */
const visible = ref(false);
/** Whether the panel is expanded while Changes is shown. */
const expanded = ref(true);
/** The last status read; null before the first one or without a project. */
const status = shallowRef<StatusSnapshot | null>(null);
/** Whether a `git.status` call runs. */
const loading = ref(false);
const status = computed(() => vcs.snapshot);
/** Whether a `git.status` round runs. */
const loading = computed(() => vcs.loading);
/** The error of the last `git.status` call itself (not git's state). */
const loadError = ref<string | null>(null);
const loadError = computed(() => vcs.loadError);
/** Whether a stage, unstage or commit runs. */
const busy = ref(false);
/** The commit message being written. */
@ -303,61 +182,60 @@ export const useChangesStore = defineStore("changes", () => {
(amend.value || groups.value.staged.length > 0),
);
/** Counts refresh requests, so a round knows whether another came in. */
let requests = 0;
/** Reads `git.status` once. */
async function loadOnce(): Promise<void> {
const result = await runWaiting("git.status");
if (!result.ok) {
loadError.value = result.error.message;
if (result.error.code === "disabled") {
status.value = null;
}
return;
}
const next = toStatus(result.value);
loadError.value = next ? null : "unexpected result of git.status";
status.value = next;
if (selectedKey.value !== null && !rows.value.some((row) => row.key === selectedKey.value)) {
watch(rows, (list) => {
if (selectedKey.value !== null && !list.some((row) => row.key === selectedKey.value)) {
selectedKey.value = null;
}
}
/** The `git.status` round running now, shared by callers. */
let running: Promise<void> | null = null;
});
/**
* Re-reads the status from git: `vcs.refresh`, `gitChanged`, project
* open. Serialised: a call while one runs makes it read once more
* afterwards and shares its promise.
* Re-reads the status from git (`vcs.refresh`, after staging): the
* shared store's serialised refresh.
*/
function refresh(): Promise<void> {
requests += 1;
if (running) {
return running;
}
loading.value = true;
running = (async () => {
let seen: number;
do {
seen = requests;
await loadOnce();
} while (seen !== requests);
})().finally(() => {
running = null;
loading.value = false;
});
return running;
return vcs.refresh();
}
/** Drops the status and the selection (project closed). */
function clear(): void {
status.value = null;
loadError.value = null;
selectedKey.value = null;
/** The message `git.lastMessage` put into the box, while it is unchanged there. */
let prefilled: string | null = null;
/**
* Fills an empty box with the last commit's message when Amend is
* checked; empties a box still holding that text when Amend is cleared.
* A failed `git.lastMessage` leaves the box empty.
*
* @param on - the new Amend state.
*/
async function onAmend(on: boolean): Promise<void> {
if (!on) {
if (prefilled !== null && message.value === prefilled) {
message.value = "";
}
prefilled = null;
return;
}
if (message.value.trim() !== "") {
return;
}
const result = await runWaiting("git.lastMessage");
if (!result.ok || !amend.value || message.value.trim() !== "") {
return;
}
const value = result.value;
const text =
typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.message === "string"
? value.message
: null;
if (text !== null) {
message.value = text;
prefilled = text;
}
}
watch(amend, (on) => {
void onAmend(on);
});
/**
* Runs a mutating git command, toasting its failure.
*
@ -464,6 +342,7 @@ export const useChangesStore = defineStore("changes", () => {
messageKey: "notification.vcs.committed",
params: { hash: hash.slice(0, SHORT_HASH), summary },
});
prefilled = null;
message.value = "";
amend.value = false;
await refresh();
@ -473,35 +352,24 @@ export const useChangesStore = defineStore("changes", () => {
}
}
/**
* Applies one engine event.
*
* @param event - the event.
*/
function onEvent(event: EngineEventPayload): void {
if (event.kind === "gitChanged" || event.kind === "projectOpened") {
void refresh();
} else if (event.kind === "projectClosed") {
clear();
}
}
/** Whether this store holds the shared status store. */
let holding = false;
/** Ends the event subscription; set while started. */
let unsubscribe: (() => void) | null = null;
/** Subscribes to engine events and reads the status once. */
/** Starts the shared status store (which reads the status once). */
function start(): void {
if (unsubscribe) {
if (holding) {
return;
}
unsubscribe = onEngineEvent(onEvent);
void refresh();
holding = true;
vcs.start();
}
/** Ends the subscription. */
/** Releases the shared status store. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
if (holding) {
holding = false;
vcs.stop();
}
}
/** Shows the tool window: `vcs.openChanges`. */
@ -569,7 +437,6 @@ export const useChangesStore = defineStore("changes", () => {
toggle,
toggleGroup,
commit,
onEvent,
start,
stop,
open,

View file

@ -1,44 +1,40 @@
/**
* Git status of the project's files for colouring file names in the
* project tree and the editor tabs (M4.4).
* The project's Git status, shared by every view that shows it (M4.4,
* shared since C6 F1): the Changes window, the file name colours in the
* project tree and the editor tabs, and the branch in the status bar.
*
* - **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.
* - **Source:** this store is the only caller of `git.status` in the UI
* (a pending outcome, so through `runWaiting`): on start, when a project
* opens, on every `gitChanged` and on {@link refresh} (`vcs.refresh`,
* after staging); never polled. One query runs at a time; requests made
* while it runs share one more query after it, so a `gitChanged` costs
* one `git.status` however many views follow it. Later features (log,
* merge, stash, remotes) read {@link snapshot} and call {@link refresh};
* they never query `git.status` themselves.
* - **Snapshot:** {@link toStatus} reads the untrusted result: unknown
* states and malformed entries are dropped, at most {@link MAX_FILES}
* files, sorted by path. A failed query keeps the last snapshot and sets
* {@link loadError}; `disabled` (no project) drops 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).
* - **Lifetime:** {@link start} / {@link stop} are counted, so `App.vue`
* and the main layout can both hold the store; the subscription ends
* with the last holder.
*/
import { defineStore } from "pinia";
import { shallowRef } from "vue";
import { computed, ref, 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";
/** Most files kept from one status. */
export const MAX_FILES = 50_000;
/** The status token names (`--lt-vcs-<name>`). */
export type VcsColour = "added" | "modified" | "deleted" | "untracked" | "ignored" | "conflicted";
/** Every state `git.status` may report. */
const STATES = new Set<string>([
/** States of one side of a file, as `git.status` names them. */
export const FILE_STATES = [
"unmodified",
"modified",
"added",
@ -48,11 +44,157 @@ const STATES = new Set<string>([
"untracked",
"ignored",
"conflicted",
]);
] as const;
/** Whether a value is a file state. */
/** A file state as `git.status` names it. */
export type GitFileState = (typeof FILE_STATES)[number];
/** The status token names (`--lt-vcs-<name>`). */
export type VcsColour = "added" | "modified" | "deleted" | "untracked" | "ignored" | "conflicted";
/** A changed file as `git.status` reports it. */
export interface ChangedFile {
/** Project-relative path with `/`. */
path: string;
/** The old path of a rename or copy. */
origPath?: string;
/** State in the index against HEAD. */
index: GitFileState;
/** State in the work tree against the index. */
worktree: GitFileState;
}
/** The repository summary of `git.status` (and of `gitChanged`). */
export interface RepoSummary {
/** Work tree root, absolute with `/`. */
root: string;
/** Current branch; absent when detached or unborn without a name. */
branch?: string;
/** Whether HEAD is detached. */
detached: boolean;
/** Full hash of HEAD; absent before the first commit. */
head?: string;
/** The current branch's upstream, e.g. `origin/main`. */
upstream?: string;
/** Commits ahead of the upstream. */
ahead?: number;
/** Commits behind the upstream. */
behind?: number;
}
/** A status as the store keeps it. */
export interface StatusSnapshot {
/** Whether a usable git was found. */
available: boolean;
/** Why git is unavailable or the repository could not be opened. */
error: string | null;
/** The repository, or null outside one. */
repo: RepoSummary | null;
/** Changed files sorted by path. */
files: ChangedFile[];
}
/**
* Whether a value is a file state.
*
* @param value - untrusted.
*/
function isState(value: unknown): value is GitFileState {
return typeof value === "string" && STATES.has(value);
return FILE_STATES.some((s) => s === value);
}
/**
* Reads one file of `git.status`; null if malformed.
*
* @param raw - an untrusted entry of `files`.
*/
export function toFile(raw: unknown): ChangedFile | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const f = raw as Record<string, unknown>;
if (typeof f.path !== "string" || f.path === "" || !isState(f.index) || !isState(f.worktree)) {
return null;
}
const file: ChangedFile = { path: f.path, index: f.index, worktree: f.worktree };
if (typeof f.origPath === "string" && f.origPath !== "") {
file.origPath = f.origPath;
}
return file;
}
/**
* Reads a count; undefined unless it is a non-negative integer.
*
* @param raw - untrusted.
*/
function toCount(raw: unknown): number | undefined {
return typeof raw === "number" && Number.isSafeInteger(raw) && raw >= 0 ? raw : undefined;
}
/**
* Reads the repository summary; null when absent or malformed.
*
* @param raw - the untrusted `repo` field.
*/
export function toRepo(raw: unknown): RepoSummary | null {
if (typeof raw !== "object" || raw === null) {
return null;
}
const r = raw as Record<string, unknown>;
if (typeof r.root !== "string") {
return null;
}
const repo: RepoSummary = { root: r.root, detached: r.detached === true };
if (typeof r.branch === "string" && r.branch !== "") {
repo.branch = r.branch;
}
if (typeof r.head === "string" && r.head !== "") {
repo.head = r.head;
}
if (typeof r.upstream === "string" && r.upstream !== "") {
repo.upstream = r.upstream;
}
const ahead = toCount(r.ahead);
const behind = toCount(r.behind);
if (ahead !== undefined) {
repo.ahead = ahead;
}
if (behind !== undefined) {
repo.behind = behind;
}
return repo;
}
/**
* Reads the result of `git.status`; null if it is not an object.
*
* @param raw - untrusted.
*/
export function toStatus(raw: unknown): StatusSnapshot | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const s = raw as Record<string, unknown>;
const files: ChangedFile[] = [];
if (Array.isArray(s.files)) {
for (const entry of s.files as unknown[]) {
if (files.length >= MAX_FILES) {
break;
}
const file = toFile(entry);
if (file) {
files.push(file);
}
}
}
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
return {
available: s.available === true,
error: typeof s.error === "string" && s.error !== "" ? s.error : null,
repo: toRepo(s.repo),
files,
};
}
/**
@ -86,6 +228,23 @@ export function statusColour(index: GitFileState, worktree: GitFileState): VcsCo
return null;
}
/**
* The colours of a snapshot's files.
*
* @param snapshot - the snapshot, or null.
* @returns colour by project-relative path, changed files only.
*/
function coloursOf(snapshot: StatusSnapshot | null): Map<string, VcsColour> {
const colours = new Map<string, VcsColour>();
for (const file of snapshot?.files ?? []) {
const colour = statusColour(file.index, file.worktree);
if (colour !== null) {
colours.set(file.path, colour);
}
}
return colours;
}
/**
* Reads the colours of a `git.status` result.
*
@ -94,33 +253,25 @@ export function statusColour(index: GitFileState, worktree: GitFileState): VcsCo
* open; null when the result is not an object.
*/
export function readStatus(value: unknown): { colours: Map<string, VcsColour>; repo: boolean } | null {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
const snapshot = toStatus(value);
if (snapshot === null) {
return null;
}
const record = value as Record<string, unknown>;
const colours = new Map<string, VcsColour>();
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<string, unknown>;
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 };
return { colours: coloursOf(snapshot), repo: snapshot.available && snapshot.repo !== null };
}
/** A failed `git.status` call, as the transport reports it. */
export interface StatusFailure {
/** The engine error code (`disabled` without a project). */
code: string;
/** Its message. */
message: string;
}
/** How the store reaches the engine; replaced in tests. */
export interface VcsStatusTransport {
/** Runs `git.status`. */
status(): Promise<{ ok: true; value: unknown } | { ok: false }>;
status(): Promise<{ ok: true; value: unknown } | { ok: false; error?: StatusFailure }>;
}
/** The transport through the engine IPC. */
@ -129,15 +280,22 @@ const engineTransport: VcsStatusTransport = {
};
export const useVcsStatusStore = defineStore("vcsStatus", () => {
/** The last status read; null before the first one or without a project. */
const snapshot = shallowRef<StatusSnapshot | null>(null);
/** Colour by project-relative path, for changed files only. */
const colours = shallowRef<ReadonlyMap<string, VcsColour>>(new Map());
/** Whether a `git.status` round runs. */
const loading = ref(false);
/** The error of the last `git.status` call itself (not git's state). */
const loadError = ref<string | null>(null);
/** Whether the project is inside a repository with a usable git. */
const repo = shallowRef(false);
const repo = computed(() => snapshot.value?.available === true && snapshot.value.repo !== null);
let transport: VcsStatusTransport = engineTransport;
let running: Promise<void> | null = null;
const queued = { again: false };
let requests = 0;
let generation = 0;
let holders = 0;
let unsubscribe: (() => void) | null = null;
/**
@ -149,51 +307,69 @@ export const useVcsStatusStore = defineStore("vcsStatus", () => {
transport = next;
}
/**
* Takes a snapshot.
*
* @param next - the snapshot, or null to forget it.
*/
function apply(next: StatusSnapshot | null): void {
snapshot.value = next;
colours.value = coloursOf(next);
}
/** Runs `git.status` once and applies it unless the project changed. */
async function query(): Promise<void> {
const asked = generation;
const result = await transport.status();
if (!result.ok || asked !== generation) {
if (asked !== generation) {
return;
}
const read = readStatus(result.value);
if (read !== null) {
colours.value = read.colours;
repo.value = read.repo;
if (!result.ok) {
loadError.value = result.error?.message ?? "git.status failed";
if (result.error?.code === "disabled") {
apply(null);
}
return;
}
}
/** Whether a refresh was asked for while the last query ran. */
function wantsAgain(): boolean {
return queued.again;
const next = toStatus(result.value);
if (next === null) {
loadError.value = "unexpected result of git.status";
return;
}
loadError.value = null;
apply(next);
}
/**
* Refreshes the status: starts a query, or, while one runs, makes sure
* one more runs after it.
* Refreshes the status: starts a round, or, while one runs, makes sure
* it queries once more and shares its promise.
*
* @returns resolves when the status is current.
*/
function refresh(): Promise<void> {
requests += 1;
if (running !== null) {
queued.again = true;
return running;
}
loading.value = true;
running = (async () => {
let seen: number;
do {
queued.again = false;
seen = requests;
await query();
} while (wantsAgain());
} while (seen !== requests);
})().finally(() => {
running = null;
})();
loading.value = false;
});
return running;
}
/** Forgets everything (project closed). */
/** Forgets everything (project closed or opened). */
function clear(): void {
generation += 1;
colours.value = new Map();
repo.value = false;
loadError.value = null;
apply(null);
}
/**
@ -225,8 +401,12 @@ export const useVcsStatusStore = defineStore("vcsStatus", () => {
}
}
/** Starts following the engine and queries once; repeated calls do nothing. */
/**
* Starts following the engine and queries once; a further holder only
* counts.
*/
function start(): void {
holders += 1;
if (unsubscribe !== null) {
return;
}
@ -234,11 +414,27 @@ export const useVcsStatusStore = defineStore("vcsStatus", () => {
void refresh();
}
/** Stops following the engine. */
/** Releases one holder; the last one stops following the engine. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
holders = Math.max(0, holders - 1);
if (holders === 0) {
unsubscribe?.();
unsubscribe = null;
}
}
return { colours, repo, configure, refresh, clear, colourOf, handle, start, stop };
return {
snapshot,
colours,
repo,
loading,
loadError,
configure,
refresh,
clear,
colourOf,
handle,
start,
stop,
};
});

View file

@ -29,6 +29,7 @@ import {
type ChangedFile,
} from "../../src/components/vcs/changes/changes";
import { useNotificationsStore } from "../../src/stores/notifications";
import { useVcsStatusStore } from "../../src/stores/vcsStatus";
/** A recorded engine call. */
interface Call {
@ -142,6 +143,8 @@ beforeEach(() => {
switch (args.command) {
case "git.status":
return Promise.resolve(gitStatus);
case "git.lastMessage":
return Promise.resolve({ message: "Last subject\n\nLast body" });
case "git.commit":
return Promise.resolve({ commit: "fedcba9876543210", summary: String(args.params.message).split("\n")[0] });
case "file.saveAll":
@ -306,6 +309,35 @@ describe("the Changes store", () => {
expect(changes.amend).toBe(false);
});
it("shares one git.status per gitChanged with the status colours", async () => {
const vcs = useVcsStatusStore(pinia);
vcs.start();
useChangesStore(pinia).start();
await flushPromises();
expect(callsOf("git.status")).toHaveLength(1);
await emit({ kind: "gitChanged", available: true, repo: null, filesChanged: true });
expect(callsOf("git.status")).toHaveLength(2);
expect(vcs.colourOf("tmp.txt")).toBe("untracked");
vcs.stop();
});
it("prefills an empty box with the last message on Amend and empties it again", async () => {
const changes = useChangesStore(pinia);
await changes.refresh();
changes.amend = true;
await flushPromises();
expect(callsOf("git.lastMessage")).toHaveLength(1);
expect(changes.message).toBe("Last subject\n\nLast body");
changes.amend = false;
await flushPromises();
expect(changes.message).toBe("");
changes.message = "mine";
changes.amend = true;
await flushPromises();
expect(changes.message).toBe("mine");
expect(callsOf("git.lastMessage")).toHaveLength(1);
});
it("keeps the message when git refuses the commit", async () => {
const changes = useChangesStore(pinia);
await changes.refresh();