orca icon indicating copy to clipboard operation
orca copied to clipboard

fix(windows): keep workspace selection and surface in sync

Open bbingz opened this issue 4 months ago β€’ 9 comments

Summary

  • keep sidebar active styling derived from the same activeWorktreeId that controls workspace overlay visibility
  • retain duplicate-row activation intent without directly mutating aria-current or active-card DOM attributes ahead of React/store state
  • ignore stale VM resume completions and errors after a newer sidebar workspace click

Related to #8289.

This PR fixes the reproduced sidebar/store navigation races, but does not reproduce or close the reported no-VM split-collapse/terminal-overlay paint race.

Screenshots

No visual design change. The fix removes the transient state where the newly clicked sidebar row looked active while the previous workspace surface remained active.

Testing

  • [ ] pnpm lint β€” code lint, switch exhaustiveness, reliability gates, and max-lines pass; the command later stops on five pre-existing missing localization keys from UsagePercentageDisplayChangeNotice.tsx on current main
  • [x] pnpm typecheck
  • [ ] pnpm test β€” not run repository-wide; four affected suites pass 39/39 tests
  • [x] pnpm build:electron-vite
  • [x] Added a deterministic regression for an older VM resume completing after a newer workspace click

Focused command:

pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/sidebar-worktree-activation.test.ts src/renderer/src/components/sidebar/sleep-worktree-activation-race.test.ts src/renderer/src/lib/worktree-activation.test.ts src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx

AI Review Report

The sidebar previously mutated mounted row DOM immediately on click, before activateWorktreeFromSidebar() completed its asynchronous ephemeral-VM resume probe. During main-process delay after a split collapse, the sidebar could therefore claim workspace A while activeWorktreeId and the central overlay correctly remained on workspace B. Removing that independent mutation makes both surfaces commit from the same store state.

The review also covered local Windows, WSL, regular SSH, user-managed runtime environments, ephemeral VMs exposed through Orca Server or runtime-owned SSH, duplicate pinned/canonical sidebar rows, folder workspaces, resume failure, and rapid A-to-B navigation. Resume still precedes activation for actual VMs; a monotonic request token prevents an older completion from pulling navigation back after a later click.

No layout, color, typography, spacing, shortcut, filesystem path, shell, SSH transport, or git-provider behavior changed.

Security Audit

No new IPC, command execution, filesystem access, authentication, network endpoint, dependency, or secret handling was added. The change only removes direct DOM attribute mutation and compares in-memory activation request numbers. Stale resume errors are suppressed only after a newer explicit user navigation owns the surface.

Notes

The split collapse was the load-correlated trigger, not an overlay ownership bug: the sidebar could advance independently while the activation IPC was queued. Terminal panes remain persistently mounted, and their visibility continues to be controlled by the existing worktree surface logic.

ELI5

On Windows, clicking a workspace in the sidebar could show that row as active while the main surface still showed the old workspace for a moment. Active styling and visible workspace now share the same source of truth, and stale VM resume results after a newer click are ignored.

bbingz avatar Jul 11 '26 22:07 bbingz

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: d784e13a-2e64-4d5b-bbc3-d8f25ae3bfd6

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 4774d38239597a2ddd027e2e900afdd14699f300 and 60b2a11ad3e623ef989d3f819bdfa6b1bf70c6c0.

πŸ“’ Files selected for processing (17)
  • src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx
  • src/renderer/src/components/sidebar/WorktreeCard.tsx
  • src/renderer/src/components/sidebar/WorktreeList.tsx
  • src/renderer/src/components/sidebar/sleep-worktree-activation-race.test.ts
  • src/renderer/src/lib/navigation-intent-integration.test.ts
  • src/renderer/src/lib/navigation-intent.ts
  • src/renderer/src/lib/sidebar-active-row-intent.test.ts
  • src/renderer/src/lib/sidebar-active-row-intent.ts
  • src/renderer/src/lib/sidebar-worktree-activation.test.ts
  • src/renderer/src/lib/sidebar-worktree-activation.ts
  • src/renderer/src/lib/worktree-activation.test.ts
  • src/renderer/src/lib/worktree-activation.ts
  • src/renderer/src/store/slices/runtime-status.test.ts
  • src/renderer/src/store/slices/runtime-status.ts
  • src/renderer/src/store/slices/ui.ts
  • src/renderer/src/store/slices/worktree-helpers.ts
  • src/renderer/src/store/slices/worktrees.ts

