Skip to content

feat(git): stage and unstage individual diff hunks - #11867

Closed
dcieslak19973 wants to merge 11 commits into
stablyai:mainfrom
dcieslak19973:dcieslak19973/hunk-level-staging
Closed

dcieslak19973 wants to merge 11 commits into
stablyai:mainfrom
dcieslak19973:dcieslak19973/hunk-level-staging

Conversation

@dcieslak19973

@dcieslak19973 dcieslak19973 commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

What: Stage or unstage a single hunk from the diff gutter — the per-chunk staging asked for in #334.
Risk: Index-only: patch bytes come verbatim from git diff -U0 and apply via git apply --cached; nothing is synthesized, per-file ops serialized. Greptile: 5/5 "Safe to merge".
State: Rebased on main today (0 behind, 0 conflicts); all review-bot threads resolved.


Addresses #334.

ELI5

Staging changes for a commit has been all-or-nothing per file; committing part of a file meant dropping to the command line. Now hovering a changed chunk in a diff shows a small button to stage — or unstage — just that piece, right in Orca. Git itself builds and applies the patch, so edge cases like missing final newlines and Windows line endings stay correct. Untracked, renamed, and binary files remain whole-file only, and outdated chunks are refused with a refresh hint instead of being misapplied.

Summary

Hovering a changed line in an unstaged or staged diff now offers a stage/unstage action for just that hunk, sitting next to the existing "add comment" affordance in the glyph margin. Previously the only staging granularity was the whole file.

The renderer sends only the hunk's line ranges — no patch text crosses the boundary. Main (and the relay, for SSH hosts) re-runs git diff -U0 for that path, matches the hunk by range, and feeds git's own patch bytes back through git apply --cached [--reverse] --unidiff-zero. Applying git's output verbatim rather than synthesizing a patch from the two Monaco buffers is the central design decision: it keeps trailing-newline, no-newline-at-EOF, and CRLF handling entirely inside git, which is where the classic partial-staging bugs live.

src/shared/git-hunk-patch.ts is a pure, unit-tested module (parse a single-file unified diff, select hunks intersecting a range, rebuild a patch from the file header plus those hunks verbatim), shared by main and the relay so both hosts apply identical semantics.

Scope and guards:

  • Untracked files are excluded — no index entry for git apply --cached to patch; whole-file staging already covers them.
  • Renames and binary paths are refused with a clear message rather than mis-applied.
  • Stale ranges — the file moved on since the diff was rendered — are refused with a refresh hint instead of a partial apply.
  • Suppressed while the large-diff fallback is active.
  • After applying, git status refreshes and the diff reloads, including when staging the last hunk empties the tab.

Commits:

  1. refactor(editor) — extracts the first-diff auto-scroll effect out of DiffViewer into useDiffViewerFirstDiffAutoScroll. Pure code move, no behavior change; DiffViewer was near the 400-line ceiling and the feature would have pushed it over. Split out so it reviews independently.
  2. feat(git) — the feature.
  3. fix(git) — review follow-ups (see AI Review Report).

Screenshots

New UI: a single 18x18 button in the diff glyph margin, appearing on hover of a changed line, immediately right of the existing comment "+" (left: 26px vs 4px). It reuses that button's exact visual treatment — this PR refactors both into one shared CSS rule with only left differing, so the two affordances cannot drift. Icon is an arrow-into-bar (stage) or arrow-out-of-bar (unstage); disabled at 50% opacity while an apply is in flight.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test (546 files; see Notes for three pre-existing Windows-only failures)
  • pnpm build — not run locally; relies on CI
  • Added or updated high-quality tests that would catch regressions

Five real-git integration tests in git-handler.test.ts: partial stage, partial unstage, an insertion hunk plus an EOF hunk in a file with no trailing newline, stale-range rejection, and concurrent same-file requests. git-hunk-patch.test.ts (8) covers parsing, range selection including zero-count insertion/deletion spans, and multi-hunk reconstruction order. diff-hunk-line-changes.test.ts (4) covers the Monaco ILineChange to unified-diff-span mapping. keyed-mutation-queue.test.ts (4) covers the serialization contract.

AI Review Report

