diff --git a/packages/bruno-electron/src/ipc/collection.js b/packages/bruno-electron/src/ipc/collection.js index f562207f46b..20da91b044a 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,13 +2780,21 @@ const registerRendererEventHandlers = (mainWindow, watcher) => { ymlBrunoConfig.size = size; ymlBrunoConfig.filesCount = filesCount; - if (watcher) { - try { + try { + 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); + } + } catch (watcherError) { + console.error('Failed to re-attach watcher after migration:', watcherError); + 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: ${watcherError.message}. Please reopen the collection.` + message: `Collection migrated to yml, but live sync could not be re-enabled: ${fallbackError.message}. Please reopen the collection.` }); } } @@ -2802,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/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..85930919f45 100644 --- a/packages/bruno-electron/src/services/mount/manager.js +++ b/packages/bruno-electron/src/services/mount/manager.js @@ -97,23 +97,42 @@ class MountManager { }; this.#mounts.set(collectionUid, entry); + await this.#coldLoad(collectionUid, entry); + return tempDirectoryPath; + } + + async remount({ collectionUid, brunoConfig }) { + const entry = this.#mounts.get(collectionUid); + if (!entry) return false; + + 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) { 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(); + }); +});