diff --git a/src/main/ipc/workspace-ports.test.ts b/src/main/ipc/workspace-ports.test.ts index c688cdb156f..ce66b79b8b6 100644 --- a/src/main/ipc/workspace-ports.test.ts +++ b/src/main/ipc/workspace-ports.test.ts @@ -258,6 +258,26 @@ describe('registerWorkspacePortHandlers', () => { port: 3002 }) }) + + it('unsubscribes the previous advertised URL listener when handlers are registered again', () => { + const store = makeStore() + const firstUnsubscribe = vi.fn() + const secondUnsubscribe = vi.fn() + const onDidChange = vi + .fn() + .mockReturnValueOnce(firstUnsubscribe) + .mockReturnValueOnce(secondUnsubscribe) + + registerWorkspacePortHandlers(store as never, { + advertisedUrlEvents: { onDidChange } + }) + registerWorkspacePortHandlers(store as never, { + advertisedUrlEvents: { onDidChange } + }) + + expect(firstUnsubscribe).toHaveBeenCalledTimes(1) + expect(secondUnsubscribe).not.toHaveBeenCalled() + }) }) function workspacePort({ pid, port }: { pid: number; port: number }): WorkspacePort { diff --git a/src/main/ipc/workspace-ports.ts b/src/main/ipc/workspace-ports.ts index b2041fa4e09..27d1df254d7 100644 --- a/src/main/ipc/workspace-ports.ts +++ b/src/main/ipc/workspace-ports.ts @@ -19,6 +19,8 @@ type WorkspacePortHandlersOptions = { getWindows?: () => BrowserWindow[] } +let unsubscribeAdvertisedUrlChanges: (() => void) | null = null + export function registerWorkspacePortHandlers( store: Store, options: WorkspacePortHandlersOptions = {} @@ -27,7 +29,8 @@ export function registerWorkspacePortHandlers( const advertisedUrlEvents = options.advertisedUrlEvents ?? advertisedUrlWatcher const getWindows = options.getWindows ?? (() => BrowserWindow.getAllWindows()) - advertisedUrlEvents.onDidChange((event) => { + unsubscribeAdvertisedUrlChanges?.() + unsubscribeAdvertisedUrlChanges = advertisedUrlEvents.onDidChange((event) => { const localWorktrees = getStoreWorkspacePortProbes(store) if (!localWorktrees.some((worktree) => worktree.id === event.worktreeId)) { return