Reviewed with Claude Code, plus the CodeRabbit and Greptile passes on this PR. Risks checked: index corruption from patch application, staleness between diff render and apply, concurrency on the same file, host parity (local/WSL/SSH/web), and guard ordering for untracked/renamed/binary paths.

Changed as a result:

  • Diff not reloading when the post-apply status refresh fails (Greptile, P2). Confirmed by reading the path: a thrown refreshGitStatusForWorktree leaves pre-apply entries in the store, shouldReloadDiffOnGitStatusChange reads those stale entries and returns true, which suppressed the explicit reloadContent — while no status change had fired to trigger the automatic one. Staging the last hunk left the tab visually unchanged until the next poll. Now tracks whether the refresh landed and forces the reload when it did not.
  • Concurrent applies on the same file (CodeRabbit, Major). Applying a hunk is read-diff-then-apply against the index with no lock. Added KeyedMutationQueue (shared) and serialized per worktree+file in both the main process and the relay; different files still apply concurrently. Honest caveat: I could not construct a case where the unserialized version actually corrupts. git apply offset-searches for a modification hunk's removal line, and in a direct experiment it also placed a stale zero-context insertion correctly. So the relay concurrency test asserts the end state of overlapping requests rather than claiming to prove ordering; KeyedMutationQueue's unit tests carry that contract. The serialization is defense-in-depth for a read-modify-write on shared state, not a fix for a demonstrated corruption.
  • Multi-hunk reconstruction test (CodeRabbit). Added — git apply rejects out-of-order hunks, so the ordering contract is worth pinning.

Verified and not changed:

  • Keyboard/command path for hunk staging (CodeRabbit, Major). Valid and worth doing, but out of scope here: the existing comment-add affordance in useDiffCommentDecorator has exactly the same limitation (hover-gated, mousedown-only, not focusable), so a keyboard path should be designed once for both rather than bolted onto the newer one. The button is not merely undiscoverable by keyboard — it is display: none until hover, so making it tabbable means changing when it renders. Happy to file a follow-up covering both buttons.
  • innerHTML assignment (ast-grep, CWE-79). False positive: the assigned values are two hardcoded module constants with no interpolation and no user input, matching how the adjacent comment button builds its icon.
  • Deriving worktreePath by slicing relativePath off filePath (CodeRabbit). Left as-is for consistency: useEditorPanelContentState.ts derives the worktree path with the identical slice for the diff read that this action pairs with. Changing one and not the other would be worse than either. Worth a follow-up that moves both to a Worktree.path lookup.

Cross-platform: the CRLF/EOF question is the main platform risk and is handled by never synthesizing patch text — git's own bytes round-trip. A regression test covers a file with no trailing newline. Paths use literalPathspec on both hosts, matching the existing stage/unstage calls. No new shortcuts or labels. WSL routing goes through the existing GitRuntimeOptions/gitOptionsForWorktree plumbing; SSH through the relay, which was extended in parallel.

Security Audit

  • Command execution: no shell; gitExecFileAsync/execFile with argument arrays, as the surrounding git code does. Patch text goes over stdin, never as an argument, so it cannot be re-parsed as flags.
  • Path handling: the IPC handlers reuse the existing 4-step guard — SSH short-circuit, resolveRegisteredWorktreePath, validateGitRelativeFilePath, getLocalGitOptionsForRegisteredWorktree — identical to git:stage/git:unstage. Pathspecs are literal-quoted.
  • IPC: two new channels (git:stageHunk, git:unstageHunk) and two runtime RPC methods, added to the allowlist. Range params are zod-validated as non-negative integers. The renderer sends only integers and a path; it cannot supply arbitrary patch content for the host to apply — the patch is always regenerated host-side from git.
  • Write scope: git apply --cached touches only the index. It never writes the working tree, and --reverse is the only other mode.
  • No secrets, auth, or dependency changes. Follow-up: none identified.

Notes

Version-skewed relays return JSON-RPC -32601 for the new methods, matching the documented pattern for relay-side additions.

Three test failures reproduce on a pristine checkout of main on this Windows machine and are unrelated to this PR: monaco-content-sync.undo-history.test.ts and both cases in node-markdown-document-discovery.test.ts (its fixture needs symlink creation, which requires elevation on Windows).

🤖 Generated with Claude Code

