M4.9: Git stash (stash, list, apply, pop, drop) with clear refusals

- crates/vcs: stash.rs (append) with Repo::stash, stash_list, stash_apply
  and stash_drop; refusals decided structurally (no commit, nothing to
  stash, unmerged files, conflicts after apply, missing or changed entry)
  plus hints for overwritten and untracked files. Works around git leaving
  untracked files behind under --literal-pathspecs. Repo::lock is
  pub(crate), as for M4.8.
- engine: git.stash, git.stashList, git.stashApply {index, pop, hash?},
  git.stashDrop through the M4.6 hook; gitChanged after changes.
- ui: stash dialog (vcs.stash, vcs.showStashes; Git menu, no shortcuts),
  two buttons in the Changes window, dirty buffers saved first, drop asks.
- Tests: vcs integration and property tests, engine test, 13 Vitest tests.
- Docs: architecture section, G8, tooling checklist, roadmap, Git row
  evidence (score left to the PM).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-29 18:49:54 +01:00
parent 65907d925a
commit e09ef8b8c0
23 changed files with 2681 additions and 13 deletions

View file

@ -0,0 +1,221 @@
//! Stash commands (M4.9): `git.stash`, `git.stashList`, `git.stashApply`
//! and `git.stashDrop`, run like every `git.*` command (a pending outcome
//! off the lock, git and the repository cached by [`super::git`]). The
//! three that change the repository emit `gitChanged`.
use lutra_vcs::StashEntry;
use serde::Deserialize;
use serde_json::{Value, json};
use super::git::start_with;
use super::params::parse;
use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State};
/// Largest index the commands take; the list holds at most 1,000 entries.
const MAX_INDEX: usize = 100_000;
/// Registers the stash commands.
///
/// # Errors
/// [`EngineError::Internal`] if an id is taken.
pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(Stash))?;
registry.register(Box::new(StashList))?;
registry.register(Box::new(StashApply))?;
registry.register(Box::new(StashDrop))?;
Ok(())
}
/// One entry as the commands return it.
fn entry_json(entry: &StashEntry) -> Value {
json!({
"index": entry.index,
"hash": entry.hash,
"branch": entry.branch,
"message": entry.message,
"wip": entry.wip,
"date": entry.date,
})
}
/// Refuses an index past [`MAX_INDEX`].
fn check_index(command: &str, index: usize) -> Result<(), EngineError> {
if index > MAX_INDEX {
return Err(EngineError::invalid_params(
command,
format!("index must be 0 to {MAX_INDEX}"),
));
}
Ok(())
}
/// Params of `git.stash`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct StashParams {
/// The entry's message; blank means git's "WIP on" message.
#[serde(default)]
message: Option<String>,
/// Stash untracked files too.
#[serde(default)]
include_untracked: bool,
}
/// `git.stash`.
struct Stash;
impl Command for Stash {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.stash",
label: "Git: Stash Changes",
menu_path: None,
default_shortcut: None,
params: "{ message?: string (blank: git's \"WIP on <branch>\" message; line breaks become spaces), includeUntracked?: boolean (false) }; stashes every local change of the repository's work tree and resets it to HEAD; returns { entry: { index: 0, hash, branch, message, wip, date } }; refused with a clear message without a commit, with unmerged files, or with nothing to stash. Dirty buffers are not saved first",
}
}
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 p: StashParams = parse(command, params)?;
start_with(
state,
command,
true,
Box::new(move |repo| {
let entry = repo.stash(p.message.as_deref(), p.include_untracked)?;
Ok(json!({"entry": entry_json(&entry)}))
}),
)
}
}
/// `git.stashList`.
struct StashList;
impl Command for StashList {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.stashList",
label: "Git: List Stashes",
menu_path: None,
default_shortcut: None,
params: "none; returns { stashes: [{ index, hash, branch: string | null, message, wip, date (ISO 8601) }] } newest first (index 0 is stash@{0}), at most 1,000",
}
}
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_with(
state,
command,
false,
Box::new(move |repo| {
let stashes: Vec<Value> = repo.stash_list()?.iter().map(entry_json).collect();
Ok(json!({"stashes": stashes}))
}),
)
}
}
/// Params of `git.stashApply`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ApplyParams {
/// The entry.
index: usize,
/// Drop the entry after applying it cleanly.
#[serde(default)]
pop: bool,
/// The entry's hash as listed; refuses when the stash changed since.
#[serde(default)]
hash: Option<String>,
}
/// `git.stashApply`.
struct StashApply;
impl Command for StashApply {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.stashApply",
label: "Git: Apply Stash",
menu_path: None,
default_shortcut: None,
params: "{ index: number (stash@{index}), pop?: boolean (false: keep the entry), hash?: the entry's hash from git.stashList, refused when the entry at index differs }; returns {}; refused with a clear message for a missing entry, unmerged files, local changes that would be overwritten, untracked files in the way, or conflicts (the files then hold conflict markers and the entry is kept)",
}
}
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 p: ApplyParams = parse(command, params)?;
check_index(command, p.index)?;
start_with(
state,
command,
true,
Box::new(move |repo| {
repo.stash_apply(p.index, p.pop, p.hash.as_deref())?;
Ok(json!({}))
}),
)
}
}
/// Params of `git.stashDrop`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct DropParams {
/// The entry.
index: usize,
/// The entry's hash as listed.
#[serde(default)]
hash: Option<String>,
}
/// `git.stashDrop`.
struct StashDrop;
impl Command for StashDrop {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.stashDrop",
label: "Git: Drop Stash",
menu_path: None,
default_shortcut: None,
params: "{ index: number (stash@{index}), hash?: the entry's hash from git.stashList, refused when the entry at index differs }; deletes the entry; returns {}",
}
}
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 p: DropParams = parse(command, params)?;
check_index(command, p.index)?;
start_with(
state,
command,
true,
Box::new(move |repo| {
repo.stash_drop(p.index, p.hash.as_deref())?;
Ok(json!({}))
}),
)
}
}

View file

@ -8,6 +8,7 @@ pub mod git_lines;
pub mod git_log;
pub mod git_merge;
pub mod git_remote;
pub mod git_stash;
pub mod goto;
mod lsp_assist;
mod lsp_diagnostics;
@ -74,5 +75,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
git_log::register(registry)?;
git_remote::register(registry)?;
git_merge::register(registry)?;
git_stash::register(registry)?;
Ok(())
}

View file

