From e23811ce1e9a83ddf37898cc7d0f53fe980e073a Mon Sep 17 00:00:00 2001 From: Christian Lauinger Date: Fri, 13 Nov 2026 20:18:56 +0100 Subject: [PATCH 1/3] fix(rebase): tolerate clean submodule commit drift Use a temporary in-memory index during replay commits so an unchanged submodule checkout does not block rebase or Continue. Keep normal dirty-file checks and restore the repository index on every exit path. Add regression coverage for pull modes, older-client recovery, conflicts, abort, hooks, gitlink resolution and failed commits. Fixes #89. --- CHANGELOG.md | 3 + CLAUDE.md | 40 ++- apps/desktop/src-tauri/src/core/branch.rs | 66 +++- apps/desktop/src-tauri/tests/git_engine.rs | 375 +++++++++++++++++++++ 4 files changed, 475 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c043d8e..95d981ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,9 @@ All notable changes to AngKorGit are documented here. The format follows `git merge` does, so `git diff ORIG_HEAD HEAD` shows what a pull brought in. ### Fixed +- **Pull with rebase handles upstream submodule updates.** Local commits now replay + when the upstream changes a submodule's recorded commit. Continue rebase also + recovers a rebase stopped by this problem in an older version. (#89) - **Discarding staged changes writes the index once and leaves other files alone.** A file whose name contains `[`, `]`, `*` or `?` no longer resets files the name happens to match. The whole batch takes Git's index lock and stops without diff --git a/CLAUDE.md b/CLAUDE.md index 20d73c8c..d5544822 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4289,11 +4289,9 @@ update CLAUDE.md or docs/ — never the code. submodule's configured `ignore` rule, so `ignore = dirty` in .gitmodules lets an edited submodule through (round seven). TRAP: libgit2's repo.statuses() does NOT apply a submodule's `ignore = dirty` — it reports WT_MODIFIED where `git status` is clean — so - the original statuses()-only check never honoured it either; only submodule_status does. FOUND WHILE TESTING THAT, - NOT FIXED: libgit2's rebase.commit() fails with GIT_EUNMERGED "unstaged changes exist in - workdir" when onto moves a submodule's recorded commit, because the replay never updates - the submodule folder; `git rebase` ignores submodules there. So a Pull with rebase whose - upstream bumped a submodule fails in the app — pre-existing on main. SKIP HOOKS SURVIVES A PAUSE: a rebase started with hooks skipped + the original statuses()-only check never honoured it either; only submodule_status does. + The replay-time submodule drift failure found while testing this is fixed by #89 + (G59). SKIP HOOKS SURVIVES A PAUSE: a rebase started with hooks skipped (Pull without hooks with pull.rebase) writes `/rebase-merge/angkorgit-skip-hooks` RIGHT AFTER repo.rebase() initializes, before any replay (aborting the rebase if the write fails); rebase_continue_with_hooks reads it before anything else and skips its @@ -4574,11 +4572,41 @@ update CLAUDE.md or docs/ — never the code. rewrites the same two functions: the change is two call sites plus helpers so its rebase stays mechanical. +- **G59 — rebase commits must tolerate a submodule left at its previous commit** + (issue #89, 2026-11-13): libgit2 1.9.6's rebase_commit_merge calls + rebase_ensure_not_dirty(false, true), whose index-to-workdir diff hard-codes + SubmoduleIgnore::Untracked. After onto changes a gitlink, the submodule folder + still points at the old commit and every replay commit fails with GIT_EUNMERGED + "unstaged changes exist in workdir". Configuring ignore = all cannot override it, + and the app's submodule::synced runs only after an Ok outcome, too late to help. + branch::commit_rebase_step wraps all three replay commit sites (initial rebase, + Continue's current step and its remaining loop). For initialized submodules with + commit drift but no staged or unstaged tracked edits inside, it copies the index + into a pathless in-memory Index, preserving entry IDs, modes, stages and flags, + and adds IndexEntryFlag::VALID only to their stage-zero gitlinks. The repository + handle uses that index only during rebase.commit; RebaseCommitIndex restores the + original index on scope exit, including errors. libgit2's diff honours VALID; + ordinary files and dirty submodules still undergo its normal worktree checks. + The temporary index cannot write to disk, and no config, checkout or real index + flags are changed. Keep libgit2's own commit path: it preserves authors/messages, + Applied handling, detached HEAD/reflog updates and the rewritten mapping used by + notes and post-rewrite. Do not hold the temporary index across next(), finish(), + hooks or #88's reapply_stopped_step; they must see the original repository index. + Raw engine rebase/pull/continue leave the submodule folder where it was; app + wrappers retain G53's existing follow rule, including after a conflict pause + (the conflicts outcome is Ok). An intentionally moved submodule during a pause + stays there on Continue. Older-client rebases stuck at commit() also resume. + Integration coverage includes explicit/configured pull, multiple replay commits, + legacy recovery, normal-file and gitlink conflicts, Continue/abort, already-applied + steps, #88's blocked replay, untracked submodule files, edited/staged submodule + files, HEAD.lock failure, unchanged disk index on failure, no leaked flags, app + synchronization, post-hook arguments/mappings and skipped hooks across a pause. + ## 9. Testing map | Suite | Location | Coverage | | --- | --- | --- | -| Rust integration (195 macOS + 1 clone; platform cases in CI) | `apps/desktop/src-tauri/tests/git_engine.rs`, `tests/clone_hooks.rs` (own binary, sets HOME) | stage/commit/history, amend, branch/merge(ff+normal+conflict+message), branch-over-tag ref resolution (merge/rebase/history filter), ff-merge preserving uncommitted changes, drag-merge sequence (checkout target → merge source), no-ff merge commit when ff possible, can-fast-forward only when strictly behind, merge message available only during conflicted merge, interactive rebase (reorder/drop + range listing, squash/reword, conflict aborts untouched, invalid-plan rejection), a rebase aborted during post-checkout returns without replaying commits or running post-rewrite, a rebase step stopped by an untracked file names that file and commit, Continue re-applies the stopped commit so every commit survives (issue #88, same history as `git rebase --continue`), a Continue while the file is still in the way stops again with the history untouched and can be retried, and a re-applied step that conflicts pauses with markers and a conflict entry, then completes after resolution, file history lists only touching commits + paginates with skip, conflict resolve, stash (whole tree + selected paths incl. an untracked-only pick, a staged pick that leaves other staged files alone and pops with a dirty index, a staged-new pick removed and restored, git CLI agreeing on stash list/show; stash_files lists tracked + untracked entries with source_oid; stash_restore_files restores chosen files incl. an untracked one and a deletion, keeps the stash, rejects unknown paths), remote-branch checkout (stale local fast-forwarded with an untracked file preserved + upstream set, diverged local kept), tags, cherry-pick (plain keeps the message verbatim; record-origin output byte-equal to `git cherry-pick -x` for plain and trailer-block messages; many: in-order with per-commit origin lines, first conflict stops the run with progress counts), revert, reset (+ unknown-mode error), history pagination with and without filters, history position lookup by full + short hash, history search positions (case-insensitive text, hash prefix, none, blank, author alone, text + author, unknown author), stashes listed in the default walk as single-parent commits with a stash decoration while their index/untracked helper commits stay hidden and a branch-filtered walk omits them, broken-symlink staging (unix), diff hunks + whole-file context, unstage_all/discard_all, discard_staged_file/all (HEAD restored for index + worktree, staged-new file deleted, other staged files untouched; a name with glob characters leaves the files it would match staged; a held index.lock changes nothing and the retry after it is gone discards and leaves no lock; either name of a staged rename restores the original; a file that replaced a folder gives the folder back), line+hunk ops on files without trailing newline, git-CLI interop, commit signing (SSH sign verified via `git verify-commit`, unsigned without config, amend re-signs, merge commit signed, failure blocks the commit and leaves HEAD/index untouched), PR checkout (fork-style refs/pull fetch creates + updates the local branch and re-runs cleanly, diverged local branch refused with HEAD untouched, same-repo tracking checkout sets the upstream), ref fingerprint (tracks refs/HEAD, ignores plain file edits), commit file lists (per-file counts without hunks), single-file commit diff scoped by pathspec, comparing two commits lists the net change exactly like `git diff --name-status A B` (a file changed and changed back is absent, a rename keeps its old path, counts and hunk lines are the net ones, swapping the commits flips additions into deletions) and works across two branches, worktrees (add lists + checks out the branch and reports is_worktree/main_path from inside the linked folder, new branch from a base commit + duplicate refused, branch held elsewhere refused, checkout of a held branch refused with HEAD untouched, dirty remove refused unless forced, prune of a deleted folder, ref fingerprint changes on add, `git worktree list --porcelain` reports the engine-created worktree and `git status` runs clean inside it), discover refuses a missing path instead of walking to the parent repo, push reports up_to_date without contacting the remote when the tip equals the tracking ref while `git push` prints Everything up-to-date, and pushes again after a new commit, push with tags lands a local tag on a bare remote through named refspecs, pull with mode rebase / configured pull.rebase keeps history linear while mode merge creates a merge commit, blame attributes lines to their commits and marks an uncommitted edit, blames at a revision and at `^`, an uncommitted edit inside a committed block keeps the author on both split halves (the G44 crash), untracked/staged-new files and paths missing from a commit get explicit errors, staging and unstaging a later hunk of a multi-hunk file leaves the other hunk alone, remote_add registers a remote that list and fetch then use while a duplicate or blank name is refused, reword of HEAD changes only the message (tree + author lines byte-equal, dirty worktree and staged file untouched), reword of an earlier commit rewrites the commits above it and returns the reworded commit's new oid while a dirty tree is refused, unpushed lists only commits missing from every refs/remotes ref, tree_files lists every path at a commit while commit_files still lists the two changed ones, index_files lists tracked and staged-new paths but no untracked file, file_contents reads a file at a commit and on disk as context lines with status unchanged, errors for a path missing from the commit and flags a NUL-byte file binary, the folder scan finds repos at any depth and repos inside repos while skipping node_modules, hidden folders, an empty `.git` folder and anything past the runaway depth guard, returns the discover-shaped path, a root that is itself a repo plus its nested repo, and an error for a missing folder, stage_files/unstage_files apply many paths in one index write, commit refuses an index that matches HEAD (HEAD and worktree untouched) and an empty first commit while a merge resolved to HEAD's tree still commits with two parents, submodules (a synced pull checks an in-sync submodule out at the bumped commit — fetching it — and leaves `git status --porcelain` empty, a synced checkout takes it back with the branch, the group Pull all does the same, a submodule with a local commit or an edited file stays where it is, an unsynced pull reports the drift as FileStatus.submodule recorded/checkedOut and discard_file, discard_all and submodule_update by path all check out the recorded commit, a submodule with only edited files reports no drift), pull_preview is empty when up to date or simply behind, lists the uncommitted files a pull would overwrite (and the real pull then fails), predicts the merge conflict a real pull then reports while leaving HEAD, status and the state files untouched, follows pull.rebase and stops at the first conflicting commit, catches a rebase conflict a merge would not have, reports none for edits that merge cleanly in both modes, and is None without an upstream or on a detached HEAD, commit hooks (a passing pre-commit commits and sees GIT_INDEX_FILE, a failing one blocks with its exit code and output as hook_failed detail and HEAD unchanged, a pre-commit that re-stages a formatted file commits the new content, commit-msg edits reach the commit while an untouched message stays byte-for-byte, a failing or emptying commit-msg blocks, no_verify skips failing hooks on commit and amend, amend runs both hooks with and without a new message, core.hooksPath wins over .git/hooks while `*.sample` and non-executable files never count, config-defined hooks are detected, commit-msg in a linked worktree writes that worktree's COMMIT_EDITMSG, both hooks see GIT_AUTHOR_NAME/EMAIL/DATE of the new commit and amend exports the original author after the identity changed, a pre-commit or commit-msg hook that checks out another branch at the same tip makes commit and amend refuse with both branch tips unchanged; pre-push gets the remote name and URL and a zero remote sha for a new branch, a failing one leaves the bare remote without the new commit and returns its output, a push with tags lists the branch update plus a lightweight and an annotated tag (tag object sha) and an up-to-date repeat sends empty stdin, push_tag runs it, a delete reads `(delete) `, a rejected non-fast-forward is left out while a force push carries the remote's current sha, it runs with empty stdin when nothing needs pushing and can fail that push, no_verify pushes past a failing hook on push and push_tag, core.hooksPath wins, a hook that outlasts an HTTP server's keep-alive timeout still lands the push and runs once, whether the server closes the idle connection or only half-closes it; post-* hooks: a branch switch, a new checked-out branch and a detached checkout run post-checkout with both heads and flag 1 while a branch made without checkout runs nothing, discarding a tracked file, all changes, staged changes and applying a stash file run post-checkout HEAD HEAD 0 once while discarding only untracked files runs nothing, post-merge 0 follows a fast-forward and a merge commit but not up to date or conflicts, amend and reword of HEAD run post-rewrite amend with old and new on stdin while a plain commit runs none, a rebase runs post-checkout orig onto 1 then post-rewrite rebase with one line per commit, a rebase onto HEAD itself or onto an upstream the branch already sits on linearly reports up_to_date, keeps the commits and runs nothing, the rebase's post-checkout sees HEAD at onto and the file without conflict markers although the rebase then stops on that conflict, Pull without hooks that stops on a rebase conflict, or on an untracked file after one commit was replayed, runs no post-rewrite when Continue (no_verify false) completes it, an up-to-date rebase still refuses unstaged or staged changes and a rebase in progress, repo_hooks reports a .husky hooksPath as inside the worktree (and ../shared-hooks or the default as not) and a pulled-in .husky/post-merge runs after a plain pull but not after a pull without hooks, (unix) a dangling `.git/hooks/post-merge` symlink into the worktree, a dangling `.git/hooks` folder symlink and a hook linked through an outside hop to a worktree file count as inside while a symlink to /usr/bin/true does not, a tracked `.husky` link to an empty folder outside counts as inside and the pull that replaces it with a folder holding post-merge runs that hook only without the skip, a hook linked to `proxy/../.husky/post-merge` with proxy linked to a worktree folder counts as inside, a core.hooksPath spelled in other letter case counts as inside exactly when the disk ignores case, an include.path to a tracked project.gitconfig holding only a comment counts as inside and the pull that adds core.hooksPath=.husky plus .husky/post-merge to it runs that hook only without the skip, a rebase goes through with only untracked files in a submodule but not with an edited one, an interactive rebase and the reword of an older commit go through with an edited submodule under `ignore = dirty` while the ordinary rebase still refuses it, and both interactive rebase and reword refuse a staged gitlink change under `ignore = all`, a quoted include through a .git symlink with a trailing space still offers the skip, a config scan that hits its 64-file limit with a tracked include still queued reports the hooks as inside the worktree, discarding three unstaged or two staged files in one call runs post-checkout once after all of them (and none for an untracked-only discard), (unix) a bulk discard records the untracked file it could not delete as failed, still restores the files before and after it and runs post-checkout once, (unix) Discard all staged changes does the same for a staged new file in a read-only folder (the files around it restored, one post-checkout seeing them), Pull all returns while a post-merge background job is running and lets it finish, while Cancel waits for a background job through a Linux pidfd or Windows job and immediately warns for a live macOS group; an exit-0 hook has no cancellation warning, and a setsid child can still write after Cancel without being seen, a fast-forward fails and leaves ORIG_HEAD and HEAD alone while ORIG_HEAD.lock is held and sets ORIG_HEAD once it is gone, and the script the pull brings runs only without the skip, a failing post-checkout's warning comes back next to the error of a replay that then fails, a fast-forward merge sets ORIG_HEAD so the post-merge hook's `git diff --name-only ORIG_HEAD HEAD` lists the new file, Pull all sets ORIG_HEAD to the old tip, a rebase paused on a conflict runs post-checkout and its continue runs post-rewrite once with the pairs from before the pause, an interactive pick + squash + drop runs post-checkout orig result 1, maps both picked commits to the squashed one and leaves the dropped one out, pull with rebase fast-forwards with post-merge when only behind and runs post-checkout + post-rewrite (no post-merge) when diverged while pull with merge runs post-merge and an up-to-date pull nothing, a failing post-checkout or post-merge comes back as a warning with exit code and output while HEAD moved, no_verify suppresses every post hook, Pull all runs post-merge in a repo that fast-forwarded but not in one already up to date, puts a failing hook on that repo's result while it still fast-forwards, and a run started skipping hooks runs none, group pull and the toolbar pull both run post-merge 0 and no post-checkout with core.hooksPath set, worktree add runs post-checkout 000… HEAD 1 inside the new worktree, and (clone_hooks.rs) a clone runs post-checkout 000… HEAD 1 from a global core.hooksPath while a no_verify clone and a clone of an empty repo run none) — skipped with a note when git ≥ 2.36 is not on PATH | +| Rust integration (204 macOS + 1 clone; platform cases in CI) | `apps/desktop/src-tauri/tests/git_engine.rs`, `tests/clone_hooks.rs` (own binary, sets HOME) | stage/commit/history, amend, branch/merge(ff+normal+conflict+message), branch-over-tag ref resolution (merge/rebase/history filter), ff-merge preserving uncommitted changes, drag-merge sequence (checkout target → merge source), no-ff merge commit when ff possible, can-fast-forward only when strictly behind, merge message available only during conflicted merge, interactive rebase (reorder/drop + range listing, squash/reword, conflict aborts untouched, invalid-plan rejection), a rebase aborted during post-checkout returns without replaying commits or running post-rewrite, a rebase step stopped by an untracked file names that file and commit, Continue re-applies the stopped commit so every commit survives (issue #88, same history as `git rebase --continue`), a Continue while the file is still in the way stops again with the history untouched and can be retried, and a re-applied step that conflicts pauses with markers and a conflict entry, then completes after resolution, submodule gitlink drift during rebase/pull/Continue (issue #89: legacy recovery, conflicts/abort, resolved gitlinks, already-applied and blocked steps, hooks/skip, app synchronization and disk-index preservation; see G59), file history lists only touching commits + paginates with skip, conflict resolve, stash (whole tree + selected paths incl. an untracked-only pick, a staged pick that leaves other staged files alone and pops with a dirty index, a staged-new pick removed and restored, git CLI agreeing on stash list/show; stash_files lists tracked + untracked entries with source_oid; stash_restore_files restores chosen files incl. an untracked one and a deletion, keeps the stash, rejects unknown paths), remote-branch checkout (stale local fast-forwarded with an untracked file preserved + upstream set, diverged local kept), tags, cherry-pick (plain keeps the message verbatim; record-origin output byte-equal to `git cherry-pick -x` for plain and trailer-block messages; many: in-order with per-commit origin lines, first conflict stops the run with progress counts), revert, reset (+ unknown-mode error), history pagination with and without filters, history position lookup by full + short hash, history search positions (case-insensitive text, hash prefix, none, blank, author alone, text + author, unknown author), stashes listed in the default walk as single-parent commits with a stash decoration while their index/untracked helper commits stay hidden and a branch-filtered walk omits them, broken-symlink staging (unix), diff hunks + whole-file context, unstage_all/discard_all, discard_staged_file/all (HEAD restored for index + worktree, staged-new file deleted, other staged files untouched; a name with glob characters leaves the files it would match staged; a held index.lock changes nothing and the retry after it is gone discards and leaves no lock; either name of a staged rename restores the original; a file that replaced a folder gives the folder back), line+hunk ops on files without trailing newline, git-CLI interop, commit signing (SSH sign verified via `git verify-commit`, unsigned without config, amend re-signs, merge commit signed, failure blocks the commit and leaves HEAD/index untouched), PR checkout (fork-style refs/pull fetch creates + updates the local branch and re-runs cleanly, diverged local branch refused with HEAD untouched, same-repo tracking checkout sets the upstream), ref fingerprint (tracks refs/HEAD, ignores plain file edits), commit file lists (per-file counts without hunks), single-file commit diff scoped by pathspec, comparing two commits lists the net change exactly like `git diff --name-status A B` (a file changed and changed back is absent, a rename keeps its old path, counts and hunk lines are the net ones, swapping the commits flips additions into deletions) and works across two branches, worktrees (add lists + checks out the branch and reports is_worktree/main_path from inside the linked folder, new branch from a base commit + duplicate refused, branch held elsewhere refused, checkout of a held branch refused with HEAD untouched, dirty remove refused unless forced, prune of a deleted folder, ref fingerprint changes on add, `git worktree list --porcelain` reports the engine-created worktree and `git status` runs clean inside it), discover refuses a missing path instead of walking to the parent repo, push reports up_to_date without contacting the remote when the tip equals the tracking ref while `git push` prints Everything up-to-date, and pushes again after a new commit, push with tags lands a local tag on a bare remote through named refspecs, pull with mode rebase / configured pull.rebase keeps history linear while mode merge creates a merge commit, blame attributes lines to their commits and marks an uncommitted edit, blames at a revision and at `^`, an uncommitted edit inside a committed block keeps the author on both split halves (the G44 crash), untracked/staged-new files and paths missing from a commit get explicit errors, staging and unstaging a later hunk of a multi-hunk file leaves the other hunk alone, remote_add registers a remote that list and fetch then use while a duplicate or blank name is refused, reword of HEAD changes only the message (tree + author lines byte-equal, dirty worktree and staged file untouched), reword of an earlier commit rewrites the commits above it and returns the reworded commit's new oid while a dirty tree is refused, unpushed lists only commits missing from every refs/remotes ref, tree_files lists every path at a commit while commit_files still lists the two changed ones, index_files lists tracked and staged-new paths but no untracked file, file_contents reads a file at a commit and on disk as context lines with status unchanged, errors for a path missing from the commit and flags a NUL-byte file binary, the folder scan finds repos at any depth and repos inside repos while skipping node_modules, hidden folders, an empty `.git` folder and anything past the runaway depth guard, returns the discover-shaped path, a root that is itself a repo plus its nested repo, and an error for a missing folder, stage_files/unstage_files apply many paths in one index write, commit refuses an index that matches HEAD (HEAD and worktree untouched) and an empty first commit while a merge resolved to HEAD's tree still commits with two parents, submodules (a synced pull checks an in-sync submodule out at the bumped commit — fetching it — and leaves `git status --porcelain` empty, a synced checkout takes it back with the branch, the group Pull all does the same, a submodule with a local commit or an edited file stays where it is, an unsynced pull reports the drift as FileStatus.submodule recorded/checkedOut and discard_file, discard_all and submodule_update by path all check out the recorded commit, a submodule with only edited files reports no drift), pull_preview is empty when up to date or simply behind, lists the uncommitted files a pull would overwrite (and the real pull then fails), predicts the merge conflict a real pull then reports while leaving HEAD, status and the state files untouched, follows pull.rebase and stops at the first conflicting commit, catches a rebase conflict a merge would not have, reports none for edits that merge cleanly in both modes, and is None without an upstream or on a detached HEAD, commit hooks (a passing pre-commit commits and sees GIT_INDEX_FILE, a failing one blocks with its exit code and output as hook_failed detail and HEAD unchanged, a pre-commit that re-stages a formatted file commits the new content, commit-msg edits reach the commit while an untouched message stays byte-for-byte, a failing or emptying commit-msg blocks, no_verify skips failing hooks on commit and amend, amend runs both hooks with and without a new message, core.hooksPath wins over .git/hooks while `*.sample` and non-executable files never count, config-defined hooks are detected, commit-msg in a linked worktree writes that worktree's COMMIT_EDITMSG, both hooks see GIT_AUTHOR_NAME/EMAIL/DATE of the new commit and amend exports the original author after the identity changed, a pre-commit or commit-msg hook that checks out another branch at the same tip makes commit and amend refuse with both branch tips unchanged; pre-push gets the remote name and URL and a zero remote sha for a new branch, a failing one leaves the bare remote without the new commit and returns its output, a push with tags lists the branch update plus a lightweight and an annotated tag (tag object sha) and an up-to-date repeat sends empty stdin, push_tag runs it, a delete reads `(delete) `, a rejected non-fast-forward is left out while a force push carries the remote's current sha, it runs with empty stdin when nothing needs pushing and can fail that push, no_verify pushes past a failing hook on push and push_tag, core.hooksPath wins, a hook that outlasts an HTTP server's keep-alive timeout still lands the push and runs once, whether the server closes the idle connection or only half-closes it; post-* hooks: a branch switch, a new checked-out branch and a detached checkout run post-checkout with both heads and flag 1 while a branch made without checkout runs nothing, discarding a tracked file, all changes, staged changes and applying a stash file run post-checkout HEAD HEAD 0 once while discarding only untracked files runs nothing, post-merge 0 follows a fast-forward and a merge commit but not up to date or conflicts, amend and reword of HEAD run post-rewrite amend with old and new on stdin while a plain commit runs none, a rebase runs post-checkout orig onto 1 then post-rewrite rebase with one line per commit, a rebase onto HEAD itself or onto an upstream the branch already sits on linearly reports up_to_date, keeps the commits and runs nothing, the rebase's post-checkout sees HEAD at onto and the file without conflict markers although the rebase then stops on that conflict, Pull without hooks that stops on a rebase conflict, or on an untracked file after one commit was replayed, runs no post-rewrite when Continue (no_verify false) completes it, an up-to-date rebase still refuses unstaged or staged changes and a rebase in progress, repo_hooks reports a .husky hooksPath as inside the worktree (and ../shared-hooks or the default as not) and a pulled-in .husky/post-merge runs after a plain pull but not after a pull without hooks, (unix) a dangling `.git/hooks/post-merge` symlink into the worktree, a dangling `.git/hooks` folder symlink and a hook linked through an outside hop to a worktree file count as inside while a symlink to /usr/bin/true does not, a tracked `.husky` link to an empty folder outside counts as inside and the pull that replaces it with a folder holding post-merge runs that hook only without the skip, a hook linked to `proxy/../.husky/post-merge` with proxy linked to a worktree folder counts as inside, a core.hooksPath spelled in other letter case counts as inside exactly when the disk ignores case, an include.path to a tracked project.gitconfig holding only a comment counts as inside and the pull that adds core.hooksPath=.husky plus .husky/post-merge to it runs that hook only without the skip, a rebase goes through with only untracked files in a submodule but not with an edited one, an interactive rebase and the reword of an older commit go through with an edited submodule under `ignore = dirty` while the ordinary rebase still refuses it, and both interactive rebase and reword refuse a staged gitlink change under `ignore = all`, a quoted include through a .git symlink with a trailing space still offers the skip, a config scan that hits its 64-file limit with a tracked include still queued reports the hooks as inside the worktree, discarding three unstaged or two staged files in one call runs post-checkout once after all of them (and none for an untracked-only discard), (unix) a bulk discard records the untracked file it could not delete as failed, still restores the files before and after it and runs post-checkout once, (unix) Discard all staged changes does the same for a staged new file in a read-only folder (the files around it restored, one post-checkout seeing them), Pull all returns while a post-merge background job is running and lets it finish, while Cancel waits for a background job through a Linux pidfd or Windows job and immediately warns for a live macOS group; an exit-0 hook has no cancellation warning, and a setsid child can still write after Cancel without being seen, a fast-forward fails and leaves ORIG_HEAD and HEAD alone while ORIG_HEAD.lock is held and sets ORIG_HEAD once it is gone, and the script the pull brings runs only without the skip, a failing post-checkout's warning comes back next to the error of a replay that then fails, a fast-forward merge sets ORIG_HEAD so the post-merge hook's `git diff --name-only ORIG_HEAD HEAD` lists the new file, Pull all sets ORIG_HEAD to the old tip, a rebase paused on a conflict runs post-checkout and its continue runs post-rewrite once with the pairs from before the pause, an interactive pick + squash + drop runs post-checkout orig result 1, maps both picked commits to the squashed one and leaves the dropped one out, pull with rebase fast-forwards with post-merge when only behind and runs post-checkout + post-rewrite (no post-merge) when diverged while pull with merge runs post-merge and an up-to-date pull nothing, a failing post-checkout or post-merge comes back as a warning with exit code and output while HEAD moved, no_verify suppresses every post hook, Pull all runs post-merge in a repo that fast-forwarded but not in one already up to date, puts a failing hook on that repo's result while it still fast-forwards, and a run started skipping hooks runs none, group pull and the toolbar pull both run post-merge 0 and no post-checkout with core.hooksPath set, worktree add runs post-checkout 000… HEAD 1 inside the new worktree, and (clone_hooks.rs) a clone runs post-checkout 000… HEAD 1 from a global core.hooksPath while a no_verify clone and a clone of an empty repo run none) — skipped with a note when git ≥ 2.36 is not on PATH | | Rust module (110 macOS; platform cases in CI) | `src/commands.rs` (2), `apps/desktop/src-tauri/src/cli.rs` (7), `src/state.rs` (1), `src/editors.rs` (5), `src/fonts.rs` (1), `src/ai_cli.rs` (18 macOS + Linux/Windows cases), `src/error.rs` (10), `src/core/hooks.rs` (12 macOS + Linux/Windows cases), `src/core/remote.rs` (20), `src/core/group_update.rs` (2), `src/terminal.rs` (3), `src/core/accounts.rs` (7), `src/core/sign.rs` (7), `src/forge.rs` (7), `src/proc.rs` (1), `src/watcher.rs` (7) | AI-CLI runner: program allowlist (incl. Cursor's `agent` and `cursor-agent` names), stdout capture via fake agent script, {OUTPUT_FILE} substitution, kill-on-timeout, a timed-out tree capture also killing the grandchild the shell started, a background process holding the pipes after exit not holding up the capture, cancellation waiting for a background job and stopping it at the deadline when a Linux pidfd or Windows job can signal it, macOS tracking a live group but reporting uncertainty immediately, and retain_for_cancel dropping an exit-0 tree, Cursor version-folder keys and the .cmd launcher → newest node.exe/index.js resolution (none for other agents or a missing versions dir) · error mapping: HTTP status extraction from libgit2 messages, 401/402/403 explanations, unmapped codes kept verbatim, io NotFound → not_found while other io errors stay io, hook failures serialize code hook_failed with the output as detail while other errors carry none · hooks: git version parsing incl. Apple and Windows suffixes, author dates in git's raw `@ <±hhmm>` form, runner choice (git for no input or ≥ 2.40, the hook file on unix for 2.36–2.39, a warning otherwise), the pre-push line format (new, up to date left out, delete, unknown remote commit kept), the direct runner handing a hook its args and stdin (unix), a hook without a shebang still getting its args, stdin, env and cwd through sh, only ENOEXEC triggering that retry, git-style whitespace cleanup of an edited message, output tail on a char boundary, post-checkout/post-merge/post-rewrite args and stdin in git's format with identical rebase pairs dropped, post-merge only after ok or fast_forward · forge proxy: api-subdomain host allowlist (dot-anchored), per-provider auth headers, bitbucket email requirement, unknown provider rejected, missing-token vs no-account message · SSH key resolution: `~` expansion, configured key ordered ahead of defaults, dedupe when the configured key IS a default, blank config ignored, generation never targeting an existing key · push refspec shapes (plain/force/tags never forced) · a retried push skips the pre-push hook only for update lines it already approved · rejection message quotes the server lines after the ref list (sideband lines trimmed, de-duplicated, "remote:" and rule lines dropped, capped at 12) · repo account-binding parse (valid/malformed) · accounts: upsert keeps both same-host accounts + default flags, one default per host, preferred-before-default candidate order, port-loose host match, ssh URLs ignored · signing config: off by default, ssh setup read from git config, empty-string values read as unset, ssh-without-key and x509 are clear errors, openpgp falls back to the committer identity, literal-key detection, ~ expansion · proc: no bare `Command::new` anywhere outside proc.rs (G31) · recents: new paths go on top in order, an existing path moves instead of duplicating, the list caps at RECENT_LIMIT · watcher: metadata filter unchanged for main repos, `worktrees/*/HEAD|gitdir|locked` relevant while `worktrees/*/index` is noise, a linked worktree watches its own gitdir + the shared commondir, main repos need no extra roots, a slow watch for the previous repo never replaces the current one, a late stop for the previous repo keeps the current watch, a stop while a watch is in flight drops it | | Unit (341) | `tests/unit/*.test.ts` | actionError (busy responses use info without a failure prefix, other errors keep default or custom formatting), themeContrast (every palette keeps body ≥ 7:1, muted ≥ 5.5:1, faint ≥ 4.5:1 against background and surface, in that order, and defines its own code comment colour), settingsFilter (AND terms, section labels, catalog coverage of every JSX card title), GraphLayout (incl. pagination stability, lane reuse), wordDiff (round-trip), conflict parse/serialize (diff3 labels, CRLF, bare markers, 8+-char content lines, close-without-separator — all lossless), cliAgents (per-agent argv/stdin shape incl. Cursor print mode with the prompt last, ANSI/OSC cleaning, output-file preference, error surfacing), aiProviders (empty/whitespace/missing content rejected for openai-compatible + ollama, HTTP status+body surfaced, real content passes; OpenAI itself gets max_completion_tokens while other compatible hosts and LM Studio keep max_tokens, a rejected temperature is dropped and remembered, a rejected max_tokens or max_completion_tokens swaps once and never loops, an unrelated 400 is not retried, a reasoning model that spent its budget thinking gets one retry at REASONING_MIN_TOKENS that sticks, a budget that ran out without reasoning explains itself), aiCapabilities (review conventions: absent by default, general-only, general+project order with precedence note, whitespace = absent, clipping), aiTextSegments (token parse: adjacent tokens, unclosed/inner-asterisk/multi-line markers stay literal, ** inside backticks is code), reviewSignature (staged-only, order-insensitive, unstaged-edit + set changes alter it, newline filenames don't collide, hashText determinism), commitStyle (prefix rule matching/tokens/ticket-fallthrough, `$`-sequence literalness, preset instructions, post-generation prefix enforcement), pullRequestUrl (https/scp/ssh remotes, non-standard ports kept, http preserved, ssh port dropped, Bitbucket Server /scm/ shape, .git-behind-slash strip, unknown forge → null), aiModels (per-provider list endpoints/headers incl. Groq-style base URLs, generateContent filtering for Gemini, dedupe/sort, invalid-JSON + HTTP-status errors, cli → empty without a request), forge (parseForgeRemote for all three forges + rejects, provider creation gating, github/gitlab/bitbucket adapters: request URLs, field mapping incl. fork + draft detection, create payloads, error-message surfacing incl. github field-level validation entries without a message, checkoutSpec shapes incl. bitbucket fork → null, pickForgeRemote upstream-first ordering, github 403 create refusals explained (fine-grained token into another owner's repo, missing pull request permission, rate limit left verbatim), gitlab self-hosted https→http transport fallback — GET-only (a retried POST could file a duplicate MR), never for gitlab.com or api-level errors, working scheme remembered per host and safe under concurrent fallbacks, reviewer candidates per forge + reviewer ids embedded/requested on create incl. github follow-up failure tolerance, authorAvatar per forge: github commit author, gitlab avatar-by-email URL encoding, bitbucket commit author user), worktree (folder-name slug from repo + branch, sibling-path suggestion incl. Windows separators, parentDirectory), highlight (block-comment continuation: JSDoc carried and closed, line comments and glob strings not treated as open, mid-line close resumes code, xml opener, no-block-comment languages ignore the flag; embedded languages: astro on the xml grammar, svelte/toml mappings, whole-file frontmatter + script/style blocks incl. lang="ts"/"scss" and a single-line script tag, hunk walk from line 1 and mid-file back to the first fence or closer, template-only hunk marks nothing, non-markup → null; shebangs: direct and env forms incl. -S and VAR=val, version suffixes, unknown interpreter and non-shebang → null, name and extension win over the shebang, diffFirstLine prefers the new side and falls back to a deleted file's old side), commitMessage (split/join round-trip, CRLF, second line without blank line is body, newline never enters the summary), fileFilter (empty/whitespace query passes all, case-insensitive substring, every term required), webUrl (https/scp/ssh:// remotes → repository page, ssh port dropped, http + web port kept, Bitbucket Server browse page, Bitbucket Cloud untouched, trailing slash, local path → null), blameable (hasCommittedHistory true for every tracked change kind, false for untracked and staged-new), imageMime (one media type per engine image extension, null otherwise), renderCap (lines at or under 5,000 chars stay whole, longer ones clip and count the hidden tail, custom cap), fork → upstream pull requests (github head `owner:branch`, gitlab GET target id then POST on the source project with target_project_id, bitbucket source.repository, forgeTargets dedupes same-host remotes and defaultForgeTarget prefers `upstream`), allFiles (tree paths marked with their change, deleted files kept, no duplicate paths, foldersWithChanges lists every ancestor of a changed file and nothing otherwise), fetchRemotes (continues after a failure and reports failures), patchText (headers + hunk headers + prefixed lines, rename old path, multi-file join, hasReviewableText rejects null/binary/image/empty), single-file review + explain prompts (file/where/sibling context lines, sibling cap at 30, section labels, conventions order, patch at the end, 4096-token budget), aiReport (labelled sections, bullet severities, continuation lines, verdict tones, unstructured fallback, bold inside a sentence is not a label), locateDiffLine (exact match prefers additions, deletion/context fallback, whitespace-insensitive whole-line hit, tiny/absent snippets null), commit review + explain prompts (commit line, file list capped at 30, conventions, patch at the end), terminalKeys (Alt+Up/Down map to ESC[1;3A/B on keydown only, every other modifier/key/phase left to xterm), chord (key from event.code so ⌥A stays A, unsupported keys null, id round-trip, exact modifier match, per-platform labels, no-modifier/reserved problems per platform, repoForChord lookup), repoGroups (empty/duplicate names ignoring case and the renamed group, least-used colour with wrap, recents bucketed in order with the rest ungrouped, a deleted group's paths fall back to ungrouped while empty groups stay listed, worktree inherits its main's group unless mapped itself, tabClusters/orderRepoTabs cluster open tabs by group with ungrouped last and leave a group-less strip alone, moveRepoGroup places a group before or after another and ignores self or unknown targets), tabLabels (unique names get no hint, nearest distinguishing parent folder, walks further up when parents collide, case-insensitive names and Windows separators), linePairs + pairHunk (the issue #62 hunk, single replacement always one row, comment block before a rewritten line, dissimilar deletion unpaired, pure runs unchanged, positional fallback past the cap, identical lines anchor, the demo load hunk; lineSimilarity ignores punctuation and repeats and compares symbol-only lines by text), remotes (pickRemote upstream → origin → first, pushSetsUpstream only for no upstream or the same remote), diffLocation (new line number for additions and context, old number and old path for a deletion, the clicked split pane wins, column only when given, none without a number on that side; columnAt counts characters from one, an emoji as one, nothing past the text or inside the clipped tail of a line over 5,000 characters) | | E2E (153) | `tests/e2e/smoke.spec.ts` | the AI button in the commit message editor keeps the summary focused after the click and Escape closes the editor while the stubbed Ollama /api/chat answer is held (the late answer is discarded), then fills summary + description from the commit's own diff and saves, folder rows in the working-copy tree stage and unstage everything inside them (one engine call each, chevron still folds, indeterminate in All files), stepping with n / the header chevron / p marks the active change rows and counts "k of n changes" in inline, split and wrapped views, View options stays open across two toggles, Settings filter (autofocus, SSH-only, first catalog hit across sections, locate flash, section-label match, no results, Escape clears then closes, close resets, AI section preset), splash→welcome, the AI chip names Ollama on the demo defaults, reads Set up AI when the CLI provider has no agent, Claude Code once picked, turns ok after Test connection, stale when the provider changes back to Ollama, and survives a reload, Blame is disabled in the file menu and the diff header for the untracked demo file while a tracked file keeps it enabled, the remote row menu's Open in browser opens the demo remote's GitHub page in a popup and the palette lists Open repository in browser, the sidebar and graph branch menus carry a fast-forward entry next to merge that is disabled while the current branch is ahead, settings installs the command line tool, settings lists the demo editors and picking Zed relabels the toolbar button and its menu, the Pull options menu offers merge and rebase, the status bar reports Fetched just now after the auto fetch, retries every remote after a partial auto fetch failure, keeps the timestamp and faint failed remote hint through partial and offline fetches, updates the timestamp on Pull, and explains the disabled Fetch button when no remotes exist, the diff header's Blame button opens file history in the blame pane with the Working copy row selected, per-hunk author buttons and an uncommitted hunk that disappears when a commit row is picked, a Blame at this commit menu, the Diff view toggle brings the diff controls back and Escape returns to the graph, the palette's Blame… picks a file and opens its blame pane, open repo, graph, inspector, palette, search, conflict resolver line picks, single-conflict nav + per-conflict take-all, per-block conflict hand edit, interactive rebase dialog + multi-select squash, cherry-pick dialog with the source-reference checkbox on by default, multi-select cherry-pick listing both commits and confirming, diff auto-jump lands at the first change with no scroll animation (frame-traced scrollTop), long path stays inside the discard confirm dialog, commit action buttons stay inside a narrow working copy panel (the row wraps), sidebar branch names align with and without the HEAD tick (measured left offsets), hovering a working-copy file reveals its full path, opening a diff folds the sidebar away and the toggle brings back the graph, avatars stay visible after a diff open/close round-trip (stubbed Gravatar), diff text selection survives the right-click copy menu and Esc closes only the menu, sidebar lists the demo pull requests and the create dialog opens, reconnecting an account opens the prefilled token form with focus in the token field, a file history row's Open commit button closes the panel and selects that commit in the graph, the author box finds commits with the graph lanes intact and combines with the text search, commit search finds matches in the full graph (n of m pill, Enter/Previous step, query survives selecting another commit, Escape clears), a search result that lands after a click keeps the clicked commit selected while clicking a match moves the pill to 2 of n and Enter steps to 3, searching a commit hash jumps to it in the full graph, a short hash prefix jumps too while an unknown hex word says No matches, a missing hash keeps the graph with No matches, mod+f focuses the commit search, sidebar lists the demo worktrees (incl. a missing-folder row) and the new-worktree dialog re-suggests the folder as the branch name is typed, the inner line of a JSDoc block in the demo CommitGraph.tsx diff renders as one hljs-comment span (guards the DiffViewer → prepareCommentStates wiring, which the unit tests cannot see), collapse-all folds every section and branch folder and a reopened section comes back with its folders closed, the inspector keeps its width (±1px) when a diff folds the sidebar away and both widths return on Escape (measured via data-panel-id after dragging the sidebar handle), the commit box renders the summary larger and bolder than the description with Enter/Backspace moving between them and commit disabled on an empty summary, dragging the commit box's top edge grows the description and double-click resets it, the Changes header's fold button collapses that list's folders (nested file hidden) and flips to expand-all, and no fold button exists in flat mode, the top graph row shows a whole `main` chip with no HEAD chip and no clipped chip text plus a 7-char hash copy button, the graph display menu hides the hash column and brings it back, the sidebar accordion pins collapsed headers at the bottom under an open Branches section and moves the Tags header up when Tags opens, the welcome page flags the demo's missing folder and opens a repository via ↓ + ⏎ from the autofocused search, the conflict resolver renders positive integer line numbers in A, B and Result with each starting at 1, the checked-out branch chip is opaque while another local branch's chip stays translucent, double-clicking the separated `origin/main` chip opens the reset prompt naming the 2 commits that would be lost and Cancel dismisses it (the demo repo puts origin/main 2 commits behind main so the split is real), the diff header's History button opens that same file's history panel and closes the diff, a working-copy row's "Stash this file…" opens the dialog naming that file and the toolbar pop button restores the latest demo stash, shift-click selects three working-copy rows and the bulk menu offers Stage 3 / Stash 3 files, the working-copy filter hides non-matching rows with "1 of 2" counts and the clear button restores them, the commit file filter narrows five demo files to one and Escape resets it, selecting the demo stash shows the stash hint and the hover restore button on a file toasts the restore, right-clicking a plain commit's file offers File history / Show in Finder / Copy path and no stash Apply entry, staged rows offer discard from the row, the menu and the header trash icon, the sidebar is visible again after a reload that happened with a diff open, the demo stash renders as a graph row with an Archive node and a dashed chip whose menu pops it, ↓ then → opens the second commit's first file with the file list focused, ↓/↑ walk files, twelve → presses stay on the same file and one ← returns to the graph on the same commit, the Graph display menu's "Lane color band" removes and restores the tail rects, the inspector stops at its minimum width when dragged and folds/returns for file history, dragging the sidebar shut and back open in one gesture shows its content again, conflict picks land in file order with a mixed-state side checkbox, the resolver picks with A/B/↑/↓ and ⌘⏎ opens the next conflicted file, leaving with picks asks first while Escape closes a clean resolver, right-clicking the main tip row offers Push main ↑2 while an inner commit's menu has no push, hovering the feature/diff-viewer chip stacks both its refs in a panel whose first chip sits on the row chip (≤2px) with the folded `release/0.4` under it, and right-clicking that one opens its Checkout menu (no reset entry for a plain local), the top row shows `main` as its visible chip although `hotfix/lane-colors` comes first in the refs and only `main` carries the check inside the stacked panel, right-clicking the separated `origin/main` chip offers "Reset main to this…" and opens the same reset dialog, clicking a working-copy file then ↓/↓/↑ moves the diff through ipc.ts → palette-seed.sql → Architecture.md and back — the Remotes header's Add remote button opens the add dialog with the button disabled until name and URL are filled, right-clicking the terminal shows Copy (disabled without a selection)/Paste/Select all/Clear terminal, Settings → Git → Clone destination remembers a chosen folder and the clone dialog's destination starts there, a four-row drag selection in the palette-seed diff stays a Range and still copies all four lines via ⌘C after its rows scroll out of the virtualizer in either direction, and reads the same text once scrolled back, the pushed demo commit opens the editor and Save asks "Rewrite a pushed commit?" (Cancel keeps the draft) while the top commit opens the inline editor on double-click (Esc cancels, Save rewrites the heading, body and graph row), the GitHub account form keeps the classic token link and adds the fine-grained page inline while the Token label still focuses the input, the Fonts card's Interface picker lists proportional fonts first and Code lists monospace first, picking Helvetica Neue/Fira Code changes --font-sans/--font-mono and the terminal follows Code until Menlo + 16 px is picked for it, all of it survives a reload and Reset fonts clears it, sidebar section headers and bodies carry no fill and no top border while each header shows a filled gold icon tile and a filled count badge, the commit Files header's A token narrows five files to one with All pressed off and back, the All files view lists Roadmap.md at the commit with 5 changed, keeps a change-free folder collapsed until clicked, opens the unchanged file with an unchanged badge and no @@ header while Folder tree hides it again, the working copy's All files view shows README.md beside the stage/unstage checkboxes of the changed files and opens it without a Stage file button, dragging a selection below the diff grows it past six lines from the start row and ⌘C copies the same text before and after scrolling away, the diff header's AI actions menu reviews the open file (busy strip → demo response under the header, Copy, fold to one line and back, full-view dialog, button disabled meanwhile, closing and reopening the diff dismisses the result) then explains it and Dismiss removes the panel, the inspector's Review with AI reviews the selected commit (Stop reviewing while busy, AI review card → demo response, Dismiss), file history's diff pane shows no change arrows on a commit that did not touch palette-seed.sql and, on the Working copy row, `n` jumps the scroller to the one change, `p` from the top wraps to it and the header's Next change button lands on the same offset, a second repo opened from the palette becomes a tab that ⌘1 / ⌘⇧] switch between (wrapping), the tab menu's Keyboard shortcut… capture box flags a bare `t` as no_modifier and ⌘K as reserved without opening the palette, saving ⌃⇧T shows the chip on the tab and the chord switches to it, and Settings → Shortcuts lists and removes it, Force push from the Push menu opens a "Force push?" confirm naming origin/main that Cancel dismisses without pushing, and repositories can be grouped on the welcome page: Add to group → New group… creates Frontend with a picked colour (Create disabled on an empty name, a duplicate name shows the taken hint), dragging a row onto the header moves it (counts 2 and 2), Enter in the name field creates Backend, the header menu's Move up puts Backend first (Move down disabled at the bottom) and Move down restores it, the header button collapses and re-expands it, searching flattens the list to the two matching rows, Open all in tabs opens both Frontend repos as tabs whose titles end in · Frontend, the tab menu's Move to group re-homes one to Backend and the strip splits into two clusters with chips, clicking the Backend chip hides its tab and shows Backend1, collapsing Frontend keeps the active tab visible, ⌘2 switches to the hidden temple-ui and reveals it, both chips expand again, the Backend chip's menu counts 1 under Close its tabs and Collapse other groups folds Frontend to Frontend1 while ⌘1 still reaches its hidden tab, Expand all groups brings both back, dragging the Backend chip onto the first cluster's left edge puts Backend first so ⌘1 reaches temple-ui and dragging it back restores Frontend, narrowing the window to 300px shows the overflow list whose temple-ui entry switches tabs and widening hides it again, no separators or overflow button exist with two tabs, the switcher lists repos under data-switcher-group labels, the palette's Close all in Backend closes its one open tab while Open all in Backend says 2 repositories, and Ungroup… confirms and leaves the repos in the list, the long-line diff scrollbar stays at the viewport bottom, pans both split panes together, accepts arrow keys and Shift+wheel, and disappears when wrapping is enabled, the code diff opened from a selected commit also scrolls horizontally in inline and split views, and a trackpad pan of one wheel event per frame moves the long-line diff by the whole gesture with no backward step, dragging the drawn thumb moves the layers by exactly the engine's scrollLeft and a click on the track pages back to 0, and a text selection dragged past the pane's right edge pans the long lines, grows the selection and stops panning when the pointer comes back, scanning ~/projects from the welcome page lists four repos with two marked In recents and disabled, unticking one adds the other to the recents list, a seeded tab whose folder is missing closes with a toast while two same-named angkorgit tabs show forks / projects hints and a unique one shows none, ⌘P on the welcome page filters four recents to temple-ui and Enter opens it as the only tab, ⌘P marks it Current and opens angkorgit as a second tab, a third ⌘P marks temple-ui Open tab and switches back without a new tab, ⌘K still opens the command palette, and ⌘T opens a picked folder as a third tab, the all files layout stacks the five demo commit files with GraphRow.tsx scrolled to the top and "2 of 5", clicking Architecture.md in the inspector scrolls it to the top ("4 of 5"), side by side applies inside the cards, a user wheel at the top moves the inspector highlight to CommitGraph.tsx, one file and then all files collapse and expand, Show one file returns to DiffPanel and the choice survives a reload, clicking a file in the inspector still jumps to it after scrolling reached it once and ← inside the page returns to the graph, a stash file never offers the all files layout even with 'all' remembered while a plain commit still gets it, a click into a file diff followed by ← closes it and returns to the graph, ⌘⏎ with nothing staged toasts "Stage some changes first" and commits nothing, and a file filter that hides every staged file leaves Commit enabled with the full count, and eleven tabs shrink to fit an 820px window with the inactive close buttons gone and no overflow button, scroll past their 48px floor at 480px and come back to their natural widths at 1440px, and What's new opens from the welcome footer and the status bar bell with its unread dot cleared once seen and after a reload, and a drifted demo submodule row has no Discard button, its menu offers Update submodule to efec64c without Discard changes…, and its hover Update button toasts the checkout and clears the row, and the Pull button carries a conflict warning whose tooltip names the files, opens "This pull will conflict" (Cancel closes, Pull and resolve pulls), switches to "Your changes are in the way" whose Stash 2 files… opens the stash dialog with those files, and shows no warning without a predicted problem, and a failing demo pre-commit hook opens the hook dialog with ANSI-free lint output (Close keeps the message and commits nothing, Commit without hooks commits) while a ticked Skip hooks commits directly and clears itself, and a repo without hooks shows no Skip hooks box, and a hook that fails after switching to another tab only toasts "Nothing was committed in angkorgit" there (no dialog, no commit, the other tab never shows Running hooks…) while the first tab keeps its draft and shows the waiting failure when the user returns, a commit hook keeps Commit busy as Running hooks… across selecting a graph commit and coming back and its failure dialog appears while the graph commit is shown, and Commit without hooks never reads Running hooks… while text typed during the run survives the commit, and a failing demo pre-push hook makes the toolbar Push open "A hook stopped the push" with ANSI-free test output while the Push menu offers Push without hooks (absent in a repo without hooks) and the dialog's Push without hooks pushes main, and after a Push without hooks that the remote rejects as non-fast-forward the dialog's Force push keeps skipping the hook and pushes main forced, and when develop was checked out while the hook ran the rejected dialog still names origin/main with Pull with rebase disabled ("Check out main first…") and Cancel focused, nothing pulls, and once main is checked out again the same dialog enables and focuses Pull with rebase, which pulls, and a graph chip takes its lane colour while every lane line is a rail (no cubic curves) and the WIP banner is opaque, a 14-lane demo history scrolls the graph sideways by exactly each wheel step, by the drawn thumb and back to 0 on a track click while vertical scrolling stays put, and dragging the Graph header edge narrows the column and its scrollbar, survives a reload and double-click resets it, and a running demo post-checkout shows a loading toast and responds to a second checkout with an info toast naming post-checkout and the repository, with no red failure toast, and a failing demo post-checkout hook shows a warning toast after "Checkout develop done" whose Show output opens the warning dialog with ANSI-free output and only Copy output and Close, the Pull menu's Pull without hooks pulls without the post-merge warning a plain Pull then shows (and is absent without hooks), and Pull all puts a post-merge warning with a collapsed Hook output on every updated row ("2 hook warnings") while Pull all without hooks from the group menu shows none, and a hook folder inside the worktree offers Pull without hooks and Pull all without hooks before any hook exists (but no Push without hooks), and the Pull menu shows Pull without hooks after the hook setup changed between two opens, Pull without hooks with a predicted conflict opens "This pull will conflict" first and Pull and resolve then pulls without the post-merge warning, and discarding three selected files shows one post-checkout warning, while a bulk discard that fails for one file names it with the reason and shows no success toast, and so does the Staged header's Discard all staged changes, and the Only matches toggle narrows a "merge" search to the matching commits with "n matching commits", steps them with Enter and brings the full graph back on the same commit, also when the search box is cleared — all on demo mode, and a squeezed same-name tab hint stays at least 18px wide in a 480px window, and graph nodes whose lanes leave the column stay inside it, pinned to an edge, at rest and after scrolling right, and right-clicking the 7th character of a diff line offers Copy path and line with `path:line:7` (copied, toast) while a right-click past the end of the text drops the column, and two cmd-selected commits offer Compare these commits, which puts a From/To header over the newer commit's file list (no message editor or AI buttons), opens a file diff and the all files layout labelled `older..newer`, swaps the direction from the header and leaves compare mode on a plain click, while three selected commits get no Compare entry, and switching to light and back recolours every element on the repo page in the same frame while hover fades keep their duration | diff --git a/apps/desktop/src-tauri/src/core/branch.rs b/apps/desktop/src-tauri/src/core/branch.rs index 711521cb..cea4e4e3 100644 --- a/apps/desktop/src-tauri/src/core/branch.rs +++ b/apps/desktop/src-tauri/src/core/branch.rs @@ -364,7 +364,7 @@ pub(crate) fn rebase_with_hooks( if index.has_conflicts() { return Ok(paused_rebase()); } - match rebase.commit(None, &sig, None) { + match commit_rebase_step(&repo, &mut rebase, &sig) { Ok(_) => {} Err(e) if e.code() == git2::ErrorCode::Applied => {} Err(e) => return Err(e.into()), @@ -381,6 +381,66 @@ pub(crate) fn rebase_with_hooks( }) } +struct RebaseCommitIndex<'repo> { + repo: &'repo Repository, + original: git2::Index, +} + +impl Drop for RebaseCommitIndex<'_> { + fn drop(&mut self) { + let _ = self.repo.set_index(&mut self.original); + } +} + +fn commit_rebase_step( + repo: &Repository, + rebase: &mut git2::Rebase<'_>, + signature: &git2::Signature<'_>, +) -> Result { + let original = repo.index()?; + let mut drifted = Vec::new(); + for submodule in repo.submodules()? { + let (Some(recorded), Some(checked_out)) = (submodule.index_id(), submodule.workdir_id()) + else { + continue; + }; + if recorded == checked_out { + continue; + } + let Some(name) = submodule.name() else { + continue; + }; + let status = repo.submodule_status(name, git2::SubmoduleIgnore::Untracked)?; + if status.intersects( + git2::SubmoduleStatus::WD_ADDED + | git2::SubmoduleStatus::WD_DELETED + | git2::SubmoduleStatus::WD_INDEX_MODIFIED + | git2::SubmoduleStatus::WD_WD_MODIFIED, + ) { + continue; + } + if let Some(mut entry) = original.get_path(submodule.path(), 0) { + if entry.mode == u32::from(git2::FileMode::Commit) { + entry.flags |= git2::IndexEntryFlag::VALID.bits(); + drifted.push(entry); + } + } + } + if drifted.is_empty() || original.has_conflicts() { + return rebase.commit(None, signature, None); + } + let mut temporary = git2::Index::new()?; + for entry in original.iter() { + temporary.add(&entry)?; + } + for entry in drifted { + temporary.add(&entry)?; + } + repo.set_index(&mut temporary)?; + let _restore = RebaseCommitIndex { repo, original }; + rebase.commit(None, signature, None) +} + fn rewritten_pairs(repo: &Repository) -> Vec<(git2::Oid, git2::Oid)> { let file = rebase_state_dir(repo).join("rewritten"); let Ok(text) = std::fs::read_to_string(file) else { @@ -423,7 +483,7 @@ pub(crate) fn rebase_continue_with_hooks( }); } } - match rebase.commit(None, &sig, None) { + match commit_rebase_step(&repo, &mut rebase, &sig) { Ok(_) => {} Err(e) if e.code() == git2::ErrorCode::Applied => {} Err(e) => return Err(e.into()), @@ -437,7 +497,7 @@ pub(crate) fn rebase_continue_with_hooks( if index.has_conflicts() { return Ok(paused_rebase()); } - match rebase.commit(None, &sig, None) { + match commit_rebase_step(&repo, &mut rebase, &sig) { Ok(_) => {} Err(e) if e.code() == git2::ErrorCode::Applied => {} Err(e) => return Err(e.into()), diff --git a/apps/desktop/src-tauri/tests/git_engine.rs b/apps/desktop/src-tauri/tests/git_engine.rs index 03c2bf43..dcca0c72 100644 --- a/apps/desktop/src-tauri/tests/git_engine.rs +++ b/apps/desktop/src-tauri/tests/git_engine.rs @@ -4325,6 +4325,381 @@ impl SubmoduleFixture { } } +fn submodule_rebase_topic(fx: &SubmoduleFixture) { + fx.local.write("notes.txt", "local note\n"); + commit_all(&fx.local, "local note"); + fx.local.write("later.txt", "another local note\n"); + commit_all(&fx.local, "later local note"); + core::fetch(fx.local.path(), "origin", false, false).unwrap(); +} + +fn assert_submodule_rebase_complete(fx: &SubmoduleFixture, checked_out: &str) { + let repo = &fx.local; + assert!(!rebase_in_progress(repo)); + assert_eq!(git_in(&repo.dir, &["branch", "--show-current"]), "master"); + assert_eq!(rev(repo, "HEAD~2"), rev(repo, "origin/master")); + assert_eq!( + &head_summaries(repo)[..3], + ["later local note", "local note", "bump lib"] + ); + assert_eq!(repo.read("notes.txt"), "local note\n"); + assert_eq!(repo.read("later.txt"), "another local note\n"); + assert_eq!(git_in(&repo.dir, &["rev-parse", ":deps/lib"]), fx.second); + assert_eq!(fx.checked_out(), checked_out); + assert_eq!( + git_in(&repo.dir, &["ls-files", "-v", "deps/lib"]), + "H deps/lib" + ); +} + +#[test] +fn rebase_replays_local_commits_when_upstream_moves_a_submodule() { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + fx.local + .write("deps/lib/scratch.txt", "untracked submodule work\n"); + + let outcome = core::rebase(fx.local.path(), "origin/master").unwrap(); + assert_eq!(outcome.status, "ok"); + assert_submodule_rebase_complete(&fx, &fx.first); + assert_eq!( + fx.local.read("deps/lib/scratch.txt"), + "untracked submodule work\n" + ); + assert_eq!( + git_in(&fx.local.dir, &["status", "--porcelain"]), + "M deps/lib" + ); +} + +#[test] +fn pull_with_rebase_replays_local_commits_when_upstream_moves_a_submodule() { + for mode in [Some("rebase"), None] { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + core::set_config(Some(fx.local.path()), "pull.rebase", "true", false).unwrap(); + + let outcome = core::pull(fx.local.path(), "origin", mode).unwrap(); + assert_eq!(outcome.status, "ok"); + assert_submodule_rebase_complete(&fx, &fx.first); + } +} + +#[test] +fn continue_recovers_a_rebase_stopped_by_submodule_drift_in_an_older_client() { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + stop_rebase_on_submodule_drift(&fx); + + let outcome = core::rebase_continue(fx.local.path()).unwrap(); + assert_eq!(outcome.status, "ok"); + assert_submodule_rebase_complete(&fx, &fx.first); +} + +fn stop_rebase_on_submodule_drift(fx: &SubmoduleFixture) { + let repo = git2::Repository::open(fx.local.path()).unwrap(); + let upstream = repo.find_reference("refs/remotes/origin/master").unwrap(); + let upstream = repo.reference_to_annotated_commit(&upstream).unwrap(); + let mut rebase = repo.rebase(None, Some(&upstream), None, None).unwrap(); + rebase.next().unwrap().unwrap(); + let error = rebase + .commit(None, &repo.signature().unwrap(), None) + .unwrap_err(); + assert_eq!(error.code(), git2::ErrorCode::Unmerged); + assert!(error.message().contains("unstaged changes")); +} + +#[test] +fn submodule_drift_does_not_hide_edited_files_or_leak_index_flags_on_continue() { + for blocked in [ + "parent edit", + "submodule edit", + "submodule staged edit", + "head lock", + ] { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + stop_rebase_on_submodule_drift(&fx); + let repo = &fx.local; + let index_path = repo.dir.join(".git/index"); + let before_index = std::fs::read(&index_path).unwrap(); + let before_head = rev(repo, "HEAD"); + match blocked { + "parent edit" => repo.write("README.md", "unsaved parent edit\n"), + "submodule edit" | "submodule staged edit" => { + repo.write("deps/lib/lib.txt", "unsaved submodule edit\n"); + if blocked == "submodule staged edit" { + git_in(&fx.local_sub(), &["add", "lib.txt"]); + } + } + "head lock" => { + std::fs::write(repo.dir.join(".git/HEAD.lock"), "another git process\n").unwrap(); + } + _ => unreachable!(), + } + + assert!(core::rebase_continue(repo.path()).is_err(), "{blocked}"); + assert!(rebase_in_progress(repo)); + assert_eq!(rev(repo, "HEAD"), before_head); + assert_eq!(std::fs::read(&index_path).unwrap(), before_index); + assert_eq!( + git_in(&repo.dir, &["ls-files", "-v", "deps/lib"]), + "H deps/lib" + ); + match blocked { + "parent edit" => { + assert_eq!(repo.read("README.md"), "unsaved parent edit\n"); + repo.write("README.md", "parent\n"); + } + "submodule edit" | "submodule staged edit" => { + assert_eq!(repo.read("deps/lib/lib.txt"), "unsaved submodule edit\n"); + git_in(&fx.local_sub(), &["reset", "--hard", "-q", "HEAD"]); + } + "head lock" => std::fs::remove_file(repo.dir.join(".git/HEAD.lock")).unwrap(), + _ => unreachable!(), + } + core::rebase_continue(repo.path()).unwrap(); + assert_submodule_rebase_complete(&fx, &fx.first); + } +} + +#[test] +fn app_rebase_and_pull_follow_the_submodule_and_keep_the_rewrite_hooks() { + if !hooks_runnable() { + return; + } + for operation in ["rebase", "pull", "configured pull"] { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + let repo = &fx.local; + let first = rev(repo, "HEAD~1"); + let second = rev(repo, "HEAD"); + let onto = rev(repo, "origin/master"); + record_post_hooks(&default_hooks(repo), POST_HOOK_LOG); + core::set_config(Some(repo.path()), "pull.rebase", "true", false).unwrap(); + + let outcome = match operation { + "rebase" => core::post_hooks::rebase(repo.path(), "origin/master", false), + "pull" => core::post_hooks::pull(repo.path(), "origin", Some("rebase"), false), + "configured pull" => core::post_hooks::pull(repo.path(), "origin", None, false), + _ => unreachable!(), + } + .into_result() + .unwrap(); + assert_eq!(outcome.value.status, "ok"); + assert_submodule_rebase_complete(&fx, &fx.second); + assert!(core::status(repo.path()).unwrap().files.is_empty()); + assert_eq!( + post_hook_runs(repo), + vec![ + format!("post-checkout {second} {onto} 1"), + "post-rewrite rebase".to_string(), + format!("{first} {}", rev(repo, "HEAD~1")), + format!("{second} {}", rev(repo, "HEAD")), + ] + ); + } +} + +#[test] +fn a_submodule_bump_can_pause_for_conflicts_then_continue_or_abort() { + if !hooks_runnable() { + return; + } + for action in ["continue", "skip hooks", "abort"] { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + let repo = &fx.local; + repo.write("README.md", "local parent edit\n"); + let conflict = commit_all(repo, "local parent edit"); + repo.write("last.txt", "last\n"); + let last = commit_all(repo, "last local note"); + fx._upstream.write("README.md", "upstream parent edit\n"); + let onto = commit_all(&fx._upstream, "upstream parent edit"); + let first = rev(repo, "HEAD~3"); + let second = rev(repo, "HEAD~2"); + record_post_hooks(&default_hooks(repo), POST_HOOK_LOG); + + let paused = core::post_hooks::pull( + repo.path(), + "origin", + Some("rebase"), + action == "skip hooks", + ) + .into_result() + .unwrap(); + assert_eq!(paused.value.status, "conflicts"); + assert!(rebase_in_progress(repo)); + assert_eq!(core::conflict_list(repo.path()).unwrap(), vec!["README.md"]); + assert_eq!(fx.checked_out(), fx.second); + assert_eq!( + post_hook_runs(repo), + if action == "skip hooks" { + vec![] + } else { + vec![format!("post-checkout {last} {onto} 1")] + } + ); + if action == "abort" { + core::submodule_synced(repo.path(), || core::rebase_abort(repo.path())).unwrap(); + assert!(!rebase_in_progress(repo)); + assert_eq!(rev(repo, "HEAD"), last); + assert_eq!(repo.read("README.md"), "local parent edit\n"); + assert_eq!(fx.checked_out(), fx.first); + assert!(post_hook_runs(repo).is_empty()); + continue; + } + git_in(&fx.local_sub(), &["checkout", "-q", &fx.first]); + assert_eq!( + core::rebase_continue(repo.path()).unwrap().status, + "conflicts" + ); + repo.write("README.md", "resolved parent edit\n"); + core::stage_file(repo.path(), "README.md").unwrap(); + let continued = core::post_hooks::rebase_continue(repo.path(), false).unwrap(); + assert_eq!(continued.value.status, "ok"); + assert!(!rebase_in_progress(repo)); + assert_eq!(rev(repo, "HEAD~4"), onto); + assert_eq!(repo.read("README.md"), "resolved parent edit\n"); + assert_eq!(repo.read("last.txt"), "last\n"); + assert_eq!(git_in(&repo.dir, &["rev-parse", ":deps/lib"]), fx.second); + assert_eq!(fx.checked_out(), fx.first); + assert_eq!( + git_in(&repo.dir, &["ls-files", "-v", "deps/lib"]), + "H deps/lib" + ); + assert_eq!( + post_hook_runs(repo), + if action == "skip hooks" { + vec![] + } else { + vec![ + "post-rewrite rebase".to_string(), + format!("{first} {}", rev(repo, "HEAD~3")), + format!("{second} {}", rev(repo, "HEAD~2")), + format!("{conflict} {}", rev(repo, "HEAD~1")), + format!("{last} {}", rev(repo, "HEAD")), + ] + } + ); + } +} + +#[test] +fn rebase_skips_an_already_applied_step_despite_submodule_drift() { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + fx._upstream.write("notes.txt", "local note\n"); + let onto = commit_all(&fx._upstream, "upstream note"); + core::fetch(fx.local.path(), "origin", false, false).unwrap(); + + let outcome = core::rebase(fx.local.path(), "origin/master").unwrap(); + assert_eq!(outcome.status, "ok"); + assert!(!rebase_in_progress(&fx.local)); + assert_eq!(rev(&fx.local, "HEAD~1"), onto); + assert_eq!( + &head_summaries(&fx.local)[..2], + ["later local note", "upstream note"] + ); + assert_eq!(fx.checked_out(), fx.first); + assert_eq!( + git_in(&fx.local.dir, &["ls-files", "-v", "deps/lib"]), + "H deps/lib" + ); +} + +#[test] +fn rebase_keeps_a_resolved_gitlink_and_replays_the_commits_after_it() { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + fx._library.write("lib.txt", "three\n"); + let third = commit_all(&fx._library, "lib three"); + git_in(&fx.local_sub(), &["fetch", "-q", "origin"]); + git_in(&fx.local_sub(), &["checkout", "-q", &third]); + core::stage_file(fx.local.path(), "deps/lib").unwrap(); + core::commit(fx.local.path(), "local lib bump", false).unwrap(); + fx.local.write("after.txt", "after the lib bump\n"); + commit_all(&fx.local, "after lib bump"); + + let paused = core::rebase(fx.local.path(), "origin/master").unwrap(); + assert_eq!(paused.status, "conflicts"); + assert_eq!( + core::conflict_list(fx.local.path()).unwrap(), + vec!["deps/lib"] + ); + assert_eq!( + core::rebase_continue(fx.local.path()).unwrap().status, + "conflicts" + ); + git_in(&fx.local_sub(), &["checkout", "-q", &fx.first]); + git_in( + &fx.local.dir, + &[ + "update-index", + "--cacheinfo", + &format!("160000,{third},deps/lib"), + ], + ); + + let outcome = core::rebase_continue(fx.local.path()).unwrap(); + assert_eq!(outcome.status, "ok"); + assert!(!rebase_in_progress(&fx.local)); + assert_eq!(rev(&fx.local, "HEAD~4"), rev(&fx.local, "origin/master")); + assert_eq!( + &head_summaries(&fx.local)[..5], + [ + "after lib bump", + "local lib bump", + "later local note", + "local note", + "bump lib" + ] + ); + assert_eq!(git_in(&fx.local.dir, &["rev-parse", ":deps/lib"]), third); + assert_eq!( + git_in(&fx.local.dir, &["rev-parse", "HEAD:deps/lib"]), + third + ); + assert_eq!(fx.checked_out(), fx.first); + assert_eq!(fx.local.read("after.txt"), "after the lib bump\n"); + assert_eq!( + git_in(&fx.local.dir, &["ls-files", "-v", "deps/lib"]), + "H deps/lib" + ); +} + +#[test] +fn submodule_drift_does_not_skip_a_replay_stopped_by_an_untracked_file() { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + std::fs::remove_file(fx.local.dir.join("later.txt")).unwrap(); + commit_all(&fx.local, "remove later note"); + fx.local.write("later.txt", "untracked parent work\n"); + + let error = core::rebase(fx.local.path(), "origin/master") + .unwrap_err() + .to_string(); + assert!(error.contains("later.txt"), "{error}"); + assert_eq!(fx.local.read("later.txt"), "untracked parent work\n"); + assert!(core::rebase_continue(fx.local.path()).is_err()); + std::fs::remove_file(fx.local.dir.join("later.txt")).unwrap(); + + let outcome = core::rebase_continue(fx.local.path()).unwrap(); + assert_eq!(outcome.status, "ok"); + assert_eq!( + &head_summaries(&fx.local)[..4], + [ + "remove later note", + "later local note", + "local note", + "bump lib" + ] + ); + assert!(!rebase_in_progress(&fx.local)); + assert_eq!(fx.checked_out(), fx.first); + assert!(!fx.local.dir.join("later.txt").exists()); +} + #[test] fn pull_moves_a_submodule_that_was_at_the_recorded_commit() { let fx = SubmoduleFixture::new(); From 45d58f8720aed483aab10637d1c46fabb106f53d Mon Sep 17 00:00:00 2001 From: Christian Lauinger Date: Fri, 13 Nov 2026 20:34:00 +0100 Subject: [PATCH 2/3] fix(rebase): follow submodules when resuming older rebases Recover eligible submodule checkouts from the original rebase tree when no app baseline exists. Save baselines across pauses and failed attempts so intentional checkout moves remain excluded from automatic updates. Exercise recovery through the app wrapper, require an updated checkout before post-rewrite and verify Stage all cannot revert the upstream gitlink. Cover retry, deliberate moves, blocked replay and invalid recovery metadata. --- CHANGELOG.md | 3 +- CLAUDE.md | 23 +++- apps/desktop/src-tauri/src/core/post_hooks.rs | 6 +- apps/desktop/src-tauri/src/core/submodule.rs | 85 +++++++++++- apps/desktop/src-tauri/tests/git_engine.rs | 128 +++++++++++++++++- 5 files changed, 233 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 95d981ba..c91ac9f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,7 +47,8 @@ All notable changes to AngKorGit are documented here. The format follows ### Fixed - **Pull with rebase handles upstream submodule updates.** Local commits now replay when the upstream changes a submodule's recorded commit. Continue rebase also - recovers a rebase stopped by this problem in an older version. (#89) + recovers a rebase stopped by this problem in an older version and updates clean + submodules still at their pre-rebase commits. (#89) - **Discarding staged changes writes the index once and leaves other files alone.** A file whose name contains `[`, `]`, `*` or `?` no longer resets files the name happens to match. The whole batch takes Git's index lock and stops without diff --git a/CLAUDE.md b/CLAUDE.md index d5544822..dc7991d1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4593,20 +4593,35 @@ update CLAUDE.md or docs/ — never the code. notes and post-rewrite. Do not hold the temporary index across next(), finish(), hooks or #88's reapply_stopped_step; they must see the original repository index. Raw engine rebase/pull/continue leave the submodule folder where it was; app - wrappers retain G53's existing follow rule, including after a conflict pause - (the conflicts outcome is Ok). An intentionally moved submodule during a pause - stays there on Continue. Older-client rebases stuck at commit() also resume. + wrappers use submodule::synced_rebase for rebase, pull and Continue. It keeps + eligible (name, checked-out OID) baselines in the per-worktree rebase-merge/ + angkorgit-submodules JSON file while a rebase is paused, also after an error. + Successful outcomes apply G53's safe follow rule before post-rewrite runs and + refresh the saved baseline to the resulting checkout; conflict outcomes are Ok + and follow too. Continue combines currently in-sync submodules with saved + baselines only where the checkout still matches. A submodule deliberately moved + after a pause is excluded, even when moved back to its original commit. For an + older-client rebase with no baseline file, the original rebase HEAD tree supplies + the baseline: only clean checkouts still at those gitlinks follow the completed + rebase's recorded commits. Without this fallback, the raw engine finished but + the app left stale gitlinks that Stage all could inadvertently roll back (G53). + Malformed baseline data is an error, never a reason to guess original eligibility. + The file is deleted with rebase state on finish/abort. Failed Continue attempts + leave checkouts untouched and preserve the baseline for retry after edits clear. Integration coverage includes explicit/configured pull, multiple replay commits, legacy recovery, normal-file and gitlink conflicts, Continue/abort, already-applied steps, #88's blocked replay, untracked submodule files, edited/staged submodule files, HEAD.lock failure, unchanged disk index on failure, no leaked flags, app synchronization, post-hook arguments/mappings and skipped hooks across a pause. + Recovery tests use the app wrapper, require the followed checkout before the + rewrite hook, verify Stage all has no gitlink rollback, and cover retry after + failure, deliberately moved legacy checkouts and app-started blocked replay. ## 9. Testing map | Suite | Location | Coverage | | --- | --- | --- | -| Rust integration (204 macOS + 1 clone; platform cases in CI) | `apps/desktop/src-tauri/tests/git_engine.rs`, `tests/clone_hooks.rs` (own binary, sets HOME) | stage/commit/history, amend, branch/merge(ff+normal+conflict+message), branch-over-tag ref resolution (merge/rebase/history filter), ff-merge preserving uncommitted changes, drag-merge sequence (checkout target → merge source), no-ff merge commit when ff possible, can-fast-forward only when strictly behind, merge message available only during conflicted merge, interactive rebase (reorder/drop + range listing, squash/reword, conflict aborts untouched, invalid-plan rejection), a rebase aborted during post-checkout returns without replaying commits or running post-rewrite, a rebase step stopped by an untracked file names that file and commit, Continue re-applies the stopped commit so every commit survives (issue #88, same history as `git rebase --continue`), a Continue while the file is still in the way stops again with the history untouched and can be retried, and a re-applied step that conflicts pauses with markers and a conflict entry, then completes after resolution, submodule gitlink drift during rebase/pull/Continue (issue #89: legacy recovery, conflicts/abort, resolved gitlinks, already-applied and blocked steps, hooks/skip, app synchronization and disk-index preservation; see G59), file history lists only touching commits + paginates with skip, conflict resolve, stash (whole tree + selected paths incl. an untracked-only pick, a staged pick that leaves other staged files alone and pops with a dirty index, a staged-new pick removed and restored, git CLI agreeing on stash list/show; stash_files lists tracked + untracked entries with source_oid; stash_restore_files restores chosen files incl. an untracked one and a deletion, keeps the stash, rejects unknown paths), remote-branch checkout (stale local fast-forwarded with an untracked file preserved + upstream set, diverged local kept), tags, cherry-pick (plain keeps the message verbatim; record-origin output byte-equal to `git cherry-pick -x` for plain and trailer-block messages; many: in-order with per-commit origin lines, first conflict stops the run with progress counts), revert, reset (+ unknown-mode error), history pagination with and without filters, history position lookup by full + short hash, history search positions (case-insensitive text, hash prefix, none, blank, author alone, text + author, unknown author), stashes listed in the default walk as single-parent commits with a stash decoration while their index/untracked helper commits stay hidden and a branch-filtered walk omits them, broken-symlink staging (unix), diff hunks + whole-file context, unstage_all/discard_all, discard_staged_file/all (HEAD restored for index + worktree, staged-new file deleted, other staged files untouched; a name with glob characters leaves the files it would match staged; a held index.lock changes nothing and the retry after it is gone discards and leaves no lock; either name of a staged rename restores the original; a file that replaced a folder gives the folder back), line+hunk ops on files without trailing newline, git-CLI interop, commit signing (SSH sign verified via `git verify-commit`, unsigned without config, amend re-signs, merge commit signed, failure blocks the commit and leaves HEAD/index untouched), PR checkout (fork-style refs/pull fetch creates + updates the local branch and re-runs cleanly, diverged local branch refused with HEAD untouched, same-repo tracking checkout sets the upstream), ref fingerprint (tracks refs/HEAD, ignores plain file edits), commit file lists (per-file counts without hunks), single-file commit diff scoped by pathspec, comparing two commits lists the net change exactly like `git diff --name-status A B` (a file changed and changed back is absent, a rename keeps its old path, counts and hunk lines are the net ones, swapping the commits flips additions into deletions) and works across two branches, worktrees (add lists + checks out the branch and reports is_worktree/main_path from inside the linked folder, new branch from a base commit + duplicate refused, branch held elsewhere refused, checkout of a held branch refused with HEAD untouched, dirty remove refused unless forced, prune of a deleted folder, ref fingerprint changes on add, `git worktree list --porcelain` reports the engine-created worktree and `git status` runs clean inside it), discover refuses a missing path instead of walking to the parent repo, push reports up_to_date without contacting the remote when the tip equals the tracking ref while `git push` prints Everything up-to-date, and pushes again after a new commit, push with tags lands a local tag on a bare remote through named refspecs, pull with mode rebase / configured pull.rebase keeps history linear while mode merge creates a merge commit, blame attributes lines to their commits and marks an uncommitted edit, blames at a revision and at `^`, an uncommitted edit inside a committed block keeps the author on both split halves (the G44 crash), untracked/staged-new files and paths missing from a commit get explicit errors, staging and unstaging a later hunk of a multi-hunk file leaves the other hunk alone, remote_add registers a remote that list and fetch then use while a duplicate or blank name is refused, reword of HEAD changes only the message (tree + author lines byte-equal, dirty worktree and staged file untouched), reword of an earlier commit rewrites the commits above it and returns the reworded commit's new oid while a dirty tree is refused, unpushed lists only commits missing from every refs/remotes ref, tree_files lists every path at a commit while commit_files still lists the two changed ones, index_files lists tracked and staged-new paths but no untracked file, file_contents reads a file at a commit and on disk as context lines with status unchanged, errors for a path missing from the commit and flags a NUL-byte file binary, the folder scan finds repos at any depth and repos inside repos while skipping node_modules, hidden folders, an empty `.git` folder and anything past the runaway depth guard, returns the discover-shaped path, a root that is itself a repo plus its nested repo, and an error for a missing folder, stage_files/unstage_files apply many paths in one index write, commit refuses an index that matches HEAD (HEAD and worktree untouched) and an empty first commit while a merge resolved to HEAD's tree still commits with two parents, submodules (a synced pull checks an in-sync submodule out at the bumped commit — fetching it — and leaves `git status --porcelain` empty, a synced checkout takes it back with the branch, the group Pull all does the same, a submodule with a local commit or an edited file stays where it is, an unsynced pull reports the drift as FileStatus.submodule recorded/checkedOut and discard_file, discard_all and submodule_update by path all check out the recorded commit, a submodule with only edited files reports no drift), pull_preview is empty when up to date or simply behind, lists the uncommitted files a pull would overwrite (and the real pull then fails), predicts the merge conflict a real pull then reports while leaving HEAD, status and the state files untouched, follows pull.rebase and stops at the first conflicting commit, catches a rebase conflict a merge would not have, reports none for edits that merge cleanly in both modes, and is None without an upstream or on a detached HEAD, commit hooks (a passing pre-commit commits and sees GIT_INDEX_FILE, a failing one blocks with its exit code and output as hook_failed detail and HEAD unchanged, a pre-commit that re-stages a formatted file commits the new content, commit-msg edits reach the commit while an untouched message stays byte-for-byte, a failing or emptying commit-msg blocks, no_verify skips failing hooks on commit and amend, amend runs both hooks with and without a new message, core.hooksPath wins over .git/hooks while `*.sample` and non-executable files never count, config-defined hooks are detected, commit-msg in a linked worktree writes that worktree's COMMIT_EDITMSG, both hooks see GIT_AUTHOR_NAME/EMAIL/DATE of the new commit and amend exports the original author after the identity changed, a pre-commit or commit-msg hook that checks out another branch at the same tip makes commit and amend refuse with both branch tips unchanged; pre-push gets the remote name and URL and a zero remote sha for a new branch, a failing one leaves the bare remote without the new commit and returns its output, a push with tags lists the branch update plus a lightweight and an annotated tag (tag object sha) and an up-to-date repeat sends empty stdin, push_tag runs it, a delete reads `(delete) `, a rejected non-fast-forward is left out while a force push carries the remote's current sha, it runs with empty stdin when nothing needs pushing and can fail that push, no_verify pushes past a failing hook on push and push_tag, core.hooksPath wins, a hook that outlasts an HTTP server's keep-alive timeout still lands the push and runs once, whether the server closes the idle connection or only half-closes it; post-* hooks: a branch switch, a new checked-out branch and a detached checkout run post-checkout with both heads and flag 1 while a branch made without checkout runs nothing, discarding a tracked file, all changes, staged changes and applying a stash file run post-checkout HEAD HEAD 0 once while discarding only untracked files runs nothing, post-merge 0 follows a fast-forward and a merge commit but not up to date or conflicts, amend and reword of HEAD run post-rewrite amend with old and new on stdin while a plain commit runs none, a rebase runs post-checkout orig onto 1 then post-rewrite rebase with one line per commit, a rebase onto HEAD itself or onto an upstream the branch already sits on linearly reports up_to_date, keeps the commits and runs nothing, the rebase's post-checkout sees HEAD at onto and the file without conflict markers although the rebase then stops on that conflict, Pull without hooks that stops on a rebase conflict, or on an untracked file after one commit was replayed, runs no post-rewrite when Continue (no_verify false) completes it, an up-to-date rebase still refuses unstaged or staged changes and a rebase in progress, repo_hooks reports a .husky hooksPath as inside the worktree (and ../shared-hooks or the default as not) and a pulled-in .husky/post-merge runs after a plain pull but not after a pull without hooks, (unix) a dangling `.git/hooks/post-merge` symlink into the worktree, a dangling `.git/hooks` folder symlink and a hook linked through an outside hop to a worktree file count as inside while a symlink to /usr/bin/true does not, a tracked `.husky` link to an empty folder outside counts as inside and the pull that replaces it with a folder holding post-merge runs that hook only without the skip, a hook linked to `proxy/../.husky/post-merge` with proxy linked to a worktree folder counts as inside, a core.hooksPath spelled in other letter case counts as inside exactly when the disk ignores case, an include.path to a tracked project.gitconfig holding only a comment counts as inside and the pull that adds core.hooksPath=.husky plus .husky/post-merge to it runs that hook only without the skip, a rebase goes through with only untracked files in a submodule but not with an edited one, an interactive rebase and the reword of an older commit go through with an edited submodule under `ignore = dirty` while the ordinary rebase still refuses it, and both interactive rebase and reword refuse a staged gitlink change under `ignore = all`, a quoted include through a .git symlink with a trailing space still offers the skip, a config scan that hits its 64-file limit with a tracked include still queued reports the hooks as inside the worktree, discarding three unstaged or two staged files in one call runs post-checkout once after all of them (and none for an untracked-only discard), (unix) a bulk discard records the untracked file it could not delete as failed, still restores the files before and after it and runs post-checkout once, (unix) Discard all staged changes does the same for a staged new file in a read-only folder (the files around it restored, one post-checkout seeing them), Pull all returns while a post-merge background job is running and lets it finish, while Cancel waits for a background job through a Linux pidfd or Windows job and immediately warns for a live macOS group; an exit-0 hook has no cancellation warning, and a setsid child can still write after Cancel without being seen, a fast-forward fails and leaves ORIG_HEAD and HEAD alone while ORIG_HEAD.lock is held and sets ORIG_HEAD once it is gone, and the script the pull brings runs only without the skip, a failing post-checkout's warning comes back next to the error of a replay that then fails, a fast-forward merge sets ORIG_HEAD so the post-merge hook's `git diff --name-only ORIG_HEAD HEAD` lists the new file, Pull all sets ORIG_HEAD to the old tip, a rebase paused on a conflict runs post-checkout and its continue runs post-rewrite once with the pairs from before the pause, an interactive pick + squash + drop runs post-checkout orig result 1, maps both picked commits to the squashed one and leaves the dropped one out, pull with rebase fast-forwards with post-merge when only behind and runs post-checkout + post-rewrite (no post-merge) when diverged while pull with merge runs post-merge and an up-to-date pull nothing, a failing post-checkout or post-merge comes back as a warning with exit code and output while HEAD moved, no_verify suppresses every post hook, Pull all runs post-merge in a repo that fast-forwarded but not in one already up to date, puts a failing hook on that repo's result while it still fast-forwards, and a run started skipping hooks runs none, group pull and the toolbar pull both run post-merge 0 and no post-checkout with core.hooksPath set, worktree add runs post-checkout 000… HEAD 1 inside the new worktree, and (clone_hooks.rs) a clone runs post-checkout 000… HEAD 1 from a global core.hooksPath while a no_verify clone and a clone of an empty repo run none) — skipped with a note when git ≥ 2.36 is not on PATH | +| Rust integration (208 macOS + 1 clone; platform cases in CI) | `apps/desktop/src-tauri/tests/git_engine.rs`, `tests/clone_hooks.rs` (own binary, sets HOME) | stage/commit/history, amend, branch/merge(ff+normal+conflict+message), branch-over-tag ref resolution (merge/rebase/history filter), ff-merge preserving uncommitted changes, drag-merge sequence (checkout target → merge source), no-ff merge commit when ff possible, can-fast-forward only when strictly behind, merge message available only during conflicted merge, interactive rebase (reorder/drop + range listing, squash/reword, conflict aborts untouched, invalid-plan rejection), a rebase aborted during post-checkout returns without replaying commits or running post-rewrite, a rebase step stopped by an untracked file names that file and commit, Continue re-applies the stopped commit so every commit survives (issue #88, same history as `git rebase --continue`), a Continue while the file is still in the way stops again with the history untouched and can be retried, and a re-applied step that conflicts pauses with markers and a conflict entry, then completes after resolution, submodule gitlink drift during rebase/pull/Continue (issue #89: legacy recovery, conflicts/abort, resolved gitlinks, already-applied and blocked steps, hooks/skip, app synchronization and disk-index preservation; see G59), file history lists only touching commits + paginates with skip, conflict resolve, stash (whole tree + selected paths incl. an untracked-only pick, a staged pick that leaves other staged files alone and pops with a dirty index, a staged-new pick removed and restored, git CLI agreeing on stash list/show; stash_files lists tracked + untracked entries with source_oid; stash_restore_files restores chosen files incl. an untracked one and a deletion, keeps the stash, rejects unknown paths), remote-branch checkout (stale local fast-forwarded with an untracked file preserved + upstream set, diverged local kept), tags, cherry-pick (plain keeps the message verbatim; record-origin output byte-equal to `git cherry-pick -x` for plain and trailer-block messages; many: in-order with per-commit origin lines, first conflict stops the run with progress counts), revert, reset (+ unknown-mode error), history pagination with and without filters, history position lookup by full + short hash, history search positions (case-insensitive text, hash prefix, none, blank, author alone, text + author, unknown author), stashes listed in the default walk as single-parent commits with a stash decoration while their index/untracked helper commits stay hidden and a branch-filtered walk omits them, broken-symlink staging (unix), diff hunks + whole-file context, unstage_all/discard_all, discard_staged_file/all (HEAD restored for index + worktree, staged-new file deleted, other staged files untouched; a name with glob characters leaves the files it would match staged; a held index.lock changes nothing and the retry after it is gone discards and leaves no lock; either name of a staged rename restores the original; a file that replaced a folder gives the folder back), line+hunk ops on files without trailing newline, git-CLI interop, commit signing (SSH sign verified via `git verify-commit`, unsigned without config, amend re-signs, merge commit signed, failure blocks the commit and leaves HEAD/index untouched), PR checkout (fork-style refs/pull fetch creates + updates the local branch and re-runs cleanly, diverged local branch refused with HEAD untouched, same-repo tracking checkout sets the upstream), ref fingerprint (tracks refs/HEAD, ignores plain file edits), commit file lists (per-file counts without hunks), single-file commit diff scoped by pathspec, comparing two commits lists the net change exactly like `git diff --name-status A B` (a file changed and changed back is absent, a rename keeps its old path, counts and hunk lines are the net ones, swapping the commits flips additions into deletions) and works across two branches, worktrees (add lists + checks out the branch and reports is_worktree/main_path from inside the linked folder, new branch from a base commit + duplicate refused, branch held elsewhere refused, checkout of a held branch refused with HEAD untouched, dirty remove refused unless forced, prune of a deleted folder, ref fingerprint changes on add, `git worktree list --porcelain` reports the engine-created worktree and `git status` runs clean inside it), discover refuses a missing path instead of walking to the parent repo, push reports up_to_date without contacting the remote when the tip equals the tracking ref while `git push` prints Everything up-to-date, and pushes again after a new commit, push with tags lands a local tag on a bare remote through named refspecs, pull with mode rebase / configured pull.rebase keeps history linear while mode merge creates a merge commit, blame attributes lines to their commits and marks an uncommitted edit, blames at a revision and at `^`, an uncommitted edit inside a committed block keeps the author on both split halves (the G44 crash), untracked/staged-new files and paths missing from a commit get explicit errors, staging and unstaging a later hunk of a multi-hunk file leaves the other hunk alone, remote_add registers a remote that list and fetch then use while a duplicate or blank name is refused, reword of HEAD changes only the message (tree + author lines byte-equal, dirty worktree and staged file untouched), reword of an earlier commit rewrites the commits above it and returns the reworded commit's new oid while a dirty tree is refused, unpushed lists only commits missing from every refs/remotes ref, tree_files lists every path at a commit while commit_files still lists the two changed ones, index_files lists tracked and staged-new paths but no untracked file, file_contents reads a file at a commit and on disk as context lines with status unchanged, errors for a path missing from the commit and flags a NUL-byte file binary, the folder scan finds repos at any depth and repos inside repos while skipping node_modules, hidden folders, an empty `.git` folder and anything past the runaway depth guard, returns the discover-shaped path, a root that is itself a repo plus its nested repo, and an error for a missing folder, stage_files/unstage_files apply many paths in one index write, commit refuses an index that matches HEAD (HEAD and worktree untouched) and an empty first commit while a merge resolved to HEAD's tree still commits with two parents, submodules (a synced pull checks an in-sync submodule out at the bumped commit — fetching it — and leaves `git status --porcelain` empty, a synced checkout takes it back with the branch, the group Pull all does the same, a submodule with a local commit or an edited file stays where it is, an unsynced pull reports the drift as FileStatus.submodule recorded/checkedOut and discard_file, discard_all and submodule_update by path all check out the recorded commit, a submodule with only edited files reports no drift), pull_preview is empty when up to date or simply behind, lists the uncommitted files a pull would overwrite (and the real pull then fails), predicts the merge conflict a real pull then reports while leaving HEAD, status and the state files untouched, follows pull.rebase and stops at the first conflicting commit, catches a rebase conflict a merge would not have, reports none for edits that merge cleanly in both modes, and is None without an upstream or on a detached HEAD, commit hooks (a passing pre-commit commits and sees GIT_INDEX_FILE, a failing one blocks with its exit code and output as hook_failed detail and HEAD unchanged, a pre-commit that re-stages a formatted file commits the new content, commit-msg edits reach the commit while an untouched message stays byte-for-byte, a failing or emptying commit-msg blocks, no_verify skips failing hooks on commit and amend, amend runs both hooks with and without a new message, core.hooksPath wins over .git/hooks while `*.sample` and non-executable files never count, config-defined hooks are detected, commit-msg in a linked worktree writes that worktree's COMMIT_EDITMSG, both hooks see GIT_AUTHOR_NAME/EMAIL/DATE of the new commit and amend exports the original author after the identity changed, a pre-commit or commit-msg hook that checks out another branch at the same tip makes commit and amend refuse with both branch tips unchanged; pre-push gets the remote name and URL and a zero remote sha for a new branch, a failing one leaves the bare remote without the new commit and returns its output, a push with tags lists the branch update plus a lightweight and an annotated tag (tag object sha) and an up-to-date repeat sends empty stdin, push_tag runs it, a delete reads `(delete) `, a rejected non-fast-forward is left out while a force push carries the remote's current sha, it runs with empty stdin when nothing needs pushing and can fail that push, no_verify pushes past a failing hook on push and push_tag, core.hooksPath wins, a hook that outlasts an HTTP server's keep-alive timeout still lands the push and runs once, whether the server closes the idle connection or only half-closes it; post-* hooks: a branch switch, a new checked-out branch and a detached checkout run post-checkout with both heads and flag 1 while a branch made without checkout runs nothing, discarding a tracked file, all changes, staged changes and applying a stash file run post-checkout HEAD HEAD 0 once while discarding only untracked files runs nothing, post-merge 0 follows a fast-forward and a merge commit but not up to date or conflicts, amend and reword of HEAD run post-rewrite amend with old and new on stdin while a plain commit runs none, a rebase runs post-checkout orig onto 1 then post-rewrite rebase with one line per commit, a rebase onto HEAD itself or onto an upstream the branch already sits on linearly reports up_to_date, keeps the commits and runs nothing, the rebase's post-checkout sees HEAD at onto and the file without conflict markers although the rebase then stops on that conflict, Pull without hooks that stops on a rebase conflict, or on an untracked file after one commit was replayed, runs no post-rewrite when Continue (no_verify false) completes it, an up-to-date rebase still refuses unstaged or staged changes and a rebase in progress, repo_hooks reports a .husky hooksPath as inside the worktree (and ../shared-hooks or the default as not) and a pulled-in .husky/post-merge runs after a plain pull but not after a pull without hooks, (unix) a dangling `.git/hooks/post-merge` symlink into the worktree, a dangling `.git/hooks` folder symlink and a hook linked through an outside hop to a worktree file count as inside while a symlink to /usr/bin/true does not, a tracked `.husky` link to an empty folder outside counts as inside and the pull that replaces it with a folder holding post-merge runs that hook only without the skip, a hook linked to `proxy/../.husky/post-merge` with proxy linked to a worktree folder counts as inside, a core.hooksPath spelled in other letter case counts as inside exactly when the disk ignores case, an include.path to a tracked project.gitconfig holding only a comment counts as inside and the pull that adds core.hooksPath=.husky plus .husky/post-merge to it runs that hook only without the skip, a rebase goes through with only untracked files in a submodule but not with an edited one, an interactive rebase and the reword of an older commit go through with an edited submodule under `ignore = dirty` while the ordinary rebase still refuses it, and both interactive rebase and reword refuse a staged gitlink change under `ignore = all`, a quoted include through a .git symlink with a trailing space still offers the skip, a config scan that hits its 64-file limit with a tracked include still queued reports the hooks as inside the worktree, discarding three unstaged or two staged files in one call runs post-checkout once after all of them (and none for an untracked-only discard), (unix) a bulk discard records the untracked file it could not delete as failed, still restores the files before and after it and runs post-checkout once, (unix) Discard all staged changes does the same for a staged new file in a read-only folder (the files around it restored, one post-checkout seeing them), Pull all returns while a post-merge background job is running and lets it finish, while Cancel waits for a background job through a Linux pidfd or Windows job and immediately warns for a live macOS group; an exit-0 hook has no cancellation warning, and a setsid child can still write after Cancel without being seen, a fast-forward fails and leaves ORIG_HEAD and HEAD alone while ORIG_HEAD.lock is held and sets ORIG_HEAD once it is gone, and the script the pull brings runs only without the skip, a failing post-checkout's warning comes back next to the error of a replay that then fails, a fast-forward merge sets ORIG_HEAD so the post-merge hook's `git diff --name-only ORIG_HEAD HEAD` lists the new file, Pull all sets ORIG_HEAD to the old tip, a rebase paused on a conflict runs post-checkout and its continue runs post-rewrite once with the pairs from before the pause, an interactive pick + squash + drop runs post-checkout orig result 1, maps both picked commits to the squashed one and leaves the dropped one out, pull with rebase fast-forwards with post-merge when only behind and runs post-checkout + post-rewrite (no post-merge) when diverged while pull with merge runs post-merge and an up-to-date pull nothing, a failing post-checkout or post-merge comes back as a warning with exit code and output while HEAD moved, no_verify suppresses every post hook, Pull all runs post-merge in a repo that fast-forwarded but not in one already up to date, puts a failing hook on that repo's result while it still fast-forwards, and a run started skipping hooks runs none, group pull and the toolbar pull both run post-merge 0 and no post-checkout with core.hooksPath set, worktree add runs post-checkout 000… HEAD 1 inside the new worktree, and (clone_hooks.rs) a clone runs post-checkout 000… HEAD 1 from a global core.hooksPath while a no_verify clone and a clone of an empty repo run none) — skipped with a note when git ≥ 2.36 is not on PATH | | Rust module (110 macOS; platform cases in CI) | `src/commands.rs` (2), `apps/desktop/src-tauri/src/cli.rs` (7), `src/state.rs` (1), `src/editors.rs` (5), `src/fonts.rs` (1), `src/ai_cli.rs` (18 macOS + Linux/Windows cases), `src/error.rs` (10), `src/core/hooks.rs` (12 macOS + Linux/Windows cases), `src/core/remote.rs` (20), `src/core/group_update.rs` (2), `src/terminal.rs` (3), `src/core/accounts.rs` (7), `src/core/sign.rs` (7), `src/forge.rs` (7), `src/proc.rs` (1), `src/watcher.rs` (7) | AI-CLI runner: program allowlist (incl. Cursor's `agent` and `cursor-agent` names), stdout capture via fake agent script, {OUTPUT_FILE} substitution, kill-on-timeout, a timed-out tree capture also killing the grandchild the shell started, a background process holding the pipes after exit not holding up the capture, cancellation waiting for a background job and stopping it at the deadline when a Linux pidfd or Windows job can signal it, macOS tracking a live group but reporting uncertainty immediately, and retain_for_cancel dropping an exit-0 tree, Cursor version-folder keys and the .cmd launcher → newest node.exe/index.js resolution (none for other agents or a missing versions dir) · error mapping: HTTP status extraction from libgit2 messages, 401/402/403 explanations, unmapped codes kept verbatim, io NotFound → not_found while other io errors stay io, hook failures serialize code hook_failed with the output as detail while other errors carry none · hooks: git version parsing incl. Apple and Windows suffixes, author dates in git's raw `@ <±hhmm>` form, runner choice (git for no input or ≥ 2.40, the hook file on unix for 2.36–2.39, a warning otherwise), the pre-push line format (new, up to date left out, delete, unknown remote commit kept), the direct runner handing a hook its args and stdin (unix), a hook without a shebang still getting its args, stdin, env and cwd through sh, only ENOEXEC triggering that retry, git-style whitespace cleanup of an edited message, output tail on a char boundary, post-checkout/post-merge/post-rewrite args and stdin in git's format with identical rebase pairs dropped, post-merge only after ok or fast_forward · forge proxy: api-subdomain host allowlist (dot-anchored), per-provider auth headers, bitbucket email requirement, unknown provider rejected, missing-token vs no-account message · SSH key resolution: `~` expansion, configured key ordered ahead of defaults, dedupe when the configured key IS a default, blank config ignored, generation never targeting an existing key · push refspec shapes (plain/force/tags never forced) · a retried push skips the pre-push hook only for update lines it already approved · rejection message quotes the server lines after the ref list (sideband lines trimmed, de-duplicated, "remote:" and rule lines dropped, capped at 12) · repo account-binding parse (valid/malformed) · accounts: upsert keeps both same-host accounts + default flags, one default per host, preferred-before-default candidate order, port-loose host match, ssh URLs ignored · signing config: off by default, ssh setup read from git config, empty-string values read as unset, ssh-without-key and x509 are clear errors, openpgp falls back to the committer identity, literal-key detection, ~ expansion · proc: no bare `Command::new` anywhere outside proc.rs (G31) · recents: new paths go on top in order, an existing path moves instead of duplicating, the list caps at RECENT_LIMIT · watcher: metadata filter unchanged for main repos, `worktrees/*/HEAD|gitdir|locked` relevant while `worktrees/*/index` is noise, a linked worktree watches its own gitdir + the shared commondir, main repos need no extra roots, a slow watch for the previous repo never replaces the current one, a late stop for the previous repo keeps the current watch, a stop while a watch is in flight drops it | | Unit (341) | `tests/unit/*.test.ts` | actionError (busy responses use info without a failure prefix, other errors keep default or custom formatting), themeContrast (every palette keeps body ≥ 7:1, muted ≥ 5.5:1, faint ≥ 4.5:1 against background and surface, in that order, and defines its own code comment colour), settingsFilter (AND terms, section labels, catalog coverage of every JSX card title), GraphLayout (incl. pagination stability, lane reuse), wordDiff (round-trip), conflict parse/serialize (diff3 labels, CRLF, bare markers, 8+-char content lines, close-without-separator — all lossless), cliAgents (per-agent argv/stdin shape incl. Cursor print mode with the prompt last, ANSI/OSC cleaning, output-file preference, error surfacing), aiProviders (empty/whitespace/missing content rejected for openai-compatible + ollama, HTTP status+body surfaced, real content passes; OpenAI itself gets max_completion_tokens while other compatible hosts and LM Studio keep max_tokens, a rejected temperature is dropped and remembered, a rejected max_tokens or max_completion_tokens swaps once and never loops, an unrelated 400 is not retried, a reasoning model that spent its budget thinking gets one retry at REASONING_MIN_TOKENS that sticks, a budget that ran out without reasoning explains itself), aiCapabilities (review conventions: absent by default, general-only, general+project order with precedence note, whitespace = absent, clipping), aiTextSegments (token parse: adjacent tokens, unclosed/inner-asterisk/multi-line markers stay literal, ** inside backticks is code), reviewSignature (staged-only, order-insensitive, unstaged-edit + set changes alter it, newline filenames don't collide, hashText determinism), commitStyle (prefix rule matching/tokens/ticket-fallthrough, `$`-sequence literalness, preset instructions, post-generation prefix enforcement), pullRequestUrl (https/scp/ssh remotes, non-standard ports kept, http preserved, ssh port dropped, Bitbucket Server /scm/ shape, .git-behind-slash strip, unknown forge → null), aiModels (per-provider list endpoints/headers incl. Groq-style base URLs, generateContent filtering for Gemini, dedupe/sort, invalid-JSON + HTTP-status errors, cli → empty without a request), forge (parseForgeRemote for all three forges + rejects, provider creation gating, github/gitlab/bitbucket adapters: request URLs, field mapping incl. fork + draft detection, create payloads, error-message surfacing incl. github field-level validation entries without a message, checkoutSpec shapes incl. bitbucket fork → null, pickForgeRemote upstream-first ordering, github 403 create refusals explained (fine-grained token into another owner's repo, missing pull request permission, rate limit left verbatim), gitlab self-hosted https→http transport fallback — GET-only (a retried POST could file a duplicate MR), never for gitlab.com or api-level errors, working scheme remembered per host and safe under concurrent fallbacks, reviewer candidates per forge + reviewer ids embedded/requested on create incl. github follow-up failure tolerance, authorAvatar per forge: github commit author, gitlab avatar-by-email URL encoding, bitbucket commit author user), worktree (folder-name slug from repo + branch, sibling-path suggestion incl. Windows separators, parentDirectory), highlight (block-comment continuation: JSDoc carried and closed, line comments and glob strings not treated as open, mid-line close resumes code, xml opener, no-block-comment languages ignore the flag; embedded languages: astro on the xml grammar, svelte/toml mappings, whole-file frontmatter + script/style blocks incl. lang="ts"/"scss" and a single-line script tag, hunk walk from line 1 and mid-file back to the first fence or closer, template-only hunk marks nothing, non-markup → null; shebangs: direct and env forms incl. -S and VAR=val, version suffixes, unknown interpreter and non-shebang → null, name and extension win over the shebang, diffFirstLine prefers the new side and falls back to a deleted file's old side), commitMessage (split/join round-trip, CRLF, second line without blank line is body, newline never enters the summary), fileFilter (empty/whitespace query passes all, case-insensitive substring, every term required), webUrl (https/scp/ssh:// remotes → repository page, ssh port dropped, http + web port kept, Bitbucket Server browse page, Bitbucket Cloud untouched, trailing slash, local path → null), blameable (hasCommittedHistory true for every tracked change kind, false for untracked and staged-new), imageMime (one media type per engine image extension, null otherwise), renderCap (lines at or under 5,000 chars stay whole, longer ones clip and count the hidden tail, custom cap), fork → upstream pull requests (github head `owner:branch`, gitlab GET target id then POST on the source project with target_project_id, bitbucket source.repository, forgeTargets dedupes same-host remotes and defaultForgeTarget prefers `upstream`), allFiles (tree paths marked with their change, deleted files kept, no duplicate paths, foldersWithChanges lists every ancestor of a changed file and nothing otherwise), fetchRemotes (continues after a failure and reports failures), patchText (headers + hunk headers + prefixed lines, rename old path, multi-file join, hasReviewableText rejects null/binary/image/empty), single-file review + explain prompts (file/where/sibling context lines, sibling cap at 30, section labels, conventions order, patch at the end, 4096-token budget), aiReport (labelled sections, bullet severities, continuation lines, verdict tones, unstructured fallback, bold inside a sentence is not a label), locateDiffLine (exact match prefers additions, deletion/context fallback, whitespace-insensitive whole-line hit, tiny/absent snippets null), commit review + explain prompts (commit line, file list capped at 30, conventions, patch at the end), terminalKeys (Alt+Up/Down map to ESC[1;3A/B on keydown only, every other modifier/key/phase left to xterm), chord (key from event.code so ⌥A stays A, unsupported keys null, id round-trip, exact modifier match, per-platform labels, no-modifier/reserved problems per platform, repoForChord lookup), repoGroups (empty/duplicate names ignoring case and the renamed group, least-used colour with wrap, recents bucketed in order with the rest ungrouped, a deleted group's paths fall back to ungrouped while empty groups stay listed, worktree inherits its main's group unless mapped itself, tabClusters/orderRepoTabs cluster open tabs by group with ungrouped last and leave a group-less strip alone, moveRepoGroup places a group before or after another and ignores self or unknown targets), tabLabels (unique names get no hint, nearest distinguishing parent folder, walks further up when parents collide, case-insensitive names and Windows separators), linePairs + pairHunk (the issue #62 hunk, single replacement always one row, comment block before a rewritten line, dissimilar deletion unpaired, pure runs unchanged, positional fallback past the cap, identical lines anchor, the demo load hunk; lineSimilarity ignores punctuation and repeats and compares symbol-only lines by text), remotes (pickRemote upstream → origin → first, pushSetsUpstream only for no upstream or the same remote), diffLocation (new line number for additions and context, old number and old path for a deletion, the clicked split pane wins, column only when given, none without a number on that side; columnAt counts characters from one, an emoji as one, nothing past the text or inside the clipped tail of a line over 5,000 characters) | | E2E (153) | `tests/e2e/smoke.spec.ts` | the AI button in the commit message editor keeps the summary focused after the click and Escape closes the editor while the stubbed Ollama /api/chat answer is held (the late answer is discarded), then fills summary + description from the commit's own diff and saves, folder rows in the working-copy tree stage and unstage everything inside them (one engine call each, chevron still folds, indeterminate in All files), stepping with n / the header chevron / p marks the active change rows and counts "k of n changes" in inline, split and wrapped views, View options stays open across two toggles, Settings filter (autofocus, SSH-only, first catalog hit across sections, locate flash, section-label match, no results, Escape clears then closes, close resets, AI section preset), splash→welcome, the AI chip names Ollama on the demo defaults, reads Set up AI when the CLI provider has no agent, Claude Code once picked, turns ok after Test connection, stale when the provider changes back to Ollama, and survives a reload, Blame is disabled in the file menu and the diff header for the untracked demo file while a tracked file keeps it enabled, the remote row menu's Open in browser opens the demo remote's GitHub page in a popup and the palette lists Open repository in browser, the sidebar and graph branch menus carry a fast-forward entry next to merge that is disabled while the current branch is ahead, settings installs the command line tool, settings lists the demo editors and picking Zed relabels the toolbar button and its menu, the Pull options menu offers merge and rebase, the status bar reports Fetched just now after the auto fetch, retries every remote after a partial auto fetch failure, keeps the timestamp and faint failed remote hint through partial and offline fetches, updates the timestamp on Pull, and explains the disabled Fetch button when no remotes exist, the diff header's Blame button opens file history in the blame pane with the Working copy row selected, per-hunk author buttons and an uncommitted hunk that disappears when a commit row is picked, a Blame at this commit menu, the Diff view toggle brings the diff controls back and Escape returns to the graph, the palette's Blame… picks a file and opens its blame pane, open repo, graph, inspector, palette, search, conflict resolver line picks, single-conflict nav + per-conflict take-all, per-block conflict hand edit, interactive rebase dialog + multi-select squash, cherry-pick dialog with the source-reference checkbox on by default, multi-select cherry-pick listing both commits and confirming, diff auto-jump lands at the first change with no scroll animation (frame-traced scrollTop), long path stays inside the discard confirm dialog, commit action buttons stay inside a narrow working copy panel (the row wraps), sidebar branch names align with and without the HEAD tick (measured left offsets), hovering a working-copy file reveals its full path, opening a diff folds the sidebar away and the toggle brings back the graph, avatars stay visible after a diff open/close round-trip (stubbed Gravatar), diff text selection survives the right-click copy menu and Esc closes only the menu, sidebar lists the demo pull requests and the create dialog opens, reconnecting an account opens the prefilled token form with focus in the token field, a file history row's Open commit button closes the panel and selects that commit in the graph, the author box finds commits with the graph lanes intact and combines with the text search, commit search finds matches in the full graph (n of m pill, Enter/Previous step, query survives selecting another commit, Escape clears), a search result that lands after a click keeps the clicked commit selected while clicking a match moves the pill to 2 of n and Enter steps to 3, searching a commit hash jumps to it in the full graph, a short hash prefix jumps too while an unknown hex word says No matches, a missing hash keeps the graph with No matches, mod+f focuses the commit search, sidebar lists the demo worktrees (incl. a missing-folder row) and the new-worktree dialog re-suggests the folder as the branch name is typed, the inner line of a JSDoc block in the demo CommitGraph.tsx diff renders as one hljs-comment span (guards the DiffViewer → prepareCommentStates wiring, which the unit tests cannot see), collapse-all folds every section and branch folder and a reopened section comes back with its folders closed, the inspector keeps its width (±1px) when a diff folds the sidebar away and both widths return on Escape (measured via data-panel-id after dragging the sidebar handle), the commit box renders the summary larger and bolder than the description with Enter/Backspace moving between them and commit disabled on an empty summary, dragging the commit box's top edge grows the description and double-click resets it, the Changes header's fold button collapses that list's folders (nested file hidden) and flips to expand-all, and no fold button exists in flat mode, the top graph row shows a whole `main` chip with no HEAD chip and no clipped chip text plus a 7-char hash copy button, the graph display menu hides the hash column and brings it back, the sidebar accordion pins collapsed headers at the bottom under an open Branches section and moves the Tags header up when Tags opens, the welcome page flags the demo's missing folder and opens a repository via ↓ + ⏎ from the autofocused search, the conflict resolver renders positive integer line numbers in A, B and Result with each starting at 1, the checked-out branch chip is opaque while another local branch's chip stays translucent, double-clicking the separated `origin/main` chip opens the reset prompt naming the 2 commits that would be lost and Cancel dismisses it (the demo repo puts origin/main 2 commits behind main so the split is real), the diff header's History button opens that same file's history panel and closes the diff, a working-copy row's "Stash this file…" opens the dialog naming that file and the toolbar pop button restores the latest demo stash, shift-click selects three working-copy rows and the bulk menu offers Stage 3 / Stash 3 files, the working-copy filter hides non-matching rows with "1 of 2" counts and the clear button restores them, the commit file filter narrows five demo files to one and Escape resets it, selecting the demo stash shows the stash hint and the hover restore button on a file toasts the restore, right-clicking a plain commit's file offers File history / Show in Finder / Copy path and no stash Apply entry, staged rows offer discard from the row, the menu and the header trash icon, the sidebar is visible again after a reload that happened with a diff open, the demo stash renders as a graph row with an Archive node and a dashed chip whose menu pops it, ↓ then → opens the second commit's first file with the file list focused, ↓/↑ walk files, twelve → presses stay on the same file and one ← returns to the graph on the same commit, the Graph display menu's "Lane color band" removes and restores the tail rects, the inspector stops at its minimum width when dragged and folds/returns for file history, dragging the sidebar shut and back open in one gesture shows its content again, conflict picks land in file order with a mixed-state side checkbox, the resolver picks with A/B/↑/↓ and ⌘⏎ opens the next conflicted file, leaving with picks asks first while Escape closes a clean resolver, right-clicking the main tip row offers Push main ↑2 while an inner commit's menu has no push, hovering the feature/diff-viewer chip stacks both its refs in a panel whose first chip sits on the row chip (≤2px) with the folded `release/0.4` under it, and right-clicking that one opens its Checkout menu (no reset entry for a plain local), the top row shows `main` as its visible chip although `hotfix/lane-colors` comes first in the refs and only `main` carries the check inside the stacked panel, right-clicking the separated `origin/main` chip offers "Reset main to this…" and opens the same reset dialog, clicking a working-copy file then ↓/↓/↑ moves the diff through ipc.ts → palette-seed.sql → Architecture.md and back — the Remotes header's Add remote button opens the add dialog with the button disabled until name and URL are filled, right-clicking the terminal shows Copy (disabled without a selection)/Paste/Select all/Clear terminal, Settings → Git → Clone destination remembers a chosen folder and the clone dialog's destination starts there, a four-row drag selection in the palette-seed diff stays a Range and still copies all four lines via ⌘C after its rows scroll out of the virtualizer in either direction, and reads the same text once scrolled back, the pushed demo commit opens the editor and Save asks "Rewrite a pushed commit?" (Cancel keeps the draft) while the top commit opens the inline editor on double-click (Esc cancels, Save rewrites the heading, body and graph row), the GitHub account form keeps the classic token link and adds the fine-grained page inline while the Token label still focuses the input, the Fonts card's Interface picker lists proportional fonts first and Code lists monospace first, picking Helvetica Neue/Fira Code changes --font-sans/--font-mono and the terminal follows Code until Menlo + 16 px is picked for it, all of it survives a reload and Reset fonts clears it, sidebar section headers and bodies carry no fill and no top border while each header shows a filled gold icon tile and a filled count badge, the commit Files header's A token narrows five files to one with All pressed off and back, the All files view lists Roadmap.md at the commit with 5 changed, keeps a change-free folder collapsed until clicked, opens the unchanged file with an unchanged badge and no @@ header while Folder tree hides it again, the working copy's All files view shows README.md beside the stage/unstage checkboxes of the changed files and opens it without a Stage file button, dragging a selection below the diff grows it past six lines from the start row and ⌘C copies the same text before and after scrolling away, the diff header's AI actions menu reviews the open file (busy strip → demo response under the header, Copy, fold to one line and back, full-view dialog, button disabled meanwhile, closing and reopening the diff dismisses the result) then explains it and Dismiss removes the panel, the inspector's Review with AI reviews the selected commit (Stop reviewing while busy, AI review card → demo response, Dismiss), file history's diff pane shows no change arrows on a commit that did not touch palette-seed.sql and, on the Working copy row, `n` jumps the scroller to the one change, `p` from the top wraps to it and the header's Next change button lands on the same offset, a second repo opened from the palette becomes a tab that ⌘1 / ⌘⇧] switch between (wrapping), the tab menu's Keyboard shortcut… capture box flags a bare `t` as no_modifier and ⌘K as reserved without opening the palette, saving ⌃⇧T shows the chip on the tab and the chord switches to it, and Settings → Shortcuts lists and removes it, Force push from the Push menu opens a "Force push?" confirm naming origin/main that Cancel dismisses without pushing, and repositories can be grouped on the welcome page: Add to group → New group… creates Frontend with a picked colour (Create disabled on an empty name, a duplicate name shows the taken hint), dragging a row onto the header moves it (counts 2 and 2), Enter in the name field creates Backend, the header menu's Move up puts Backend first (Move down disabled at the bottom) and Move down restores it, the header button collapses and re-expands it, searching flattens the list to the two matching rows, Open all in tabs opens both Frontend repos as tabs whose titles end in · Frontend, the tab menu's Move to group re-homes one to Backend and the strip splits into two clusters with chips, clicking the Backend chip hides its tab and shows Backend1, collapsing Frontend keeps the active tab visible, ⌘2 switches to the hidden temple-ui and reveals it, both chips expand again, the Backend chip's menu counts 1 under Close its tabs and Collapse other groups folds Frontend to Frontend1 while ⌘1 still reaches its hidden tab, Expand all groups brings both back, dragging the Backend chip onto the first cluster's left edge puts Backend first so ⌘1 reaches temple-ui and dragging it back restores Frontend, narrowing the window to 300px shows the overflow list whose temple-ui entry switches tabs and widening hides it again, no separators or overflow button exist with two tabs, the switcher lists repos under data-switcher-group labels, the palette's Close all in Backend closes its one open tab while Open all in Backend says 2 repositories, and Ungroup… confirms and leaves the repos in the list, the long-line diff scrollbar stays at the viewport bottom, pans both split panes together, accepts arrow keys and Shift+wheel, and disappears when wrapping is enabled, the code diff opened from a selected commit also scrolls horizontally in inline and split views, and a trackpad pan of one wheel event per frame moves the long-line diff by the whole gesture with no backward step, dragging the drawn thumb moves the layers by exactly the engine's scrollLeft and a click on the track pages back to 0, and a text selection dragged past the pane's right edge pans the long lines, grows the selection and stops panning when the pointer comes back, scanning ~/projects from the welcome page lists four repos with two marked In recents and disabled, unticking one adds the other to the recents list, a seeded tab whose folder is missing closes with a toast while two same-named angkorgit tabs show forks / projects hints and a unique one shows none, ⌘P on the welcome page filters four recents to temple-ui and Enter opens it as the only tab, ⌘P marks it Current and opens angkorgit as a second tab, a third ⌘P marks temple-ui Open tab and switches back without a new tab, ⌘K still opens the command palette, and ⌘T opens a picked folder as a third tab, the all files layout stacks the five demo commit files with GraphRow.tsx scrolled to the top and "2 of 5", clicking Architecture.md in the inspector scrolls it to the top ("4 of 5"), side by side applies inside the cards, a user wheel at the top moves the inspector highlight to CommitGraph.tsx, one file and then all files collapse and expand, Show one file returns to DiffPanel and the choice survives a reload, clicking a file in the inspector still jumps to it after scrolling reached it once and ← inside the page returns to the graph, a stash file never offers the all files layout even with 'all' remembered while a plain commit still gets it, a click into a file diff followed by ← closes it and returns to the graph, ⌘⏎ with nothing staged toasts "Stage some changes first" and commits nothing, and a file filter that hides every staged file leaves Commit enabled with the full count, and eleven tabs shrink to fit an 820px window with the inactive close buttons gone and no overflow button, scroll past their 48px floor at 480px and come back to their natural widths at 1440px, and What's new opens from the welcome footer and the status bar bell with its unread dot cleared once seen and after a reload, and a drifted demo submodule row has no Discard button, its menu offers Update submodule to efec64c without Discard changes…, and its hover Update button toasts the checkout and clears the row, and the Pull button carries a conflict warning whose tooltip names the files, opens "This pull will conflict" (Cancel closes, Pull and resolve pulls), switches to "Your changes are in the way" whose Stash 2 files… opens the stash dialog with those files, and shows no warning without a predicted problem, and a failing demo pre-commit hook opens the hook dialog with ANSI-free lint output (Close keeps the message and commits nothing, Commit without hooks commits) while a ticked Skip hooks commits directly and clears itself, and a repo without hooks shows no Skip hooks box, and a hook that fails after switching to another tab only toasts "Nothing was committed in angkorgit" there (no dialog, no commit, the other tab never shows Running hooks…) while the first tab keeps its draft and shows the waiting failure when the user returns, a commit hook keeps Commit busy as Running hooks… across selecting a graph commit and coming back and its failure dialog appears while the graph commit is shown, and Commit without hooks never reads Running hooks… while text typed during the run survives the commit, and a failing demo pre-push hook makes the toolbar Push open "A hook stopped the push" with ANSI-free test output while the Push menu offers Push without hooks (absent in a repo without hooks) and the dialog's Push without hooks pushes main, and after a Push without hooks that the remote rejects as non-fast-forward the dialog's Force push keeps skipping the hook and pushes main forced, and when develop was checked out while the hook ran the rejected dialog still names origin/main with Pull with rebase disabled ("Check out main first…") and Cancel focused, nothing pulls, and once main is checked out again the same dialog enables and focuses Pull with rebase, which pulls, and a graph chip takes its lane colour while every lane line is a rail (no cubic curves) and the WIP banner is opaque, a 14-lane demo history scrolls the graph sideways by exactly each wheel step, by the drawn thumb and back to 0 on a track click while vertical scrolling stays put, and dragging the Graph header edge narrows the column and its scrollbar, survives a reload and double-click resets it, and a running demo post-checkout shows a loading toast and responds to a second checkout with an info toast naming post-checkout and the repository, with no red failure toast, and a failing demo post-checkout hook shows a warning toast after "Checkout develop done" whose Show output opens the warning dialog with ANSI-free output and only Copy output and Close, the Pull menu's Pull without hooks pulls without the post-merge warning a plain Pull then shows (and is absent without hooks), and Pull all puts a post-merge warning with a collapsed Hook output on every updated row ("2 hook warnings") while Pull all without hooks from the group menu shows none, and a hook folder inside the worktree offers Pull without hooks and Pull all without hooks before any hook exists (but no Push without hooks), and the Pull menu shows Pull without hooks after the hook setup changed between two opens, Pull without hooks with a predicted conflict opens "This pull will conflict" first and Pull and resolve then pulls without the post-merge warning, and discarding three selected files shows one post-checkout warning, while a bulk discard that fails for one file names it with the reason and shows no success toast, and so does the Staged header's Discard all staged changes, and the Only matches toggle narrows a "merge" search to the matching commits with "n matching commits", steps them with Enter and brings the full graph back on the same commit, also when the search box is cleared — all on demo mode, and a squeezed same-name tab hint stays at least 18px wide in a 480px window, and graph nodes whose lanes leave the column stay inside it, pinned to an edge, at rest and after scrolling right, and right-clicking the 7th character of a diff line offers Copy path and line with `path:line:7` (copied, toast) while a right-click past the end of the text drops the column, and two cmd-selected commits offer Compare these commits, which puts a From/To header over the newer commit's file list (no message editor or AI buttons), opens a file diff and the all files layout labelled `older..newer`, swaps the direction from the header and leaves compare mode on a plain click, while three selected commits get no Compare entry, and switching to light and back recolours every element on the repo page in the same frame while hover fades keep their duration | diff --git a/apps/desktop/src-tauri/src/core/post_hooks.rs b/apps/desktop/src-tauri/src/core/post_hooks.rs index 987a0dce..893f26de 100644 --- a/apps/desktop/src-tauri/src/core/post_hooks.rs +++ b/apps/desktop/src-tauri/src/core/post_hooks.rs @@ -161,7 +161,7 @@ pub fn pull( no_verify: bool, ) -> Hooked> { let mut hooks = PostHooks::new(no_verify); - let outcome = submodule::synced(path, || { + let outcome = submodule::synced_rebase(path, || { remote::pull_with_hooks(path, remote_name, mode, &mut hooks) }); finished_or_failed(path, outcome, hooks) @@ -175,7 +175,7 @@ pub fn pull_branch(path: &str, branch_name: &str, no_verify: bool) -> AppResult< pub fn rebase(path: &str, upstream: &str, no_verify: bool) -> Hooked> { let mut hooks = PostHooks::new(no_verify); - let outcome = submodule::synced(path, || { + let outcome = submodule::synced_rebase(path, || { branch::rebase_with_hooks(path, upstream, &mut hooks) }); finished_or_failed(path, outcome, hooks) @@ -183,7 +183,7 @@ pub fn rebase(path: &str, upstream: &str, no_verify: bool) -> Hooked AppResult> { let mut hooks = PostHooks::new(no_verify); - let outcome = submodule::synced(path, || { + let outcome = submodule::synced_rebase(path, || { branch::rebase_continue_with_hooks(path, &mut hooks) })?; Ok(finished(path, outcome, hooks)) diff --git a/apps/desktop/src-tauri/src/core/submodule.rs b/apps/desktop/src-tauri/src/core/submodule.rs index 742a6890..cdc263a6 100644 --- a/apps/desktop/src-tauri/src/core/submodule.rs +++ b/apps/desktop/src-tauri/src/core/submodule.rs @@ -1,6 +1,6 @@ use git2::{Oid, Repository, Submodule, SubmoduleIgnore, SubmoduleStatus}; -use crate::error::AppResult; +use crate::error::{AppError, AppResult}; use super::types::{SubmoduleCommits, SubmoduleInfo}; @@ -54,6 +54,89 @@ pub fn synced(path: &str, op: impl FnOnce() -> AppResult) -> AppResult Ok(result) } +const REBASE_BASELINE: &str = "angkorgit-submodules"; + +pub fn synced_rebase(path: &str, op: impl FnOnce() -> AppResult) -> AppResult { + let before = rebase_baseline(&super::repo::open(path)?)?; + let result = op(); + if result.is_ok() { + follow_recorded(path, &before, true); + } + save_rebase_baseline(path, &before, result.is_ok())?; + result +} + +fn rebase_baseline(repo: &Repository) -> AppResult> { + let mut before = at_recorded_commit(repo); + if repo.state() != git2::RepositoryState::RebaseMerge { + return Ok(before); + } + let file = repo.path().join("rebase-merge").join(REBASE_BASELINE); + let saved = match std::fs::read(file) { + Ok(bytes) => serde_json::from_slice::>(&bytes) + .map_err(|error| { + AppError::other(format!("Cannot read rebase submodule baseline: {error}")) + })? + .into_iter() + .map(|(name, oid)| Ok((name, Oid::from_str(&oid)?))) + .collect::>>()?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let rebase = repo.open_rebase(None)?; + let original = rebase + .orig_head_id() + .ok_or_else(|| AppError::other("The rebase has no original commit"))?; + let tree = repo.find_commit(original)?.tree()?; + repo.submodules()? + .iter() + .filter_map(|submodule| { + let entry = tree.get_path(submodule.path()).ok()?; + let name = submodule.name()?.to_string(); + (entry.kind() == Some(git2::ObjectType::Commit)).then(|| (name, entry.id())) + }) + .collect() + } + Err(error) => return Err(error.into()), + }; + for (name, previous) in saved { + if before.iter().any(|(existing, _)| existing == &name) { + continue; + } + if repo + .find_submodule(&name) + .ok() + .and_then(|sub| sub.workdir_id()) + == Some(previous) + { + before.push((name, previous)); + } + } + Ok(before) +} + +fn save_rebase_baseline(path: &str, before: &[(String, Oid)], followed: bool) -> AppResult<()> { + let repo = super::repo::open(path)?; + if repo.state() != git2::RepositoryState::RebaseMerge { + return Ok(()); + } + let saved: Vec<_> = before + .iter() + .filter_map(|(name, previous)| { + let submodule = repo.find_submodule(name).ok()?; + let current = submodule.workdir_id()?; + (current == *previous || (followed && submodule.index_id() == Some(current))) + .then(|| (name, current.to_string())) + }) + .collect(); + let bytes = serde_json::to_vec(&saved).map_err(|error| { + AppError::other(format!("Cannot save rebase submodule baseline: {error}")) + })?; + std::fs::write( + repo.path().join("rebase-merge").join(REBASE_BASELINE), + bytes, + )?; + Ok(()) +} + pub fn at_recorded_commit(repo: &Repository) -> Vec<(String, Oid)> { let Ok(submodules) = repo.submodules() else { return Vec::new(); diff --git a/apps/desktop/src-tauri/tests/git_engine.rs b/apps/desktop/src-tauri/tests/git_engine.rs index dcca0c72..a7097669 100644 --- a/apps/desktop/src-tauri/tests/git_engine.rs +++ b/apps/desktop/src-tauri/tests/git_engine.rs @@ -4390,10 +4390,33 @@ fn continue_recovers_a_rebase_stopped_by_submodule_drift_in_an_older_client() { let fx = SubmoduleFixture::new(); submodule_rebase_topic(&fx); stop_rebase_on_submodule_drift(&fx); + fx.local + .write("deps/lib/scratch.txt", "untracked submodule work\n"); + if hooks_runnable() { + write_hook( + &default_hooks(&fx.local), + "post-rewrite", + &format!("git -C deps/lib rev-parse HEAD > '{POST_HOOK_LOG}'"), + ); + } - let outcome = core::rebase_continue(fx.local.path()).unwrap(); - assert_eq!(outcome.status, "ok"); - assert_submodule_rebase_complete(&fx, &fx.first); + let outcome = core::post_hooks::rebase_continue(fx.local.path(), false).unwrap(); + assert_eq!(outcome.value.status, "ok"); + assert_submodule_rebase_complete(&fx, &fx.second); + assert_eq!( + fx.local.read("deps/lib/scratch.txt"), + "untracked submodule work\n" + ); + if hooks_runnable() { + assert_eq!(post_hook_runs(&fx.local), vec![fx.second.clone()]); + } + std::fs::remove_file(fx.local.dir.join("deps/lib/scratch.txt")).unwrap(); + assert!(core::status(fx.local.path()).unwrap().files.is_empty()); + core::stage_all(fx.local.path()).unwrap(); + assert_eq!( + git_in(&fx.local.dir, &["diff", "--cached", "--name-only"]), + "" + ); } fn stop_rebase_on_submodule_drift(fx: &SubmoduleFixture) { @@ -4409,6 +4432,105 @@ fn stop_rebase_on_submodule_drift(fx: &SubmoduleFixture) { assert!(error.message().contains("unstaged changes")); } +#[test] +fn app_continue_retries_submodule_recovery_after_a_failed_continue() { + for file in ["README.md", "deps/lib/lib.txt"] { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + stop_rebase_on_submodule_drift(&fx); + let original = fx.local.read(file); + fx.local.write(file, "unsaved work\n"); + + assert!(core::post_hooks::rebase_continue(fx.local.path(), true).is_err()); + assert_eq!(fx.checked_out(), fx.first); + assert_eq!(fx.local.read(file), "unsaved work\n"); + fx.local.write(file, &original); + + let outcome = core::post_hooks::rebase_continue(fx.local.path(), true).unwrap(); + assert_eq!(outcome.value.status, "ok"); + assert_submodule_rebase_complete(&fx, &fx.second); + assert!(core::status(fx.local.path()).unwrap().files.is_empty()); + } +} + +#[test] +fn legacy_rebase_recovery_preserves_a_submodule_moved_to_another_commit() { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + stop_rebase_on_submodule_drift(&fx); + git_in( + &fx.local_sub(), + &[ + "commit", + "-q", + "--allow-empty", + "-m", + "intentional local move", + ], + ); + let moved = fx.checked_out(); + + let outcome = core::post_hooks::rebase_continue(fx.local.path(), true).unwrap(); + assert_eq!(outcome.value.status, "ok"); + assert_submodule_rebase_complete(&fx, &moved); +} + +#[test] +fn invalid_rebase_submodule_baselines_do_not_fall_back_to_original_gitlinks() { + for contents in ["interrupted JSON", "[[\"library\",\"invalid commit\"]]"] { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + stop_rebase_on_submodule_drift(&fx); + std::fs::write( + fx.local.dir.join(".git/rebase-merge/angkorgit-submodules"), + contents, + ) + .unwrap(); + let index = std::fs::read(fx.local.dir.join(".git/index")).unwrap(); + let head = rev(&fx.local, "HEAD"); + + assert!(core::post_hooks::rebase_continue(fx.local.path(), true).is_err()); + assert_eq!(rev(&fx.local, "HEAD"), head); + assert_eq!( + std::fs::read(fx.local.dir.join(".git/index")).unwrap(), + index + ); + assert_eq!(fx.checked_out(), fx.first); + assert!(rebase_in_progress(&fx.local)); + } +} + +#[test] +fn app_rebase_continues_following_submodules_after_a_blocked_replay() { + let fx = SubmoduleFixture::new(); + submodule_rebase_topic(&fx); + std::fs::remove_file(fx.local.dir.join("later.txt")).unwrap(); + commit_all(&fx.local, "remove later note"); + fx.local.write("later.txt", "untracked parent work\n"); + + assert!( + core::post_hooks::rebase(fx.local.path(), "origin/master", true) + .into_result() + .is_err() + ); + assert_eq!(fx.checked_out(), fx.first); + std::fs::remove_file(fx.local.dir.join("later.txt")).unwrap(); + let outcome = core::post_hooks::rebase_continue(fx.local.path(), true).unwrap(); + assert_eq!(outcome.value.status, "ok"); + assert_eq!(fx.checked_out(), fx.second); + assert!(!rebase_in_progress(&fx.local)); + assert!(core::status(fx.local.path()).unwrap().files.is_empty()); + assert_eq!( + &head_summaries(&fx.local)[..4], + [ + "remove later note", + "later local note", + "local note", + "bump lib" + ] + ); +} + #[test] fn submodule_drift_does_not_hide_edited_files_or_leak_index_flags_on_continue() { for blocked in [ From 10edd31d05713bf389ff7a87af572cc26f0517a5 Mon Sep 17 00:00:00 2001 From: Christian Lauinger Date: Fri, 13 Nov 2026 20:52:24 +0100 Subject: [PATCH 3/3] fix(rebase): make submodule recovery state best effort Publish synced baseline snapshots through an atomic tempfile replacement and preserve rebase outcomes when saving recovery metadata fails. Keep the old snapshot intact on partial writes. Try normal replay commits before inspecting submodules and retain the original libgit2 error when optional inspection fails. Cover atomic publication, partial write failures, conflict and blocker outcomes, and intermediate malformed gitmodules. --- CLAUDE.md | 22 +++++- apps/desktop/src-tauri/Cargo.toml | 4 +- apps/desktop/src-tauri/src/core/branch.rs | 21 +++++- apps/desktop/src-tauri/src/core/submodule.rs | 63 ++++++++++++++-- apps/desktop/src-tauri/tests/git_engine.rs | 79 ++++++++++++++++++++ 5 files changed, 173 insertions(+), 16 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index dc7991d1..ba7b61b5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ craftsmanship from Cambodia 🇰🇭. | Router | react-router-dom 6 (MemoryRouter: `/welcome`, `/repo`) | | | Icons / fonts | lucide-react · Inter Variable + JetBrains Mono (self-hosted @fontsource) | | | Key libs | @tanstack/react-virtual, react-resizable-panels, cmdk, sonner, @xterm/xterm, highlight.js (lib/core + 26 langs) | | -| Rust deps | tauri-plugin-dialog/opener, portable-pty, keyring 3, notify-debouncer-mini, reqwest (rustls), which 7, base64, thiserror, same-file (hook paths by file identity); tempfile for tests only | | +| Rust deps | tauri-plugin-dialog/opener, portable-pty, keyring 3, notify-debouncer-mini, reqwest (rustls), which 7, base64, thiserror, same-file (hook paths by file identity); tempfile for atomic rebase baseline writes and tests | | ## 3. Monorepo layout (pnpm workspaces) @@ -4580,7 +4580,11 @@ update CLAUDE.md or docs/ — never the code. "unstaged changes exist in workdir". Configuring ignore = all cannot override it, and the app's submodule::synced runs only after an Ok outcome, too late to help. branch::commit_rebase_step wraps all three replay commit sites (initial rebase, - Continue's current step and its remaining loop). For initialized submodules with + Continue's current step and its remaining loop). It tries plain rebase.commit + first; only an Unmerged error in the Rebase class activates the workaround. + Submodule enumeration/status failures then preserve that original commit error + rather than introducing optional inspection failures. Successful ordinary + commits never inspect submodules. For initialized submodules with commit drift but no staged or unstaged tracked edits inside, it copies the index into a pathless in-memory Index, preserving entry IDs, modes, stages and flags, and adds IndexEntryFlag::VALID only to their stage-zero gitlinks. The repository @@ -4596,6 +4600,12 @@ update CLAUDE.md or docs/ — never the code. wrappers use submodule::synced_rebase for rebase, pull and Continue. It keeps eligible (name, checked-out OID) baselines in the per-worktree rebase-merge/ angkorgit-submodules JSON file while a rebase is paused, also after an error. + Saves use a tempfile in that same directory, write_all + sync_all, then atomic + persist/replace (including on Windows); partial writes never truncate the live + baseline and failed saves clean up their temporary file. Save failures are + logged and never replace the operation's Ok/conflicts/error result, including + #88's blocker message. Baseline recovery is auxiliary; missing-submodule + enumeration while inferring a legacy baseline is best-effort too. Successful outcomes apply G53's safe follow rule before post-rewrite runs and refresh the saved baseline to the resulting checkout; conflict outcomes are Ok and follow too. Continue combines currently in-sync submodules with saved @@ -4616,13 +4626,17 @@ update CLAUDE.md or docs/ — never the code. Recovery tests use the app wrapper, require the followed checkout before the rewrite hook, verify Stage all has no gitlink rollback, and cover retry after failure, deliberately moved legacy checkouts and app-started blocked replay. + Atomic-publish tests check the old snapshot stays readable during a partial + write and after a simulated disk-full error. Integration tests force snapshot + publication failure after conflicts and a #88 stop, and replay plain-file + commits with an intermediate malformed .gitmodules that a later commit repairs. ## 9. Testing map | Suite | Location | Coverage | | --- | --- | --- | -| Rust integration (208 macOS + 1 clone; platform cases in CI) | `apps/desktop/src-tauri/tests/git_engine.rs`, `tests/clone_hooks.rs` (own binary, sets HOME) | stage/commit/history, amend, branch/merge(ff+normal+conflict+message), branch-over-tag ref resolution (merge/rebase/history filter), ff-merge preserving uncommitted changes, drag-merge sequence (checkout target → merge source), no-ff merge commit when ff possible, can-fast-forward only when strictly behind, merge message available only during conflicted merge, interactive rebase (reorder/drop + range listing, squash/reword, conflict aborts untouched, invalid-plan rejection), a rebase aborted during post-checkout returns without replaying commits or running post-rewrite, a rebase step stopped by an untracked file names that file and commit, Continue re-applies the stopped commit so every commit survives (issue #88, same history as `git rebase --continue`), a Continue while the file is still in the way stops again with the history untouched and can be retried, and a re-applied step that conflicts pauses with markers and a conflict entry, then completes after resolution, submodule gitlink drift during rebase/pull/Continue (issue #89: legacy recovery, conflicts/abort, resolved gitlinks, already-applied and blocked steps, hooks/skip, app synchronization and disk-index preservation; see G59), file history lists only touching commits + paginates with skip, conflict resolve, stash (whole tree + selected paths incl. an untracked-only pick, a staged pick that leaves other staged files alone and pops with a dirty index, a staged-new pick removed and restored, git CLI agreeing on stash list/show; stash_files lists tracked + untracked entries with source_oid; stash_restore_files restores chosen files incl. an untracked one and a deletion, keeps the stash, rejects unknown paths), remote-branch checkout (stale local fast-forwarded with an untracked file preserved + upstream set, diverged local kept), tags, cherry-pick (plain keeps the message verbatim; record-origin output byte-equal to `git cherry-pick -x` for plain and trailer-block messages; many: in-order with per-commit origin lines, first conflict stops the run with progress counts), revert, reset (+ unknown-mode error), history pagination with and without filters, history position lookup by full + short hash, history search positions (case-insensitive text, hash prefix, none, blank, author alone, text + author, unknown author), stashes listed in the default walk as single-parent commits with a stash decoration while their index/untracked helper commits stay hidden and a branch-filtered walk omits them, broken-symlink staging (unix), diff hunks + whole-file context, unstage_all/discard_all, discard_staged_file/all (HEAD restored for index + worktree, staged-new file deleted, other staged files untouched; a name with glob characters leaves the files it would match staged; a held index.lock changes nothing and the retry after it is gone discards and leaves no lock; either name of a staged rename restores the original; a file that replaced a folder gives the folder back), line+hunk ops on files without trailing newline, git-CLI interop, commit signing (SSH sign verified via `git verify-commit`, unsigned without config, amend re-signs, merge commit signed, failure blocks the commit and leaves HEAD/index untouched), PR checkout (fork-style refs/pull fetch creates + updates the local branch and re-runs cleanly, diverged local branch refused with HEAD untouched, same-repo tracking checkout sets the upstream), ref fingerprint (tracks refs/HEAD, ignores plain file edits), commit file lists (per-file counts without hunks), single-file commit diff scoped by pathspec, comparing two commits lists the net change exactly like `git diff --name-status A B` (a file changed and changed back is absent, a rename keeps its old path, counts and hunk lines are the net ones, swapping the commits flips additions into deletions) and works across two branches, worktrees (add lists + checks out the branch and reports is_worktree/main_path from inside the linked folder, new branch from a base commit + duplicate refused, branch held elsewhere refused, checkout of a held branch refused with HEAD untouched, dirty remove refused unless forced, prune of a deleted folder, ref fingerprint changes on add, `git worktree list --porcelain` reports the engine-created worktree and `git status` runs clean inside it), discover refuses a missing path instead of walking to the parent repo, push reports up_to_date without contacting the remote when the tip equals the tracking ref while `git push` prints Everything up-to-date, and pushes again after a new commit, push with tags lands a local tag on a bare remote through named refspecs, pull with mode rebase / configured pull.rebase keeps history linear while mode merge creates a merge commit, blame attributes lines to their commits and marks an uncommitted edit, blames at a revision and at `^`, an uncommitted edit inside a committed block keeps the author on both split halves (the G44 crash), untracked/staged-new files and paths missing from a commit get explicit errors, staging and unstaging a later hunk of a multi-hunk file leaves the other hunk alone, remote_add registers a remote that list and fetch then use while a duplicate or blank name is refused, reword of HEAD changes only the message (tree + author lines byte-equal, dirty worktree and staged file untouched), reword of an earlier commit rewrites the commits above it and returns the reworded commit's new oid while a dirty tree is refused, unpushed lists only commits missing from every refs/remotes ref, tree_files lists every path at a commit while commit_files still lists the two changed ones, index_files lists tracked and staged-new paths but no untracked file, file_contents reads a file at a commit and on disk as context lines with status unchanged, errors for a path missing from the commit and flags a NUL-byte file binary, the folder scan finds repos at any depth and repos inside repos while skipping node_modules, hidden folders, an empty `.git` folder and anything past the runaway depth guard, returns the discover-shaped path, a root that is itself a repo plus its nested repo, and an error for a missing folder, stage_files/unstage_files apply many paths in one index write, commit refuses an index that matches HEAD (HEAD and worktree untouched) and an empty first commit while a merge resolved to HEAD's tree still commits with two parents, submodules (a synced pull checks an in-sync submodule out at the bumped commit — fetching it — and leaves `git status --porcelain` empty, a synced checkout takes it back with the branch, the group Pull all does the same, a submodule with a local commit or an edited file stays where it is, an unsynced pull reports the drift as FileStatus.submodule recorded/checkedOut and discard_file, discard_all and submodule_update by path all check out the recorded commit, a submodule with only edited files reports no drift), pull_preview is empty when up to date or simply behind, lists the uncommitted files a pull would overwrite (and the real pull then fails), predicts the merge conflict a real pull then reports while leaving HEAD, status and the state files untouched, follows pull.rebase and stops at the first conflicting commit, catches a rebase conflict a merge would not have, reports none for edits that merge cleanly in both modes, and is None without an upstream or on a detached HEAD, commit hooks (a passing pre-commit commits and sees GIT_INDEX_FILE, a failing one blocks with its exit code and output as hook_failed detail and HEAD unchanged, a pre-commit that re-stages a formatted file commits the new content, commit-msg edits reach the commit while an untouched message stays byte-for-byte, a failing or emptying commit-msg blocks, no_verify skips failing hooks on commit and amend, amend runs both hooks with and without a new message, core.hooksPath wins over .git/hooks while `*.sample` and non-executable files never count, config-defined hooks are detected, commit-msg in a linked worktree writes that worktree's COMMIT_EDITMSG, both hooks see GIT_AUTHOR_NAME/EMAIL/DATE of the new commit and amend exports the original author after the identity changed, a pre-commit or commit-msg hook that checks out another branch at the same tip makes commit and amend refuse with both branch tips unchanged; pre-push gets the remote name and URL and a zero remote sha for a new branch, a failing one leaves the bare remote without the new commit and returns its output, a push with tags lists the branch update plus a lightweight and an annotated tag (tag object sha) and an up-to-date repeat sends empty stdin, push_tag runs it, a delete reads `(delete) `, a rejected non-fast-forward is left out while a force push carries the remote's current sha, it runs with empty stdin when nothing needs pushing and can fail that push, no_verify pushes past a failing hook on push and push_tag, core.hooksPath wins, a hook that outlasts an HTTP server's keep-alive timeout still lands the push and runs once, whether the server closes the idle connection or only half-closes it; post-* hooks: a branch switch, a new checked-out branch and a detached checkout run post-checkout with both heads and flag 1 while a branch made without checkout runs nothing, discarding a tracked file, all changes, staged changes and applying a stash file run post-checkout HEAD HEAD 0 once while discarding only untracked files runs nothing, post-merge 0 follows a fast-forward and a merge commit but not up to date or conflicts, amend and reword of HEAD run post-rewrite amend with old and new on stdin while a plain commit runs none, a rebase runs post-checkout orig onto 1 then post-rewrite rebase with one line per commit, a rebase onto HEAD itself or onto an upstream the branch already sits on linearly reports up_to_date, keeps the commits and runs nothing, the rebase's post-checkout sees HEAD at onto and the file without conflict markers although the rebase then stops on that conflict, Pull without hooks that stops on a rebase conflict, or on an untracked file after one commit was replayed, runs no post-rewrite when Continue (no_verify false) completes it, an up-to-date rebase still refuses unstaged or staged changes and a rebase in progress, repo_hooks reports a .husky hooksPath as inside the worktree (and ../shared-hooks or the default as not) and a pulled-in .husky/post-merge runs after a plain pull but not after a pull without hooks, (unix) a dangling `.git/hooks/post-merge` symlink into the worktree, a dangling `.git/hooks` folder symlink and a hook linked through an outside hop to a worktree file count as inside while a symlink to /usr/bin/true does not, a tracked `.husky` link to an empty folder outside counts as inside and the pull that replaces it with a folder holding post-merge runs that hook only without the skip, a hook linked to `proxy/../.husky/post-merge` with proxy linked to a worktree folder counts as inside, a core.hooksPath spelled in other letter case counts as inside exactly when the disk ignores case, an include.path to a tracked project.gitconfig holding only a comment counts as inside and the pull that adds core.hooksPath=.husky plus .husky/post-merge to it runs that hook only without the skip, a rebase goes through with only untracked files in a submodule but not with an edited one, an interactive rebase and the reword of an older commit go through with an edited submodule under `ignore = dirty` while the ordinary rebase still refuses it, and both interactive rebase and reword refuse a staged gitlink change under `ignore = all`, a quoted include through a .git symlink with a trailing space still offers the skip, a config scan that hits its 64-file limit with a tracked include still queued reports the hooks as inside the worktree, discarding three unstaged or two staged files in one call runs post-checkout once after all of them (and none for an untracked-only discard), (unix) a bulk discard records the untracked file it could not delete as failed, still restores the files before and after it and runs post-checkout once, (unix) Discard all staged changes does the same for a staged new file in a read-only folder (the files around it restored, one post-checkout seeing them), Pull all returns while a post-merge background job is running and lets it finish, while Cancel waits for a background job through a Linux pidfd or Windows job and immediately warns for a live macOS group; an exit-0 hook has no cancellation warning, and a setsid child can still write after Cancel without being seen, a fast-forward fails and leaves ORIG_HEAD and HEAD alone while ORIG_HEAD.lock is held and sets ORIG_HEAD once it is gone, and the script the pull brings runs only without the skip, a failing post-checkout's warning comes back next to the error of a replay that then fails, a fast-forward merge sets ORIG_HEAD so the post-merge hook's `git diff --name-only ORIG_HEAD HEAD` lists the new file, Pull all sets ORIG_HEAD to the old tip, a rebase paused on a conflict runs post-checkout and its continue runs post-rewrite once with the pairs from before the pause, an interactive pick + squash + drop runs post-checkout orig result 1, maps both picked commits to the squashed one and leaves the dropped one out, pull with rebase fast-forwards with post-merge when only behind and runs post-checkout + post-rewrite (no post-merge) when diverged while pull with merge runs post-merge and an up-to-date pull nothing, a failing post-checkout or post-merge comes back as a warning with exit code and output while HEAD moved, no_verify suppresses every post hook, Pull all runs post-merge in a repo that fast-forwarded but not in one already up to date, puts a failing hook on that repo's result while it still fast-forwards, and a run started skipping hooks runs none, group pull and the toolbar pull both run post-merge 0 and no post-checkout with core.hooksPath set, worktree add runs post-checkout 000… HEAD 1 inside the new worktree, and (clone_hooks.rs) a clone runs post-checkout 000… HEAD 1 from a global core.hooksPath while a no_verify clone and a clone of an empty repo run none) — skipped with a note when git ≥ 2.36 is not on PATH | -| Rust module (110 macOS; platform cases in CI) | `src/commands.rs` (2), `apps/desktop/src-tauri/src/cli.rs` (7), `src/state.rs` (1), `src/editors.rs` (5), `src/fonts.rs` (1), `src/ai_cli.rs` (18 macOS + Linux/Windows cases), `src/error.rs` (10), `src/core/hooks.rs` (12 macOS + Linux/Windows cases), `src/core/remote.rs` (20), `src/core/group_update.rs` (2), `src/terminal.rs` (3), `src/core/accounts.rs` (7), `src/core/sign.rs` (7), `src/forge.rs` (7), `src/proc.rs` (1), `src/watcher.rs` (7) | AI-CLI runner: program allowlist (incl. Cursor's `agent` and `cursor-agent` names), stdout capture via fake agent script, {OUTPUT_FILE} substitution, kill-on-timeout, a timed-out tree capture also killing the grandchild the shell started, a background process holding the pipes after exit not holding up the capture, cancellation waiting for a background job and stopping it at the deadline when a Linux pidfd or Windows job can signal it, macOS tracking a live group but reporting uncertainty immediately, and retain_for_cancel dropping an exit-0 tree, Cursor version-folder keys and the .cmd launcher → newest node.exe/index.js resolution (none for other agents or a missing versions dir) · error mapping: HTTP status extraction from libgit2 messages, 401/402/403 explanations, unmapped codes kept verbatim, io NotFound → not_found while other io errors stay io, hook failures serialize code hook_failed with the output as detail while other errors carry none · hooks: git version parsing incl. Apple and Windows suffixes, author dates in git's raw `@ <±hhmm>` form, runner choice (git for no input or ≥ 2.40, the hook file on unix for 2.36–2.39, a warning otherwise), the pre-push line format (new, up to date left out, delete, unknown remote commit kept), the direct runner handing a hook its args and stdin (unix), a hook without a shebang still getting its args, stdin, env and cwd through sh, only ENOEXEC triggering that retry, git-style whitespace cleanup of an edited message, output tail on a char boundary, post-checkout/post-merge/post-rewrite args and stdin in git's format with identical rebase pairs dropped, post-merge only after ok or fast_forward · forge proxy: api-subdomain host allowlist (dot-anchored), per-provider auth headers, bitbucket email requirement, unknown provider rejected, missing-token vs no-account message · SSH key resolution: `~` expansion, configured key ordered ahead of defaults, dedupe when the configured key IS a default, blank config ignored, generation never targeting an existing key · push refspec shapes (plain/force/tags never forced) · a retried push skips the pre-push hook only for update lines it already approved · rejection message quotes the server lines after the ref list (sideband lines trimmed, de-duplicated, "remote:" and rule lines dropped, capped at 12) · repo account-binding parse (valid/malformed) · accounts: upsert keeps both same-host accounts + default flags, one default per host, preferred-before-default candidate order, port-loose host match, ssh URLs ignored · signing config: off by default, ssh setup read from git config, empty-string values read as unset, ssh-without-key and x509 are clear errors, openpgp falls back to the committer identity, literal-key detection, ~ expansion · proc: no bare `Command::new` anywhere outside proc.rs (G31) · recents: new paths go on top in order, an existing path moves instead of duplicating, the list caps at RECENT_LIMIT · watcher: metadata filter unchanged for main repos, `worktrees/*/HEAD|gitdir|locked` relevant while `worktrees/*/index` is noise, a linked worktree watches its own gitdir + the shared commondir, main repos need no extra roots, a slow watch for the previous repo never replaces the current one, a late stop for the previous repo keeps the current watch, a stop while a watch is in flight drops it | +| Rust integration (210 macOS + 1 clone; platform cases in CI) | `apps/desktop/src-tauri/tests/git_engine.rs`, `tests/clone_hooks.rs` (own binary, sets HOME) | stage/commit/history, amend, branch/merge(ff+normal+conflict+message), branch-over-tag ref resolution (merge/rebase/history filter), ff-merge preserving uncommitted changes, drag-merge sequence (checkout target → merge source), no-ff merge commit when ff possible, can-fast-forward only when strictly behind, merge message available only during conflicted merge, interactive rebase (reorder/drop + range listing, squash/reword, conflict aborts untouched, invalid-plan rejection), a rebase aborted during post-checkout returns without replaying commits or running post-rewrite, a rebase step stopped by an untracked file names that file and commit, Continue re-applies the stopped commit so every commit survives (issue #88, same history as `git rebase --continue`), a Continue while the file is still in the way stops again with the history untouched and can be retried, and a re-applied step that conflicts pauses with markers and a conflict entry, then completes after resolution, submodule gitlink drift during rebase/pull/Continue (issue #89: legacy recovery, conflicts/abort, resolved gitlinks, already-applied and blocked steps, hooks/skip, app synchronization and disk-index preservation; see G59), file history lists only touching commits + paginates with skip, conflict resolve, stash (whole tree + selected paths incl. an untracked-only pick, a staged pick that leaves other staged files alone and pops with a dirty index, a staged-new pick removed and restored, git CLI agreeing on stash list/show; stash_files lists tracked + untracked entries with source_oid; stash_restore_files restores chosen files incl. an untracked one and a deletion, keeps the stash, rejects unknown paths), remote-branch checkout (stale local fast-forwarded with an untracked file preserved + upstream set, diverged local kept), tags, cherry-pick (plain keeps the message verbatim; record-origin output byte-equal to `git cherry-pick -x` for plain and trailer-block messages; many: in-order with per-commit origin lines, first conflict stops the run with progress counts), revert, reset (+ unknown-mode error), history pagination with and without filters, history position lookup by full + short hash, history search positions (case-insensitive text, hash prefix, none, blank, author alone, text + author, unknown author), stashes listed in the default walk as single-parent commits with a stash decoration while their index/untracked helper commits stay hidden and a branch-filtered walk omits them, broken-symlink staging (unix), diff hunks + whole-file context, unstage_all/discard_all, discard_staged_file/all (HEAD restored for index + worktree, staged-new file deleted, other staged files untouched; a name with glob characters leaves the files it would match staged; a held index.lock changes nothing and the retry after it is gone discards and leaves no lock; either name of a staged rename restores the original; a file that replaced a folder gives the folder back), line+hunk ops on files without trailing newline, git-CLI interop, commit signing (SSH sign verified via `git verify-commit`, unsigned without config, amend re-signs, merge commit signed, failure blocks the commit and leaves HEAD/index untouched), PR checkout (fork-style refs/pull fetch creates + updates the local branch and re-runs cleanly, diverged local branch refused with HEAD untouched, same-repo tracking checkout sets the upstream), ref fingerprint (tracks refs/HEAD, ignores plain file edits), commit file lists (per-file counts without hunks), single-file commit diff scoped by pathspec, comparing two commits lists the net change exactly like `git diff --name-status A B` (a file changed and changed back is absent, a rename keeps its old path, counts and hunk lines are the net ones, swapping the commits flips additions into deletions) and works across two branches, worktrees (add lists + checks out the branch and reports is_worktree/main_path from inside the linked folder, new branch from a base commit + duplicate refused, branch held elsewhere refused, checkout of a held branch refused with HEAD untouched, dirty remove refused unless forced, prune of a deleted folder, ref fingerprint changes on add, `git worktree list --porcelain` reports the engine-created worktree and `git status` runs clean inside it), discover refuses a missing path instead of walking to the parent repo, push reports up_to_date without contacting the remote when the tip equals the tracking ref while `git push` prints Everything up-to-date, and pushes again after a new commit, push with tags lands a local tag on a bare remote through named refspecs, pull with mode rebase / configured pull.rebase keeps history linear while mode merge creates a merge commit, blame attributes lines to their commits and marks an uncommitted edit, blames at a revision and at `^`, an uncommitted edit inside a committed block keeps the author on both split halves (the G44 crash), untracked/staged-new files and paths missing from a commit get explicit errors, staging and unstaging a later hunk of a multi-hunk file leaves the other hunk alone, remote_add registers a remote that list and fetch then use while a duplicate or blank name is refused, reword of HEAD changes only the message (tree + author lines byte-equal, dirty worktree and staged file untouched), reword of an earlier commit rewrites the commits above it and returns the reworded commit's new oid while a dirty tree is refused, unpushed lists only commits missing from every refs/remotes ref, tree_files lists every path at a commit while commit_files still lists the two changed ones, index_files lists tracked and staged-new paths but no untracked file, file_contents reads a file at a commit and on disk as context lines with status unchanged, errors for a path missing from the commit and flags a NUL-byte file binary, the folder scan finds repos at any depth and repos inside repos while skipping node_modules, hidden folders, an empty `.git` folder and anything past the runaway depth guard, returns the discover-shaped path, a root that is itself a repo plus its nested repo, and an error for a missing folder, stage_files/unstage_files apply many paths in one index write, commit refuses an index that matches HEAD (HEAD and worktree untouched) and an empty first commit while a merge resolved to HEAD's tree still commits with two parents, submodules (a synced pull checks an in-sync submodule out at the bumped commit — fetching it — and leaves `git status --porcelain` empty, a synced checkout takes it back with the branch, the group Pull all does the same, a submodule with a local commit or an edited file stays where it is, an unsynced pull reports the drift as FileStatus.submodule recorded/checkedOut and discard_file, discard_all and submodule_update by path all check out the recorded commit, a submodule with only edited files reports no drift), pull_preview is empty when up to date or simply behind, lists the uncommitted files a pull would overwrite (and the real pull then fails), predicts the merge conflict a real pull then reports while leaving HEAD, status and the state files untouched, follows pull.rebase and stops at the first conflicting commit, catches a rebase conflict a merge would not have, reports none for edits that merge cleanly in both modes, and is None without an upstream or on a detached HEAD, commit hooks (a passing pre-commit commits and sees GIT_INDEX_FILE, a failing one blocks with its exit code and output as hook_failed detail and HEAD unchanged, a pre-commit that re-stages a formatted file commits the new content, commit-msg edits reach the commit while an untouched message stays byte-for-byte, a failing or emptying commit-msg blocks, no_verify skips failing hooks on commit and amend, amend runs both hooks with and without a new message, core.hooksPath wins over .git/hooks while `*.sample` and non-executable files never count, config-defined hooks are detected, commit-msg in a linked worktree writes that worktree's COMMIT_EDITMSG, both hooks see GIT_AUTHOR_NAME/EMAIL/DATE of the new commit and amend exports the original author after the identity changed, a pre-commit or commit-msg hook that checks out another branch at the same tip makes commit and amend refuse with both branch tips unchanged; pre-push gets the remote name and URL and a zero remote sha for a new branch, a failing one leaves the bare remote without the new commit and returns its output, a push with tags lists the branch update plus a lightweight and an annotated tag (tag object sha) and an up-to-date repeat sends empty stdin, push_tag runs it, a delete reads `(delete) `, a rejected non-fast-forward is left out while a force push carries the remote's current sha, it runs with empty stdin when nothing needs pushing and can fail that push, no_verify pushes past a failing hook on push and push_tag, core.hooksPath wins, a hook that outlasts an HTTP server's keep-alive timeout still lands the push and runs once, whether the server closes the idle connection or only half-closes it; post-* hooks: a branch switch, a new checked-out branch and a detached checkout run post-checkout with both heads and flag 1 while a branch made without checkout runs nothing, discarding a tracked file, all changes, staged changes and applying a stash file run post-checkout HEAD HEAD 0 once while discarding only untracked files runs nothing, post-merge 0 follows a fast-forward and a merge commit but not up to date or conflicts, amend and reword of HEAD run post-rewrite amend with old and new on stdin while a plain commit runs none, a rebase runs post-checkout orig onto 1 then post-rewrite rebase with one line per commit, a rebase onto HEAD itself or onto an upstream the branch already sits on linearly reports up_to_date, keeps the commits and runs nothing, the rebase's post-checkout sees HEAD at onto and the file without conflict markers although the rebase then stops on that conflict, Pull without hooks that stops on a rebase conflict, or on an untracked file after one commit was replayed, runs no post-rewrite when Continue (no_verify false) completes it, an up-to-date rebase still refuses unstaged or staged changes and a rebase in progress, repo_hooks reports a .husky hooksPath as inside the worktree (and ../shared-hooks or the default as not) and a pulled-in .husky/post-merge runs after a plain pull but not after a pull without hooks, (unix) a dangling `.git/hooks/post-merge` symlink into the worktree, a dangling `.git/hooks` folder symlink and a hook linked through an outside hop to a worktree file count as inside while a symlink to /usr/bin/true does not, a tracked `.husky` link to an empty folder outside counts as inside and the pull that replaces it with a folder holding post-merge runs that hook only without the skip, a hook linked to `proxy/../.husky/post-merge` with proxy linked to a worktree folder counts as inside, a core.hooksPath spelled in other letter case counts as inside exactly when the disk ignores case, an include.path to a tracked project.gitconfig holding only a comment counts as inside and the pull that adds core.hooksPath=.husky plus .husky/post-merge to it runs that hook only without the skip, a rebase goes through with only untracked files in a submodule but not with an edited one, an interactive rebase and the reword of an older commit go through with an edited submodule under `ignore = dirty` while the ordinary rebase still refuses it, and both interactive rebase and reword refuse a staged gitlink change under `ignore = all`, a quoted include through a .git symlink with a trailing space still offers the skip, a config scan that hits its 64-file limit with a tracked include still queued reports the hooks as inside the worktree, discarding three unstaged or two staged files in one call runs post-checkout once after all of them (and none for an untracked-only discard), (unix) a bulk discard records the untracked file it could not delete as failed, still restores the files before and after it and runs post-checkout once, (unix) Discard all staged changes does the same for a staged new file in a read-only folder (the files around it restored, one post-checkout seeing them), Pull all returns while a post-merge background job is running and lets it finish, while Cancel waits for a background job through a Linux pidfd or Windows job and immediately warns for a live macOS group; an exit-0 hook has no cancellation warning, and a setsid child can still write after Cancel without being seen, a fast-forward fails and leaves ORIG_HEAD and HEAD alone while ORIG_HEAD.lock is held and sets ORIG_HEAD once it is gone, and the script the pull brings runs only without the skip, a failing post-checkout's warning comes back next to the error of a replay that then fails, a fast-forward merge sets ORIG_HEAD so the post-merge hook's `git diff --name-only ORIG_HEAD HEAD` lists the new file, Pull all sets ORIG_HEAD to the old tip, a rebase paused on a conflict runs post-checkout and its continue runs post-rewrite once with the pairs from before the pause, an interactive pick + squash + drop runs post-checkout orig result 1, maps both picked commits to the squashed one and leaves the dropped one out, pull with rebase fast-forwards with post-merge when only behind and runs post-checkout + post-rewrite (no post-merge) when diverged while pull with merge runs post-merge and an up-to-date pull nothing, a failing post-checkout or post-merge comes back as a warning with exit code and output while HEAD moved, no_verify suppresses every post hook, Pull all runs post-merge in a repo that fast-forwarded but not in one already up to date, puts a failing hook on that repo's result while it still fast-forwards, and a run started skipping hooks runs none, group pull and the toolbar pull both run post-merge 0 and no post-checkout with core.hooksPath set, worktree add runs post-checkout 000… HEAD 1 inside the new worktree, and (clone_hooks.rs) a clone runs post-checkout 000… HEAD 1 from a global core.hooksPath while a no_verify clone and a clone of an empty repo run none) — skipped with a note when git ≥ 2.36 is not on PATH | +| Rust module (112 macOS; platform cases in CI) | `src/commands.rs` (2), `src/core/submodule.rs` (2 atomic baseline-write tests), `apps/desktop/src-tauri/src/cli.rs` (7), `src/state.rs` (1), `src/editors.rs` (5), `src/fonts.rs` (1), `src/ai_cli.rs` (18 macOS + Linux/Windows cases), `src/error.rs` (10), `src/core/hooks.rs` (12 macOS + Linux/Windows cases), `src/core/remote.rs` (20), `src/core/group_update.rs` (2), `src/terminal.rs` (3), `src/core/accounts.rs` (7), `src/core/sign.rs` (7), `src/forge.rs` (7), `src/proc.rs` (1), `src/watcher.rs` (7) | AI-CLI runner: program allowlist (incl. Cursor's `agent` and `cursor-agent` names), stdout capture via fake agent script, {OUTPUT_FILE} substitution, kill-on-timeout, a timed-out tree capture also killing the grandchild the shell started, a background process holding the pipes after exit not holding up the capture, cancellation waiting for a background job and stopping it at the deadline when a Linux pidfd or Windows job can signal it, macOS tracking a live group but reporting uncertainty immediately, and retain_for_cancel dropping an exit-0 tree, Cursor version-folder keys and the .cmd launcher → newest node.exe/index.js resolution (none for other agents or a missing versions dir) · error mapping: HTTP status extraction from libgit2 messages, 401/402/403 explanations, unmapped codes kept verbatim, io NotFound → not_found while other io errors stay io, hook failures serialize code hook_failed with the output as detail while other errors carry none · hooks: git version parsing incl. Apple and Windows suffixes, author dates in git's raw `@ <±hhmm>` form, runner choice (git for no input or ≥ 2.40, the hook file on unix for 2.36–2.39, a warning otherwise), the pre-push line format (new, up to date left out, delete, unknown remote commit kept), the direct runner handing a hook its args and stdin (unix), a hook without a shebang still getting its args, stdin, env and cwd through sh, only ENOEXEC triggering that retry, git-style whitespace cleanup of an edited message, output tail on a char boundary, post-checkout/post-merge/post-rewrite args and stdin in git's format with identical rebase pairs dropped, post-merge only after ok or fast_forward · forge proxy: api-subdomain host allowlist (dot-anchored), per-provider auth headers, bitbucket email requirement, unknown provider rejected, missing-token vs no-account message · SSH key resolution: `~` expansion, configured key ordered ahead of defaults, dedupe when the configured key IS a default, blank config ignored, generation never targeting an existing key · push refspec shapes (plain/force/tags never forced) · a retried push skips the pre-push hook only for update lines it already approved · rejection message quotes the server lines after the ref list (sideband lines trimmed, de-duplicated, "remote:" and rule lines dropped, capped at 12) · repo account-binding parse (valid/malformed) · accounts: upsert keeps both same-host accounts + default flags, one default per host, preferred-before-default candidate order, port-loose host match, ssh URLs ignored · signing config: off by default, ssh setup read from git config, empty-string values read as unset, ssh-without-key and x509 are clear errors, openpgp falls back to the committer identity, literal-key detection, ~ expansion · proc: no bare `Command::new` anywhere outside proc.rs (G31) · recents: new paths go on top in order, an existing path moves instead of duplicating, the list caps at RECENT_LIMIT · watcher: metadata filter unchanged for main repos, `worktrees/*/HEAD|gitdir|locked` relevant while `worktrees/*/index` is noise, a linked worktree watches its own gitdir + the shared commondir, main repos need no extra roots, a slow watch for the previous repo never replaces the current one, a late stop for the previous repo keeps the current watch, a stop while a watch is in flight drops it | | Unit (341) | `tests/unit/*.test.ts` | actionError (busy responses use info without a failure prefix, other errors keep default or custom formatting), themeContrast (every palette keeps body ≥ 7:1, muted ≥ 5.5:1, faint ≥ 4.5:1 against background and surface, in that order, and defines its own code comment colour), settingsFilter (AND terms, section labels, catalog coverage of every JSX card title), GraphLayout (incl. pagination stability, lane reuse), wordDiff (round-trip), conflict parse/serialize (diff3 labels, CRLF, bare markers, 8+-char content lines, close-without-separator — all lossless), cliAgents (per-agent argv/stdin shape incl. Cursor print mode with the prompt last, ANSI/OSC cleaning, output-file preference, error surfacing), aiProviders (empty/whitespace/missing content rejected for openai-compatible + ollama, HTTP status+body surfaced, real content passes; OpenAI itself gets max_completion_tokens while other compatible hosts and LM Studio keep max_tokens, a rejected temperature is dropped and remembered, a rejected max_tokens or max_completion_tokens swaps once and never loops, an unrelated 400 is not retried, a reasoning model that spent its budget thinking gets one retry at REASONING_MIN_TOKENS that sticks, a budget that ran out without reasoning explains itself), aiCapabilities (review conventions: absent by default, general-only, general+project order with precedence note, whitespace = absent, clipping), aiTextSegments (token parse: adjacent tokens, unclosed/inner-asterisk/multi-line markers stay literal, ** inside backticks is code), reviewSignature (staged-only, order-insensitive, unstaged-edit + set changes alter it, newline filenames don't collide, hashText determinism), commitStyle (prefix rule matching/tokens/ticket-fallthrough, `$`-sequence literalness, preset instructions, post-generation prefix enforcement), pullRequestUrl (https/scp/ssh remotes, non-standard ports kept, http preserved, ssh port dropped, Bitbucket Server /scm/ shape, .git-behind-slash strip, unknown forge → null), aiModels (per-provider list endpoints/headers incl. Groq-style base URLs, generateContent filtering for Gemini, dedupe/sort, invalid-JSON + HTTP-status errors, cli → empty without a request), forge (parseForgeRemote for all three forges + rejects, provider creation gating, github/gitlab/bitbucket adapters: request URLs, field mapping incl. fork + draft detection, create payloads, error-message surfacing incl. github field-level validation entries without a message, checkoutSpec shapes incl. bitbucket fork → null, pickForgeRemote upstream-first ordering, github 403 create refusals explained (fine-grained token into another owner's repo, missing pull request permission, rate limit left verbatim), gitlab self-hosted https→http transport fallback — GET-only (a retried POST could file a duplicate MR), never for gitlab.com or api-level errors, working scheme remembered per host and safe under concurrent fallbacks, reviewer candidates per forge + reviewer ids embedded/requested on create incl. github follow-up failure tolerance, authorAvatar per forge: github commit author, gitlab avatar-by-email URL encoding, bitbucket commit author user), worktree (folder-name slug from repo + branch, sibling-path suggestion incl. Windows separators, parentDirectory), highlight (block-comment continuation: JSDoc carried and closed, line comments and glob strings not treated as open, mid-line close resumes code, xml opener, no-block-comment languages ignore the flag; embedded languages: astro on the xml grammar, svelte/toml mappings, whole-file frontmatter + script/style blocks incl. lang="ts"/"scss" and a single-line script tag, hunk walk from line 1 and mid-file back to the first fence or closer, template-only hunk marks nothing, non-markup → null; shebangs: direct and env forms incl. -S and VAR=val, version suffixes, unknown interpreter and non-shebang → null, name and extension win over the shebang, diffFirstLine prefers the new side and falls back to a deleted file's old side), commitMessage (split/join round-trip, CRLF, second line without blank line is body, newline never enters the summary), fileFilter (empty/whitespace query passes all, case-insensitive substring, every term required), webUrl (https/scp/ssh:// remotes → repository page, ssh port dropped, http + web port kept, Bitbucket Server browse page, Bitbucket Cloud untouched, trailing slash, local path → null), blameable (hasCommittedHistory true for every tracked change kind, false for untracked and staged-new), imageMime (one media type per engine image extension, null otherwise), renderCap (lines at or under 5,000 chars stay whole, longer ones clip and count the hidden tail, custom cap), fork → upstream pull requests (github head `owner:branch`, gitlab GET target id then POST on the source project with target_project_id, bitbucket source.repository, forgeTargets dedupes same-host remotes and defaultForgeTarget prefers `upstream`), allFiles (tree paths marked with their change, deleted files kept, no duplicate paths, foldersWithChanges lists every ancestor of a changed file and nothing otherwise), fetchRemotes (continues after a failure and reports failures), patchText (headers + hunk headers + prefixed lines, rename old path, multi-file join, hasReviewableText rejects null/binary/image/empty), single-file review + explain prompts (file/where/sibling context lines, sibling cap at 30, section labels, conventions order, patch at the end, 4096-token budget), aiReport (labelled sections, bullet severities, continuation lines, verdict tones, unstructured fallback, bold inside a sentence is not a label), locateDiffLine (exact match prefers additions, deletion/context fallback, whitespace-insensitive whole-line hit, tiny/absent snippets null), commit review + explain prompts (commit line, file list capped at 30, conventions, patch at the end), terminalKeys (Alt+Up/Down map to ESC[1;3A/B on keydown only, every other modifier/key/phase left to xterm), chord (key from event.code so ⌥A stays A, unsupported keys null, id round-trip, exact modifier match, per-platform labels, no-modifier/reserved problems per platform, repoForChord lookup), repoGroups (empty/duplicate names ignoring case and the renamed group, least-used colour with wrap, recents bucketed in order with the rest ungrouped, a deleted group's paths fall back to ungrouped while empty groups stay listed, worktree inherits its main's group unless mapped itself, tabClusters/orderRepoTabs cluster open tabs by group with ungrouped last and leave a group-less strip alone, moveRepoGroup places a group before or after another and ignores self or unknown targets), tabLabels (unique names get no hint, nearest distinguishing parent folder, walks further up when parents collide, case-insensitive names and Windows separators), linePairs + pairHunk (the issue #62 hunk, single replacement always one row, comment block before a rewritten line, dissimilar deletion unpaired, pure runs unchanged, positional fallback past the cap, identical lines anchor, the demo load hunk; lineSimilarity ignores punctuation and repeats and compares symbol-only lines by text), remotes (pickRemote upstream → origin → first, pushSetsUpstream only for no upstream or the same remote), diffLocation (new line number for additions and context, old number and old path for a deletion, the clicked split pane wins, column only when given, none without a number on that side; columnAt counts characters from one, an emoji as one, nothing past the text or inside the clipped tail of a line over 5,000 characters) | | E2E (153) | `tests/e2e/smoke.spec.ts` | the AI button in the commit message editor keeps the summary focused after the click and Escape closes the editor while the stubbed Ollama /api/chat answer is held (the late answer is discarded), then fills summary + description from the commit's own diff and saves, folder rows in the working-copy tree stage and unstage everything inside them (one engine call each, chevron still folds, indeterminate in All files), stepping with n / the header chevron / p marks the active change rows and counts "k of n changes" in inline, split and wrapped views, View options stays open across two toggles, Settings filter (autofocus, SSH-only, first catalog hit across sections, locate flash, section-label match, no results, Escape clears then closes, close resets, AI section preset), splash→welcome, the AI chip names Ollama on the demo defaults, reads Set up AI when the CLI provider has no agent, Claude Code once picked, turns ok after Test connection, stale when the provider changes back to Ollama, and survives a reload, Blame is disabled in the file menu and the diff header for the untracked demo file while a tracked file keeps it enabled, the remote row menu's Open in browser opens the demo remote's GitHub page in a popup and the palette lists Open repository in browser, the sidebar and graph branch menus carry a fast-forward entry next to merge that is disabled while the current branch is ahead, settings installs the command line tool, settings lists the demo editors and picking Zed relabels the toolbar button and its menu, the Pull options menu offers merge and rebase, the status bar reports Fetched just now after the auto fetch, retries every remote after a partial auto fetch failure, keeps the timestamp and faint failed remote hint through partial and offline fetches, updates the timestamp on Pull, and explains the disabled Fetch button when no remotes exist, the diff header's Blame button opens file history in the blame pane with the Working copy row selected, per-hunk author buttons and an uncommitted hunk that disappears when a commit row is picked, a Blame at this commit menu, the Diff view toggle brings the diff controls back and Escape returns to the graph, the palette's Blame… picks a file and opens its blame pane, open repo, graph, inspector, palette, search, conflict resolver line picks, single-conflict nav + per-conflict take-all, per-block conflict hand edit, interactive rebase dialog + multi-select squash, cherry-pick dialog with the source-reference checkbox on by default, multi-select cherry-pick listing both commits and confirming, diff auto-jump lands at the first change with no scroll animation (frame-traced scrollTop), long path stays inside the discard confirm dialog, commit action buttons stay inside a narrow working copy panel (the row wraps), sidebar branch names align with and without the HEAD tick (measured left offsets), hovering a working-copy file reveals its full path, opening a diff folds the sidebar away and the toggle brings back the graph, avatars stay visible after a diff open/close round-trip (stubbed Gravatar), diff text selection survives the right-click copy menu and Esc closes only the menu, sidebar lists the demo pull requests and the create dialog opens, reconnecting an account opens the prefilled token form with focus in the token field, a file history row's Open commit button closes the panel and selects that commit in the graph, the author box finds commits with the graph lanes intact and combines with the text search, commit search finds matches in the full graph (n of m pill, Enter/Previous step, query survives selecting another commit, Escape clears), a search result that lands after a click keeps the clicked commit selected while clicking a match moves the pill to 2 of n and Enter steps to 3, searching a commit hash jumps to it in the full graph, a short hash prefix jumps too while an unknown hex word says No matches, a missing hash keeps the graph with No matches, mod+f focuses the commit search, sidebar lists the demo worktrees (incl. a missing-folder row) and the new-worktree dialog re-suggests the folder as the branch name is typed, the inner line of a JSDoc block in the demo CommitGraph.tsx diff renders as one hljs-comment span (guards the DiffViewer → prepareCommentStates wiring, which the unit tests cannot see), collapse-all folds every section and branch folder and a reopened section comes back with its folders closed, the inspector keeps its width (±1px) when a diff folds the sidebar away and both widths return on Escape (measured via data-panel-id after dragging the sidebar handle), the commit box renders the summary larger and bolder than the description with Enter/Backspace moving between them and commit disabled on an empty summary, dragging the commit box's top edge grows the description and double-click resets it, the Changes header's fold button collapses that list's folders (nested file hidden) and flips to expand-all, and no fold button exists in flat mode, the top graph row shows a whole `main` chip with no HEAD chip and no clipped chip text plus a 7-char hash copy button, the graph display menu hides the hash column and brings it back, the sidebar accordion pins collapsed headers at the bottom under an open Branches section and moves the Tags header up when Tags opens, the welcome page flags the demo's missing folder and opens a repository via ↓ + ⏎ from the autofocused search, the conflict resolver renders positive integer line numbers in A, B and Result with each starting at 1, the checked-out branch chip is opaque while another local branch's chip stays translucent, double-clicking the separated `origin/main` chip opens the reset prompt naming the 2 commits that would be lost and Cancel dismisses it (the demo repo puts origin/main 2 commits behind main so the split is real), the diff header's History button opens that same file's history panel and closes the diff, a working-copy row's "Stash this file…" opens the dialog naming that file and the toolbar pop button restores the latest demo stash, shift-click selects three working-copy rows and the bulk menu offers Stage 3 / Stash 3 files, the working-copy filter hides non-matching rows with "1 of 2" counts and the clear button restores them, the commit file filter narrows five demo files to one and Escape resets it, selecting the demo stash shows the stash hint and the hover restore button on a file toasts the restore, right-clicking a plain commit's file offers File history / Show in Finder / Copy path and no stash Apply entry, staged rows offer discard from the row, the menu and the header trash icon, the sidebar is visible again after a reload that happened with a diff open, the demo stash renders as a graph row with an Archive node and a dashed chip whose menu pops it, ↓ then → opens the second commit's first file with the file list focused, ↓/↑ walk files, twelve → presses stay on the same file and one ← returns to the graph on the same commit, the Graph display menu's "Lane color band" removes and restores the tail rects, the inspector stops at its minimum width when dragged and folds/returns for file history, dragging the sidebar shut and back open in one gesture shows its content again, conflict picks land in file order with a mixed-state side checkbox, the resolver picks with A/B/↑/↓ and ⌘⏎ opens the next conflicted file, leaving with picks asks first while Escape closes a clean resolver, right-clicking the main tip row offers Push main ↑2 while an inner commit's menu has no push, hovering the feature/diff-viewer chip stacks both its refs in a panel whose first chip sits on the row chip (≤2px) with the folded `release/0.4` under it, and right-clicking that one opens its Checkout menu (no reset entry for a plain local), the top row shows `main` as its visible chip although `hotfix/lane-colors` comes first in the refs and only `main` carries the check inside the stacked panel, right-clicking the separated `origin/main` chip offers "Reset main to this…" and opens the same reset dialog, clicking a working-copy file then ↓/↓/↑ moves the diff through ipc.ts → palette-seed.sql → Architecture.md and back — the Remotes header's Add remote button opens the add dialog with the button disabled until name and URL are filled, right-clicking the terminal shows Copy (disabled without a selection)/Paste/Select all/Clear terminal, Settings → Git → Clone destination remembers a chosen folder and the clone dialog's destination starts there, a four-row drag selection in the palette-seed diff stays a Range and still copies all four lines via ⌘C after its rows scroll out of the virtualizer in either direction, and reads the same text once scrolled back, the pushed demo commit opens the editor and Save asks "Rewrite a pushed commit?" (Cancel keeps the draft) while the top commit opens the inline editor on double-click (Esc cancels, Save rewrites the heading, body and graph row), the GitHub account form keeps the classic token link and adds the fine-grained page inline while the Token label still focuses the input, the Fonts card's Interface picker lists proportional fonts first and Code lists monospace first, picking Helvetica Neue/Fira Code changes --font-sans/--font-mono and the terminal follows Code until Menlo + 16 px is picked for it, all of it survives a reload and Reset fonts clears it, sidebar section headers and bodies carry no fill and no top border while each header shows a filled gold icon tile and a filled count badge, the commit Files header's A token narrows five files to one with All pressed off and back, the All files view lists Roadmap.md at the commit with 5 changed, keeps a change-free folder collapsed until clicked, opens the unchanged file with an unchanged badge and no @@ header while Folder tree hides it again, the working copy's All files view shows README.md beside the stage/unstage checkboxes of the changed files and opens it without a Stage file button, dragging a selection below the diff grows it past six lines from the start row and ⌘C copies the same text before and after scrolling away, the diff header's AI actions menu reviews the open file (busy strip → demo response under the header, Copy, fold to one line and back, full-view dialog, button disabled meanwhile, closing and reopening the diff dismisses the result) then explains it and Dismiss removes the panel, the inspector's Review with AI reviews the selected commit (Stop reviewing while busy, AI review card → demo response, Dismiss), file history's diff pane shows no change arrows on a commit that did not touch palette-seed.sql and, on the Working copy row, `n` jumps the scroller to the one change, `p` from the top wraps to it and the header's Next change button lands on the same offset, a second repo opened from the palette becomes a tab that ⌘1 / ⌘⇧] switch between (wrapping), the tab menu's Keyboard shortcut… capture box flags a bare `t` as no_modifier and ⌘K as reserved without opening the palette, saving ⌃⇧T shows the chip on the tab and the chord switches to it, and Settings → Shortcuts lists and removes it, Force push from the Push menu opens a "Force push?" confirm naming origin/main that Cancel dismisses without pushing, and repositories can be grouped on the welcome page: Add to group → New group… creates Frontend with a picked colour (Create disabled on an empty name, a duplicate name shows the taken hint), dragging a row onto the header moves it (counts 2 and 2), Enter in the name field creates Backend, the header menu's Move up puts Backend first (Move down disabled at the bottom) and Move down restores it, the header button collapses and re-expands it, searching flattens the list to the two matching rows, Open all in tabs opens both Frontend repos as tabs whose titles end in · Frontend, the tab menu's Move to group re-homes one to Backend and the strip splits into two clusters with chips, clicking the Backend chip hides its tab and shows Backend1, collapsing Frontend keeps the active tab visible, ⌘2 switches to the hidden temple-ui and reveals it, both chips expand again, the Backend chip's menu counts 1 under Close its tabs and Collapse other groups folds Frontend to Frontend1 while ⌘1 still reaches its hidden tab, Expand all groups brings both back, dragging the Backend chip onto the first cluster's left edge puts Backend first so ⌘1 reaches temple-ui and dragging it back restores Frontend, narrowing the window to 300px shows the overflow list whose temple-ui entry switches tabs and widening hides it again, no separators or overflow button exist with two tabs, the switcher lists repos under data-switcher-group labels, the palette's Close all in Backend closes its one open tab while Open all in Backend says 2 repositories, and Ungroup… confirms and leaves the repos in the list, the long-line diff scrollbar stays at the viewport bottom, pans both split panes together, accepts arrow keys and Shift+wheel, and disappears when wrapping is enabled, the code diff opened from a selected commit also scrolls horizontally in inline and split views, and a trackpad pan of one wheel event per frame moves the long-line diff by the whole gesture with no backward step, dragging the drawn thumb moves the layers by exactly the engine's scrollLeft and a click on the track pages back to 0, and a text selection dragged past the pane's right edge pans the long lines, grows the selection and stops panning when the pointer comes back, scanning ~/projects from the welcome page lists four repos with two marked In recents and disabled, unticking one adds the other to the recents list, a seeded tab whose folder is missing closes with a toast while two same-named angkorgit tabs show forks / projects hints and a unique one shows none, ⌘P on the welcome page filters four recents to temple-ui and Enter opens it as the only tab, ⌘P marks it Current and opens angkorgit as a second tab, a third ⌘P marks temple-ui Open tab and switches back without a new tab, ⌘K still opens the command palette, and ⌘T opens a picked folder as a third tab, the all files layout stacks the five demo commit files with GraphRow.tsx scrolled to the top and "2 of 5", clicking Architecture.md in the inspector scrolls it to the top ("4 of 5"), side by side applies inside the cards, a user wheel at the top moves the inspector highlight to CommitGraph.tsx, one file and then all files collapse and expand, Show one file returns to DiffPanel and the choice survives a reload, clicking a file in the inspector still jumps to it after scrolling reached it once and ← inside the page returns to the graph, a stash file never offers the all files layout even with 'all' remembered while a plain commit still gets it, a click into a file diff followed by ← closes it and returns to the graph, ⌘⏎ with nothing staged toasts "Stage some changes first" and commits nothing, and a file filter that hides every staged file leaves Commit enabled with the full count, and eleven tabs shrink to fit an 820px window with the inactive close buttons gone and no overflow button, scroll past their 48px floor at 480px and come back to their natural widths at 1440px, and What's new opens from the welcome footer and the status bar bell with its unread dot cleared once seen and after a reload, and a drifted demo submodule row has no Discard button, its menu offers Update submodule to efec64c without Discard changes…, and its hover Update button toasts the checkout and clears the row, and the Pull button carries a conflict warning whose tooltip names the files, opens "This pull will conflict" (Cancel closes, Pull and resolve pulls), switches to "Your changes are in the way" whose Stash 2 files… opens the stash dialog with those files, and shows no warning without a predicted problem, and a failing demo pre-commit hook opens the hook dialog with ANSI-free lint output (Close keeps the message and commits nothing, Commit without hooks commits) while a ticked Skip hooks commits directly and clears itself, and a repo without hooks shows no Skip hooks box, and a hook that fails after switching to another tab only toasts "Nothing was committed in angkorgit" there (no dialog, no commit, the other tab never shows Running hooks…) while the first tab keeps its draft and shows the waiting failure when the user returns, a commit hook keeps Commit busy as Running hooks… across selecting a graph commit and coming back and its failure dialog appears while the graph commit is shown, and Commit without hooks never reads Running hooks… while text typed during the run survives the commit, and a failing demo pre-push hook makes the toolbar Push open "A hook stopped the push" with ANSI-free test output while the Push menu offers Push without hooks (absent in a repo without hooks) and the dialog's Push without hooks pushes main, and after a Push without hooks that the remote rejects as non-fast-forward the dialog's Force push keeps skipping the hook and pushes main forced, and when develop was checked out while the hook ran the rejected dialog still names origin/main with Pull with rebase disabled ("Check out main first…") and Cancel focused, nothing pulls, and once main is checked out again the same dialog enables and focuses Pull with rebase, which pulls, and a graph chip takes its lane colour while every lane line is a rail (no cubic curves) and the WIP banner is opaque, a 14-lane demo history scrolls the graph sideways by exactly each wheel step, by the drawn thumb and back to 0 on a track click while vertical scrolling stays put, and dragging the Graph header edge narrows the column and its scrollbar, survives a reload and double-click resets it, and a running demo post-checkout shows a loading toast and responds to a second checkout with an info toast naming post-checkout and the repository, with no red failure toast, and a failing demo post-checkout hook shows a warning toast after "Checkout develop done" whose Show output opens the warning dialog with ANSI-free output and only Copy output and Close, the Pull menu's Pull without hooks pulls without the post-merge warning a plain Pull then shows (and is absent without hooks), and Pull all puts a post-merge warning with a collapsed Hook output on every updated row ("2 hook warnings") while Pull all without hooks from the group menu shows none, and a hook folder inside the worktree offers Pull without hooks and Pull all without hooks before any hook exists (but no Push without hooks), and the Pull menu shows Pull without hooks after the hook setup changed between two opens, Pull without hooks with a predicted conflict opens "This pull will conflict" first and Pull and resolve then pulls without the post-merge warning, and discarding three selected files shows one post-checkout warning, while a bulk discard that fails for one file names it with the reason and shows no success toast, and so does the Staged header's Discard all staged changes, and the Only matches toggle narrows a "merge" search to the matching commits with "n matching commits", steps them with Enter and brings the full graph back on the same commit, also when the search box is cleared — all on demo mode, and a squeezed same-name tab hint stays at least 18px wide in a 480px window, and graph nodes whose lanes leave the column stay inside it, pinned to an edge, at rest and after scrolling right, and right-clicking the 7th character of a diff line offers Copy path and line with `path:line:7` (copied, toast) while a right-click past the end of the text drops the column, and two cmd-selected commits offer Compare these commits, which puts a From/To header over the newer commit's file list (no message editor or AI buttons), opens a file diff and the all files layout labelled `older..newer`, swaps the direction from the header and leaves compare mode on a plain click, while three selected commits get no Compare entry, and switching to light and back recolours every element on the repo page in the same frame while hover fades keep their duration | diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 314b3288..e570c316 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -34,6 +34,7 @@ notify-debouncer-mini = "0.4" reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] } which = "7" same-file = "1" +tempfile = "3" fontdb = { version = "0.24", default-features = false, features = ["std", "fs", "memmap", "fontconfig"] } [target.'cfg(unix)'.dependencies] @@ -51,9 +52,6 @@ gtk = "0.18" libssh2-sys = { version = "0.3", features = ["openssl-on-win32", "vendored-openssl"] } windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Threading"] } -[dev-dependencies] -tempfile = "3" - [profile.release] codegen-units = 1 lto = true diff --git a/apps/desktop/src-tauri/src/core/branch.rs b/apps/desktop/src-tauri/src/core/branch.rs index cea4e4e3..fa65105b 100644 --- a/apps/desktop/src-tauri/src/core/branch.rs +++ b/apps/desktop/src-tauri/src/core/branch.rs @@ -397,9 +397,22 @@ fn commit_rebase_step( rebase: &mut git2::Rebase<'_>, signature: &git2::Signature<'_>, ) -> Result { + let error = match rebase.commit(None, signature, None) { + Ok(oid) => return Ok(oid), + Err(error) + if error.code() == git2::ErrorCode::Unmerged + && error.class() == git2::ErrorClass::Rebase => + { + error + } + Err(error) => return Err(error), + }; let original = repo.index()?; let mut drifted = Vec::new(); - for submodule in repo.submodules()? { + let Ok(submodules) = repo.submodules() else { + return Err(error); + }; + for submodule in submodules { let (Some(recorded), Some(checked_out)) = (submodule.index_id(), submodule.workdir_id()) else { continue; @@ -410,7 +423,9 @@ fn commit_rebase_step( let Some(name) = submodule.name() else { continue; }; - let status = repo.submodule_status(name, git2::SubmoduleIgnore::Untracked)?; + let Ok(status) = repo.submodule_status(name, git2::SubmoduleIgnore::Untracked) else { + return Err(error); + }; if status.intersects( git2::SubmoduleStatus::WD_ADDED | git2::SubmoduleStatus::WD_DELETED @@ -427,7 +442,7 @@ fn commit_rebase_step( } } if drifted.is_empty() || original.has_conflicts() { - return rebase.commit(None, signature, None); + return Err(error); } let mut temporary = git2::Index::new()?; for entry in original.iter() { diff --git a/apps/desktop/src-tauri/src/core/submodule.rs b/apps/desktop/src-tauri/src/core/submodule.rs index cdc263a6..16badcdd 100644 --- a/apps/desktop/src-tauri/src/core/submodule.rs +++ b/apps/desktop/src-tauri/src/core/submodule.rs @@ -1,4 +1,5 @@ use git2::{Oid, Repository, Submodule, SubmoduleIgnore, SubmoduleStatus}; +use std::{io::Write, path::Path}; use crate::error::{AppError, AppResult}; @@ -62,7 +63,9 @@ pub fn synced_rebase(path: &str, op: impl FnOnce() -> AppResult) -> AppRes if result.is_ok() { follow_recorded(path, &before, true); } - save_rebase_baseline(path, &before, result.is_ok())?; + if let Err(error) = save_rebase_baseline(path, &before, result.is_ok()) { + eprintln!("Cannot save rebase submodule baseline in {path}: {error}"); + } result } @@ -86,7 +89,8 @@ fn rebase_baseline(repo: &Repository) -> AppResult> { .orig_head_id() .ok_or_else(|| AppError::other("The rebase has no original commit"))?; let tree = repo.find_commit(original)?.tree()?; - repo.submodules()? + repo.submodules() + .unwrap_or_default() .iter() .filter_map(|submodule| { let entry = tree.get_path(submodule.path()).ok()?; @@ -130,10 +134,22 @@ fn save_rebase_baseline(path: &str, before: &[(String, Oid)], followed: bool) -> let bytes = serde_json::to_vec(&saved).map_err(|error| { AppError::other(format!("Cannot save rebase submodule baseline: {error}")) })?; - std::fs::write( - repo.path().join("rebase-merge").join(REBASE_BASELINE), - bytes, - )?; + publish_rebase_baseline(&repo.path().join("rebase-merge"), |file| { + file.write_all(&bytes) + })?; + Ok(()) +} + +fn publish_rebase_baseline( + directory: &Path, + write: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>, +) -> std::io::Result<()> { + let mut temporary = tempfile::NamedTempFile::new_in(directory)?; + write(temporary.as_file_mut())?; + temporary.as_file().sync_all()?; + temporary + .persist(directory.join(REBASE_BASELINE)) + .map_err(|error| error.error)?; Ok(()) } @@ -235,3 +251,38 @@ fn run_update(sub: &mut Submodule, init: bool, fetch: bool) -> AppResult<()> { sub.update(init, Some(&mut opts))?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn publishing_a_baseline_replaces_only_the_complete_snapshot() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join(REBASE_BASELINE); + std::fs::write(&file, b"[ ]").unwrap(); + publish_rebase_baseline(directory.path(), |temporary| { + temporary.write_all(b"[")?; + assert_eq!(std::fs::read(&file).unwrap(), b"[ ]"); + temporary.write_all(b"]") + }) + .unwrap(); + assert_eq!(std::fs::read(&file).unwrap(), b"[]"); + assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1); + } + + #[test] + fn a_partial_baseline_write_failure_keeps_the_previous_snapshot() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join(REBASE_BASELINE); + let previous = b"[[\"library\",\"0123456789012345678901234567890123456789\"]]"; + std::fs::write(&file, previous).unwrap(); + let result = publish_rebase_baseline(directory.path(), |temporary| { + temporary.write_all(b"[")?; + Err(std::io::Error::other("disk full")) + }); + assert!(result.is_err()); + assert_eq!(std::fs::read(&file).unwrap(), previous); + assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1); + } +} diff --git a/apps/desktop/src-tauri/tests/git_engine.rs b/apps/desktop/src-tauri/tests/git_engine.rs index a7097669..55cae05d 100644 --- a/apps/desktop/src-tauri/tests/git_engine.rs +++ b/apps/desktop/src-tauri/tests/git_engine.rs @@ -1514,6 +1514,85 @@ fn rebase_linearizes_history() { assert!(repo.dir.join("feature.txt").exists()); } +#[test] +fn rebase_replays_plain_file_commits_that_temporarily_break_gitmodules() { + let repo = TempRepo::new(); + repo.write("base.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, true).unwrap(); + repo.write(".gitmodules", "[submodule \"broken\"\n"); + commit_all(&repo, "broken module metadata"); + repo.write(".gitmodules", ""); + commit_all(&repo, "repair module metadata"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("upstream.txt", "upstream\n"); + let onto = commit_all(&repo, "upstream"); + core::checkout_branch(repo.path(), "topic").unwrap(); + + let result = core::post_hooks::rebase(repo.path(), "master", true) + .into_result() + .unwrap(); + assert_eq!(result.value.status, "ok"); + assert_eq!(rev(&repo, "HEAD~2"), onto); + assert_eq!( + &head_summaries(&repo)[..2], + ["repair module metadata", "broken module metadata"] + ); + assert_eq!(repo.read(".gitmodules"), ""); + assert!(core::status(repo.path()).unwrap().files.is_empty()); +} + +#[test] +fn rebase_baseline_write_failures_preserve_conflicts_and_blocked_step_errors() { + if !hooks_runnable() { + return; + } + for conflict in [false, true] { + let repo = TempRepo::new(); + topic_with_a_later_file(&repo); + if conflict { + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("a.txt", "upstream edit\n"); + commit_all(&repo, "upstream edit"); + core::checkout_branch(repo.path(), "topic").unwrap(); + repo.write("a.txt", "local edit\n"); + commit_all(&repo, "local edit"); + } else { + repo.write("later.txt", "untracked work\n"); + } + write_hook( + &default_hooks(&repo), + "post-checkout", + "mkdir .git/rebase-merge/angkorgit-submodules", + ); + + let result = core::post_hooks::rebase(repo.path(), "master", false).into_result(); + if conflict { + assert_eq!(result.unwrap().value.status, "conflicts"); + assert_eq!(core::conflict_list(repo.path()).unwrap(), vec!["a.txt"]); + } else { + let error = result + .err() + .expect("the replay must still report its blocker") + .to_string(); + assert!(error.contains("later.txt"), "{error}"); + assert!(error.contains("add later"), "{error}"); + assert!(error.contains("in the way"), "{error}"); + } + assert!(rebase_in_progress(&repo)); + std::fs::remove_dir(repo.dir.join(".git/rebase-merge/angkorgit-submodules")).unwrap(); + if conflict { + repo.write("a.txt", "resolved\n"); + core::stage_file(repo.path(), "a.txt").unwrap(); + } else { + std::fs::remove_file(repo.dir.join("later.txt")).unwrap(); + } + let result = core::post_hooks::rebase_continue(repo.path(), true).unwrap(); + assert_eq!(result.value.status, "ok"); + assert!(!rebase_in_progress(&repo)); + } +} + fn head_summaries(repo: &TempRepo) -> Vec { let git = git2::Repository::open(repo.path()).unwrap(); let mut walk = git.revwalk().unwrap();