@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds per-hunk staging and unstaging from the diff gutter. The renderer sends only line ranges; the main process (and relay for SSH hosts) re-runs git diff -U0, matches the hunk by range via the new git-hunk-patch.ts module, and feeds git's own patch bytes back through git apply --cached [--reverse] --unidiff-zero — keeping all EOL/no-newline-at-EOF handling inside git.

  • src/shared/git-hunk-patch.ts — pure, unit-tested parser/selector/rebuilder shared by main and relay; correct handling of zero-count insertion/deletion spans and verbatim hunk body lines.
  • src/shared/keyed-mutation-queue.ts — per-key serializer for the read-diff-then-apply sequence; correct promise chaining on both settle paths and clean map-entry release.
  • UI layer — an absolutely-positioned Monaco overlay button tracks the hovered changed line; the scroll/visibility guard (lastDisplay === 'flex') and statusRefreshed flag for reload-after-apply are both correctly implemented.

Confidence Score: 5/5

  • Safe to merge. The core patch-apply path is sound: git's own bytes are used verbatim, concurrency is serialized per file, and the security boundary is unchanged.
  • The design is correct end-to-end. The two findings are both minor: guard-ordering produces a wrong error message for binary files (a path the UI already prevents from being reached), and a missing separator in the queue key risks only unnecessary serialization between unrelated files, never data corruption. Neither affects correctness of staging operations.
  • No files require special attention. The guard-ordering fix in staging.ts and git-handler-worktree-change-operations.ts is straightforward.

Important Files Changed

Filename Overview
src/shared/git-hunk-patch.ts New pure module: parses single-file unified diffs, selects hunks by range, and rebuilds patches verbatim. Logic is clean; edge cases (zero-count insertion/deletion spans, no-newline markers) handled correctly and covered by tests.
src/shared/keyed-mutation-queue.ts New serialization primitive. Promise chaining is correct — failed tasks settle the tail cleanly and don't wedge the key. Map cleanup logic (delete only if still the last tail) prevents stale-key growth.
src/main/git/source-control/staging.ts Adds stageHunk/unstageHunk via applyHunkRangeToIndex; re-runs git diff then applies verbatim patch bytes over stdin. Guard ordering: stale-hunks fires before binary/rename, so binary files receive a misleading "stale" error (though the UI prevents reaching this path). Key function uses no separator between worktreePath and filePath, unlike the relay which uses a space separator.
src/relay/git-handler-worktree-change-operations.ts Relay-side stageHunk/unstageHunk added with the same guard sequence as the main process. Per-file serialization via KeyedMutationQueue is correct. Uses a space separator in the queue key (" "), which is inconsistent with staging.ts (no separator), but both are self-contained instances.
src/renderer/src/components/editor/useDiffHunkStaging.ts Monaco overlay button that follows the hovered changed line. Scroll handler correctly gates on lastDisplay === 'flex' (the fix for re-showing after mouse-leave). click/busy/disable handshake is correct; cleanup disposes all subscriptions and removes the button from the DOM.
src/renderer/src/components/editor/useDiffHunkStagingAction.ts Computes stage/unstage config for the active diff tab. statusRefreshed flag (the previous-thread fix) is correctly implemented. resolveWorktreePath falls back safely when the worktree record is absent.
src/renderer/src/components/editor/diff-hunk-line-changes.ts Translates Monaco ILineChange to DiffHunkRange. Zero-count convention (Monaco end=0 → count=0) matches unified-diff semantics exactly. Deletion anchoring on the modified-pane line is correct.
src/main/ipc/filesystem.ts Two new IPC handlers (git:stageHunk, git:unstageHunk) follow the existing 4-step security guard pattern. Range parameters are not Zod-validated at the IPC layer (consistent with neighboring handlers), but are validated in the RPC path via GitHunkRangeParams.
src/main/runtime/rpc/methods/git-params.ts GitHunkRangeParams extends GitFilePath with a Zod-validated range object; all four fields are constrained to non-negative integers, matching the DiffHunkRange type.
src/main/runtime/runtime-rpc/runtime-rpc-mobile-method-allowlist.ts git.stageHunk and git.unstageHunk correctly added to the mobile allowlist.
src/renderer/src/web/preload-api/web-git-api.ts Web preload correctly adds stageHunk/unstageHunk via the new mutateGitHunk helper, consistent with mutateGitPath for file-level operations.