@ -505,6 +505,10 @@ mod tests {
"git.showAt",
"git.showCommit",
"git.stage",
"git.stash",
"git.stashApply",
"git.stashDrop",
"git.stashList",
"git.status",
"git.unstage",
"goto.class",

View file

@ -0,0 +1,189 @@
//! The stash commands (M4.9) through the engine: `git.stash`,
//! `git.stashList`, `git.stashApply` with and without pop, `git.stashDrop`,
//! refusals as `failed` with a clear message, bad params, and `gitChanged`
//! after the changes only. 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, Event, 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]) -> String {
let out = Command::new("git")
.args(args)
.current_dir(dir)
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
/// An engine with `root` open, recording events.
struct Host {
/// The engine.
engine: Mutex<Engine>,
/// Events published so far.
events: Mutex<Vec<Event>>,
}
impl Host {
/// Opens `root` as the project.
fn open(root: &Path) -> Self {
let host = Self {
engine: Mutex::new(Engine::new().unwrap()),
events: Mutex::new(Vec::new()),
};
host.run("project.open", json!({"path": root})).unwrap();
host
}
/// Runs a command the way hosts do.
fn run(&self, command: &str, params: Value) -> Result<Value, EngineError> {
run_waiting(
|| self.engine.lock().unwrap(),
command,
params,
|events| self.events.lock().unwrap().extend_from_slice(events),
)
.map(|o| o.value)
}
/// Takes the number of `gitChanged` events so far and forgets them.
fn git_changed(&self) -> usize {
let mut events = self.events.lock().unwrap();
let count = events
.iter()
.filter(|e| matches!(e, Event::GitChanged(_)))
.count();
events.clear();
count
}
}
#[test]
fn stash_list_apply_and_drop() {
if !have_git() {
return;
}
let dir = tempfile::tempdir().unwrap();
let d = dir.path();
git(d, &["init", "-q", "-b", "main"]);
for (key, value) in [
("user.name", "Lutra Test"),
("user.email", "test@lutra.invalid"),
("commit.gpgsign", "false"),
("core.autocrlf", "false"),
("core.hooksPath", ".git/hooks"),
] {
git(d, &["config", key, value]);
}
std::fs::write(d.join("a.php"), "<?php // 1\n").unwrap();
git(d, &["add", "-A"]);
git(d, &["commit", "-q", "-m", "First"]);
let host = Host::open(d);
assert_eq!(
host.run("git.stashList", Value::Null).unwrap(),
json!({"stashes": []})
);
let err = host.run("git.stash", json!({})).unwrap_err();
assert_eq!(err.code(), "failed");
assert!(err.to_string().contains("no local changes"), "{err}");
host.git_changed();
std::fs::write(d.join("a.php"), "<?php // 2\n").unwrap();
std::fs::write(d.join("new.php"), "<?php\n").unwrap();
let stashed = host
.run(
"git.stash",
json!({"message": "work", "includeUntracked": true}),
)
.unwrap();
let entry = &stashed["entry"];
assert_eq!(entry["index"], 0);
assert_eq!(entry["message"], "work");
assert_eq!(entry["branch"], "main");
assert_eq!(entry["wip"], false);
assert!(!d.join("new.php").exists());
assert_eq!(host.git_changed(), 1);
let list = host.run("git.stashList", json!({})).unwrap();
assert_eq!(list["stashes"][0]["hash"], entry["hash"]);
assert_eq!(host.git_changed(), 0);
let err = host
.run("git.stashApply", json!({"index": 0, "hash": "0000000"}))
.unwrap_err();
assert_eq!(err.code(), "failed");
assert!(err.to_string().contains("Refresh the list"), "{err}");
host.run(
"git.stashApply",
json!({"index": 0, "pop": true, "hash": entry["hash"]}),
)
.unwrap();
assert_eq!(
std::fs::read_to_string(d.join("a.php")).unwrap(),
"<?php // 2\n"
);
assert!(d.join("new.php").exists());
assert_eq!(host.git_changed(), 1);
assert_eq!(
host.run("git.stashList", Value::Null).unwrap()["stashes"],
json!([])
);
host.run("git.stash", Value::Null).unwrap();
host.run("git.stashApply", json!({"index": 0})).unwrap();
assert_eq!(
host.run("git.stashList", Value::Null).unwrap()["stashes"]
.as_array()
.unwrap()
.len(),
1
);
host.run("git.stashDrop", json!({"index": 0})).unwrap();
let err = host.run("git.stashDrop", json!({"index": 0})).unwrap_err();
assert_eq!(err.code(), "failed");
assert!(err.to_string().contains("The stash is empty."), "{err}");
for (command, params) in [
("git.stash", json!({"bogus": 1})),
("git.stash", json!({"includeUntracked": "yes"})),
("git.stashList", json!([1])),
("git.stashApply", json!({})),
("git.stashApply", json!({"index": -1})),
("git.stashApply", json!({"index": 100_001})),
("git.stashApply", json!({"index": 0, "hash": "stash@{0}"})),
("git.stashDrop", json!({"index": "0"})),
] {
let err = host.run(command, params.clone()).unwrap_err();
assert_eq!(err.code(), "invalid_params", "{command} {params}");
}
}

View file

@ -27,6 +27,7 @@ pub mod porcelain;
mod remote;
mod repo;
pub mod runner;
pub mod stash;
mod watch;
pub use error::VcsError;
@ -41,6 +42,7 @@ pub use repo::{
decode,
};
pub use runner::{Cancel, ProgressSink, redact_urls};
pub use stash::StashEntry;
pub use watch::{RepoWatch, fingerprint};
mod merge;
pub use merge::{

588
crates/vcs/src/stash.rs Normal file
View file

@ -0,0 +1,588 @@
//! Stash (M4.9): set local changes aside, list the stash, apply or pop an
//! entry, drop one.
//!
//! The stash belongs to the whole repository, not to the project folder:
//! `git stash push` takes every change of the work tree, as git does.
//!
//! Refusals carry a sentence that says what to do, followed by git's own
//! message where git gave one. The checks that decide which sentence fit
//! are structural (does HEAD exist, did `refs/stash` move, are there
//! unmerged index entries), so they work whatever language git speaks;
//! only the hints for overwritten files and existing untracked files
//! read git's English text, and without a match git's message stands
//! alone.
use crate::Repo;
use crate::VcsError;
use crate::repo::SMALL_CAP;
use crate::runner::{Call, HOOK_TIMEOUT};
/// Most entries [`Repo::stash_list`] returns.
pub const STASH_LIST_CAP: usize = 1000;
/// Most characters of a stash message; longer ones are cut.
pub const STASH_MESSAGE_CAP: usize = 1000;
/// Most bytes of paths one `git clean` call gets as arguments.
const CLEAN_CHUNK: usize = 16 * 1024;
/// Separator before each record of the list format.
const RECORD: u8 = 0x1e;
/// The list format: hash, reflog subject, date (strict ISO 8601); fields
/// NUL-separated, each record starting with [`RECORD`].
const LIST_FORMAT: &str = "--format=%x1e%H%x00%gs%x00%cI";
/// One stash entry.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StashEntry {
/// Its position: 0 is the newest (`stash@{0}`).
pub index: usize,
/// The stash commit's full hash; it identifies the entry when indexes
/// shift.
pub hash: String,
/// The branch it was made on; `None` when the subject has another
/// form, `(no branch)` for a detached HEAD.
pub branch: Option<String>,
/// The message given, or git's `<short hash> <subject>` of the commit
/// it was made on when none was given.
pub message: String,
/// Whether no message was given (git's "WIP on" entry).
pub wip: bool,
/// When it was made, strict ISO 8601.
pub date: String,
}
impl Repo {
/// The stash, newest first, at most [`STASH_LIST_CAP`] entries.
///
/// # Errors
/// The runner's errors or git's refusal. No stash is an empty list.
pub fn stash_list(&self) -> Result<Vec<StashEntry>, VcsError> {
if self.stash_top()?.is_none() {
return Ok(Vec::new());
}
let count = format!("--max-count={STASH_LIST_CAP}");
let output = self
.run(Call::read(
self.root(),
&["stash", "list", LIST_FORMAT, &count],
SMALL_CAP,
))?
.checked()?;
Ok(parse_stash_list(&output.stdout))
}
/// Stashes the local changes of the whole work tree (staged and not)
/// and resets it to HEAD.
///
/// # Parameters
/// - `message`: the entry's message; blank means git's "WIP on"
/// message. Line breaks become spaces, other control characters are
/// dropped, and it is cut at [`STASH_MESSAGE_CAP`] characters.
/// - `include_untracked`: stash untracked files too (ignored files
/// never).
///
/// # Returns
/// The new entry (`stash@{0}`).
///
/// # Errors
/// [`VcsError::Git`] with a clear sentence when the repository has no
/// commit yet, when files are unmerged, or when there is nothing to
/// stash; git's refusal otherwise.
pub fn stash(
&self,
message: Option<&str>,
include_untracked: bool,
) -> Result<StashEntry, VcsError> {
let message = message.map(clean_message).filter(|m| !m.is_empty());
let _guard = self.lock();
if !self.has_commit()? {
return Err(VcsError::Git(
"Nothing can be stashed before the first commit. Commit once, then stash."
.to_string(),
));
}
self.refuse_unmerged("Stashing")?;
let before = self.stash_top()?;
let mut args = vec!["stash", "push", "--quiet"];
if include_untracked {
args.push("--include-untracked");
}
let message_arg = message.map(|m| format!("--message={m}"));
args.extend(message_arg.as_deref());
self.run(Call::write(self.root(), &args).timeout(HOOK_TIMEOUT))?
.checked()?;
let after = self.stash_top()?;
if after.is_none() || after == before {
let hint = if include_untracked {
"There are no local changes to stash."
} else {
"There are no local changes to stash. Untracked files are stashed only when untracked files are included."
};
return Err(VcsError::Git(hint.to_string()));
}
if include_untracked {
self.remove_stashed_untracked()?;
}
self.stash_list()?
.into_iter()
.next()
.ok_or_else(|| VcsError::BadOutput("stash list is empty after stashing".to_string()))
}
/// Applies a stash entry to the work tree; with `pop` the entry is
/// dropped when it applied cleanly.
///
/// # Parameters
/// - `index`: the entry (`stash@{index}`).
/// - `pop`: drop the entry after applying it.
/// - `hash`: the entry's hash as the caller listed it; when given and
/// the entry at `index` has another hash (the stash changed since),
/// nothing is applied.
///
/// # Errors
/// [`VcsError::InvalidName`] for a hash that is not 4 to 64 hex
/// digits; [`VcsError::Git`] with a clear sentence for a missing or
/// changed entry, unmerged files, conflicts while applying (the files
/// then hold conflict markers and the entry is kept), local changes
/// that would be overwritten and untracked files in the way; git's
/// refusal otherwise.
pub fn stash_apply(&self, index: usize, pop: bool, hash: Option<&str>) -> Result<(), VcsError> {
let _guard = self.lock();
let reference = self.stash_entry(index, hash)?;
self.refuse_unmerged("Applying a stash")?;
let action = if pop { "pop" } else { "apply" };
let output = self.run(
Call::write(self.root(), &["stash", action, "--quiet", &reference])
.timeout(HOOK_TIMEOUT),
)?;
if output.success() {
return Ok(());
}
let message = output.message();
let conflicts = self.unmerged_count()?;
if conflicts > 0 {
let kept = if pop {
" The stash entry was kept; drop it once the conflicts are resolved."
} else {
""
};
return Err(VcsError::Git(format!(
"The stash was applied with conflicts in {conflicts} {}. Resolve them in the Changes window.{kept}",
if conflicts == 1 { "file" } else { "files" },
)));
}
Err(VcsError::Git(explain(&message)))
}
/// Drops a stash entry. It cannot be restored from Lutra afterwards.
///
/// # Parameters
/// - `index`: the entry (`stash@{index}`).
/// - `hash`: as for [`Repo::stash_apply`].
///
/// # Errors
/// As [`Repo::stash_apply`] for a missing or changed entry, or git's
/// refusal.
pub fn stash_drop(&self, index: usize, hash: Option<&str>) -> Result<(), VcsError> {
let _guard = self.lock();
let reference = self.stash_entry(index, hash)?;
self.run(Call::write(
self.root(),
&["stash", "drop", "--quiet", &reference],
))?
.checked()?;
Ok(())
}
/// The reference `stash@{index}` after checking the entry exists and,
/// when `hash` is given, is the one the caller saw.
fn stash_entry(&self, index: usize, hash: Option<&str>) -> Result<String, VcsError> {
if let Some(hash) = hash {
check_hash(hash)?;
}
let list = self.stash_list()?;
let Some(entry) = list.get(index) else {
return Err(VcsError::Git(if list.is_empty() {
"The stash is empty.".to_string()
} else {
format!(
"There is no stash entry {index}; the stash holds {} {}. Refresh the list.",
list.len(),
if list.len() == 1 { "entry" } else { "entries" },
)
}));
};
if let Some(hash) = hash
&& !entry.hash.starts_with(&hash.to_ascii_lowercase())
{
return Err(VcsError::Git(
"The stash changed since it was listed. Refresh the list and try again."
.to_string(),
));
}
Ok(format!("stash@{{{index}}}"))
}
/// Removes the untracked files the newest entry holds from the work
/// tree, as `git stash push --include-untracked` should have done.
///
/// Every call runs with `--literal-pathspecs`, and under it git's stash
/// stores untracked files without removing them (git's internal clean
/// uses a pathspec with magic). So the files listed in the entry's
/// untracked tree (`stash@{0}^3`) go through `git clean -f`, which only
/// ever removes untracked files, in chunks of at most
/// [`CLEAN_CHUNK`] bytes of arguments; folders left empty are removed.
/// A folder that cannot be removed is left (`.ok()`): it is empty and
/// git does not see it.
///
/// # Errors
/// The runner's errors or git's refusal.
fn remove_stashed_untracked(&self) -> Result<(), VcsError> {
let output = self.run(Call::read(
self.root(),
&[
"ls-tree",
"-r",
"-z",
"--name-only",
"--full-tree",
"stash@{0}^3",
],
SMALL_CAP,
))?;
if !output.success() {
return Ok(());
}
let paths: Vec<String> = output
.stdout
.split(|b| *b == 0)
.filter(|p| !p.is_empty())
.map(|p| String::from_utf8_lossy(p).into_owned())
.collect();
for chunk in chunks(&paths, CLEAN_CHUNK) {
let mut args = vec!["clean", "-f", "-q", "--"];
args.extend(chunk.iter().map(String::as_str));
self.run(Call::write(self.root(), &args))?.checked()?;
}
let mut dirs: Vec<&str> = paths
.iter()
.flat_map(|p| p.match_indices('/').filter_map(move |(i, _)| p.get(..i)))
.collect();
dirs.sort_unstable_by_key(|d| std::cmp::Reverse(d.len()));
dirs.dedup();
for dir in dirs {
std::fs::remove_dir(self.root().join(dir)).ok();
}
Ok(())
}
/// The hash `refs/stash` points to, `None` without a stash.
fn stash_top(&self) -> Result<Option<String>, VcsError> {
let output = self.run(Call::read(
self.root(),
&["rev-parse", "--verify", "--quiet", "refs/stash"],
4096,
))?;
if !output.success() {
return Ok(None);
}
let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(Some(text).filter(|t| !t.is_empty()))
}
/// Whether HEAD points to a commit.
fn has_commit(&self) -> Result<bool, VcsError> {
Ok(self
.run(Call::read(
self.root(),
&["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
4096,
))?
.success())
}
/// How many paths have unmerged index entries (merge conflicts).
fn unmerged_count(&self) -> Result<usize, VcsError> {
let output = self
.run(Call::read(
self.root(),
&["ls-files", "--unmerged", "-z"],
SMALL_CAP,
))?
.checked()?;
Ok(count_unmerged(&output.stdout))
}
/// Refuses while files are unmerged, naming `what` was refused.
fn refuse_unmerged(&self, what: &str) -> Result<(), VcsError> {
let count = self.unmerged_count()?;
if count == 0 {
return Ok(());
}
Err(VcsError::Git(format!(
"{what} is not possible while {count} {} merge conflicts. Resolve them first.",
if count == 1 { "file has" } else { "files have" },
)))
}
}
/// Splits paths into groups whose total length stays within `limit` bytes
/// (a path longer than the limit forms its own group), so a command line
/// stays below Windows' 32,767 characters.
fn chunks(paths: &[String], limit: usize) -> Vec<&[String]> {
let mut out = Vec::new();
let mut start = 0;
let mut size = 0;
for (i, path) in paths.iter().enumerate() {
let len = path.len() + 1;
if i > start && size + len > limit {
out.extend(paths.get(start..i));
start = i;
size = 0;
}
size += len;
}
if start < paths.len() {
out.extend(paths.get(start..));
}
out
}
/// A message git can take: line breaks become spaces, other control
/// characters are dropped, the ends trimmed, the length capped.
fn clean_message(message: &str) -> String {
message
.chars()
.filter_map(|c| match c {
'\n' | '\r' | '\t' => Some(' '),
c if c.is_control() => None,
c => Some(c),
})
.take(STASH_MESSAGE_CAP)
.collect::<String>()
.trim()
.to_string()
}
/// Rejects anything but 4 to 64 hex digits.
fn check_hash(hash: &str) -> Result<(), VcsError> {
if (4..=64).contains(&hash.len()) && hash.bytes().all(|b| b.is_ascii_hexdigit()) {
Ok(())
} else {
Err(VcsError::InvalidName(hash.to_string()))
}
}
/// Puts a sentence that says what to do before git's message, for the
/// refusals that have one.
fn explain(message: &str) -> String {
let hint = if message.contains("would be overwritten") {
Some(
"Local changes to files the stash also changes would be overwritten. Commit, stash or roll them back first.",
)
} else if message.contains("already exists, no checkout")
|| message.contains("could not restore untracked files")
{
Some(
"Untracked files from the stash already exist in the working tree. Move or delete them first.",
)
} else {
None
};
match hint {
Some(hint) if message.trim().is_empty() => hint.to_string(),
Some(hint) => format!("{hint}\n\n{}", message.trim()),
None => message.trim().to_string(),
}
}
/// Counts the distinct paths of `ls-files --unmerged -z` (one line per
/// stage: `<mode> <oid> <stage>\t<path>`).
pub fn count_unmerged(bytes: &[u8]) -> usize {
let mut paths: Vec<&[u8]> = bytes
.split(|b| *b == 0)
.filter_map(|line| {
let tab = line.iter().position(|b| *b == b'\t')?;
line.get(tab + 1..).filter(|p| !p.is_empty())
})
.collect();
paths.sort_unstable();
paths.dedup();
paths.len()
}
/// Splits a reflog subject (`On main: message`, `WIP on main: abc1234
/// subject`) into branch, message and whether it is a "WIP" entry. Other
/// forms keep the whole subject as the message.
pub fn parse_subject(subject: &str) -> (Option<String>, String, bool) {
let (rest, wip) = if let Some(rest) = subject.strip_prefix("WIP on ") {
(rest, true)
} else if let Some(rest) = subject.strip_prefix("On ") {
(rest, false)
} else {
return (None, subject.to_string(), false);
};
match rest.split_once(": ") {
Some((branch, message)) if !branch.is_empty() => {
(Some(branch.to_string()), message.to_string(), wip)
}
_ => (None, subject.to_string(), false),
}
}
/// Parses the [`LIST_FORMAT`] output; the position of a record is its
/// index. Records without a hash are skipped (and do not count).
pub fn parse_stash_list(bytes: &[u8]) -> Vec<StashEntry> {
let mut entries = Vec::new();
for record in bytes.split(|b| *b == RECORD) {
let text = String::from_utf8_lossy(record);
let text = text.trim_end_matches(['\n', '\r']);
let mut fields = text.split('\0');
let (Some(hash), Some(subject), Some(date)) = (fields.next(), fields.next(), fields.next())
else {
continue;
};
let hash = hash.trim();
if hash.is_empty() {
continue;
}
let (branch, message, wip) = parse_subject(subject);
entries.push(StashEntry {
index: entries.len(),
hash: hash.to_string(),
branch,
message,
wip,
date: date.trim().to_string(),
});
}
entries
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::indexing_slicing)]
use super::*;
use proptest::prelude::*;
#[test]
fn list_records_parse() {
let bytes = b"\x1eaaa\0WIP on main: 41aa1cf init\x002026-10-28T18:08:36+01:00\n\x1ebbb\0On feature/x: my work\x002026-10-28T18:00:00Z\n\x1eccc\0odd subject\0d\n";
let entries = parse_stash_list(bytes);
assert_eq!(entries.len(), 3);
assert_eq!(entries[0].index, 0);
assert_eq!(entries[0].branch.as_deref(), Some("main"));
assert_eq!(entries[0].message, "41aa1cf init");
assert!(entries[0].wip);
assert_eq!(entries[1].branch.as_deref(), Some("feature/x"));
assert_eq!(entries[1].message, "my work");
assert!(!entries[1].wip);
assert_eq!(entries[1].date, "2026-10-28T18:00:00Z");
assert_eq!(entries[2].branch, None);
assert_eq!(entries[2].message, "odd subject");
assert_eq!(entries[2].index, 2);
}
#[test]
fn short_records_are_skipped() {
assert!(parse_stash_list(b"\x1eaaa\0only two").is_empty());
assert!(parse_stash_list(b"").is_empty());
let entries = parse_stash_list(b"\x1e\0x\0d\x1eh\0On m: x\0d");
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].index, 0);
}
#[test]
fn subjects_split() {
assert_eq!(
parse_subject("On main: a: b"),
(Some("main".into()), "a: b".into(), false)
);
assert_eq!(
parse_subject("WIP on (no branch): abc x"),
(Some("(no branch)".into()), "abc x".into(), true)
);
assert_eq!(parse_subject("On : x"), (None, "On : x".into(), false));
assert_eq!(
parse_subject("autostash"),
(None, "autostash".into(), false)
);
}
#[test]
fn messages_are_cleaned() {
assert_eq!(clean_message(" a\nb\r\tc\u{1b}d "), "a b cd");
assert_eq!(clean_message("\n"), "");
assert_eq!(
clean_message(&"x".repeat(2000)).chars().count(),
STASH_MESSAGE_CAP
);
assert_eq!(clean_message("--all"), "--all");
}
#[test]
fn unmerged_paths_are_counted_once() {
let bytes = b"100644 aaa 1\ta.php\x00100644 bbb 2\ta.php\x00100644 ccc 3\ta.php\x00100644 ddd 2\tb c.php\0";
assert_eq!(count_unmerged(bytes), 2);
assert_eq!(count_unmerged(b""), 0);
assert_eq!(count_unmerged(b"no tab\0"), 0);
}
#[test]
fn refusals_get_a_hint() {
let overwritten = explain(
"error: Your local changes to the following files would be overwritten by merge:\n\ta\nAborting\n",
);
assert!(overwritten.starts_with("Local changes to files"));
assert!(overwritten.ends_with("Aborting"));
let untracked = explain(
"u already exists, no checkout\nerror: could not restore untracked files from stash",
);
assert!(untracked.starts_with("Untracked files from the stash"));
assert_eq!(explain(" something else \n"), "something else");
}
#[test]
fn paths_are_chunked() {
let paths: Vec<String> = ["aaaa", "bbbb", "cccc", &"d".repeat(30)]
.iter()
.map(|s| s.to_string())
.collect();
let groups = chunks(&paths, 10);
assert_eq!(groups.len(), 3);
assert_eq!(groups[0], &paths[..2]);
assert_eq!(groups[2], &paths[3..]);
assert!(chunks(&[], 10).is_empty());
}
#[test]
fn hashes_are_checked() {
assert!(check_hash("abcd").is_ok());
assert!(check_hash("abc").is_err());
assert!(check_hash("stash@{0}").is_err());
assert!(check_hash("-abcd").is_err());
}
proptest! {
#[test]
fn parsers_never_panic(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
let entries = parse_stash_list(&bytes);
for (i, entry) in entries.iter().enumerate() {
prop_assert_eq!(entry.index, i);
}
let _ = count_unmerged(&bytes);
let _ = parse_subject(&String::from_utf8_lossy(&bytes));
let _ = explain(&String::from_utf8_lossy(&bytes));
}
#[test]
fn cleaned_messages_have_no_controls(text in any::<String>()) {
let cleaned = clean_message(&text);
prop_assert!(!cleaned.chars().any(char::is_control));
prop_assert!(cleaned.chars().count() <= STASH_MESSAGE_CAP);
}
}
}

