fix: unwatch ssh filesystem roots on dispose (#4176)

This commit is contained in:
Neil
2026-05-31 06:59:16 -07:00
committed by GitHub
parent 403ac726aa
commit 000e995303
4 changed files with 102 additions and 1 deletions
+35
View File
@@ -1,3 +1,6 @@
/* eslint-disable max-lines -- Why: filesystem watcher tests share module-level
state across local, WSL, and SSH lifecycle paths; keeping them together makes
closeAllWatchers cleanup regressions visible in one suite. */
import { beforeEach, describe, expect, it, vi } from 'vitest'
const { handleMock, getSshFilesystemProviderMock } = vi.hoisted(() => ({
@@ -138,6 +141,38 @@ describe('registerFilesystemWatcherHandlers', () => {
vi.useRealTimers()
})
it('retries SSH worktree watches when provider setup rejects', async () => {
vi.useFakeTimers()
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
const sendMock = vi.fn()
const sender = { isDestroyed: () => false, send: sendMock, once: vi.fn(), id: 1 }
const unwatchMock = vi.fn()
const retryWatchMock = vi.fn().mockResolvedValue(unwatchMock)
getSshFilesystemProviderMock
.mockReturnValueOnce({
watch: vi.fn().mockRejectedValue(new Error('provider disposed'))
})
.mockReturnValue({ watch: retryWatchMock })
await expect(
handlers['fs:watchWorktree'](
{ sender },
{ worktreePath: '/home/me/repo', connectionId: 'conn-1' }
)
).resolves.toBeUndefined()
await vi.advanceTimersByTimeAsync(1_000)
expect(retryWatchMock).toHaveBeenCalledWith('/home/me/repo', expect.any(Function))
handlers['fs:unwatchWorktree'](
{ sender: { id: 1 } },
{ worktreePath: '/home/me/repo', connectionId: 'conn-1' }
)
expect(unwatchMock).toHaveBeenCalledTimes(1)
warnSpy.mockRestore()
vi.useRealTimers()
})
it('cancels pending SSH watch retries during watcher shutdown', async () => {
vi.useFakeTimers()
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+3
View File
@@ -630,6 +630,9 @@ async function doInstallRemoteWatcher(
} satisfies FsChangedPayload)
}
})
} catch (err) {
console.warn(`[filesystem-watcher] SSH watcher unavailable for ${key}:`, err)
return 'unavailable'
} finally {
if (inFlightRemoteInstalls.get(key) === cancelToken) {
inFlightRemoteInstalls.delete(key)
@@ -471,6 +471,43 @@ describe('SshFilesystemProvider', () => {
expect(mux.notify).toHaveBeenCalledWith('fs.unwatch', { rootPath: '/home/user/project' })
})
it('sends fs.unwatch for active roots when disposed', async () => {
const callback = vi.fn()
await provider.watch('/home/user/project', callback)
provider.dispose()
expect(mux.notify).toHaveBeenCalledWith('fs.unwatch', { rootPath: '/home/user/project' })
const notifHandler = mux.onNotification.mock.calls[0][0]
notifHandler('fs.changed', {
events: [{ kind: 'update', absolutePath: '/home/user/project/file.ts' }]
})
expect(callback).not.toHaveBeenCalled()
})
it('unwatches when disposed while fs.watch setup is still resolving', async () => {
let resolveWatch: () => void = () => {}
mux.request.mockImplementationOnce(
() =>
new Promise<void>((resolve) => {
resolveWatch = resolve
})
)
const callback = vi.fn()
const pendingWatch = provider.watch('/home/user/project', callback)
provider.dispose()
resolveWatch()
await expect(pendingWatch).rejects.toThrow('SSH filesystem provider disposed')
expect(mux.notify).toHaveBeenCalledWith('fs.unwatch', { rootPath: '/home/user/project' })
const notifHandler = mux.onNotification.mock.calls[0][0]
notifHandler('fs.changed', {
events: [{ kind: 'update', absolutePath: '/home/user/project/file.ts' }]
})
expect(callback).not.toHaveBeenCalled()
})
it('does not send fs.unwatch while other roots are watched', async () => {
const cb1 = vi.fn()
const cb2 = vi.fn()
+27 -1
View File
@@ -49,6 +49,7 @@ export class SshFilesystemProvider implements IFilesystemProvider {
// the provider is torn down on disconnect, routing events to stale state.
private unsubscribeNotifications: (() => void) | null = null
private tempDirPromise: Promise<string> | null = null
private disposed = false
// Why: relays from a previous build may not implement fs.readFileStream.
// We log the fallback once per session at warn level so users on stale
// relays get diagnosed quickly without per-read log spam.
@@ -78,10 +79,17 @@ export class SshFilesystemProvider implements IFilesystemProvider {
}
dispose(): void {
if (this.disposed) {
return
}
this.disposed = true
if (this.unsubscribeNotifications) {
this.unsubscribeNotifications()
this.unsubscribeNotifications = null
}
for (const rootPath of this.watchListeners.keys()) {
this.notifyUnwatch(rootPath)
}
this.watchListeners.clear()
}
@@ -251,10 +259,16 @@ export class SshFilesystemProvider implements IFilesystemProvider {
}
async watch(rootPath: string, callback: (events: FsChangeEvent[]) => void): Promise<() => void> {
if (this.disposed) {
throw new Error('SSH filesystem provider disposed')
}
let registration = this.watchListeners.get(rootPath)
if (registration) {
registration.callbacks.add(callback)
await registration.setupPromise
if (this.disposed || this.watchListeners.get(rootPath) !== registration) {
throw new Error('SSH filesystem provider disposed')
}
return this.createWatchUnsubscribe(rootPath, registration, callback)
}
@@ -271,10 +285,22 @@ export class SshFilesystemProvider implements IFilesystemProvider {
registration = { callbacks, setupPromise }
this.watchListeners.set(rootPath, registration)
await setupPromise
if (this.disposed || this.watchListeners.get(rootPath) !== registration) {
this.notifyUnwatch(rootPath)
throw new Error('SSH filesystem provider disposed')
}
return this.createWatchUnsubscribe(rootPath, registration, callback)
}
private notifyUnwatch(rootPath: string): void {
try {
this.mux.notify('fs.unwatch', { rootPath })
} catch {
// Connection teardown may already have closed the mux; disposal must continue.
}
}
private createWatchUnsubscribe(
rootPath: string,
registration: WatchRegistration,
@@ -284,7 +310,7 @@ export class SshFilesystemProvider implements IFilesystemProvider {
registration.callbacks.delete(callback)
if (registration.callbacks.size === 0 && this.watchListeners.get(rootPath) === registration) {
this.watchListeners.delete(rootPath)
this.mux.notify('fs.unwatch', { rootPath })
this.notifyUnwatch(rootPath)
}
}
}