Sequence Diagram

sequenceDiagram
    participant R as Renderer<br/>(useDiffHunkStagingAction)
    participant IPC as IPC / RPC
    participant M as Main Process<br/>(staging.ts)
    participant Q as KeyedMutationQueue
    participant G as git

    R->>IPC: "stageHunk(worktreePath, filePath, {oldStart,oldCount,newStart,newCount})"
    IPC->>M: validateGitRelativeFilePath + gitOptions
    M->>Q: run(worktreePath+filePath, task)
    Q->>M: serialize (per file)
    M->>G: "diff -U0 --no-color --no-ext-diff -- <file>"
    G-->>M: unified diff text
    M->>M: "parseSingleFileUnifiedDiff()<br/>selectHunksForRange()<br/>buildPatchForHunks()"
    M->>G: apply --cached --unidiff-zero - [stdin: patch]
    G-->>M: exit 0
    M-->>IPC: void
    IPC-->>R: ok
    R->>R: refreshGitStatusForWorktree()
    R->>R: "shouldReloadDiffOnGitStatusChange()<br/>→ reloadContent() if needed"
Loading

Reviews (7): Last reviewed commit: "fix(git): unconditional hunk staging in ..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds selective staging and unstaging for text diff hunks. The change parses current zero-context diffs, validates ranges, rejects stale, renamed, binary, and multi-file patches, and applies selected patches to the index. It exposes local, SSH, preload, web, RPC, and runtime APIs. The diff editor displays hunk actions, converts Monaco changes to unified-diff ranges, refreshes status, and reloads content after mutations. Tests cover patch parsing, range selection, index updates, insertions, deletions, concurrent mutations, and stale ranges.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed, but it lacks the required before-and-after visual proof for this UI change and omits several template sections. Add before-and-after screenshots or a video, then complete the missing template sections and checklist items.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely states the primary change: staging and unstaging individual diff hunks.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/renderer/src/components/editor/useDiffHunkStagingAction.ts (1)

40-43: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Get worktreePath from the worktree record instead of slicing relativePath.

activeFile.filePath is absolute, but the character slice produces a truncated root if filePath and relativePath disagree on separators, casing, or normalization. Use the Worktree.path lookup for activeFile.worktreeId, or validate the suffix before slicing.

Source: Coding guidelines

src/shared/git-hunk-patch.test.ts (1)

126-146: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add a multi-hunk reconstruction test for buildPatchForHunks.

The only test here rebuilds a patch from one selected hunk. buildPatchForHunks output is applied directly via git apply --cached in both src/main/git/status.ts and src/relay/git-handler.ts. Add a test that selects two or more hunks and asserts the rebuilt patch preserves their original order, to guard the ordering contract this reconstruction depends on.

✅ Proposed additional test
 describe('buildPatchForHunks', () => {
   it('rebuilds a verbatim patch from the header and the selected hunk', () => {
     const parsed = parseSingleFileUnifiedDiff(MULTI_HUNK_PATCH)
     if (!parsed) {
       throw new Error('expected parsed patch')
     }
     const rebuilt = buildPatchForHunks(parsed, [parsed.hunks[1]])
     expect(rebuilt).toBe(
       [
         'diff --git a/src/example.ts b/src/example.ts',
         'index 1111111..2222222 100644',
         '--- a/src/example.ts',
         '+++ b/src/example.ts',
         '@@ -7,0 +8,2 @@ function two() {',
         '+  // inserted',
         '+  console.log("two")',
         ''
       ].join('\n')
     )
   })
+
+  it('preserves hunk order when rebuilding a patch with multiple selected hunks', () => {
+    const parsed = parseSingleFileUnifiedDiff(MULTI_HUNK_PATCH)
+    if (!parsed) {
+      throw new Error('expected parsed patch')
+    }
+    const rebuilt = buildPatchForHunks(parsed, [parsed.hunks[0], parsed.hunks[2]])
+    expect(rebuilt).toBe(
+      [
+        'diff --git a/src/example.ts b/src/example.ts',
+        'index 1111111..2222222 100644',
+        '--- a/src/example.ts',
+        '+++ b/src/example.ts',
+        '@@ -2,1 +2,1 @@ function one() {',
+        '-  return 1',
+        '+  return 100',
+        '@@ -12,2 +14,0 @@ function three() {',
+        '-  // removed',
+        '-  console.log("three")',
+        ''
+      ].join('\n')
+    )
+  })
 })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0fef92ed-1489-424d-92ec-cd56df62f199

