Skip to content

fix(workspaces): stop unchanged smart-sort refresh loops - #8277

Closed
bbingz wants to merge 3 commits into
stablyai:mainfrom
bbingz:fix/remote-host-smart-sort-loop
Closed

bbingz wants to merge 3 commits into
stablyai:mainfrom
bbingz:fix/remote-host-smart-sort-loop

Conversation

@bbingz

@bbingz bbingz commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Closes #8272.

Summary

  • Make worktree sort-order persistence a no-op when existing per-host ranks already encode the requested order.
  • Share the same persistence boundary between local IPC and remote runtimes; remote runtimes now skip cache invalidation and reposChanged broadcasts for unchanged orders.
  • Add the missing deterministic regression where a runtime catalog resolves before an older local catalog and both hosts remain in renderer state.

Composition with #9342 (merged 2026-07-24): that fix added the same no-mint guard separately at each call site. Its guard and this PR's skip-unchanged short-circuit are complementary — one decides which ids may be written, the other whether any write is needed — and both now live in a single persistWorktreeSortOrder helper (src/main/worktree-sort-order-persistence.ts) called from src/main/ipc/worktrees.ts and src/main/runtime/orca-runtime.ts, instead of two overlapping call-site guards.

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — not run in full; the five affected suites re-run post-rebase at 23439b8: 286/286 passed.
  • pnpm build — not run; no build-system or packaging behavior changed.
  • Added high-quality tests for the cross-host fetch race and unchanged/changed persistence boundaries.

Targeted command:

pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/worktrees.test.ts src/renderer/src/store/slices/repos-all-hosts.test.ts src/renderer/src/store/slices/repos-cross-host-fetch-race.test.ts src/main/worktree-sort-order-persistence.test.ts src/main/runtime/rpc/methods/worktree.test.ts

AI Review Report

Reviewed both loops described in #8272. Current main already merges fetched catalogs inside set(state), so the stale local-vs-runtime overwrite is structurally fixed; the new race test locks that behavior. The remaining loop came from every Smart-order effect call replacing all ranks with fresh timestamps and the runtime broadcasting reposChanged, even when relative order was unchanged.

The persistence review checked first-time/missing ranks, changed order, tied or invalid ranks, duplicate IDs, single-host and split-host calls, local IPC, remote runtime notification behavior, and concurrent repeated calls. Only a complete strictly descending rank sequence is considered unchanged; ambiguous state is repaired rather than skipped.

Cross-platform behavior was checked explicitly. The helper is path- and platform-neutral, uses owner-host metadata only, and does not alter shortcuts, labels, filesystem paths, shells, SSH routing, or git-provider behavior. It applies equally to macOS/Linux local hosts and Windows/remote runtimes.

Security Audit

The change reads existing worktree metadata and writes the same bounded sortOrder fields as before. It adds no command execution, IPC surface, authentication, secrets, filesystem access, or dependencies. Malformed duplicate IDs, missing metadata, non-finite ranks, and ties fail toward re-persistence rather than suppressing an update. No security follow-up is required.

Notes

For a genuinely changed order, ranks are still rewritten and the remote runtime still invalidates its resolved cache and emits reposChanged. For an unchanged order, the runtime returns { updated: 0 } without a broad refresh, breaking the persist -> reposChanged -> refresh -> sortEpoch -> persist cycle.

ELI5

Smart-sort could keep rewriting worktree order and broadcasting changes even when the order had not really changed, causing refresh loops. Persistence is a no-op when ranks already match, including on remote runtimes, so the UI stops thrashing.

@coderabbitai

coderabbitai Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds shared worktree sort-order persistence that validates existing ranks, avoids redundant writes, and assigns descending timestamp-based ranks when needed. The IPC and runtime reorder paths now use this helper and return early when no updates occur. Adds tests for ordering persistence scenarios and a renderer test covering remote repository results arriving before a pending local fetch.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy #8272 by fixing the catalog race, skipping unchanged persistence, preserving changed-order notifications, and adding regression tests.
Out of Scope Changes check ✅ Passed All implementation and test changes directly support the linked issue objectives and contain no unrelated scope.
Title check ✅ Passed The title clearly identifies the main change: preventing refresh loops caused by unchanged smart-sort persistence.
Description check ✅ Passed The description includes all required sections, explains testing limitations, and documents AI review, security checks, platform coverage, and follow-up risks.

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.

@bbingz

bbingz commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@bbingz
bbingz force-pushed the fix/remote-host-smart-sort-loop branch from 0990010 to 3a6c69b Compare July 22, 2026 01:33
@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (34c160442f9e77d8162b4c54ecd9b39f0ba6a4f2). Conflicts resolved in: worktrees.ts (kept persistWorktreeSortOrder no-op-when-unchanged path). Ready for re-review.

@bbingz
bbingz force-pushed the fix/remote-host-smart-sort-loop branch from 3a6c69b to 0cc96ef Compare July 24, 2026 09:01
@bbingz

bbingz commented Jul 24, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (981653f27d). One composition detail worth noting, since upstream touched the same code path in the meantime:

#9342 (don't mint worktreeMeta from a sidebar sort-order snapshot) added a no-mint guard to both worktrees:persistSortOrder and persistManagedWorktreeSortOrder. That guard and this PR's skip-unchanged no-op are complementary rather than redundant, so instead of leaving two overlapping guards at the call sites, both now go through one persistWorktreeSortOrder helper that does both: it returns 0 when ranks are already strictly descending, and it only rewrites ids that already have meta — never minting for unknown ids.

The reason this is still needed on top of #9342: without it every smart-sort recompute still calls setWorktreeMeta plus a cache invalidate and reposChanged even when nothing changed, which is exactly what sustains the refresh loop. The early { updated: 0 } return now skips the invalidate and notify.

