From 88f88a178f56c7e0d30bba78781d421ba6b38fb5 Mon Sep 17 00:00:00 2001 From: Chirag Chandrashekhar Date: Fri, 10 Jul 2026 18:47:41 +0530 Subject: [PATCH 1/2] fix(migration): reattach mountv2 watcher after yml migration The migrate-to-yml handler tore down the collection watcher and re-attached it the v1 way (no fileIndex, no temp-dir watcher), so a collection mounted via mountv2 lost cache-backed live sync after migration and the file cache kept stale .bru entries. Add MountManager.remount, which re-reconciles the cache against disk and re-attaches the watcher through the shared cold-load path while preserving the existing transient directory. The migrate handler now delegates to it when the collection is v2-mounted and falls back to the v1 watcher otherwise. --- packages/bruno-electron/src/ipc/collection.js | 16 ++++++----- packages/bruno-electron/src/ipc/mount.js | 3 +- .../src/services/mount/manager.js | 28 ++++++++++++++++--- 3 files changed, 35 insertions(+), 12 deletions(-) diff --git a/packages/bruno-electron/src/ipc/collection.js b/packages/bruno-electron/src/ipc/collection.js index f562207f46b..9cc924fc948 100644 --- a/packages/bruno-electron/src/ipc/collection.js +++ b/packages/bruno-electron/src/ipc/collection.js @@ -77,6 +77,7 @@ const { getProcessEnvVars } = require('../store/process-env'); const { getOAuth2TokenUsingAuthorizationCode, getOAuth2TokenUsingClientCredentials, getOAuth2TokenUsingPasswordCredentials, getOAuth2TokenUsingImplicitGrant, refreshOauth2Token } = require('../utils/oauth2'); const { getCertsAndProxyConfig } = require('./network/cert-utils'); const collectionWatcher = require('../app/collection-watcher'); +const { remount: remountCollectionV2 } = require('./mount'); const { transformBrunoConfigBeforeSave, transformBrunoConfigAfterRead } = require('../utils/transformBrunoConfig'); const { REQUEST_TYPES } = require('../utils/constants'); const { cancelOAuth2AuthorizationRequest, isOauth2AuthorizationRequestInProgress } = require('../utils/oauth2-protocol-handler'); @@ -2779,15 +2780,16 @@ const registerRendererEventHandlers = (mainWindow, watcher) => { ymlBrunoConfig.size = size; ymlBrunoConfig.filesCount = filesCount; - if (watcher) { - try { + try { + const remounted = await remountCollectionV2({ collectionUid, brunoConfig: ymlBrunoConfig, win: mainWindow }); + if (!remounted && watcher) { watcher.addWatcher(mainWindow, collectionPathname, collectionUid, ymlBrunoConfig, false, undefined, { ignoreInitial: true }); - } catch (watcherError) { - console.error('Failed to re-attach watcher after migration:', watcherError); - mainWindow.webContents.send('main:display-error', { - message: `Collection migrated to yml, but live sync could not be re-enabled: ${watcherError.message}. Please reopen the collection.` - }); } + } catch (watcherError) { + console.error('Failed to re-attach watcher after migration:', watcherError); + mainWindow.webContents.send('main:display-error', { + message: `Collection migrated to yml, but live sync could not be re-enabled: ${watcherError.message}. Please reopen the collection.` + }); } return ymlBrunoConfig; diff --git a/packages/bruno-electron/src/ipc/mount.js b/packages/bruno-electron/src/ipc/mount.js index 628106cbacd..3f682b183bd 100644 --- a/packages/bruno-electron/src/ipc/mount.js +++ b/packages/bruno-electron/src/ipc/mount.js @@ -30,6 +30,7 @@ const registerMountIpc = () => { }; const unmount = (collectionUid) => manager.unmount(collectionUid); +const remount = (params) => manager.remount(params); const shutdown = () => manager.shutdown(); -module.exports = { registerMountIpc, unmount, shutdown }; +module.exports = { registerMountIpc, unmount, remount, shutdown }; diff --git a/packages/bruno-electron/src/services/mount/manager.js b/packages/bruno-electron/src/services/mount/manager.js index d5f77099dd4..b3135852d89 100644 --- a/packages/bruno-electron/src/services/mount/manager.js +++ b/packages/bruno-electron/src/services/mount/manager.js @@ -97,23 +97,43 @@ class MountManager { }; this.#mounts.set(collectionUid, entry); + await this.#coldLoad(collectionUid, entry); + return tempDirectoryPath; + } + + async remount({ collectionUid, brunoConfig, win }) { + const entry = this.#mounts.get(collectionUid); + if (!entry) return false; + + if (win) entry.win = win; + if (brunoConfig) entry.brunoConfig = brunoConfig; + + // the caller tore the watcher down (e.g. yml migration rewrote every file); + // clear it before re-reconciling the cache against disk and re-attaching + const collectionWatcher = require('../../app/collection-watcher'); + collectionWatcher.removeWatcher(entry.collectionPath, entry.win, collectionUid); + + await this.#coldLoad(collectionUid, entry); + return true; + } + + async #coldLoad(collectionUid, entry) { entry.emit.loading(true); try { - entry.state = this.#getIndex().entries(collectionPath); + entry.state = this.#getIndex().entries(entry.collectionPath); await this.#reconcile(entry); await this.#emitTree(collectionUid, entry); // skip the startup walk (already done) and stage live edits into the cache const collectionWatcher = require('../../app/collection-watcher'); - collectionWatcher.addWatcher(entry.win, collectionPath, collectionUid, brunoConfig, false, false, { + collectionWatcher.addWatcher(entry.win, entry.collectionPath, collectionUid, entry.brunoConfig, false, false, { ignoreInitial: true, fileIndex: this.#getIndex() }); - collectionWatcher.addTempDirectoryWatcher(entry.win, tempDirectoryPath, collectionUid, collectionPath); + collectionWatcher.addTempDirectoryWatcher(entry.win, entry.tempDirectoryPath, collectionUid, entry.collectionPath); } finally { entry.emit.loading(false); } - return tempDirectoryPath; } async unmount(collectionUid) { From 4daf0ff62ade62a8ec38d6fe361ce2979ee6177c Mon Sep 17 00:00:00 2001 From: Chirag Chandrashekhar Date: Mon, 13 Jul 2026 14:34:29 +0530 Subject: [PATCH 2/2] test(mount): cover remount; address review feedback - Drop the unused win param from MountManager.remount; it always reuses the mount-time win/emit (a real window swap goes through mount()'s reload branch, which refreshes both). - Migration success path now falls back to a plain watcher when remount throws, not only when it returns false; the reopen-collection toast is the last resort. - Migration rollback path prefers remount for v2-mounted collections too, falling back to the v1 watcher. - Add unit tests for remount: successful reattach + tree re-emit, unknown collection returns false, watcher-removal failure propagates. --- packages/bruno-electron/src/ipc/collection.js | 26 ++-- .../src/services/mount/manager.js | 3 +- .../src/services/mount/manager.spec.js | 116 ++++++++++++++++++ 3 files changed, 134 insertions(+), 11 deletions(-) create mode 100644 packages/bruno-electron/src/services/mount/manager.spec.js diff --git a/packages/bruno-electron/src/ipc/collection.js b/packages/bruno-electron/src/ipc/collection.js index 9cc924fc948..20da91b044a 100644 --- a/packages/bruno-electron/src/ipc/collection.js +++ b/packages/bruno-electron/src/ipc/collection.js @@ -2781,15 +2781,22 @@ const registerRendererEventHandlers = (mainWindow, watcher) => { ymlBrunoConfig.filesCount = filesCount; try { - const remounted = await remountCollectionV2({ collectionUid, brunoConfig: ymlBrunoConfig, win: mainWindow }); + const remounted = await remountCollectionV2({ collectionUid, brunoConfig: ymlBrunoConfig }); if (!remounted && watcher) { watcher.addWatcher(mainWindow, collectionPathname, collectionUid, ymlBrunoConfig, false, undefined, { ignoreInitial: true }); } } catch (watcherError) { console.error('Failed to re-attach watcher after migration:', watcherError); - mainWindow.webContents.send('main:display-error', { - message: `Collection migrated to yml, but live sync could not be re-enabled: ${watcherError.message}. Please reopen the collection.` - }); + try { + if (watcher) { + watcher.addWatcher(mainWindow, collectionPathname, collectionUid, ymlBrunoConfig, false, undefined, { ignoreInitial: true }); + } + } catch (fallbackError) { + console.error('Fallback watcher attach failed after migration:', fallbackError); + mainWindow.webContents.send('main:display-error', { + message: `Collection migrated to yml, but live sync could not be re-enabled: ${fallbackError.message}. Please reopen the collection.` + }); + } } return ymlBrunoConfig; @@ -2804,13 +2811,14 @@ const registerRendererEventHandlers = (mainWindow, watcher) => { } // Restart the watcher on the original bru collection - if (watcher) { - try { - const config = JSON.parse(fs.readFileSync(path.join(collectionPathname, 'bruno.json'), 'utf8')); + try { + const config = JSON.parse(fs.readFileSync(path.join(collectionPathname, 'bruno.json'), 'utf8')); + const remounted = await remountCollectionV2({ collectionUid, brunoConfig: config }); + if (!remounted && watcher) { watcher.addWatcher(mainWindow, collectionPathname, collectionUid, config); - } catch (watcherError) { - console.error('Failed to restart watcher after migration error:', watcherError); } + } catch (watcherError) { + console.error('Failed to restart watcher after migration error:', watcherError); } throw error; } diff --git a/packages/bruno-electron/src/services/mount/manager.js b/packages/bruno-electron/src/services/mount/manager.js index b3135852d89..85930919f45 100644 --- a/packages/bruno-electron/src/services/mount/manager.js +++ b/packages/bruno-electron/src/services/mount/manager.js @@ -101,11 +101,10 @@ class MountManager { return tempDirectoryPath; } - async remount({ collectionUid, brunoConfig, win }) { + async remount({ collectionUid, brunoConfig }) { const entry = this.#mounts.get(collectionUid); if (!entry) return false; - if (win) entry.win = win; if (brunoConfig) entry.brunoConfig = brunoConfig; // the caller tore the watcher down (e.g. yml migration rewrote every file); diff --git a/packages/bruno-electron/src/services/mount/manager.spec.js b/packages/bruno-electron/src/services/mount/manager.spec.js new file mode 100644 index 00000000000..cc371d1f139 --- /dev/null +++ b/packages/bruno-electron/src/services/mount/manager.spec.js @@ -0,0 +1,116 @@ +const os = require('node:os'); +const path = require('node:path'); + +jest.mock('electron', () => ({ + app: { getPath: () => require('node:os').tmpdir() } +})); + +jest.mock('../../app/collection-watcher', () => ({ + addWatcher: jest.fn(), + addTempDirectoryWatcher: jest.fn(), + removeWatcher: jest.fn() +})); + +jest.mock('./file-index', () => ({ + FileIndex: jest.fn().mockImplementation(() => ({ + entries: jest.fn(() => new Map()), + status: jest.fn(async () => ({ added: [], updated: [], removed: [] })), + transaction: jest.fn((fn) => fn()), + stage: jest.fn(), + clear: jest.fn(), + close: jest.fn(), + dbPath: require('node:path').join(require('node:os').tmpdir(), 'mount-index.db') + })) +})); + +jest.mock('../pool', () => ({ + JobType: { ParseFile: 'ParseFile' }, + getPool: jest.fn(() => ({ run: jest.fn() })), + destroyPool: jest.fn(async () => {}) +})); + +jest.mock('./tree-builder', () => ({ + buildTree: jest.fn(() => ({ items: [], environments: [] })) +})); + +jest.mock('../../utils/mount', () => ({ + defaultClassify: jest.fn(() => null), + uidForSeed: jest.fn((seed) => `uid-${seed}`) +})); + +jest.mock('../../cache/requestUids', () => ({ + getRequestUid: jest.fn(() => 'request-uid') +})); + +const { MountManager } = require('./manager'); +const collectionWatcher = require('../../app/collection-watcher'); + +const makeEmit = () => ({ loading: jest.fn(), tree: jest.fn(), config: jest.fn() }); + +const mountCollection = async (manager, { collectionUid = 'col-1', brunoConfig = {} } = {}) => { + const win = { id: 1 }; + const emit = makeEmit(); + const collectionPath = path.join(os.tmpdir(), collectionUid); + const tempDirectoryPath = await manager.mount({ win, collectionPath, collectionUid, brunoConfig, emit }); + return { win, emit, collectionPath: path.resolve(collectionPath), tempDirectoryPath }; +}; + +describe('MountManager.remount', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('reattaches the cache-backed watcher and re-emits the tree', async () => { + const manager = new MountManager(); + const { win, emit, collectionPath, tempDirectoryPath } = await mountCollection(manager, { + collectionUid: 'col-1', + brunoConfig: { format: 'bru' } + }); + jest.clearAllMocks(); + + const result = await manager.remount({ collectionUid: 'col-1', brunoConfig: { format: 'yml' } }); + + expect(result).toBe(true); + expect(collectionWatcher.removeWatcher).toHaveBeenCalledWith(collectionPath, win, 'col-1'); + + expect(collectionWatcher.addWatcher).toHaveBeenCalledTimes(1); + const addWatcherArgs = collectionWatcher.addWatcher.mock.calls[0]; + expect(addWatcherArgs[0]).toBe(win); + expect(addWatcherArgs[1]).toBe(collectionPath); + expect(addWatcherArgs[2]).toBe('col-1'); + expect(addWatcherArgs[3]).toEqual({ format: 'yml' }); + expect(addWatcherArgs[6]).toEqual(expect.objectContaining({ ignoreInitial: true })); + expect(addWatcherArgs[6].fileIndex).toBeTruthy(); + + // the transient directory is preserved so the renderer's stored path stays valid + expect(collectionWatcher.addTempDirectoryWatcher).toHaveBeenCalledWith(win, tempDirectoryPath, 'col-1', collectionPath); + + expect(emit.tree).toHaveBeenCalledTimes(1); + expect(emit.loading).toHaveBeenNthCalledWith(1, true); + expect(emit.loading).toHaveBeenLastCalledWith(false); + }); + + it('returns false and does no lifecycle work for an unmounted collection', async () => { + const manager = new MountManager(); + + const result = await manager.remount({ collectionUid: 'never-mounted' }); + + expect(result).toBe(false); + expect(collectionWatcher.removeWatcher).not.toHaveBeenCalled(); + expect(collectionWatcher.addWatcher).not.toHaveBeenCalled(); + expect(collectionWatcher.addTempDirectoryWatcher).not.toHaveBeenCalled(); + }); + + it('propagates a watcher-removal failure without reattaching', async () => { + const manager = new MountManager(); + await mountCollection(manager, { collectionUid: 'col-1' }); + jest.clearAllMocks(); + + collectionWatcher.removeWatcher.mockImplementationOnce(() => { + throw new Error('removeWatcher failed'); + }); + + await expect(manager.remount({ collectionUid: 'col-1' })).rejects.toThrow('removeWatcher failed'); + expect(collectionWatcher.addWatcher).not.toHaveBeenCalled(); + }); +});