📥 Commits

Reviewing files that changed from the base of the PR and between 072133f and 3fead52.

📒 Files selected for processing (27)
  • src/main/git/status.ts
  • src/main/ipc/filesystem.ts
  • src/main/providers/git-provider-contract.ts
  • src/main/providers/ssh-git-provider.ts
  • src/main/runtime/orca-runtime-git.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/git-params.ts
  • src/main/runtime/rpc/methods/git.ts
  • src/main/runtime/runtime-rpc.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/relay/git-handler.test.ts
  • src/relay/git-handler.ts
  • src/renderer/src/assets/main.css
  • src/renderer/src/components/editor/DiffViewer.tsx
  • src/renderer/src/components/editor/EditorContent.tsx
  • src/renderer/src/components/editor/diff-hunk-line-changes.test.ts
  • src/renderer/src/components/editor/diff-hunk-line-changes.ts
  • src/renderer/src/components/editor/diff-viewer-props.ts
  • src/renderer/src/components/editor/useDiffHunkStaging.ts
  • src/renderer/src/components/editor/useDiffHunkStagingAction.ts
  • src/renderer/src/components/editor/useDiffViewerFirstDiffAutoScroll.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/runtime/runtime-git-client.ts
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/git-hunk-patch.test.ts
  • src/shared/git-hunk-patch.ts

Comment thread src/relay/git-handler.ts Resolved
dcieslak19973 added a commit to dcieslak19973/orca that referenced this pull request Aug 1, 2026
…erialize hunk applies

Review follow-ups on stablyai#11867.

When refreshGitStatusForWorktree threw, the store kept its pre-apply entries.
shouldReloadDiffOnGitStatusChange then read those stale entries, saw the file
still in its area, and suppressed the explicit reload — while no status change
had fired to trigger the automatic one. Staging the last hunk of a file left
the diff visually unchanged until the next poll. Track whether the refresh
landed and force the reload when it did not.

Applying a hunk is read-diff-then-apply against the index, with no lock. Two
overlapping requests for one file could have the second build its patch from a
pre-apply diff. Serialize per worktree+file in both the main process and the
relay; different files still apply concurrently.

Note: git apply recovers from a stale patch on its own in the cases I could
construct — it offset-searches for a modification hunk's `-` line, and it
placed a stale zero-context insertion correctly too. So the relay test asserts
the end state of concurrent requests rather than claiming to prove the
ordering; KeyedMutationQueue's unit tests carry that contract.

Co-Authored-By: Claude Opus 5 <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/renderer/src/components/editor/useDiffHunkStaging.test.tsx (1)

74-76: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten this test comment.

Keep the rationale, but reduce it to one concise line.

As per coding guidelines: “Comments must be concise, limited to non-obvious information, and preferably one line.”

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8da8f215-ab5c-4e38-ac6e-3a7070391568

📥 Commits

Reviewing files that changed from the base of the PR and between a5eab6a and 6f78663.

📒 Files selected for processing (2)
  • src/renderer/src/components/editor/useDiffHunkStaging.test.tsx
  • src/renderer/src/components/editor/useDiffHunkStaging.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/editor/useDiffHunkStaging.ts

@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from 39c26c3 to 6c06b44 Compare August 2, 2026 21:38
@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from 6c06b44 to 375de69 Compare August 3, 2026 15:16
@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from 375de69 to e984e29 Compare August 4, 2026 21:08
@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from e984e29 to 6dc8539 Compare August 5, 2026 00:15
@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from 6dc8539 to 04083bc Compare August 5, 2026 04:16
@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from 04083bc to 6453b9b Compare August 5, 2026 19:05
dcieslak19973 added a commit to dcieslak19973/orca that referenced this pull request Aug 7, 2026
…erialize hunk applies