πŸ“ Walkthrough

Walkthrough

Navigation intent tokens now coordinate UI navigation, worktree and folder activation, runtime status refreshes, and asynchronous VM resume handling. Stale operations no longer apply navigation or runtime state changes, and stale wake failures do not show errors. Sidebar activation records and reconciles the selected duplicate row without immediate DOM activation. Tests cover intent propagation, stale-operation suppression, runtime status guards, and row reconciliation.

πŸš₯ Pre-merge checks | βœ… 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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
Title check βœ… Passed The title clearly summarizes the primary fix: synchronizing workspace selection with the visible workspace surface on Windows.
Description check βœ… Passed The description includes all required sections and provides clear scope, testing results, review coverage, security findings, and known limitations.
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.

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[bot] avatar Jul 11 '26 23:07 coderabbitai[bot]

@coderabbitai review

bbingz avatar Jul 13 '26 10:07 bbingz

βœ… 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.

coderabbitai[bot] avatar Jul 13 '26 10:07 coderabbitai[bot]

Taking a look!

OrcaWin avatar Jul 20 '26 19:07 OrcaWin

πŸ” Opus deep review of the stale-workspace-surface fix (#8289) β€” reviewed on our rebased branch OrcaWin/pr-8325-rebase (the author fork is unpushable; this branch is intended for a superseding PR).

Verdict: the fix is correct and I found no regressions or perf issues.

What I verified:

  • Store-driven selection is airtight. Active state (aria-current, isActive, isActiveSurface) is now driven entirely by store activeWorktreeId (WorktreeList.tsx:4745). primaryActiveWorktreeRow only chooses primary vs secondary among rows the store already marks active, so the sidebar can no longer paint a card active ahead of the workspace surface. The removed imperative markSidebarWorktreeActiveImmediately DOM path is fully gone with no dangling refs; getMountedWorktreeOptions is still legitimately used by revealMountedWorktreeElement.
  • The last-request-wins guard is sound. The module-level monotonic latestActivationRequest counter correctly discards a late VM-resume completion (and its error toast) once a newer sidebar click has taken over β€” both resolution orders, rapid same-worktree double-clicks (dedupes), and the synchronous folder branch are all handled.
  • No new latency. The awaited resumeWorkspace IPC round-trip is pre-existing on main; this PR only adds two cheap identity checks. Pure renderer logic β€” no metaKey/path-separator/OS assumptions, so it behaves identically on macOS/Linux/Windows, and the guarded IPC is renderer↔local-main (not over SSH).

What I changed (test-only, addressing prior-review nits):

  • Added coverage for the error-path guard (sidebar-worktree-activation.ts:23), which previously had zero tests: a stale wake rejection must not toast, plus a positive case confirming the current click still toasts.
  • Added afterEach(() => vi.unstubAllGlobals()) cleanup for the window stub.

Checks: typecheck:web βœ… (exit 0), oxlint on all changed files βœ… (0 warnings), vitest βœ… (6/6 in sidebar-worktree-activation.test.ts, plus the sleep-race suite).

Pushed as 13afedca2 on OrcaWin/pr-8325-rebase. Residual risk: this PR intentionally scopes to the store-driven-selection + stale-VM-resume half of #8289; the terminal-overlay/split-collapse hardening (deterministic refit after split collapse, overlay-ownership invariant, PTY handler ownership) remains a legitimate open follow-up and shouldn't be auto-closed by this merge. Not merging β€” leaving that to the superseding PR. πŸš€

OrcaWin avatar Jul 21 '26 17:07 OrcaWin

Hey! πŸ‘‹ We rebased this onto the latest main (it had drifted ~75 commits behind) and pushed a couple of small review fixes here to try to help it land β€” the rebase came through cleanly with no conflicts. The extra changes are test-only: coverage for the stale VM-resume error-path guard (a superseded wake failure shouldn't toast) plus a positive current-click case, and an afterEach global-stub cleanup. Verified green locally: typecheck:web + typecheck:node (exit 0), oxlint clean on the changed dirs, and the activation/sleep-race suites pass (8/8). CI should be green now. πŸš€

OrcaWin avatar Jul 21 '26 21:07 OrcaWin

@OrcaWin Thanks for the Opus review and for rebasing/pushing the extra test coverage.

Confirming the fork branch is MERGEABLE on current main. If you prefer to land from OrcaWin/pr-8325-rebase instead, that works for me β€” just say which head should be canonical and I’ll align.

bbingz avatar Jul 22 '26 01:07 bbingz

Rebased this onto the latest main and pushed the review fixes here to help get it landed β€” CI should be green now. Thanks so much for the contribution!

To answer your earlier question: this branch (bbingz:fix/windows-stale-workspace-surface) is the canonical head β€” no need to align anything on your side.

OrcaWin avatar Jul 28 '26 04:07 OrcaWin

Greptile Summary

This PR fixes a Windows-specific sidebar/workspace surface synchronization race where clicking a new workspace row could briefly show it as active in the sidebar while the main surface still displayed the previous workspace. The fix removes direct DOM mutation (markSidebarWorktreeActiveImmediately) and replaces it with a monotonic navigation intent counter that both the sidebar active-row state and async VM resume operations use as a shared source of truth.

  • New navigation-intent.ts module: introduces a module-level monotonic counter with a pub-sub mechanism; beginNavigationIntent() advances the counter and notifies subscribers on every user-initiated navigation, while isCurrentNavigationIntent() lets async steps bail out when a newer click has taken ownership.
  • Sidebar active row now intent-driven: VirtualizedWorktreeViewport subscribes to the intent via useSyncExternalStore; reconcileSidebarActiveRowIntent clears primaryActiveWorktreeRow whenever the stored intent no longer matches the current one, ensuring active styling and the visible workspace surface always derive from the same state.
  • VM resume guarded at every await point: activateWorktreeFromSidebar checks isCurrentNavigationIntent after each await (resume, dynamic import, env list, status refresh), so a slow VM wake cannot override a more recent workspace click; a new shouldApply callback in refreshRuntimeEnvironmentStatus extends this guard into an in-flight status write.

Confidence Score: 5/5

Safe to merge; the change removes a direct DOM mutation race and replaces it with a well-tested monotonic intent counter that all navigation paths share.

The logic is correct end-to-end: every async await point in the VM resume chain is guarded, the sidebar active-row state is now derived from the same counter that controls surface visibility, and dedicated regression tests cover the stale-resume, stale-error-toast, stale-runtime-refresh, and shouldApply-gate scenarios. No security surface, IPC, or data path was changed.

Files Needing Attention: No files require special attention. The one minor redundancy (double beginNavigationIntent() call in the history-navigation view activator) is harmless and does not affect correctness.

Important Files Changed

Filename Overview
src/renderer/src/lib/navigation-intent.ts New module introducing the monotonic intent counter and pub-sub mechanism that is the backbone of this fix; implementation is clean and minimal.
src/renderer/src/lib/sidebar-worktree-activation.ts Core fix: begins a navigation intent before the VM resume await chain and guards every async continuation with isCurrentNavigationIntent(); stale errors are also suppressed correctly.
src/renderer/src/components/sidebar/WorktreeList.tsx Removes markSidebarWorktreeActiveImmediately DOM mutation; active row state is now driven by useSyncExternalStore over the navigation intent, reconciled via reconcileSidebarActiveRowIntent after each intent change.
src/renderer/src/lib/worktree-activation.ts activateAndRevealWorktree and activateAndRevealFolderWorkspace now accept and propagate navigationIntent; functions create their own intent when called without one, ensuring every activation path participates in the intent protocol.
src/renderer/src/store/slices/ui.ts setActiveView now accepts a navigationIntent option and guards the state write; all page-open/close actions call beginNavigationIntent() so any in-flight sidebar activation is invalidated by explicit page navigation.
src/renderer/src/store/slices/worktrees.ts setActiveWorktree and setActiveFolderWorkspace both accept navigationIntent and guard the state write, preventing a stale VM resume from overwriting a more recent workspace selection.
src/renderer/src/store/slices/runtime-status.ts refreshRuntimeEnvironmentStatus gains a shouldApply callback to let callers veto publishing a status result that arrived after a newer navigation; the test for the guarded path is correctly added.
src/renderer/src/lib/sidebar-active-row-intent.ts New helper type and reconcile function; logic is correct β€” clears the active row intent when the intent counter has advanced or the row is no longer in the list.
src/renderer/src/lib/sidebar-worktree-activation.test.ts Well-expanded test suite: covers stale resume suppression, stale runtime-env refresh suppression, stale error toast suppression, and the shouldApply gate β€” all the async races this PR targets.
src/renderer/src/lib/navigation-intent-integration.test.ts New integration test file verifying that every navigation surface (worktree, folder workspace, page opens, history nav, raw setActiveWorktree) correctly advances the intent counter.

Sequence Diagram

sequenceDiagram
    participant User
    participant WorktreeCard
    participant SidebarActivation as activateWorktreeFromSidebar
    participant NavIntent as navigation-intent
    participant EphemeralVM as window.api.ephemeralVm
    participant Store as AppStore

    User->>WorktreeCard: click workspace A (VM)
    WorktreeCard->>SidebarActivation: activateWorktreeFromSidebar('wt-A', onIntentStarted)
    SidebarActivation->>NavIntent: "beginNavigationIntent() β†’ intent=5"
    SidebarActivation->>WorktreeCard: "onIntentStarted(5) β†’ setPrimaryActiveRowIntent({wt-A, intent:5})"
    SidebarActivation->>EphemeralVM: "resumeWorkspace({workspaceId:'wt-A'}) [awaits…]"

    Note over User,Store: User clicks workspace B before VM resume completes

    User->>WorktreeCard: click workspace B (local)
    WorktreeCard->>SidebarActivation: activateWorktreeFromSidebar('wt-B', onIntentStarted)
    SidebarActivation->>NavIntent: "beginNavigationIntent() β†’ intent=6"
    SidebarActivation->>WorktreeCard: "onIntentStarted(6) β†’ setPrimaryActiveRowIntent({wt-B, intent:6})"
    SidebarActivation->>Store: "activateAndRevealWorktree('wt-B', {navigationIntent:6})"
    Store->>Store: setActiveWorktree('wt-B') βœ“

    Note over EphemeralVM,SidebarActivation: wt-A VM resume eventually resolves

    EphemeralVM-->>SidebarActivation: resume result
    SidebarActivation->>NavIntent: isCurrentNavigationIntent(5) β†’ false
    SidebarActivation-->>SidebarActivation: return early β€” stale activation suppressed βœ“

    Note over WorktreeCard,Store: Sidebar and surface both reflect workspace B

Reviews (2): Last reviewed commit: "fix(windows): preserve latest navigation..." | Re-trigger Greptile

greptile-apps avatar Jul 29 '26 07:07 greptile-apps

[!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.

coderabbitai[bot] avatar Aug 06 '26 00:08 coderabbitai[bot]

Closing as part of fork PR backlog cleanup.

This branch is long-conflicted (DIRTY) against current main and is not on the active campaign rebase list. Feel free to reopen or cut a fresh PR from an updated branch if the change is still needed.

bbingz avatar Aug 10 '26 03:08 bbingz