Skip to content

fix(sidebar): let the scroll anchor follow a re-keyed row - #11543

Merged
nwparker merged 1 commit into
mainfrom
nwparker/sidebar-anchor-follow-rekeyed-row
Jul 30, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/sidebar-anchor-follow-rekeyed-row

Conversation

@nwparker

@nwparker nwparker commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Description

Second, independent cause of "the left sidebar scrolls by itself". #11530 fixed the reveal path; this one has nothing to do with reveal.

Creating a child worktree makes buildRenderableRows fold the parent and its descendants into a single lineage-group render row, which rewrites the parent's virtual row key. A scroll anchor recorded under the old key could no longer find its row, fell through to a fallback key — a different row — and pinned that to the viewport top.

Measured: scrollTop 520 → 700, a +180px jump, with no revealWorktreeInSidebar involved.

ELI5

The sidebar remembers your place with a bookmark: "the row at the top is this one, and you're 20px into it."

When a workspace gets its first child, Orca merges the parent and its children into one combined row — and in doing so gives it a new name. The bookmark still said the old name, and nothing answered to it anymore. So the sidebar reached for its backup plan: "if the bookmarked row is gone, it must have been deleted, so pin whatever slid up into its place." But the row wasn't deleted — it was standing right there under a new name. The sidebar pinned the next row instead, and everything lurched 180px.

Now the list hands restore a small "this row was renamed to that" note, so the bookmark can follow its own row. The backup plan still applies to genuinely deleted rows.

Root cause

getRenderRowKey gives the same workspace two different keys depending on whether it currently has children:

wt:<sectionKey>:<worktreeId>   ->   lineage-group:<sectionKey>:lineage:<worktreeId>

runVirtualizedScrollAnchorRestore resolved anchor.key, then anchor.fallbackKeys. Those fallbacks encode a specific assumption — "the anchored row was removed and the row below slid up" — which is only sound for deletions. A re-key is not a deletion, so the fallback silently pinned a neighbour and forced the within-row offset to 0.

The reproduction's own decomposition proves the fix and rules out the obvious alternative:

resolution resulting scrollTop
fallback row, offset forced to 0 700 ← the bug
fallback row, offset preserved 720 (worse)
parent's new lineage-group key, original offset 520 — no movement

So the defect was never the offset = 0 line; it was that the anchor had no way to follow a row whose identity was rewritten.

Design

A caller-supplied rekeyedRowKeys?: ReadonlyMap<string, string>. Resolution becomes: exact anchor.key → followed (re-keyed) key, if it names a row in this render → anchor.fallbackKeys.

The offset transfers for a followed key (same row, new name) but is still dropped for a genuine fallback (different row) — the deletion semantics are preserved exactly. On the followed branch only, the offset is clamped to the resolved row's height, mirroring the record-time clamp, so a group dissolving back into a single card cannot overshoot.

WorktreeList owns the key scheme, so it builds the map; the hook stays generic. getRenderRowKey moved to worktree-list-virtual-rows.ts alongside the other row helpers (still re-exported from WorktreeList for existing importers) — WorktreeList.tsx net shrinks by 19 lines.

What this deliberately does not do

An earlier design added a general "stable row identity" subsystem — a new public anchor field, a new hook option, a record-time transform, a resolver type, and 3 new test files. An adversarial review rejected it: the generality was inert for 6 of 7 row shapes, and it introduced a bug where an unclamped offset was written back into the anchor. This ships ~40 lines instead. If pending → real or pin/unpin are ever shown to jump in practice, they extend the same map with one entry each — on evidence.

The sidebar's missing restoreSignal is not bundled. It is verifiably non-curative here: at the moment the child lands no user scroll has happened, so the divergence guard passes while the structural gate opens, and restore still lands at 700. It is a real gap, but a separate PR.

Proof of regression

Reverting only the resolution change (back to exact-key → fallbacks):

 ❯ useVirtualizedScrollAnchor.listener-deps.test.ts (12 tests | 3 failed)
   × keeps the sidebar still (dom path) when the anchored parent folds into a lineage group
   × keeps the sidebar still (measured path) when the anchored parent folds into a lineage group
   × does not scroll when a child worktree folds the anchored parent into a group

AssertionError: expected 700 to be 520 // Object.is equality
- Expected  520
+ Received  700

 Tests  3 failed | 9 passed (12)

Exactly the reported +180px. I reproduced this red independently of the agent that wrote the tests. The three control tests stayed green under the revert, confirming they are not coupled to the follow branch.

Proof of fix

  • Targeted: 27 passed across the two test files.
  • Sidebar + hooks suites: 270 files, 2,395 tests passed.
  • Full unit suite: see below.
  • pnpm run typecheck:web: passed.
  • pnpm run check:code-quality:changed: 0 new findings across 6 files.
  • oxlint + oxfmt --check clean.

Proof of no regression

  • CombinedDiffViewer is provably unaffected — it is the only other consumer of this hook, never passes rekeyedRowKeys, so followedKey is always undefined and resolution degenerates byte-for-byte to today's two-step logic. Covered by explicit "no rekey map supplied" tests asserting the old 700 behavior still happens.
  • Genuine deletions unchanged — a map with no matching entry still resolves a fallback with offset 0.
  • Stale map entries are ignored — a rekey target not rendered this pass degrades to the fallback rather than leaving the anchor unresolved.
  • The scroll-listener effect and its deps are untouched; rekeyedRowKeys is read only in the restore effect. No new useLayoutEffect.
  • getRenderRowKey output is unchanged, so the reveal path (findPreferredRenderRowIndexForWorktree, revealMountedWorktreeElement), drag, context-menu, and elementsCache pruning all keep their existing key namespace.

Known limitation

The jump requires the anchored top-visible row to be exactly the parent gaining its first child (or losing its last). If that parent sits above or below the anchor row, the anchor key survives and restore already held position correctly. Scrolling within an already-formed lineage group as it grows is a separate composite-row concern and is not addressed here.

Made with Orca 🐋

Creating a child worktree folds the parent and its children into one
lineage-group render row, which rewrites the parent's virtual row key. A scroll
anchor recorded under the old key could no longer find it, fell through to a
fallback key, and pinned a different row to the viewport top -- a measured
+180px jump with no sidebar reveal involved.

Give restore an optional old-key -> new-key map so an anchor can follow its own
row. The within-row offset transfers for a followed key (same row, new name)
but is still dropped for a genuine fallback (different row).
@greptile-apps

greptile-apps Bot commented Jul 30, 2026

Copy link
Copy Markdown

Greptile Summary

Fixes a second independent cause of the left sidebar jumping by teaching the scroll anchor restore to follow a row that was re-keyed in place rather than mistaking it for a deletion. When a workspace gains its first child, buildRenderableRows promotes the parent from a plain wt: item row to a lineage-group: row at the same pixel position; the old anchor key became unresolvable, fell through to a fallback key pointing at the neighbour below, and produced a measured +180 px jump.

  • buildLineageRowRekeyMap (new, in worktree-list-virtual-rows.ts) builds a per-render old key → new key map covering both the fold direction (wt: → lineage-group:) and the dissolve direction (lineage-group: → wt:), keyed by section so pinned and unpinned copies of the same workspace never cross-contaminate.
  • runVirtualizedScrollAnchorRestore gains a rekeyedRowKeys parameter; resolution is now: exact key → followed (re-keyed) key present in this render → fallback keys. The within-row offset transfers on a followed key (same row, new name) and is clamped to the new row height; it is dropped on a fallback (different row, deletion semantics preserved unchanged).
  • CombinedDiffViewer is unaffected — it never passes rekeyedRowKeys, so the new branch is inert and the old two-step logic is byte-for-byte identical for that caller.

Confidence Score: 5/5

Safe to merge. The change is well-contained: the new resolution branch is only reached when a caller explicitly supplies rekeyedRowKeys, and the sole caller (WorktreeList) derives that map from the same renderRows it already passes. All existing callers without the map degrade byte-for-byte to the prior two-step logic.

The fix is minimal (~40 lines of logic), every branch in the restore function is exercised by the new tests including exact-key, followed-key, genuine-delete, stale-map, and dissolve-clamp paths, and the regression scenario (scrollTop 700 vs 520) is reproduced and verified green in both DOM and measured paths. The key construction in buildLineageRowRekeyMap is consistent with getRenderRowKey and buildRenderableRows. No new layout effects, no changes to the scroll-listener path, and CombinedDiffViewer is explicitly covered by a regression test.

Files Needing Attention: No files require special attention. The core logic change in virtualized-scroll-anchor-restore.ts is thoroughly tested, and worktree-list-virtual-rows.ts gains its new export alongside matching unit tests.

Important Files Changed

Filename Overview
src/renderer/src/hooks/virtualized-scroll-anchor-restore.ts Core fix: adds a "followed key" resolution step (old key → new key via rekeyedRowKeys) between exact-key and fallback paths, with offset transfer and height-clamp logic for the followed branch.
src/renderer/src/components/sidebar/worktree-list-virtual-rows.ts getRenderRowKey moved here from WorktreeList.tsx; new buildLineageRowRekeyMap builds the bidirectional fold/dissolve lookup table used by the restore fix.
src/renderer/src/components/sidebar/WorktreeList.tsx Net -19 lines: getRenderRowKey re-exported from its new home; lineageRowRekeys memo added and wired into useVirtualizedScrollAnchor as rekeyedRowKeys.
src/renderer/src/hooks/useVirtualizedScrollAnchor.ts rekeyedRowKeys option added to the options type, destructured, passed through to runVirtualizedScrollAnchorRestore, and included in the restore effect's deps array.
src/renderer/src/hooks/useVirtualizedScrollAnchor.listener-deps.test.ts New test suite directly exercises runVirtualizedScrollAnchorRestore with fold/dissolve/delete/stale-map scenarios and a full hook integration test; existing listener-deps tests are unmodified.
src/renderer/src/components/sidebar/worktree-list-virtual-rows.test.ts Six new tests for buildLineageRowRekeyMap covering fold, dissolve, round-trip, cross-section isolation, non-lineage rows, and empty input.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["anchor.key"] --> B{rowIndexByKey\nhas exact key?}
    B -- yes --> E["resolvedKey = anchor.key\noffset = anchor.offset\nno clamp"]
    B -- no --> C{rekeyedRowKeys\nhas anchor.key?}
    C -- no --> D{fallbackKeys\nhas a rendered key?}
    C -- yes --> F{followedKey\nrendered this pass?}
    F -- no --> D
    F -- yes --> G["resolvedKey = followedKey\noffset = anchor.offset\nclamped to row height"]
    D -- yes --> H["resolvedKey = fallbackKey\noffset = 0\nnew row semantics"]
    D -- no --> I["unresolvable:\npendingRestoreRef = false\nreturn"]
    E --> J["restoreFromDomElement\nor restoreFromMeasuredItem\nor scrollToIndex"]
    G --> J
    H --> J
Loading

Reviews (1): Last reviewed commit: "fix(sidebar): let the scroll anchor foll..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: bc9cd5df-52bc-476d-b526-a9576106ca36

📥 Commits

Reviewing files that changed from the base of the PR and between 9eede00 and 36bf857.

📒 Files selected for processing (6)
  • src/renderer/src/components/sidebar/WorktreeList.tsx
  • src/renderer/src/components/sidebar/worktree-list-virtual-rows.test.ts
  • src/renderer/src/components/sidebar/worktree-list-virtual-rows.ts
  • src/renderer/src/hooks/useVirtualizedScrollAnchor.listener-deps.test.ts
  • src/renderer/src/hooks/useVirtualizedScrollAnchor.ts
  • src/renderer/src/hooks/virtualized-scroll-anchor-restore.ts

📝 Walkthrough

Walkthrough

The change centralizes render-row key generation and adds lineage row re-key mappings for fold, unfold, and dissolve transitions. The virtualized scroll-anchor hook and restore function now resolve changed row keys and clamp offsets to current row heights. The sidebar supplies computed mappings while preserving the existing key export. Tests cover mapping behavior, fallback restoration, stale targets, offset clamping, and integrated sidebar anchor updates.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it does not follow the required template and is missing Screenshots, Testing, AI Review Report, Security Audit, and Notes. Rewrite the PR description using all required template sections, including screenshots or 'No visual change', testing checklist, AI review, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately describes the main change: scroll anchors now follow re-keyed sidebar rows.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

@nwparker
nwparker merged commit abec358 into main Jul 30, 2026
42 checks passed
@nwparker
nwparker deleted the nwparker/sidebar-anchor-follow-rekeyed-row branch July 30, 2026 23:55
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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.

1 participant