Review follow-ups on stablyai#11867.

When refreshGitStatusForWorktree threw, the store kept its pre-apply entries.
shouldReloadDiffOnGitStatusChange then read those stale entries, saw the file
still in its area, and suppressed the explicit reload — while no status change
had fired to trigger the automatic one. Staging the last hunk of a file left
the diff visually unchanged until the next poll. Track whether the refresh
landed and force the reload when it did not.

Applying a hunk is read-diff-then-apply against the index, with no lock. Two
overlapping requests for one file could have the second build its patch from a
pre-apply diff. Serialize per worktree+file in both the main process and the
relay; different files still apply concurrently.

Note: git apply recovers from a stale patch on its own in the cases I could
construct — it offset-searches for a modification hunk's `-` line, and it
placed a stale zero-context insertion correctly too. So the relay test asserts
the end state of concurrent requests rather than claiming to prove the
ordering; KeyedMutationQueue's unit tests carry that contract.

Co-Authored-By: Claude Opus 5 <[email protected]>
@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from 6453b9b to 9264125 Compare August 7, 2026 02:32
@dcieslak19973

Copy link
Copy Markdown
Contributor Author

Upstream PR Checks is still awaiting workflow approval, so I ran the identical suite on my fork against this PR's exact head (261e09fc2):

https://github.com/dcieslak19973/orca/actions/runs/31218060402 — all 43 jobs green: typecheck, static analysis, packaging (linux + windows), Git compatibility, shell contracts, cross-version wire compatibility, and all 16 test shards.

This run also caught a real defect that upstream PR Checks would have failed on: check:react-doctor:changed flagged a ref written during render in useDiffHunkStaging.ts (impure, and double-applied under StrictMode). Fixed in 261e09fc2 by syncing the ref on commit instead — it is only read from deferred DOM handlers, so nothing about the behaviour changes. The green run above is the fixed head.

Posting so the suite result is visible without needing the approval click first.

@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from 466b134 to cca6c77 Compare August 15, 2026 00:26
@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch 2 times, most recently from b9c4fc1 to b618e83 Compare August 16, 2026 15:01
@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from b618e83 to 9a278d1 Compare August 19, 2026 01:39
@nwparker nwparker removed the P1 label Aug 19, 2026
@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from 9a278d1 to 25be1a8 Compare August 28, 2026 04:41
dcieslak19973 and others added 11 commits August 30, 2026 16:58
Pure code move, no behavior change. DiffViewer is near the 400-line
ceiling and the next feature would push it over; this effect is
self-contained and reads better named.

Co-Authored-By: Claude Opus 5 <[email protected]>
Hovering a changed line in an unstaged or staged diff now offers a
stage/unstage action for just that hunk, next to the existing comment
affordance. Previously the only granularity was the whole file.