246
crates/vcs/tests/stash.rs Normal file
View file

@ -0,0 +1,246 @@
//! Stash (M4.9) against real repositories in temp folders: stash with and
//! without a message and untracked files, the list, apply, pop and drop,
//! and every refusal (no commit, nothing to stash, unmerged files,
//! conflicts, overwritten changes, untracked files in the way, a missing or
//! changed entry). Every test 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 lutra_vcs::{Git, Repo, VcsError};
/// The installed git, or `None` (with a message) when there is none.
fn installed() -> Option<Git> {
match Git::detect("") {
Ok(git) => Some(git),
Err(e) => {
eprintln!("skipped: no usable git installed ({e})");
None
}
}
}
/// Runs git in `dir` for test setup and asserts it succeeded.
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.args(args)
.current_dir(dir)
.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE")
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
/// A new repository on `main` with a local identity.
fn init(dir: &Path) {
git(dir, &["init", "-q", "-b", "main"]);
for (key, value) in [
("user.name", "Lutra Test"),
("user.email", "test@lutra.invalid"),
("commit.gpgsign", "false"),
("core.autocrlf", "false"),
("core.hooksPath", ".git/hooks"),
] {
git(dir, &["config", key, value]);
}
}
/// Writes a file.
fn write(dir: &Path, path: &str, text: &str) {
std::fs::write(dir.join(path), text).unwrap();
}
/// Reads a file.
fn read(dir: &Path, path: &str) -> String {
std::fs::read_to_string(dir.join(path)).unwrap()
}
/// A repository with `a.txt` committed, opened.
fn repo_with_commit(git_: &Git, dir: &Path) -> Repo {
init(dir);
write(dir, "a.txt", "one\n");
git(dir, &["add", "-A"]);
git(dir, &["commit", "-q", "-m", "init"]);
git_.open(dir).unwrap().expect("a repository")
}
/// The message of a `VcsError::Git`.
fn refusal(result: Result<impl std::fmt::Debug, VcsError>) -> String {
match result {
Err(VcsError::Git(message)) => message,
other => panic!("expected a refusal, got {other:?}"),
}
}
#[test]
fn stash_list_apply_pop_drop() {
let Some(g) = installed() else { return };
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let repo = repo_with_commit(&g, dir);
assert!(repo.stash_list().unwrap().is_empty());
write(dir, "a.txt", "two\n");
let first = repo.stash(Some(" first\nline "), false).unwrap();
assert_eq!(first.index, 0);
assert_eq!(first.message, "first line");
assert_eq!(first.branch.as_deref(), Some("main"));
assert!(!first.wip);
assert_eq!(read(dir, "a.txt"), "one\n");
write(dir, "a.txt", "three\n");
let second = repo.stash(None, false).unwrap();
assert!(second.wip);
assert!(second.message.ends_with("init"), "{}", second.message);
let list = repo.stash_list().unwrap();
assert_eq!(list.len(), 2);
assert_eq!(list[0].hash, second.hash);
assert_eq!(list[1].hash, first.hash);
assert_eq!(list[1].index, 1);
assert!(!list[0].date.is_empty());
repo.stash_apply(1, false, Some(&first.hash)).unwrap();
assert_eq!(read(dir, "a.txt"), "two\n");
assert_eq!(repo.stash_list().unwrap().len(), 2);
git(dir, &["checkout", "--", "a.txt"]);
repo.stash_apply(0, true, second.hash.get(..8)).unwrap();
assert_eq!(read(dir, "a.txt"), "three\n");
let list = repo.stash_list().unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].hash, first.hash);
repo.stash_drop(0, Some(&first.hash)).unwrap();
assert!(repo.stash_list().unwrap().is_empty());
}
#[test]
fn untracked_files_only_with_the_flag() {
let Some(g) = installed() else { return };
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let repo = repo_with_commit(&g, dir);
write(dir, "new.txt", "new\n");
let message = refusal(repo.stash(None, false));
assert!(message.contains("no local changes"), "{message}");
assert!(message.contains("untracked"), "{message}");
assert!(dir.join("new.txt").exists());
std::fs::create_dir_all(dir.join("d/e")).unwrap();
write(dir, "d/e/-f.txt", "deep\n");
repo.stash(Some("with untracked"), true).unwrap();
assert!(!dir.join("new.txt").exists());
assert!(!dir.join("d").exists());
assert_eq!(read(dir, "a.txt"), "one\n");
repo.stash_apply(0, true, None).unwrap();
assert_eq!(read(dir, "new.txt"), "new\n");
assert_eq!(read(dir, "d/e/-f.txt"), "deep\n");
assert!(repo.stash_list().unwrap().is_empty());
}
#[test]
fn nothing_to_stash_and_no_commit() {
let Some(g) = installed() else { return };
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
init(dir);
write(dir, "a.txt", "x\n");
let repo = g.open(dir).unwrap().unwrap();
let message = refusal(repo.stash(None, true));
assert!(message.contains("first commit"), "{message}");
git(dir, &["add", "-A"]);
git(dir, &["commit", "-q", "-m", "init"]);
let message = refusal(repo.stash(Some("x"), true));
assert_eq!(message, "There are no local changes to stash.");
assert!(repo.stash_list().unwrap().is_empty());
}
#[test]
fn missing_and_changed_entries_are_refused() {
let Some(g) = installed() else { return };
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let repo = repo_with_commit(&g, dir);
assert_eq!(refusal(repo.stash_drop(0, None)), "The stash is empty.");
write(dir, "a.txt", "two\n");
let entry = repo.stash(None, false).unwrap();
let message = refusal(repo.stash_apply(3, false, None));
assert!(message.contains("no stash entry 3"), "{message}");
assert!(message.contains("1 entry"), "{message}");
let message = refusal(repo.stash_drop(0, Some("deadbeef")));
assert!(message.contains("changed since it was listed"), "{message}");
assert!(matches!(
repo.stash_drop(0, Some("stash@{0}")),
Err(VcsError::InvalidName(_))
));
assert_eq!(repo.stash_list().unwrap()[0].hash, entry.hash);
}
#[test]
fn overwritten_changes_and_untracked_in_the_way() {
let Some(g) = installed() else { return };
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let repo = repo_with_commit(&g, dir);
write(dir, "a.txt", "stashed\n");
repo.stash(None, false).unwrap();
write(dir, "a.txt", "local\n");
let message = refusal(repo.stash_apply(0, true, None));
assert!(message.contains("would be overwritten"), "{message}");
assert_eq!(read(dir, "a.txt"), "local\n");
assert_eq!(repo.stash_list().unwrap().len(), 1);
git(dir, &["checkout", "--", "a.txt"]);
repo.stash_drop(0, None).unwrap();
write(dir, "u.txt", "stashed\n");
repo.stash(None, true).unwrap();
write(dir, "u.txt", "in the way\n");
let message = refusal(repo.stash_apply(0, false, None));
assert!(message.contains("already exist"), "{message}");
assert_eq!(read(dir, "u.txt"), "in the way\n");
}
#[test]
fn conflicts_keep_the_entry_and_block_the_next_stash() {
let Some(g) = installed() else { return };
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
let repo = repo_with_commit(&g, dir);
write(dir, "a.txt", "stashed\n");
repo.stash(None, false).unwrap();
write(dir, "a.txt", "committed\n");
git(dir, &["commit", "-q", "-am", "change"]);
let message = refusal(repo.stash_apply(0, true, None));
assert!(message.contains("conflicts in 1 file"), "{message}");
assert!(message.contains("was kept"), "{message}");
assert_eq!(repo.stash_list().unwrap().len(), 1);
assert!(read(dir, "a.txt").contains("<<<<<<<"));
let message = refusal(repo.stash(None, false));
assert!(message.starts_with("Stashing is not possible"), "{message}");
let message = refusal(repo.stash_apply(0, false, None));
assert!(
message.starts_with("Applying a stash is not possible"),
"{message}"
);
}

View file

@ -1,6 +1,6 @@
# Architecture
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5); remotes: fetch, pull, push, clone and remote management (M4.10) · **Last updated:** 2026-10-28
> **Status:** M0 decisions recorded, M1 workspace, desktop bridge, tabs and editor, message catalog, engine construction, settings, themes, the recovery journal, notifications, UI commands, the palette, the settings dialog, the app icon and the syntax layer documented; M2 highlighting and `editor.reveal`, plus the search backend, the Find tool window, the symbol index, the Structure tool window and the go-to popup; M3 CLI and single instance, LSP client library, toolchain (PHP detection, Phpactor download), the app menu, MCP server, autosave and `flushDirty`, integrated terminal; engine ↔ Phpactor wiring and diagnostics (M3.3), pending outcomes (M3.5), completion, hover and signature help (M3.4); C5 child process groups (H1), settings dialog string and path controls and assist settings (H4), the banner-aligned themes and diagnostic/VCS tokens (H5), Phpactor UX: fast tick, messages, progress, `php -l` (H3); Git backend (M4.1), Changes tool window (M4.2); line changes, gutter markers and status colours (M4.4), diff viewer (M4.3), branches (M4.5); remotes: fetch, pull, push, clone and remote management (M4.10); stash (M4.9) · **Last updated:** 2026-10-28
## Overview
@ -707,10 +707,32 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat
- **Not yet:** an "ignore" action, a compare menu, reverting a resolution, prefilling the commit message from `MERGE_MSG`, rebase and cherry-pick conflicts, synchronised scrolling.
- **Tests:** `crates/vcs/tests/merge.rs` (5 against real temp repositories: clean merge, fast-forward, up to date, a content conflict with its versions, resolve and commit, add/add and modify/delete, abort, refusals); unit and property tests in `merge.rs`; `crates/engine/tests/git_merge.rs` (2: the command shapes, `gitChanged`, bad params, no project); Vitest `ui/tests/vcs/Merge.test.ts` (22: the merge on fixed and 300 random texts, layout, parsing, merging after `flushDirty`, the dialog's branches, list, resolve view, apply through the buffer, deleted and binary files, abort, the Changes entry point, registration).
### Stash (M4.9)
- **Backend** (`crates/vcs/src/stash.rs`, an append; `Repo::lock` became `pub(crate)`, as for M4.8): `stash`, `stash_list`, `stash_apply` and `stash_drop` on `Repo`, run through the M4.1 runner. The stash belongs to the repository, so `git stash push` takes every change of the work tree, also outside the project folder. Changes hold the repository's mutex; the entry is checked under it.
- **List:** `stash list --format=%x1e%H%x00%gs%x00%cI`, at most 1,000 entries; the position is the index. The reflog subject is split into the branch and the message (`On <branch>: <message>`, `WIP on <branch>: <hash> <subject>` for an entry without a message, flagged `wip`); another form keeps the whole subject.
- **Stash:** `stash push [--include-untracked] [--message=…]` with the 120 s timeout. The message loses control characters (line breaks become spaces) and is cut at 1,000 characters. Whether an entry was made is read from `refs/stash` before and after, not from git's text (git exits 0 with "No local changes to save").
- **`--literal-pathspecs` workaround:** every call runs with it, and under it git's `stash push --include-untracked` stores the untracked files but leaves them in the work tree (its internal clean uses a magic pathspec; found by the integration test, reproduced with git 2.47.1 by hand). So after such a stash the files listed in `stash@{0}^3` go through `git clean -f -- <paths>` (it removes untracked files only; arguments in chunks of 16 KiB, as `clean` has no `--pathspec-from-file`), and folders left empty are removed.
- **Apply, pop, drop:** `stash apply|pop|drop --quiet stash@{n}` with the 120 s timeout for apply and pop. An optional `hash` (as listed) must match the entry at `index`, so a stash changed in between (another tool, another window) is refused instead of applying the wrong entry.
- **Refusals** (`VcsError::Git`, so `failed` with the text): a sentence that says what to do, then git's own message where there is one. Decided structurally, so they hold whatever language git speaks: no commit yet (`HEAD^{commit}`), nothing to stash (`refs/stash` did not move; without `includeUntracked` the text adds that untracked files need it), unmerged files before stash or apply (`ls-files --unmerged`), a missing entry (the list's length), a changed entry (the hash), conflicts after a failed apply or pop (unmerged entries now exist: "applied with conflicts in N files … the stash entry was kept"). Two hints read git's English text and fall back to git's message alone: local changes that would be overwritten, untracked files already in the work tree.
- **Commands** (`crates/engine/src/cmd/git_stash.rs`, through M4.6's `start_with` hook; pending outcomes; `gitChanged` after stash, apply and drop):
- `git.stash {message?, includeUntracked?}` → `{entry: {index, hash, branch, message, wip, date}}`.
- `git.stashList` → `{stashes: [{index, hash, branch|null, message, wip, date}]}` newest first.
- `git.stashApply {index, pop?, hash?}` → `{}`; `git.stashDrop {index, hash?}` → `{}`.
- The result shapes and the optional `hash` are additions to the C6 contract, which named the params only. A bad hash or an index over 100,000 is `invalid_params`.
- A conflicted apply is `failed` but changed the work tree; the `.git` watch reports it as `gitChanged` within about 300 ms. `refs/stash` is not watched, so a stash made outside Lutra shows the next time the list is read.
- **UI** (`ui/src/components/vcs/stash/`): `stash.ts` is the Pinia store, `StashDialog.vue` the dialog, mounted once in `MainLayout.vue`. It supplies the UI commands `vcs.stash` (Git › Stash Changes…) and `vcs.showStashes` (Git › Stashes…), enabled with `git.stash` (an open project), without default shortcuts. The Changes window's bar has a button for each, next to refresh.
- **Form:** message (optional), "Include untracked files" (kept between uses), a note that every change of the repository is set aside. Enter or Stash runs `flushDirty()` first, so git stashes what the editor shows and the reset files reload instead of keeping unsaved edits on top; a failed save does nothing and says so. A refusal shows under the form (`role="alert"`) and the dialog stays; success closes it with an info toast.
- **List:** read with `git.stashList` each time it shows and after every change; rows show `stash@{n}`, the message ("WIP: …" for an entry without one), the branch and the local date. Up/Down/Home/End move, Enter or Apply applies, Pop applies and drops, Delete or Drop asks inline ("Drop stash@{n}? It cannot be restored.") before `git.stashDrop`. Apply and pop save dirty buffers first. Every call passes the listed hash. Refusals (conflicts, overwritten files) show under the list, which is read again.
- **Modal:** an exclusive modal (`ModalId` `stash`); Escape cancels a drop question first, then closes; the focus goes back where it was. The answer is untrusted: entries without an index or hash are dropped, at most 1,000.
- **Checked in the app** (debug build with the bundled UI, Windows 11, git 2.47.1, control port 7949, a demo repository with two stashes on two branches and a modified file; commands and screenshots only, no input): `git.stashList` 143–157 ms, `git.stash` 640 ms, a pop 366 ms, each including the control round trip. The refusals came back as written above: applying onto a modified file ("would be overwritten" with git's text), nothing to stash (with the untracked hint), a missing entry. Screenshots of the list (`stash@{n}`, WIP text, branch, date; Drop, Pop, Apply) and of the form, plus the two new buttons in the Changes bar, read in the dark theme.
- **Tests:** `crates/vcs/tests/stash.rs` (6 tests against real temp repositories: stash with and without a message, list order and hashes, apply, pop by an abbreviated hash, drop; untracked files only with the flag, including a nested folder and a name starting with `-`; no commit and nothing to stash; a missing and a changed entry, a bad hash; overwritten local changes and untracked files in the way, both leaving the work tree and the entry alone; a conflicted pop keeping the entry and blocking the next stash and apply); unit and property tests in `stash.rs` (list and subject parsing, message cleaning, unmerged counting, hints, chunking); `crates/engine/tests/git_stash.rs` (the command shapes, `gitChanged` only after changes, a changed hash, an empty stash, bad params); Vitest `ui/tests/vcs/Stash.test.ts` (13 tests: parsing, the form with `flushDirty` first, a blank message, a refusal, a failed save, Escape and focus, the list with keyboard and apply, a conflicted pop, the drop question, an empty stash, a failed read, the commands' registration, the Changes window's buttons).
## Decisions (M0)
| Question | Decision | Why |
|---|---|---|
| 2026-10-30 | minor | M4.9: stash backend (`git.stash`, `git.stashList`, `git.stashApply`, `git.stashDrop`), the `--literal-pathspecs` workaround for untracked files, the stash dialog |
| Highlighting | A Lezer grammar (`@lezer/php`, MIT) in CodeMirror highlights instantly on the UI thread. tree-sitter in `crates/syntax` stays the structural source (outline, folding, index) and later adds semantic tokens on top. | The keystroke-to-highlight budget (< 16 ms) leaves no room for an IPC round trip per keystroke; Lezer is incremental inside CodeMirror. tree-sitter gives the core one parser for every structural feature. |
| Git library | `gix` (MIT OR Apache-2.0) for reading: status, log, diff, blame, refs. Writes the library doesn't cover well (push, pull, rebase, merge, hooks, signing) run the user's `git` executable. `git2`/libgit2 is not used. | gix is pure Rust and permissively licensed; libgit2 is GPL-2.0 with a linking exception, outside the permitted licences. Shelling out for writes keeps the user's hooks, credential helpers and config working. |
| Terminal | `portable-pty` (MIT) in the new L3 crate `crates/terminal`; xterm.js (MIT) renders in the frontend. Output is streamed as events, input goes through commands. | ConPTY on Windows and Unix PTYs behind one API; xterm.js is the standard web terminal. A separate crate keeps PTY code out of the engine. |

View file

@ -1,11 +1,12 @@
# Gaps
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10); G14 English UI catalog in place · **Last updated:** 2026-10-26
> **Status:** M0 closed G1; G2 under way (text buffer, engine buffers, tabs and editor in the app, recovery journal, autosave); G3 M1 part done (project tree, palette, settings dialog with string and path controls, themes) plus the app menu (M3.9); G4 under way (tree-sitter outline and folding library, Lezer highlighting, Structure tool window); G5 under way (search backend, Find tool window, symbol index, go-to popup); G6 under way (LSP client library, PHP detection, Phpactor download, engine wiring and diagnostics, completion and hover, definition, references and rename, Phpactor dies with Lutra, faster indexing, progress and messages, `php -l` on Windows); G7 under way (`lutra` CLI and single instance, MCP server, integrated terminal); G8 under way (Git backend, M4.1; Changes window, M4.2; gutter markers and status colours, M4.4; diff viewer, M4.3; branch widget and popup, M4.5; merge conflicts, M4.8; remotes, M4.10; stash, M4.9); G14 English UI catalog in place · **Last updated:** 2026-10-26
Every known shortfall, ranked. This is the work list: unless the owner gives a task, take the highest open gap. Hours are agent wall-clock hours for one agent, all estimated.
| # | Gap | Milestone | Estimate (one agent) |
|---|---|---|---|
| 2026-10-30 | patch | G8: stash (M4.9) |
| G1 | ~~Foundation: workspace, quality gate, command registry, guard, control channel~~ closed 2026-10-14 | M0 | done (~2 h measured) |
| G2 | Editor core: ~~engine buffers, save~~ (M1.3), ~~editor UI with tabs, undo, multi-caret~~ (M1.6, CodeMirror basics), ~~recovery journal~~ (M1.7), tab management (preview, pin, split, close others, reopen), conflict UI for files changed on disk, ~~autosave~~ (M3.10), local history | M1 | ~14 h |
| G3 | Project model: ~~VFS~~ (M1.2: listing, ignore rules, native file watching with polling fallback, safe file IO), ~~project tree wiring~~ (M1.5 UI, M1.3 engine, M1.4 bridge: folder picker, live tree), tree toolbar and options, ~~showing truncated listings~~ (M1.13), ~~error notifications for the folder picker~~ (M1.12), ~~tabs~~ (M1.6), ~~command palette~~ (M1.8: commands only, global keymap, UI commands over the control channel); ~~settings~~ (backend: M1.9a; dialog with search: M1.9b; string and path controls: H4), ~~theme switching~~ (M1.10: light/dark, live, system mode; picker in the dialog, M1.9b), ~~main menu~~ (M3.9: hamburger dropdown from `menuPath`s; native macOS menu bar and display modes open) | M1 | ~24 h |
@ -13,7 +14,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, 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~~ (M4.6: Log tab with graph lanes, filters, paging, commit details, diffs at a commit, file history; no date or branch filters, no actions on commits), ~~remotes~~ (M4.10: fetch, pull by merge or rebase, push with the upstream set on the first push, clone, manage remotes, progress and cancel, explained refusals, any HTTPS or SSH server through git's credential helper and the ssh agent; no force push, tags, per-branch push targets or hosting features such as pull requests), blame, ~~conflicts~~ (M4.8: `git.merge`, conflicts list, three-pane resolve view with accept left/right per chunk, mark resolved, abort; no ignore action, compare menu or rebase conflicts), stash | 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~~ (M4.6: Log tab with graph lanes, filters, paging, commit details, diffs at a commit, file history; no date or branch filters, no actions on commits), ~~remotes~~ (M4.10: fetch, pull by merge or rebase, push with the upstream set on the first push, clone, manage remotes, progress and cancel, explained refusals, any HTTPS or SSH server through git's credential helper and the ssh agent; no force push, tags, per-branch push targets or hosting features such as pull requests), blame, ~~conflicts~~ (M4.8: `git.merge`, conflicts list, three-pane resolve view with accept left/right per chunk, mark resolved, abort; no ignore action, compare menu or rebase conflicts), ~~stash~~ (M4.9: stash with a message and optionally untracked files, list, apply, pop and drop after a question, refusals that say what to do; no partial stash, no stash diff, no "unstash as branch") | 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 |

View file

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

File diff suppressed because one or more lines are too long

View file

@ -1,6 +1,6 @@
# Tooling checklist
> **Status:** integrated terminal partial (M3.6), Git backend, Changes window, diff viewer, branches, log and remotes partial (M4.1, M4.2, M4.3, M4.5, M4.6, M4.10) · **Last updated:** 2026-10-28
> **Status:** integrated terminal partial (M3.6), Git backend, Changes window, diff viewer, branches, log, remotes and stash partial (M4.1, M4.2, M4.3, M4.5, M4.6, M4.10, M4.9) · **Last updated:** 2026-10-28
- [ ] Integrated terminal with tabs
- M3.6 (2026-10-18): PTY sessions (pwsh → powershell → cmd on Windows, `$SHELL` or `/bin/sh` on Unix; cwd = project root) in the bottom panel's Terminal tab, several terminals as sub-tabs, xterm.js rendering with Lutra's colours, copy/paste, resize, exit codes; closed with the project. Missing: settings, persistence across restarts, split tabs, search, links, the PHP interpreter in `PATH`.
@ -11,6 +11,7 @@
- M4.6 (2026-10-28): Log tab with graph lanes, message and author filters and lazy paging; commit details with each file's diff at that commit; history of a file from the tree, the editor or the menu. Missing: date and branch filters, actions on commits (cherry-pick, revert, reset, checkout), comparing two commits, blame, conflicts, stash, push/pull.
- M4.10 (2026-10-28): fetch, pull (merge or rebase, setting `git.pull.mode`; open files saved first) and push (upstream set on the first push), each with progress and Cancel in the status bar and explained refusals; Clone Repository… from any HTTPS or SSH URL or a path, then the project opens; Manage Remotes… (list with redacted URLs, add, change URL, remove). Sign-in stays with git's credential helper (its own window is allowed) and the ssh agent; terminal prompts are off, so a missing credential fails with a message. Tested against local bare repositories only. Missing: force push, tags, pushing to another branch name, fetch/pull of one branch, prune options, hosting features (pull requests, issues), checked against a real GitHub/GitLab/Forgejo server.
- M4.8 (2026-10-28): merge a branch into the current one (Git › Merge…), list the conflicted files, resolve each in a three-pane view (current branch / result / merged branch) with accept left or right per chunk and accept all, apply and mark resolved, abort the merge after a confirmation. Missing: an ignore action, comparing base/local/remote, reverting a resolution, rebase and cherry-pick conflicts, merge-message prefill.
- M4.9 (2026-10-30): stash the local changes with an optional message and optionally untracked files, then list, apply, pop or drop entries (Git menu and the Changes window), saving open files first; refusals say what to do (nothing to stash, no commit yet, unresolved conflicts, files that would be overwritten, a stash changed meanwhile). Missing: stashing selected files, a stash's diff, "unstash as branch", restoring the index, blame.
- [ ] Composer: install, update, require, scripts
- [ ] PHP interpreters: local, Docker
- [ ] Xdebug via DAP: breakpoints, stepping, variables, watches
@ -24,6 +25,7 @@
| Date | Change | Summary |
|---|---|---|
| 2026-10-30 | minor | Git: stash (M4.9) |
| 2026-10-28 | minor | Git: log and file history (M4.6) |
| 2026-10-28 | minor | Git: fetch, pull, push, clone and remote management (M4.10) |
| 2026-10-26 | minor | Git: branch widget, checkout and new branch (M4.5) |

View file

@ -19,8 +19,8 @@
* command but `menu.open` closes it.
* - **Navigation (M3.5):** the definition picker and the inline rename field
* are exclusive modals too. So is the branches popup (M4.5), and so are
* "Clone Repository…" and "Manage Remotes…" (M4.10) and the merge
* dialog (M4.8).
* "Clone Repository…" and "Manage Remotes…" (M4.10), the merge
* dialog (M4.8) and the stash dialog (M4.9).
*/
import { defineStore } from "pinia";
import { ref, watch } from "vue";
@ -38,7 +38,8 @@ export type ModalId =
| "branches"
| "clone"
| "remotes"
| "merge";
| "merge"
| "stash";
/** Store of the open exclusive modal. */
export const useModalsStore = defineStore("modals", () => {

View file

@ -51,6 +51,8 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "vcs.refresh", labelKey: "command.vcs.refresh", menuPath: "Git/Refresh Changes" },
{ id: "vcs.showLog", labelKey: "command.vcs.showLog", menuPath: "Git/Log" },
{ id: "vcs.showHistory", labelKey: "command.vcs.showHistory", menuPath: "Git/Show History" },
{ id: "vcs.stash", labelKey: "command.vcs.stash", menuPath: "Git/Stash Changes…" },
{ id: "vcs.showStashes", labelKey: "command.vcs.showStashes", menuPath: "Git/Stashes…" },
{ id: "vcs.showDiff", labelKey: "command.vcs.showDiff", menuPath: "Git/Show Diff", defaultShortcut: "Mod+Alt+Shift+D" },
{ id: "vcs.nextChange", labelKey: "command.vcs.nextChange", menuPath: "Git/Next Change", defaultShortcut: "Alt+Shift+]" },
{ id: "vcs.previousChange", labelKey: "command.vcs.previousChange", menuPath: "Git/Previous Change", defaultShortcut: "Alt+Shift+[" },

View file

@ -53,6 +53,7 @@ import ChangesToolWindow from "../vcs/changes/ChangesToolWindow.vue";
import { useChangesStore } from "../vcs/changes/changes";
import LogToolWindow from "../vcs/log/LogToolWindow.vue";
import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log";
import StashDialog from "../vcs/stash/StashDialog.vue";
import { useEditorStore } from "../../stores/editor";
import { useProjectStore } from "../../stores/project";
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
@ -326,6 +327,7 @@ onBeforeUnmount(() => {
/>
</BottomPanel>
<StatusBar />
<StashDialog />
</div>
</template>

View file

@ -7,7 +7,8 @@
* - **Status line:** the branch (or the short hash when detached) and the
* counts, or why there is nothing to show: git missing or too old (with
* a hint to the setting `git.executable`), no repository, no changes.
* A refresh button runs `vcs.refresh`.
* A refresh button runs `vcs.refresh`; two more open the stash dialog
* (M4.9) on its form (`vcs.stash`) and on its list (`vcs.showStashes`).
* - **Groups:** a header with a checkbox that stages (Changes, Untracked)
* or unstages (Staged) the whole group, then the files. Each file has a
* checkbox doing the same for itself, its name coloured by its state
@ -26,7 +27,7 @@
* message survive hiding the window. Icons are Lucide's; colours are
* tokens.
*/
import { RefreshCw } from "@lucide/vue";
import { Archive, ArchiveRestore, RefreshCw } from "@lucide/vue";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useCommandsStore } from "../../../commands/store";
import { isMac } from "../../../commands/keymap";
@ -325,6 +326,28 @@ watch(
>
<RefreshCw :size="14" />
</button>
<button
type="button"
class="changes__icon-button"
:title="t('command.vcs.stash')"
:aria-label="t('command.vcs.stash')"
:disabled="changes.phase !== 'ready' || !commands.isEnabled('vcs.stash')"
data-test="changes-stash"
@click="commands.execute('vcs.stash')"
>
<Archive :size="14" />
</button>
<button
type="button"
class="changes__icon-button"
:title="t('command.vcs.showStashes')"
:aria-label="t('command.vcs.showStashes')"
:disabled="changes.phase !== 'ready' || !commands.isEnabled('vcs.showStashes')"
data-test="changes-stashes"
@click="commands.execute('vcs.showStashes')"
>
<ArchiveRestore :size="14" />
</button>
</div>
<div
v-if="changes.phase === 'unavailable'"

View file

@ -0,0 +1,619 @@
<script setup lang="ts">
/**
* The stash dialog (M4.9), centred over the window.
*
* - **Stash form:** a message (optional), "Include untracked files" and
* Stash. Enter in the message or Stash saves dirty buffers and stashes
* (see the Stash store); a refusal shows under the form and the dialog
* stays.
* - **Stashes:** the entries, newest first: `stash@{n}`, the message (or
* git's "WIP" text), the branch and the date. Up/Down, Home and End
* move; Enter or Apply applies the selected entry, Pop applies and drops
* it, Delete or Drop asks, then drops it. A refusal (conflicts, files in
* the way, a changed stash) shows under the list.
* - **Commands:** the dialog supplies the UI commands `vcs.stash` (the
* form) and `vcs.showStashes` (the list), both enabled while `git.stash`
* is (an open project). The Changes window has buttons for both.
* - **Closing:** Escape (first it cancels a drop question), Cancel or a
* click outside; the focus goes back where it was. The dialog is an
* exclusive modal (`commands/modals.ts`).
*/
import { Archive } from "@lucide/vue";
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useModalsStore } from "../../../commands/modals";
import { useCommandsStore } from "../../../commands/store";
import { t } from "../../../i18n";
import { useStashStore, type StashEntry } from "./stash";
const stash = useStashStore();
const modals = useModalsStore();
const commands = useCommandsStore();
/** The message field. */
const messageInput = ref<HTMLInputElement | null>(null);
/** The list. */
const list = ref<HTMLElement | null>(null);
/** The dialog box; it takes the focus while the list is empty. */
const dialogBox = ref<HTMLElement | null>(null);
/** The element that had the focus before the dialog opened. */
let returnFocus: HTMLElement | null = null;
/**
* The DOM id of an entry's row.
*
* @param index - its index in the list.
*/
function rowId(index: number): string {
return `lt-stash-${String(index)}`;
}
/**
* The name git gives an entry.
*
* @param entry - the entry.
*/
function refName(entry: StashEntry): string {
return `stash@{${String(entry.index)}}`;
}
/**
* A date for the list: the local date and time, short.
*
* @param iso - ISO 8601 date.
*/
function shortDate(iso: string): string {
const date = new Date(iso);
if (Number.isNaN(date.getTime())) {
return iso;
}
return date.toLocaleString(undefined, { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
}
/**
* What a row shows as its text.
*
* @param entry - the entry.
*/
function entryText(entry: StashEntry): string {
return entry.wip ? t("vcs.stash.wip", { message: entry.message }) : entry.message;
}
/** Closes the dialog. */
function close(): void {
if (stash.open) {
stash.hide();
}
}
watch(
() => stash.open,
(isOpen) => {
if (isOpen) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement ? active : null;
modals.opened("stash", close);
} else {
modals.closed("stash");
returnFocus?.focus();
returnFocus = null;
}
},
);
watch(
() => stash.focusRequest,
async () => {
await nextTick();
if (stash.mode === "stash") {
messageInput.value?.focus();
} else {
dialogBox.value?.focus();
focusList();
}
},
);
/**
* Moves the focus into the list once it has entries, unless something in
* the dialog other than the dialog itself has it.
*/
function focusList(): void {
const active = document.activeElement;
const inside = dialogBox.value?.contains(active) === true && active !== dialogBox.value;
if (stash.open && stash.mode === "list" && (stash.list?.length ?? 0) > 0 && !inside) {
list.value?.focus();
}
}
watch(
() => stash.list,
async () => {
await nextTick();
focusList();
},
);
/** Keeps the selected row in view. */
function scrollSelected(): void {
void nextTick(() => {
const row = list.value?.querySelector<HTMLElement>(`#${rowId(stash.selected)}`);
if (row && typeof row.scrollIntoView === "function") {
row.scrollIntoView({ block: "nearest" });
}
});
}
/**
* Keyboard handling of the dialog: Escape cancels a drop question, else
* closes.
*
* @param event - the key press.
*/
function onDialogKey(event: KeyboardEvent): void {
if (event.key !== "Escape") {
return;
}
event.preventDefault();
event.stopPropagation();
if (stash.confirmDrop !== null) {
stash.cancelDrop();
list.value?.focus();
} else {
close();
}
}
/**
* Keyboard handling of the list.
*
* @param event - the key press.
*/
function onListKey(event: KeyboardEvent): void {
const count = stash.list?.length ?? 0;
const moves: Record<string, number> = { ArrowDown: 1, ArrowUp: -1, Home: -count, End: count };
const delta = moves[event.key];
const entry = stash.current;
if (delta !== undefined) {
stash.move(delta);
scrollSelected();
} else if (event.key === "Enter" && entry) {
void stash.apply(entry, false);
} else if (event.key === "Delete" && entry) {
stash.askDrop(entry);
} else {
return;
}
event.preventDefault();
event.stopPropagation();
}
/** Withdraws the command handlers; filled while mounted. */
let withdraw: (() => void)[] = [];
onMounted(() => {
const enabled = (): boolean => commands.isEnabled("git.stash");
withdraw = [
commands.provide("vcs.stash", { run: () => stash.show("stash"), enabled }),
commands.provide("vcs.showStashes", { run: () => stash.show("list"), enabled }),
];
});
onBeforeUnmount(() => {
for (const fn of withdraw) {
fn();
}
withdraw = [];
});
</script>
<template>
<div
v-if="stash.open"
class="stash"
data-test="stash"
@mousedown.self.prevent="close()"
>
<div
ref="dialogBox"
class="stash__dialog"
tabindex="-1"
role="dialog"
aria-modal="true"
aria-labelledby="lt-stash-title"
@keydown="onDialogKey"
>
<div class="stash__header">
<Archive
:size="14"
aria-hidden="true"
/>
<h2
id="lt-stash-title"
class="stash__title"
>
{{ stash.mode === "stash" ? t("vcs.stash.title") : t("vcs.stash.listTitle") }}
</h2>
<button
type="button"
class="stash__link"
data-test="stash-switch"
@click="stash.show(stash.mode === 'stash' ? 'list' : 'stash')"
>
{{ stash.mode === "stash" ? t("vcs.stash.showList") : t("vcs.stash.newStash") }}
</button>
</div>
<form
v-if="stash.mode === 'stash'"
class="stash__form"
data-test="stash-form"
@submit.prevent="stash.stash()"
>
<label
class="stash__label"
for="lt-stash-message"
>{{ t("vcs.stash.message") }}</label>
<input
id="lt-stash-message"
ref="messageInput"
v-model="stash.message"
class="stash__input"
type="text"
spellcheck="false"
autocomplete="off"
:placeholder="t('vcs.stash.messagePlaceholder')"
:aria-describedby="stash.error !== null ? 'lt-stash-error' : undefined"
data-test="stash-message"
>
<label class="stash__check">
<input
v-model="stash.includeUntracked"
type="checkbox"
data-test="stash-untracked"
>
{{ t("vcs.stash.includeUntracked") }}
</label>
<p class="stash__note">
{{ t("vcs.stash.note") }}
</p>
<p
v-if="stash.error !== null"
id="lt-stash-error"
class="stash__error"
role="alert"
data-test="stash-error"
>
{{ stash.error }}
</p>
<div class="stash__buttons">
<button
type="button"
class="stash__button"
data-test="stash-cancel"
@click="close()"
>
{{ t("common.cancel") }}
</button>
<button
type="submit"
class="stash__button stash__button--primary"
:disabled="stash.busy"
data-test="stash-submit"
>
{{ t("vcs.stash.stash") }}
</button>
</div>
</form>
<template v-else>
<p
v-if="stash.list === null || stash.list.length === 0"
class="stash__hint"
role="status"
data-test="stash-hint"
>
{{ stash.list === null ? (stash.loading ? t("vcs.stash.loading") : "") : t("vcs.stash.empty") }}
</p>
<ul
v-show="(stash.list?.length ?? 0) > 0"
ref="list"
class="stash__list"
role="listbox"
tabindex="0"
:aria-label="t('vcs.stash.listTitle')"
:aria-activedescendant="rowId(stash.selected)"
data-test="stash-list"
@keydown="onListKey"
>
<li
v-for="(entry, i) in stash.list"
:id="rowId(i)"
:key="entry.hash"
class="stash__row"
:class="{ 'stash__row--selected': stash.selected === i }"
role="option"
:aria-selected="stash.selected === i"
:data-index="entry.index"
data-test="stash-row"
@click="stash.selected = i"
@dblclick="stash.apply(entry, false)"
>
<span class="stash__ref">{{ refName(entry) }}</span>
<span class="stash__text">{{ entryText(entry) }}</span>
<span
v-if="entry.branch !== null"
class="stash__detail"
>{{ entry.branch }}</span>
<span class="stash__detail">{{ shortDate(entry.date) }}</span>
</li>
</ul>
<p
v-if="stash.error !== null"
class="stash__error"
role="alert"
data-test="stash-error"
>
{{ stash.error }}
</p>
<div
v-if="stash.confirmDrop !== null"
class="stash__confirm"
role="alertdialog"
aria-labelledby="lt-stash-confirm"
data-test="stash-confirm"
>
<span id="lt-stash-confirm">{{ t("vcs.stash.dropQuestion", { name: refName(stash.confirmDrop) }) }}</span>
<button
type="button"
class="stash__button"
data-test="stash-drop-cancel"
@click="stash.cancelDrop()"
>
{{ t("common.cancel") }}
</button>
<button
type="button"
class="stash__button stash__button--danger"
:disabled="stash.busy"
data-test="stash-drop-confirm"
@click="stash.drop()"
>
{{ t("vcs.stash.drop") }}
</button>
</div>
<div
v-else
class="stash__buttons"
>
<button
type="button"
class="stash__button"
:disabled="stash.busy || stash.current === null"
:title="t('vcs.stash.dropHint')"
data-test="stash-drop"
@click="stash.current && stash.askDrop(stash.current)"
>
{{ t("vcs.stash.drop") }}
</button>
<button
type="button"
class="stash__button"
:disabled="stash.busy || stash.current === null"
:title="t('vcs.stash.popHint')"
data-test="stash-pop"
@click="stash.current && stash.apply(stash.current, true)"
>
{{ t("vcs.stash.pop") }}
</button>
<button
type="button"
class="stash__button stash__button--primary"
:disabled="stash.busy || stash.current === null"
:title="t('vcs.stash.applyHint')"
data-test="stash-apply"
@click="stash.current && stash.apply(stash.current, false)"
>
{{ t("vcs.stash.apply") }}
</button>
</div>
</template>
</div>
</div>
</template>
<style scoped>
.stash {
position: fixed;
inset: 0;
display: flex;
align-items: flex-start;
justify-content: center;
padding-top: 12vh;
z-index: 30;
}
.stash__dialog {
width: min(560px, 92vw);
max-height: 70vh;
display: flex;
flex-direction: column;
gap: 6px;
padding: 10px;
background: var(--lt-bg);
color: var(--lt-fg);
border: 1px solid var(--lt-border);
border-radius: 6px;
outline: none;
overflow: hidden;
}
.stash__header {
display: flex;
align-items: center;
gap: 6px;
color: var(--lt-fg-muted);
}
.stash__title {
margin: 0;
font-size: 1em;
font-weight: 600;
color: var(--lt-fg);
}
.stash__link {
margin-left: auto;
padding: 0;
font: inherit;
color: var(--lt-accent);
background: none;
border: none;
cursor: pointer;
}
.stash__link:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: 1px;
}
.stash__form {
display: flex;
flex-direction: column;
gap: 6px;
}
.stash__input {
padding: 4px 8px;
font: inherit;
color: var(--lt-fg);
background: var(--lt-editor-bg);
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
}
.stash__input:focus-visible {
outline: 2px solid var(--lt-accent);
outline-offset: -1px;
}
.stash__check {
display: inline-flex;
align-items: center;
gap: 4px;
}
.stash__check input {
accent-color: var(--lt-accent);
}
.stash__note,
.stash__hint {
margin: 0;
color: var(--lt-fg-muted);
}
.stash__error {
margin: 0;
max-height: 8em;
overflow-y: auto;
white-space: pre-wrap;
color: var(--lt-error);
}
.stash__list {
flex: 1;
min-height: 0;
margin: 0;
padding: 2px 0;
list-style: none;
overflow-y: auto;
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
outline: none;
}
.stash__list:focus-visible {
box-shadow: inset 0 0 0 1px var(--lt-accent);
}
.stash__row {
display: flex;
align-items: center;
gap: 8px;
padding: 3px 8px;
white-space: nowrap;
cursor: default;
}
.stash__row:hover {
background: color-mix(in srgb, var(--lt-fg) 6%, transparent);
}
.stash__row--selected,
.stash__row--selected:hover {
background: var(--lt-editor-selection-bg);
}
.stash__ref {
flex: none;
font-family: var(--lt-font-mono);
color: var(--lt-fg-muted);
}
.stash__text {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.stash__detail {
flex: none;
color: var(--lt-fg-muted);
}
.stash__row--selected .stash__ref,
.stash__row--selected .stash__detail {
color: var(--lt-fg);
}
.stash__buttons,
.stash__confirm {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
}
.stash__confirm span {
margin-right: auto;
}
.stash__button {
padding: 2px 14px;
font: inherit;
color: var(--lt-fg);
background: transparent;
border: 1px solid var(--lt-border);
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.stash__button--primary {
background: color-mix(in srgb, var(--lt-accent) 18%, transparent);
border-color: var(--lt-accent);
}
.stash__button--danger {
background: color-mix(in srgb, var(--lt-error) 18%, transparent);
border-color: var(--lt-error);
}
.stash__button:disabled {
opacity: 0.5;
cursor: default;
}
.stash__button:focus-visible {
outline: 2px solid var(--lt-fg);
outline-offset: 1px;
}
</style>

View file

@ -0,0 +1,380 @@
/**
* The stash dialog's state (M4.9): stash the local changes, list the
* stash, apply, pop or drop an entry.
*
* - **Stash:** a message (optional) and "Include untracked files". Dirty
* buffers are saved first (`flushDirty`), so git stashes what the editor
* shows and the editor reloads the reset files instead of keeping
* unsaved edits on top of them; a save that failed cancels the stash.
* Then `git.stash {message, includeUntracked}`.
* - **List:** `git.stashList` each time the list shows and after every
* change. Apply and pop save dirty buffers first for the same reason,
* then run `git.stashApply {index, pop, hash}`; drop asks first, then
* `git.stashDrop {index, hash}`. The hash makes the engine refuse when
* the stash changed since the list was read.
* - **Refusals** (nothing to stash, conflicts, overwritten files, a changed
* stash) stay in the dialog as git's and the engine's sentence, so they
* can be read next to the list; success closes the stash form or keeps
* the list, with an info toast.
* - **Untrusted input:** the list comes from git through the engine;
* malformed entries are dropped ({@link toStashes}).
*/
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
import { t } from "../../../i18n";
import { runWaiting, type JsonValue } from "../../../ipc";
import { useAutosaveStore } from "../../../stores/autosave";
import { useNotificationsStore } from "../../../stores/notifications";
/** Most entries kept from `git.stashList` (the engine sends at most 1,000). */
export const MAX_STASHES = 1000;
/** One stash entry. */
export interface StashEntry {
/** Its position: 0 is `stash@{0}`, the newest. */
index: number;
/** The stash commit's hash. */
hash: string;
/** The branch it was made on, if known. */
branch: string | null;
/** The message, or git's `<hash> <subject>` for a "WIP" entry. */
message: string;
/** Whether it was made without a message. */
wip: boolean;
/** When it was made, ISO 8601. */
date: string;
}
/** Which part of the dialog shows. */
export type StashMode = "stash" | "list";
/**
* Reads one entry of `git.stashList`.
*
* @param raw - untrusted value.
* @returns the entry, or null when the index or hash is missing.
*/
export function toStash(raw: unknown): StashEntry | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const r = raw as Record<string, unknown>;
if (typeof r.index !== "number" || !Number.isInteger(r.index) || r.index < 0) {
return null;
}
if (typeof r.hash !== "string" || r.hash === "") {
return null;
}
return {
index: r.index,
hash: r.hash,
branch: typeof r.branch === "string" && r.branch !== "" ? r.branch : null,
message: typeof r.message === "string" ? r.message : "",
wip: r.wip === true,
date: typeof r.date === "string" ? r.date : "",
};
}
/**
* Reads `git.stashList`'s value.
*
* @param raw - untrusted value.
* @returns the entries in index order, at most {@link MAX_STASHES}, or null
* when the value has no `stashes` array.
*/
export function toStashes(raw: unknown): StashEntry[] | null {
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
return null;
}
const list = (raw as Record<string, unknown>).stashes;
if (!Array.isArray(list)) {
return null;
}
const out: StashEntry[] = [];
for (const item of list.slice(0, MAX_STASHES)) {
const entry = toStash(item);
if (entry !== null) {
out.push(entry);
}
}
return out.sort((a, b) => a.index - b.index);
}
/**
* An engine error's text for people.
*
* @param message - the error message.
*/
function reasonOf(message: string): string {
return message.trim() === "" ? "?" : message.trim();
}
/** The Stash store. */
export const useStashStore = defineStore("stash", () => {
const notifications = useNotificationsStore();
/** Whether the dialog is open. */
const open = ref(false);
/** Which part of the dialog shows. */
const mode = ref<StashMode>("stash");
/** The message typed for a new entry. */
const message = ref("");
/** Whether untracked files are stashed too. */
const includeUntracked = ref(false);
/** The last list read; null before it arrived. */
const list = shallowRef<StashEntry[] | null>(null);
/** Whether `git.stashList` runs. */
const loading = ref(false);
/** Index in {@link list} of the selected entry. */
const selected = ref(0);
/** Whether a stash, apply, pop or drop runs. */
const busy = ref(false);
/** The last refusal or read failure, shown in the dialog. */
const error = ref<string | null>(null);
/** The entry waiting for the drop to be confirmed. */
const confirmDrop = ref<StashEntry | null>(null);
/** Bumped when the dialog's first field should take the focus. */
const focusRequest = ref(0);
/** The selected entry. */
const current = computed(() => list.value?.[selected.value] ?? null);
/** Counts loads, so an older answer never replaces a newer one. */
let loads = 0;
/** Reads `git.stashList`. */
async function load(): Promise<void> {
loads += 1;
const mine = loads;
loading.value = true;
const result = await runWaiting("git.stashList");
if (mine !== loads) {
return;
}
loading.value = false;
if (!result.ok) {
error.value = reasonOf(result.error.message);
return;
}
const next = toStashes(result.value);
if (next === null) {
error.value = "unexpected result of git.stashList";
return;
}
list.value = next;
selected.value = Math.min(Math.max(0, selected.value), Math.max(0, next.length - 1));
}
/**
* Opens the dialog.
*
* @param as - `stash` for the form, `list` for the entries.
* @returns when the list arrived (`list`), at once otherwise.
*/
function show(as: StashMode): Promise<void> {
open.value = true;
mode.value = as;
error.value = null;
confirmDrop.value = null;
focusRequest.value += 1;
if (as === "stash") {
message.value = "";
return Promise.resolve();
}
selected.value = 0;
return load();
}
/** Closes the dialog. */
function hide(): void {
open.value = false;
confirmDrop.value = null;
}
/**
* Moves the selection by `delta` entries, clamped.
*
* @param delta - entries to move; positive is down.
*/
function move(delta: number): void {
const count = list.value?.length ?? 0;
confirmDrop.value = null;
selected.value = Math.min(Math.max(0, selected.value + delta), Math.max(0, count - 1));
}
/**
* Saves every dirty buffer.
*
* @returns whether every buffer was saved; otherwise the reason is in
* {@link error}.
*/
async function saveFirst(): Promise<boolean> {
const flushed = await useAutosaveStore().flushDirty();
if (flushed.error !== null || flushed.failed.length > 0) {
error.value = t("vcs.stash.notSaved");
return false;
}
return true;
}
/**
* Runs a stash command, keeping its refusal in {@link error}.
*
* @param command - the command id.
* @param params - its params.
* @returns its value, or null when it failed.
*/
async function mutate(command: string, params: JsonValue): Promise<unknown> {
const result = await runWaiting(command, params);
if (!result.ok) {
error.value = reasonOf(result.error.message);
return null;
}
error.value = null;
return result.value;
}
/**
* Saves dirty buffers, then stashes the local changes with the form's
* message and flag. Closes the dialog when it worked.
*
* @returns whether an entry was made.
*/
async function stash(): Promise<boolean> {
if (busy.value) {
return false;
}
busy.value = true;
try {
error.value = null;
if (!(await saveFirst())) {
return false;
}
const params: Record<string, JsonValue> = { includeUntracked: includeUntracked.value };
if (message.value.trim() !== "") {
params.message = message.value;
}
const value = await mutate("git.stash", params);
if (value === null) {
return false;
}
const entry =
typeof value === "object" && !Array.isArray(value) ? toStash((value as Record<string, unknown>).entry) : null;
notifications.notify({
level: "info",
messageKey: "notification.vcs.stashed",
params: { message: entry?.message ?? "" },
});
message.value = "";
hide();
return true;
} finally {
busy.value = false;
}
}
/**
* Saves dirty buffers, then applies an entry; with `pop` it is dropped
* when it applied cleanly. The list is read again either way (a
* conflicted pop keeps the entry).
*
* @param entry - the entry.
* @param pop - drop it afterwards.
* @returns whether it applied.
*/
async function apply(entry: StashEntry, pop: boolean): Promise<boolean> {
if (busy.value) {
return false;
}
busy.value = true;
confirmDrop.value = null;
try {
error.value = null;
if (!(await saveFirst())) {
return false;
}
const value = await mutate("git.stashApply", { index: entry.index, pop, hash: entry.hash });
await load();
if (value === null) {
return false;
}
notifications.notify({
level: "info",
messageKey: pop ? "notification.vcs.stashPopped" : "notification.vcs.stashApplied",
params: { name: `stash@{${String(entry.index)}}` },
});
return true;
} finally {
busy.value = false;
}
}
/**
* Asks to drop an entry: {@link confirmDrop} holds it until
* {@link drop} or {@link cancelDrop}.
*
* @param entry - the entry.
*/
function askDrop(entry: StashEntry): void {
error.value = null;
confirmDrop.value = entry;
}
/** Forgets the drop question. */
function cancelDrop(): void {
confirmDrop.value = null;
}
/**
* Drops the entry waiting in {@link confirmDrop}.
*
* @returns whether it was dropped.
*/
async function drop(): Promise<boolean> {
const entry = confirmDrop.value;
if (entry === null || busy.value) {
return false;
}
busy.value = true;
confirmDrop.value = null;
try {
const value = await mutate("git.stashDrop", { index: entry.index, hash: entry.hash });
await load();
if (value === null) {
return false;
}
notifications.notify({
level: "info",
messageKey: "notification.vcs.stashDropped",
params: { name: `stash@{${String(entry.index)}}` },
});
return true;
} finally {
busy.value = false;
}
}
return {
open,
mode,
message,
includeUntracked,
list,
loading,
selected,
busy,
error,
confirmDrop,
focusRequest,
current,
load,
show,
hide,
move,
stash,
apply,
askDrop,
cancelDrop,
drop,
};
});

View file

@ -38,6 +38,8 @@
"command.vcs.showDiff": "Show Diff",
"command.vcs.showHistory": "Show History",
"command.vcs.showLog": "Log",
"command.vcs.showStashes": "Stashes…",
"command.vcs.stash": "Stash Changes…",
"command.view.toggleProjectTree": "Show or Hide Project",
"command.view.toggleStructure": "Show or Hide Structure",
"common.cancel": "Cancel",
@ -190,6 +192,10 @@
"notification.vcs.pushedUpstream": "Pushed {branch} to {remote} and set it as the upstream",
"notification.vcs.remoteCancelled": "Git operation cancelled",
"notification.vcs.resolved": "Marked {path} as resolved",
"notification.vcs.stashApplied": "Applied {name}",
"notification.vcs.stashDropped": "Dropped {name}",
"notification.vcs.stashPopped": "Applied and dropped {name}",
"notification.vcs.stashed": "Stashed the local changes: {message}",
"notification.vfs.pumpFailed": "Applying changes on disk failed: {reason}",
"notification.watch.failed": "Lutra stopped watching the project for changes on disk: {reason}",
"palette.label": "Command palette",
@ -467,6 +473,26 @@
"vcs.remotes.url": "URL of the new remote",
"vcs.remotes.urlEmpty": "Enter the new URL.",
"vcs.remotes.urlOf": "URL of {name}",
"vcs.stash.apply": "Apply",
"vcs.stash.applyHint": "Apply the selected entry and keep it (Enter)",
"vcs.stash.drop": "Drop",
"vcs.stash.dropHint": "Delete the selected entry (Delete)",
"vcs.stash.dropQuestion": "Drop {name}? It cannot be restored.",
"vcs.stash.empty": "The stash is empty.",
"vcs.stash.includeUntracked": "Include untracked files",
"vcs.stash.listTitle": "Stashes",
"vcs.stash.loading": "Reading the stash…",
"vcs.stash.message": "Message",
"vcs.stash.messagePlaceholder": "Optional; Git names the entry after the last commit without one",
"vcs.stash.newStash": "Stash changes…",
"vcs.stash.notSaved": "Nothing was done: not every file could be saved first.",
"vcs.stash.note": "Every local change of the repository is set aside and the files go back to the last commit. Unsaved files are saved first.",
"vcs.stash.pop": "Pop",
"vcs.stash.popHint": "Apply the selected entry and drop it if it applies cleanly",
"vcs.stash.showList": "Show stashes…",
"vcs.stash.stash": "Stash",
"vcs.stash.title": "Stash Changes",
"vcs.stash.wip": "WIP: {message}",
"vcs.state.added": "added",
"vcs.state.conflicted": "conflicted",
"vcs.state.copied": "copied",

View file

@ -86,6 +86,10 @@ const RUNTIME_KEYS = new Set([
"notification.vcs.pushedUpstream",
"notification.vcs.remoteCancelled",
"notification.vcs.resolved",
"notification.vcs.stashApplied",
"notification.vcs.stashDropped",
"notification.vcs.stashPopped",
"notification.vcs.stashed",
"notification.settings.corrupt",
"notification.settings.corruptNotMoved",
"notification.settings.unavailable",

View file

@ -293,6 +293,8 @@ describe("AppMenu", () => {
"vcs.resolveConflicts",
"vcs.showDiff",
"vcs.showHistory",
"vcs.stash",
"vcs.showStashes",
"app.about",
]);
const close = document.querySelector("[data-command='buffer.close']");

View file

@ -294,6 +294,8 @@ describe("CommandPalette", () => {
"vcs.showHistory",
"view.toggleProjectTree",
"view.toggleStructure",
"vcs.stash",
"vcs.showStashes",
"terminal.open",
]);
const quit = wrapper.find("[data-command='app.quit']");

328
ui/tests/vcs/Stash.test.ts Normal file
View file

@ -0,0 +1,328 @@
/**
* Tests of the stash feature (M4.9): reading an untrusted `git.stashList`,
* the dialog's form (message, untracked flag, `flushDirty` first, a failed
* save, git's refusal kept in the dialog), the list (entries, keyboard,
* apply, pop with a conflict, drop after the question, Escape), the UI
* commands `vcs.stash` and `vcs.showStashes` and the Changes window's
* buttons. The engine is a fake behind the mocked Tauri `invoke` and
* `listen`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
const listen = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
vi.mock("@tauri-apps/api/event", () => ({ listen }));
import { useModalsStore } from "../../src/commands/modals";
import { useCommandsStore } from "../../src/commands/store";
import { UI_COMMANDS } from "../../src/commands/uiCommands";
import ChangesToolWindow from "../../src/components/vcs/changes/ChangesToolWindow.vue";
import { useChangesStore } from "../../src/components/vcs/changes/changes";
import StashDialog from "../../src/components/vcs/stash/StashDialog.vue";
import { MAX_STASHES, toStash, toStashes, useStashStore } from "../../src/components/vcs/stash/stash";
import { useNotificationsStore } from "../../src/stores/notifications";
/** A recorded engine call. */
interface Call {
/** Command id. */
command: string;
/** Its params. */
params: Record<string, unknown>;
}
/** Every engine call, in order. */
let calls: Call[];
/** What `git.stashList` answers. */
let stashes: unknown[];
/** Errors to throw, by command id. */
let failures: Record<string, { code: string; message: string }>;
/** What `file.saveAll` answers. */
let saveAll: unknown;
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components, unmounted after each test. */
let mounted: VueWrapper[];
/** Two entries as the engine sends them. */
const ENTRIES = [
{ index: 0, hash: "aaaa1111", branch: "main", message: "41aa1cf init", wip: true, date: "2026-10-28T18:08:36+01:00" },
{ index: 1, hash: "bbbb2222", branch: "feature/x", message: "half done", wip: false, date: "2026-10-27T10:00:00Z" },
];
/**
* The calls of a command.
*
* @param command - the command id.
*/
function callsOf(command: string): Call[] {
return calls.filter((c) => c.command === command);
}
/** Mounts the dialog with the command store started. */
async function mountDialog(): Promise<VueWrapper> {
const wrapper = mount(StashDialog, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(wrapper);
await useCommandsStore(pinia).start();
await flushPromises();
return wrapper;
}
/**
* The texts of the list's rows.
*
* @param wrapper - the dialog.
*/
function rows(wrapper: VueWrapper): string[] {
return wrapper.findAll("[data-test=stash-row]").map((row) => row.text());
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
calls = [];
mounted = [];
failures = {};
stashes = ENTRIES.map((e) => ({ ...e }));
saveAll = { saved: [], failed: [], skipped: [] };
Element.prototype.scrollIntoView = () => undefined;
invoke.mockReset();
listen.mockReset();
listen.mockImplementation(() => Promise.resolve(() => undefined));
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([
{ id: "git.status", label: "Git Status", enabled: true },
{ id: "git.stash", label: "Git Stash", enabled: true },
]);
}
if ((cmd !== "engine_execute" && cmd !== "engine_execute_waiting") || !args) {
return Promise.resolve(null);
}
calls.push({ command: args.command, params: args.params });
const failure = failures[args.command];
if (failure) {
return Promise.reject(Object.assign(new Error(failure.message), failure));
}
switch (args.command) {
case "git.status":
return Promise.resolve({ available: true, repo: { root: "C:/p", branch: "main", detached: false }, files: [] });
case "git.stashList":
return Promise.resolve({ stashes });
case "git.stash":
return Promise.resolve({ entry: { ...ENTRIES[1], index: 0, message: typeof args.params.message === "string" ? args.params.message : "" } });
case "file.saveAll":
return Promise.resolve(saveAll);
default:
return Promise.resolve({});
}
});
});
afterEach(() => {
for (const wrapper of mounted) {
wrapper.unmount();
}
useChangesStore(pinia).stop();
document.body.innerHTML = "";
});
describe("reading git.stashList", () => {
it("drops malformed entries, sorts by index and caps the count", () => {
expect(
toStashes({
stashes: [
{ index: 1, hash: "b", branch: "", message: 5, wip: "yes" },
{ index: 0, hash: "a", branch: "main", message: "m", wip: true, date: "d" },
{ index: -1, hash: "x" },
{ index: 2.5, hash: "y" },
{ index: 3, hash: "" },
null,
"z",
],
}),
).toEqual([
{ index: 0, hash: "a", branch: "main", message: "m", wip: true, date: "d" },
{ index: 1, hash: "b", branch: null, message: "", wip: false, date: "" },
]);
expect(toStashes(null)).toBeNull();
expect(toStashes({ stashes: "no" })).toBeNull();
expect(toStash([1])).toBeNull();
const many = Array.from({ length: MAX_STASHES + 5 }, (_, i) => ({ index: i, hash: `h${String(i)}` }));
expect(toStashes({ stashes: many })).toHaveLength(MAX_STASHES);
});
});
describe("the stash form", () => {
it("saves first, then stashes with the message and the untracked flag", async () => {
const wrapper = await mountDialog();
await useCommandsStore(pinia).execute("vcs.stash");
await flushPromises();
expect(useModalsStore(pinia).current).toBe("stash");
expect(document.activeElement).toBe(wrapper.get("[data-test=stash-message]").element);
await wrapper.get("[data-test=stash-message]").setValue("half done");
await wrapper.get("[data-test=stash-untracked]").setValue(true);
await wrapper.get("[data-test=stash-form]").trigger("submit");
await flushPromises();
const order = calls.map((c) => c.command).filter((c) => c === "file.saveAll" || c === "git.stash");
expect(order).toEqual(["file.saveAll", "git.stash"]);
expect(callsOf("git.stash")[0]?.params).toEqual({ message: "half done", includeUntracked: true });
expect(wrapper.find("[data-test=stash]").exists()).toBe(false);
const toast = useNotificationsStore(pinia).toasts.at(-1);
expect(toast?.text).toContain("half done");
expect(useModalsStore(pinia).current).toBeNull();
});
it("leaves out a blank message", async () => {
const wrapper = await mountDialog();
await useStashStore(pinia).show("stash");
await flushPromises();
await wrapper.get("[data-test=stash-message]").setValue(" ");
await wrapper.get("[data-test=stash-submit]").trigger("click");
await flushPromises();
expect(callsOf("git.stash")[0]?.params).toEqual({ includeUntracked: false });
});
it("keeps git's refusal in the dialog", async () => {
failures["git.stash"] = { code: "failed", message: "There are no local changes to stash." };
const wrapper = await mountDialog();
await useStashStore(pinia).show("stash");
await flushPromises();
await wrapper.get("[data-test=stash-form]").trigger("submit");
await flushPromises();
expect(wrapper.get("[data-test=stash-error]").text()).toBe("There are no local changes to stash.");
expect(wrapper.find("[data-test=stash]").exists()).toBe(true);
});
it("cancels when a save fails", async () => {
saveAll = { saved: [], failed: [{ id: 1, path: "a.php", message: "denied" }], skipped: [] };
const wrapper = await mountDialog();
await useStashStore(pinia).show("stash");
await flushPromises();
await wrapper.get("[data-test=stash-form]").trigger("submit");
await flushPromises();
expect(callsOf("git.stash")).toHaveLength(0);
expect(wrapper.get("[data-test=stash-error]").text()).toContain("could be saved");
});
it("closes on Escape and gives the focus back", async () => {
const before = document.createElement("button");
document.body.append(before);
before.focus();
const wrapper = await mountDialog();
await useStashStore(pinia).show("stash");
await flushPromises();
await wrapper.get("[data-test=stash-message]").trigger("keydown", { key: "Escape" });
await flushPromises();
expect(wrapper.find("[data-test=stash]").exists()).toBe(false);
expect(document.activeElement).toBe(before);
});
});
describe("the list", () => {
it("shows the entries and applies with Enter after saving", async () => {
const wrapper = await mountDialog();
await useCommandsStore(pinia).execute("vcs.showStashes");
await flushPromises();
const texts = rows(wrapper);
expect(texts).toHaveLength(2);
expect(texts[0]).toContain("stash@{0}");
expect(texts[0]).toContain("WIP: 41aa1cf init");
expect(texts[1]).toContain("half done");
expect(texts[1]).toContain("feature/x");
const list = wrapper.get("[data-test=stash-list]");
expect(document.activeElement).toBe(list.element);
await list.trigger("keydown", { key: "ArrowDown" });
await list.trigger("keydown", { key: "Enter" });
await flushPromises();
expect(callsOf("file.saveAll")).toHaveLength(1);
expect(callsOf("git.stashApply")[0]?.params).toEqual({ index: 1, pop: false, hash: "bbbb2222" });
expect(callsOf("git.stashList")).toHaveLength(2);
expect(useNotificationsStore(pinia).toasts.at(-1)?.text).toBe("Applied stash@{1}");
});
it("shows a conflicted pop's message and reads the list again", async () => {
failures["git.stashApply"] = {
code: "failed",
message: "The stash was applied with conflicts in 1 file. Resolve them in the Changes window.",
};
const wrapper = await mountDialog();
await useStashStore(pinia).show("list");
await flushPromises();
await wrapper.get("[data-test=stash-pop]").trigger("click");
await flushPromises();
expect(callsOf("git.stashApply")[0]?.params).toEqual({ index: 0, pop: true, hash: "aaaa1111" });
expect(wrapper.get("[data-test=stash-error]").text()).toContain("conflicts in 1 file");
expect(callsOf("git.stashList")).toHaveLength(2);
expect(rows(wrapper)).toHaveLength(2);
});
it("drops only after the question, and Escape cancels the question first", async () => {
const wrapper = await mountDialog();
await useStashStore(pinia).show("list");
await flushPromises();
const list = wrapper.get("[data-test=stash-list]");
await list.trigger("keydown", { key: "Delete" });
expect(wrapper.get("[data-test=stash-confirm]").text()).toContain("Drop stash@{0}?");
expect(callsOf("git.stashDrop")).toHaveLength(0);
await list.trigger("keydown", { key: "Escape" });
expect(wrapper.find("[data-test=stash-confirm]").exists()).toBe(false);
expect(wrapper.find("[data-test=stash]").exists()).toBe(true);
await wrapper.get("[data-test=stash-drop]").trigger("click");
stashes = [ENTRIES[1]].map((e) => ({ ...e, index: 0 }));
await wrapper.get("[data-test=stash-drop-confirm]").trigger("click");
await flushPromises();
expect(callsOf("git.stashDrop")[0]?.params).toEqual({ index: 0, hash: "aaaa1111" });
expect(rows(wrapper)).toHaveLength(1);
expect(callsOf("file.saveAll")).toHaveLength(0);
});
it("says when the stash is empty and switches to the form", async () => {
stashes = [];
const wrapper = await mountDialog();
await useStashStore(pinia).show("list");
await flushPromises();
expect(wrapper.get("[data-test=stash-hint]").text()).toBe("The stash is empty.");
expect(wrapper.get("[data-test=stash-apply]").attributes("disabled")).toBeDefined();
await wrapper.get("[data-test=stash-switch]").trigger("click");
await flushPromises();
expect(wrapper.find("[data-test=stash-form]").exists()).toBe(true);
});
it("shows a failed read", async () => {
failures["git.stashList"] = { code: "failed", message: "fatal: bad object" };
const wrapper = await mountDialog();
await useStashStore(pinia).show("list");
await flushPromises();
expect(wrapper.get("[data-test=stash-error]").text()).toBe("fatal: bad object");
});
});
describe("commands and entry points", () => {
it("registers vcs.stash and vcs.showStashes in the Git menu without shortcuts", () => {
for (const id of ["vcs.stash", "vcs.showStashes"]) {
const spec = UI_COMMANDS.find((c) => c.id === id);
expect(spec?.menuPath?.startsWith("Git/")).toBe(true);
expect(spec?.defaultShortcut).toBeUndefined();
}
});
it("opens the dialog from the Changes window's buttons", async () => {
useChangesStore(pinia).start();
const dialog = await mountDialog();
const changes = mount(ChangesToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(changes);
await flushPromises();
await changes.get("[data-test=changes-stash]").trigger("click");
await flushPromises();
expect(dialog.find("[data-test=stash-form]").exists()).toBe(true);
useStashStore(pinia).hide();
await flushPromises();
await changes.get("[data-test=changes-stashes]").trigger("click");
await flushPromises();
expect(rows(dialog)).toHaveLength(2);
});
});