Verified: tsc --noEmit -p config/tsconfig.node.json clean; 4 test files / 12 tests passing across worktree-sort-order-persistence, worktrees-sort-order, orca-runtime-sort-order, and repos-cross-host-fetch-race.

@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
@bbingz
bbingz force-pushed the fix/remote-host-smart-sort-loop branch from 0cc96ef to 65adf31 Compare July 29, 2026 05:49
@greptile-apps

greptile-apps Bot commented Jul 29, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes a smart-sort refresh loop by extracting sort-order persistence into a shared persistWorktreeSortOrder helper that short-circuits when the persisted ranks already encode the requested order. It also adds a deterministic regression test for the cross-host fetch race where a runtime catalog resolves before a slower local catalog.

  • worktree-sort-order-persistence.ts: new shared helper; checks for strictly-descending ranks before writing, handles duplicates/ties/unknowns, and returns the count of actually-updated entries.
  • worktrees.ts (IPC path): delegates to the new helper, inheriting its no-op guard without calling the runtime notification path.
  • orca-runtime.ts (remote path): uses the helper's return count to gate invalidateResolvedWorktreeCache and notifyReposChanged, breaking the persist → reposChanged → refresh → sortEpoch → persist loop.

Confidence Score: 4/5

Safe to merge; the change is a focused extraction of sort-order persistence logic into a shared helper with thorough unit coverage across all meaningful edge cases.

The core persistence helper and both call sites (IPC and runtime) are well-reasoned and logically sound. The IPC handler test only exercises two paths (unchanged order and empty input) — the changed-order path is covered only indirectly through the helper's own suite, leaving a small gap in integration-level confidence for that call site.

Files Needing Attention: src/main/ipc/worktrees-sort-order.test.ts — the IPC-level changed-order path has no direct test; all other files are thoroughly covered.

Important Files Changed

Filename Overview
src/main/worktree-sort-order-persistence.ts New shared helper; correctly gates writes behind a strictly-descending rank check and skips unknown IDs in both the check and write phases.
src/main/ipc/worktrees.ts IPC persistSortOrder handler now delegates to the shared helper; empty-array guard is kept as a fast path before the helper is called.
src/main/runtime/orca-runtime.ts Runtime persistManagedWorktreeSortOrder now skips cache invalidation and reposChanged broadcast when updated count is 0, directly breaking the refresh loop.
src/main/worktree-sort-order-persistence.test.ts Thorough unit tests for the helper: unchanged order, changed order, missing ranks, tied ranks, duplicates, unknown IDs, and exact write values.
src/main/ipc/worktrees-sort-order.test.ts IPC handler tests cover unchanged order and empty input; changed-order path is only exercised via the shared helper's own test suite.
src/main/runtime/orca-runtime-sort-order.test.ts Runtime tests verify the full event/cache-invalidation lifecycle for first change, no-op repeat, and subsequent real change.
src/renderer/src/store/slices/repos-cross-host-fetch-race.test.ts New regression test locks the existing merge-inside-set behavior that prevents a slow local catalog from overwriting a faster runtime catalog.

Sequence Diagram

sequenceDiagram
    participant Renderer
    participant IPC as IPC (worktrees.ts)
    participant RT as Runtime (orca-runtime.ts)
    participant Persist as persistWorktreeSortOrder
    participant Store

    Renderer->>IPC: "persistSortOrder({orderedIds})"
    IPC->>Persist: persistWorktreeSortOrder(store, orderedIds)
    Persist->>Store: getWorktreeMeta(id) × N
    alt ranks already strictly descending
        Persist-->>IPC: 0 (no-op)
        IPC-->>Renderer: undefined (no events)
    else order changed / ranks invalid
        Persist->>Store: "setWorktreeMeta(id, {sortOrder}) × N"
        Persist-->>IPC: updated count
        IPC-->>Renderer: undefined
    end

    Renderer->>RT: persistManagedWorktreeSortOrder(orderedIds)
    RT->>Persist: persistWorktreeSortOrder(store, orderedIds)
    Persist->>Store: getWorktreeMeta(id) × N
    alt ranks already strictly descending
        Persist-->>RT: 0
        RT-->>Renderer: "{updated: 0} (no cache invalidation, no reposChanged)"
    else order changed / ranks invalid
        Persist->>Store: "setWorktreeMeta(id, {sortOrder}) × N"
        Persist-->>RT: updated count
        RT->>RT: invalidateResolvedWorktreeCache()
        RT->>Renderer: reposChanged event
        RT-->>Renderer: "{updated: N}"
    end
Loading

Reviews (1): Last reviewed commit: "fix(workspaces): combine smart-sort no-o..." | Re-trigger Greptile

@bbingz
bbingz force-pushed the fix/remote-host-smart-sort-loop branch from 65adf31 to 23439b8 Compare August 5, 2026 23:44
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@bbingz

bbingz commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

Closing as superseded by current main.

The no-op smart-sort + no-mint meta guard now lives in planWorktreeSortOrderUpdates (src/shared/worktree-sort-order-update.ts) and is used by both:

  • worktrees:persistSortOrder in src/main/ipc/worktrees.ts
  • persistManagedWorktreeSortOrder in src/main/runtime/orca-runtime.ts

Rebase of this PR conflicts heavily and would only re-introduce a parallel helper. No further action needed from this branch.

@bbingz

bbingz commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by planWorktreeSortOrderUpdates on main (see prior comment).

@bbingz bbingz closed this Aug 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Remote Windows host can disappear while smart sort repeatedly refreshes it

3 participants