The renderer sends only the hunk's line ranges. Main (and the relay, for
SSH hosts) re-runs `git diff -U0`, matches the hunk by range, and feeds
git's own patch text back through `git apply --cached [--reverse]
--unidiff-zero`. Applying git's bytes verbatim rather than synthesizing a
patch keeps EOF-newline and CRLF handling git's problem.

Untracked, renamed, and binary paths are excluded (no index entry to
patch). A range that no longer matches — the file moved on since the diff
was rendered — is refused with a refresh hint instead of a partial apply.

Co-Authored-By: Claude Opus 5 <[email protected]>
…erialize hunk applies

Review follow-ups on stablyai#11867.

When refreshGitStatusForWorktree threw, the store kept its pre-apply entries.
shouldReloadDiffOnGitStatusChange then read those stale entries, saw the file
still in its area, and suppressed the explicit reload — while no status change
had fired to trigger the automatic one. Staging the last hunk of a file left
the diff visually unchanged until the next poll. Track whether the refresh
landed and force the reload when it did not.

Applying a hunk is read-diff-then-apply against the index, with no lock. Two
overlapping requests for one file could have the second build its patch from a
pre-apply diff. Serialize per worktree+file in both the main process and the
relay; different files still apply concurrently.

Note: git apply recovers from a stale patch on its own in the cases I could
construct — it offset-searches for a modification hunk's `-` line, and it
placed a stale zero-context insertion correctly too. So the relay test asserts
the end state of concurrent requests rather than claiming to prove the
ordering; KeyedMutationQueue's unit tests carry that contract.

Co-Authored-By: Claude Opus 5 <[email protected]>
`gitStatusByWorktree` is Record<string, GitStatusEntry[]>, but the post-apply
reload check reached for `.entries` on it. That resolves to
Array.prototype.entries — a function — so it typechecks and then throws
"gitStatusEntries.some is not a function" inside
shouldReloadDiffOnGitStatusChange, after the hunk had already been applied.

The throw surfaced only as a rejected promise the click handler never caught,
so staging a hunk appeared to do nothing. Adds a catch at the call site so a
future defect here is logged rather than swallowed, plus hook tests that
exercise the real store shape; the post-apply test fails with the original
`.entries` access restored.

Co-Authored-By: Claude Opus 5 <[email protected]>
…nter leaves

onDidScrollChange repositioned whenever hoverLineRef held a line, and
positionAtLine ends by showing the button. Mouse-leave only hid it without
clearing the ref, so any later scroll — Page Down, a scrollbar drag, or a
programmatic reveal — popped the button back up with no cursor near it.

Gate the scroll reposition on the button already being visible rather than
clearing hoverLineRef: the ref deliberately survives mouse-leave so a click in
the gap between the content area and the button still resolves to a line, the
same reason useDiffCommentDecorator keeps it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Optional chaining on the registered listeners let both scroll tests pass even
if the hook never subscribed to onDidScrollChange, so neither could fail for
the reason it exists. Assert registration once in setup and hand back required
callbacks.

The follow-the-line test also never moved the viewport, so it only proved the
button stayed visible. Drive getScrollTop through a mutable stub and assert the
button moves by exactly the scroll delta.

Co-Authored-By: Claude Opus 5 <[email protected]>
Writing a ref during render is impure and double-applies under StrictMode.
The ref is only read from deferred DOM handlers, so a commit-time sync is
soon enough, and declaring the effect above the main one keeps it first on
mount. Caught by check:react-doctor:changed.
… record

Slicing filePath by relativePath length produces a truncated root whenever the
two disagree on separators, casing, or normalization. Prefer Worktree.path and
keep the slice only as a fallback that validates the suffix first.

Co-Authored-By: Claude Opus 5 <[email protected]>
The shared/types barrel was removed upstream (stablyai#14447).
…ntract test

Post-rebase fixups for the hunk-staging merge (PR stablyai#11867):
- git-handler.ts kept a stray 'hunkApplyQueue' field from the pre-refactor
  file after a silent context-only merge; the real queue lives in
  GitHandlerWorktreeChangeOperations now. Remove the dead field so
  GitHandler can construct again.
- runtime-git-client-api-contract.test.ts enumerates the stable renderer
  facade; add the new stageRuntimeGitHunk/unstageRuntimeGitHunk exports.
…ission tier for hunk IPC

Review follow-ups on the PR stablyai#11867 rebase:
- EditorDiffFileSurface passed hunkStaging only when the diff was directly
  editable (isEditable, i.e. the unstaged view), so a staged diff never got
  an unstage-hunk action. Pass hunkStaging unconditionally; DiffViewer
  already gates its click affordance on hunkStaging.scope, not editable.
- git:stageHunk / git:unstageHunk IPC handlers omitted admissionTier:
  'interactive', unlike every other click-driven git mutation handler
  (stage, unstage, discard, bulkStage, ...). Add it so hunk staging shares
  the same admission-control lane.
- Removed leftover doubled/trailing blank lines in git-handler.ts and
  web-preload-api.ts left over from resolving whole-file rebase conflicts.

Added coverage: EditorDiffFileSurface.test.tsx asserts hunkStaging reaches
DiffViewer for both staged and unstaged diffSource; filesystem-git-status-
staging.test.ts asserts the interactive admission tier on both hunk IPC
handlers.
@dcieslak19973
dcieslak19973 force-pushed the dcieslak19973/hunk-level-staging branch from 25be1a8 to e65dd0b Compare August 30, 2026 22:33
@dcieslak19973

Copy link
Copy Markdown
Contributor Author

Closing this one for now. Can reopen if we want to pick hunk-level staging back up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants