Skip to content

fix(ssh): resync after watcher terminal retry - #10691

Merged
AmethystLiang merged 3 commits into
mainfrom
fix-p2-ssh-watcher-resync
Jul 28, 2026
Merged

AmethystLiang merged 3 commits into
mainfrom
fix-p2-ssh-watcher-resync

Conversation

@AmethystLiang

Copy link
Copy Markdown
Contributor

Summary

Test plan

  • Five focused watcher files: 47/47 tests passed.
  • Touched-file oxlint passed.
  • pnpm run typecheck:node passed.
  • pnpm run check:max-lines-ratchet passed.
  • git diff --check passed.

Release-scan provenance

This PR addresses the pre-existing prod-release-scan P2 finding "SSH watcher fast-retry without overflow resync" documented in /private/tmp/prod-release-worker-reports/FINAL.md and platform.md. Nearby behavior and context are tracked in #10445 and #10470.

@coderabbitai

coderabbitai Bot commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f33c89e1-ddb4-4f5b-a2c5-4e423f0ab293

📥 Commits

Reviewing files that changed from the base of the PR and between 44608c7 and 4332fe2.

📒 Files selected for processing (2)
  • src/main/ipc/filesystem-watcher-terminal-resync.test.ts
  • src/main/ipc/filesystem-watcher.ts

📝 Walkthrough

Walkthrough

The change adds current-desired listener checks and coalesced resynchronization to SSH remote watcher retry and reinstallation flows. It also adds Vitest coverage for terminal retries, provider registration, owner and renderer cancellation, teardown recovery, shutdown cleanup, and reopened watch lifecycles.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning It includes summary and testing, but omits required screenshots, AI review, security audit, and notes sections from the template. Add the missing template sections: Screenshots, full Testing checklist, AI Review Report, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the SSH watcher retry resync change and is concise.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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
🔧 Fix failing CI
  • Fix failing CI in branch fix-p2-ssh-watcher-resync

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.

🧹 Nitpick comments (3)
src/main/ipc/filesystem-watcher.ts (1)

1269-1288: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider gating the warn log behind the new closed/suspended check.

The console.warn at Line 1275 now precedes a guard that treats remoteWatchersClosed/suspendedRemoteWatcherListeners as expected, no-op outcomes. As a result, every intentional worktree close or destructive removal will log a "SSH watcher terminated" warning even though nothing actionable happens — this makes the log noisier and harder to distinguish from a real unexpected termination.

♻️ Proposed reordering
   remoteWatchers.delete(key)
-  console.warn(`[filesystem-watcher] SSH watcher terminated for ${key}:`, error)
   if (remoteWatchersClosed || suspendedRemoteWatcherListeners.has(key)) {
     return
   }
+  console.warn(`[filesystem-watcher] SSH watcher terminated for ${key}:`, error)
   const startedAt = Date.now()
src/main/ipc/filesystem-watcher-terminal-resync.test.ts (2)

41-48: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor duplication with the custom sender in the "destroyed" test.

createSender hardcodes isDestroyed: () => false, forcing the destroyed-renderer test (Line 181-186) to redeclare the same shape inline with a mutable flag. Consider extending createSender to accept an optional mutable destroyed-state, or extracting a shared MockSender type, to avoid two near-identical shapes.


179-197: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Mock captures .once() handlers by index, not by event name.

destroyedHandlers accumulates every .once() registration on the sender regardless of event, and the test fires destroyedHandlers[0]. If the implementation ever registers another .once() listener before the "destroyed" one, this assertion would silently target the wrong handler instead of failing loudly.

♻️ Proposed fix
-      once: vi.fn((_event: string, handler: () => void) => destroyedHandlers.push(handler)),
+      once: vi.fn((event: string, handler: () => void) => {
+        if (event === 'destroyed') destroyedHandlers.push(handler)
+      }),

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a12bd997-fbfa-458f-859b-f66bf9c71c96

📥 Commits

Reviewing files that changed from the base of the PR and between c67aadb and 44608c7.

📒 Files selected for processing (2)
  • src/main/ipc/filesystem-watcher-terminal-resync.test.ts
  • src/main/ipc/filesystem-watcher.ts

@AmethystLiang

Copy link
Copy Markdown
Contributor Author

@coderabbitai[bot] resovled

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmethystLiang Thanks for resolving it! 🐇


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

- Coalesce repeated recovery resyncs within 5s to reduce SSH refreshes
  during link flaps
- Abort in-flight watcher installs when a replacement provider registers,
  preventing duplicate watchers from old and new transports
- Clear resync state when removing watcher snapshots or on provider change
  to prevent stale retry timers
Avoid logging spurious warnings when a remote watcher is already closed or
suspended. Move the console.warn call in handleRemoteWatcherTerminalError()
to after the early-return checks. Refactor createSender() in tests to
properly simulate the destroyed event for better coverage of retry-cancellation
behavior.
@AmethystLiang
AmethystLiang merged commit 8b57e6e into main Jul 28, 2026
0 of 22 checks passed
Comment on lines +1314 to +1328
function flushRemoteWatcherResync(key: string): void {
const state = remoteWatcherResyncStates.get(key)
if (!state) {
return
}
state.timer = undefined
if (
remoteWatchersClosed ||
suspendedRemoteWatcherListeners.has(key) ||
!remoteWatchers.has(key)
) {
if (!desiredRemoteWatchers.has(key)) {
remoteWatcherResyncStates.delete(key)
}
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Retained listeners not cleared on early-return skip

When flushRemoteWatcherResync fires its coalesce timer but !remoteWatchers.has(key) (the watcher died again between being installed and the timer expiring) and desiredRemoteWatchers.has(key), the function returns early without clearing state.listeners. The intent is to buffer the pending overflow until the watcher reinstalls and calls requestRemoteWatcherResync again — at which point delayMs === 0 (lastSentAt still at NEGATIVE_INFINITY) triggers an immediate flush that picks up the retained listeners alongside any new ones.

This works correctly and is covered by tests, but it is a non-obvious invariant: unlike the success path (state.listeners.clear() after sending) and the fully-cancelled path (remoteWatcherResyncStates.delete(key)), this third outcome leaves the map entry in a partially-consumed state. A comment co-located with the return explaining why listeners are intentionally preserved here would help future maintainers avoid accidentally "fixing" it.

@greptile-apps

greptile-apps Bot commented Jul 28, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes a pre-existing bug where a successfully retried SSH watcher (after a terminal error) never sent an overflow event to renderers, leaving them with a stale view of the filesystem. It also introduces a 5-second coalescing window to prevent overflow spam during rapid watcher flaps, and filters stale/unregistered listeners across all overflow delivery sites.

  • Terminal retry resync: handleRemoteWatcherTerminalError now passes resyncOnInstall=true to scheduleRemoteWatcherRetry, which triggers a coalesced fs:changed overflow once the watcher successfully reinstalls.
  • Coalesced resync state: The new remoteWatcherResyncStates map (with requestRemoteWatcherResync / flushRemoteWatcherResync) replaces three independent inline listener.send(...) patterns in the retry, dormant rearm, and provider-reconnect paths; the 5-second coalesce window prevents back-to-back overflows during SSH link flaps.
  • Stale-owner filtering and cancellation guards: isCurrentDesiredRemoteWatcher is now checked before delivering any overflow; resync state is cleared on unwatch, renderer destruction, destructive removal (forgetRemoteWatcherRemovalSnapshot), and shutdown; in-flight installs are aborted on provider replacement.

Confidence Score: 4/5

Safe to merge; the bug fix and guard logic are well-scoped and all 47 tests pass, including new cases for every cancellation edge.

The core fix (adding resyncOnInstall=true to terminal-error retries) is straightforward and well-tested. The new resync state machinery is more complex — three new functions, coalesce timing, and a partially-retained state on early-return — but each branch is covered by a dedicated test case. The only observations are style-level: a cleanup inconsistency between two cancellation sites and an undocumented invariant in the early-return path of flushRemoteWatcherResync.

Files Needing Attention: The three new functions in filesystem-watcher.ts (clearRemoteWatcherResync, flushRemoteWatcherResync, requestRemoteWatcherResync) and the early-return branch in flushRemoteWatcherResync that intentionally retains state.listeners deserve a second look on review.

Important Files Changed

Filename Overview
src/main/ipc/filesystem-watcher.ts Adds RemoteWatcherResyncState map, three new helper functions (clearRemoteWatcherResync, flushRemoteWatcherResync, requestRemoteWatcherResync), and wires resyncOnInstall=true through terminal-error retries; also adds inFlight.abortController.abort() on provider replacement and missing retry cancellation in forgetRemoteWatcherRemovalSnapshot.
src/main/ipc/filesystem-watcher-terminal-resync.test.ts New test file with 9 focused cases covering: stale-owner filtering, initial-failure non-resync, provider-registration supersession, in-flight abort on replacement provider, coalesce deduplication, and cancellation on unwatch / snapshot forget / renderer destroy / destructive removal / shutdown reopen.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[SSH watcher terminal error] --> B{remoteWatchersClosed\nor suspendedListeners has key?}
    B -- yes --> Z[Return — suppress retry]
    B -- no --> C[scheduleRemoteWatcherRetry\nresyncOnInstall=true]
    C --> D{Retry timeout\nexceeded?}
    D -- yes --> E[Send overflow immediately\n+ schedule dormant rearm]
    D -- no --> F[Wait REMOTE_WATCH_RETRY_MS 1s]
    F --> G[installRemoteWatcher\nfor each live listener]
    G --> H{result?}
    H -- installed --> I[requestRemoteWatcherResync]
    H -- unavailable --> C
    H -- cancelled --> Z2[No resync — renderer\nstopped watching]
    I --> J{lastSentAt within\n5-second window?}
    J -- no/first send --> K[flushRemoteWatcherResync immediately]
    J -- yes --> L{timer already\nscheduled?}
    L -- yes --> M[Coalesce into existing timer]
    L -- no --> N[Schedule timer for remaining window]
    N --> K
    M --> K
    K --> O{watcher still\nin remoteWatchers?}
    O -- no, desired --> P[Keep state — buffer until next install]
    O -- yes --> Q[Send fs:changed overflow\nto isCurrentDesiredRemoteWatcher listeners]
    Q --> R[Update lastSentAt for next coalesce window]
Loading

Comments Outside Diff (1)

  1. src/main/ipc/filesystem-watcher.ts, line 1016-1030 (link)

    P2 Inconsistent pendingRemoteWatcherRetryListeners cleanup pattern

    forgetRemoteWatcherRemovalSnapshot now unconditionally deletes from pendingRemoteWatcherRetryListeners (outside the if (retryTimer) block), while closeRemoteWatcherForWorktreePath (line 966–971) only deletes it when a timer is present. In practice this is harmless — the two maps are always set and cleared together in scheduleRemoteWatcherRetry — but the unconditional form adopted here is more defensive and would be worth applying consistently to closeRemoteWatcherForWorktreePath as well to make the invariant explicit.

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Reviews (1): Last reviewed commit: "fix(ssh): resync after watcher terminal ..." | Re-trigger Greptile

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* fix(ssh): resync after watcher terminal retry

* fix(ssh): resync after watcher terminal retry

- Coalesce repeated recovery resyncs within 5s to reduce SSH refreshes
  during link flaps
- Abort in-flight watcher installs when a replacement provider registers,
  preventing duplicate watchers from old and new transports
- Clear resync state when removing watcher snapshots or on provider change
  to prevent stale retry timers

* fix(ssh): resync after watcher terminal retry

Avoid logging spurious warnings when a remote watcher is already closed or
suspended. Move the console.warn call in handleRemoteWatcherTerminalError()
to after the early-return checks. Refactor createSender() in tests to
properly simulate the destroyed event for better coverage of retry-cancellation
behavior.
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