From 763974f3b58aa7a25e08166aa89fa0cb4849eab6 Mon Sep 17 00:00:00 2001 From: Sid Date: Fri, 26 Jun 2026 18:25:53 +0530 Subject: [PATCH 01/11] feat(workspaces): implement active workspace restoration from snapshot - Added a new action to restore the active workspace from a snapshot. - Integrated workspace restoration into IPC events for improved user experience. - Refactored workspace loading logic to prioritize valid workspaces and handle invalid paths. - Introduced utility functions for workspace path validation and normalization. - Added tests to ensure correct functionality of workspace restoration and validation logic. --- .../src/providers/App/useIpcEvents.js | 9 +- .../ReduxStore/slices/workspaces/actions.js | 76 ++++-- packages/bruno-electron/src/ipc/workspace.js | 66 ++--- .../src/utils/workspace-startup.js | 111 ++++++++ .../tests/utils/workspace-startup.spec.js | 236 ++++++++++++++++++ .../active-workspace-restore.spec.ts | 125 ++++++++++ 6 files changed, 552 insertions(+), 71 deletions(-) create mode 100644 packages/bruno-electron/src/utils/workspace-startup.js create mode 100644 packages/bruno-electron/tests/utils/workspace-startup.spec.js create mode 100644 tests/snapshots/active-workspace-restore.spec.ts diff --git a/packages/bruno-app/src/providers/App/useIpcEvents.js b/packages/bruno-app/src/providers/App/useIpcEvents.js index b7d58871ab3..8ad6e15b0b1 100644 --- a/packages/bruno-app/src/providers/App/useIpcEvents.js +++ b/packages/bruno-app/src/providers/App/useIpcEvents.js @@ -29,7 +29,8 @@ import { collectionAddEnvFileEvent, openCollectionEvent, hydrateCollectionWithUi import { workspaceOpenedEvent, workspaceConfigUpdatedEvent, - hydrateSnapshotForOpenedCollection + hydrateSnapshotForOpenedCollection, + restoreActiveWorkspaceFromSnapshot } from 'providers/ReduxStore/slices/workspaces/actions'; import { workspaceDotEnvUpdateEvent, setWorkspaceDotEnvVariables } from 'providers/ReduxStore/slices/workspaces'; import toast from 'react-hot-toast'; @@ -115,7 +116,6 @@ const useIpcEvents = () => { dispatch(apiSpecChangeFileEvent({ data: val })); } }; - ipcRenderer.invoke('renderer:ready'); const removeCollectionTreeUpdateListener = ipcRenderer.on('main:collection-tree-updated', _collectionTreeUpdated); @@ -134,6 +134,10 @@ const useIpcEvents = () => { dispatch(workspaceOpenedEvent(workspacePath, workspaceUid, workspaceConfig)); }); + const removeWorkspacesReadyListener = ipcRenderer.on('main:workspaces-ready', () => { + dispatch(restoreActiveWorkspaceFromSnapshot()); + }); + const removeWorkspaceConfigUpdatedListener = ipcRenderer.on('main:workspace-config-updated', (workspacePath, workspaceUid, workspaceConfig) => { dispatch(workspaceConfigUpdatedEvent(workspacePath, workspaceUid, workspaceConfig)); }); @@ -368,6 +372,7 @@ const useIpcEvents = () => { removeApiSpecTreeUpdateListener(); removeOpenCollectionListener(); removeOpenWorkspaceListener(); + removeWorkspacesReadyListener(); removeWorkspaceConfigUpdatedListener(); removeWorkspaceEnvironmentAddedListener(); removeWorkspaceEnvironmentChangedListener(); diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js b/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js index 375dd0f163e..41aa647d433 100644 --- a/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js +++ b/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js @@ -27,6 +27,7 @@ import toast from 'react-hot-toast'; const { ipcRenderer } = window; let snapshotHydrationTimer = null; +let startupWorkspaceRestorePending = true; const SNAPSHOT_HYDRATION_LONG_STOP_GUARD_MS = 5 * 60 * 1000; const COLLECTION_SORT_ORDER_BY_WORKSPACE_SORTING = { @@ -792,6 +793,40 @@ export const loadLastOpenedWorkspaces = () => { }; }; +export const restoreActiveWorkspaceFromSnapshot = () => { + return async (dispatch, getState) => { + startupWorkspaceRestorePending = false; + + try { + const snapshot = await ipcRenderer.invoke('renderer:snapshot:get'); + const activeWorkspacePath = snapshot?.activeWorkspacePath; + const { workspaces } = getState().workspaces; + + if (activeWorkspacePath) { + const normalizedActiveWorkspacePath = normalizePath(activeWorkspacePath); + const matchingWorkspace = workspaces.find( + (workspace) => normalizePath(workspace.pathname || '') === normalizedActiveWorkspacePath + ); + + if (matchingWorkspace) { + await dispatch(switchWorkspace(matchingWorkspace.uid)); + return; + } + } + + const defaultWorkspace = workspaces.find((workspace) => workspace.type === 'default'); + if (defaultWorkspace) { + await dispatch(switchWorkspace(defaultWorkspace.uid)); + } + } catch (err) { + const defaultWorkspace = getState().workspaces.workspaces.find((workspace) => workspace.type === 'default'); + if (defaultWorkspace) { + await dispatch(switchWorkspace(defaultWorkspace.uid)); + } + } + }; +}; + export const workspaceOpenedEvent = (workspacePath, workspaceUid, workspaceConfig) => { return async (dispatch, getState) => { dispatch(createWorkspace({ @@ -805,16 +840,10 @@ export const workspaceOpenedEvent = (workspacePath, workspaceUid, workspaceConfi } catch (error) { } - const state = getState(); - const activeWorkspaceUid = state.workspaces.activeWorkspaceUid; - - let shouldSwitch = false; try { const snapshot = await ipcRenderer.invoke('renderer:snapshot:get'); - const activeWorkspacePath = snapshot?.activeWorkspacePath; - const normalizedWorkspacePath = normalizePath(workspacePath || ''); - const currentState = getState(); + if (!currentState.app.snapshotReady && snapshot?.extras?.devTools) { const { open } = snapshot.extras.devTools; if (open) { @@ -825,33 +854,34 @@ export const workspaceOpenedEvent = (workspacePath, workspaceUid, workspaceConfi const { activeTab = 'terminal' } = snapshot.extras.devTools; dispatch(setActiveDevToolsTab(activeTab)); } + } catch (err) { + } + + if (startupWorkspaceRestorePending) { + return; + } + + const state = getState(); + const activeWorkspaceUid = state.workspaces.activeWorkspaceUid; + let shouldSwitch = false; + + try { + const snapshot = await ipcRenderer.invoke('renderer:snapshot:get'); + const activeWorkspacePath = snapshot?.activeWorkspacePath; + const normalizedWorkspacePath = normalizePath(workspacePath || ''); if (activeWorkspacePath) { const normalizedActiveWorkspacePath = normalizePath(activeWorkspacePath); shouldSwitch = normalizedWorkspacePath === normalizedActiveWorkspacePath; - - // If the snapshot points to a workspace that no longer exists on disk, - // fall back to the default workspace instead of leaving stale active state. - if (!shouldSwitch && workspaceConfig.type === 'default') { - const lastOpenedWorkspacePaths = await ipcRenderer.invoke('renderer:get-last-opened-workspaces').catch(() => []); - const normalizedLastOpenedWorkspacePaths = new Set( - (Array.isArray(lastOpenedWorkspacePaths) ? lastOpenedWorkspacePaths : []) - .map((pathname) => normalizePath(pathname)) - ); - const hasActiveWorkspacePath = normalizedLastOpenedWorkspacePaths.has(normalizedActiveWorkspacePath); - - if (!hasActiveWorkspacePath) { - shouldSwitch = true; - } - } } else { shouldSwitch = !activeWorkspaceUid || workspaceConfig.type === 'default'; } } catch (err) { shouldSwitch = !activeWorkspaceUid || workspaceConfig.type === 'default'; } + if (shouldSwitch) { - dispatch(switchWorkspace(workspaceUid)); + await dispatch(switchWorkspace(workspaceUid)); } }; }; diff --git a/packages/bruno-electron/src/ipc/workspace.js b/packages/bruno-electron/src/ipc/workspace.js index 8c9c15bcf1c..7bcd6b55596 100644 --- a/packages/bruno-electron/src/ipc/workspace.js +++ b/packages/bruno-electron/src/ipc/workspace.js @@ -11,6 +11,7 @@ const LastOpenedWorkspaces = require('../store/last-opened-workspaces'); const { defaultWorkspaceManager } = require('../store/default-workspace'); const { globalEnvironmentsManager } = require('../store/workspace-environments'); const { globalEnvironmentsStore } = require('../store/global-environments'); +const { resolveLastOpenedWorkspacePaths } = require('../utils/workspace-startup'); const { createWorkspaceConfig, @@ -236,23 +237,9 @@ const registerWorkspaceIpc = (mainWindow, workspaceWatcher) => { ipcMain.handle('renderer:get-last-opened-workspaces', async () => { try { - const workspacePaths = lastOpenedWorkspaces.getAll(); - const validWorkspaces = []; - const invalidPaths = []; - - for (const workspacePath of workspacePaths) { - const workspaceYmlPath = path.join(workspacePath, 'workspace.yml'); - - if (fs.existsSync(workspaceYmlPath)) { - validWorkspaces.push(workspacePath); - } else { - invalidPaths.push(workspacePath); - } - } - - for (const invalidPath of invalidPaths) { - lastOpenedWorkspaces.remove(invalidPath); - } + const { validWorkspaces } = resolveLastOpenedWorkspacePaths(lastOpenedWorkspaces, { + validateConfig: true + }); return validWorkspaces; } catch (error) { @@ -691,45 +678,32 @@ const registerWorkspaceIpc = (mainWindow, workspaceWatcher) => { } } - const workspacePaths = lastOpenedWorkspaces.getAll(); - const invalidPaths = []; - - for (const workspacePath of workspacePaths) { - if (defaultWorkspacePath && workspacePath === defaultWorkspacePath) { - continue; - } - - const workspaceYmlPath = path.join(workspacePath, 'workspace.yml'); + const { validWorkspaces } = resolveLastOpenedWorkspacePaths(lastOpenedWorkspaces, { + defaultWorkspacePath + }); - if (fs.existsSync(workspaceYmlPath)) { - try { - const workspaceConfig = readWorkspaceConfig(workspacePath); - validateWorkspaceConfig(workspaceConfig); - const workspaceUid = getWorkspaceUid(workspacePath); - const isDefault = workspaceUid === 'default'; - const configForClient = prepareWorkspaceConfigForClient(workspaceConfig, workspacePath, isDefault); + for (const workspacePath of validWorkspaces) { + try { + const workspaceConfig = readWorkspaceConfig(workspacePath); + const workspaceUid = getWorkspaceUid(workspacePath); + const isDefault = workspaceUid === 'default'; + const configForClient = prepareWorkspaceConfigForClient(workspaceConfig, workspacePath, isDefault); - win.webContents.send('main:workspace-opened', workspacePath, workspaceUid, configForClient); + win.webContents.send('main:workspace-opened', workspacePath, workspaceUid, configForClient); - if (workspaceWatcher) { - workspaceWatcher.addWatcher(win, workspacePath); - } - } catch (error) { - console.error(`Error loading workspace ${workspacePath}:`, error); - invalidPaths.push(workspacePath); + if (workspaceWatcher) { + workspaceWatcher.addWatcher(win, workspacePath); } - } else { - invalidPaths.push(workspacePath); + } catch (error) { + console.error(`Error loading workspace ${workspacePath}:`, error); + lastOpenedWorkspaces.remove(workspacePath); } } - - for (const invalidPath of invalidPaths) { - lastOpenedWorkspaces.remove(invalidPath); - } } catch (error) { console.error('Error initializing workspaces:', error); } + win.webContents.send('main:workspaces-ready'); ipcMain.emit('main:workspaces-ready', win); }); }; diff --git a/packages/bruno-electron/src/utils/workspace-startup.js b/packages/bruno-electron/src/utils/workspace-startup.js new file mode 100644 index 00000000000..693e0f39001 --- /dev/null +++ b/packages/bruno-electron/src/utils/workspace-startup.js @@ -0,0 +1,111 @@ +const fs = require('fs'); +const path = require('path'); +const snapshotManager = require('../services/snapshot'); +const { readWorkspaceConfig, validateWorkspaceConfig } = require('./workspace-config'); + +const normalizeWorkspacePathname = (workspacePath) => { + if (typeof workspacePath !== 'string' || !workspacePath.length) { + return ''; + } + + return path.normalize(workspacePath.replace(/\\+$/, '').replace(/\/+$/, '')); +}; + +const prioritizeActiveWorkspacePath = (workspacePaths, activeWorkspacePath) => { + if (!activeWorkspacePath || !Array.isArray(workspacePaths) || workspacePaths.length <= 1) { + return workspacePaths; + } + + const normalizedActivePath = normalizeWorkspacePathname(activeWorkspacePath); + if (!normalizedActivePath) { + return workspacePaths; + } + + const activeIndex = workspacePaths.findIndex( + (workspacePath) => normalizeWorkspacePathname(workspacePath) === normalizedActivePath + ); + + if (activeIndex <= 0) { + return workspacePaths; + } + + const prioritizedPaths = [...workspacePaths]; + const [activePath] = prioritizedPaths.splice(activeIndex, 1); + prioritizedPaths.unshift(activePath); + return prioritizedPaths; +}; + +const isValidWorkspacePathOnDisk = (workspacePath, { validateConfig = false } = {}) => { + const workspaceYmlPath = path.join(workspacePath, 'workspace.yml'); + + if (!fs.existsSync(workspaceYmlPath)) { + return false; + } + + if (!validateConfig) { + return true; + } + + try { + const workspaceConfig = readWorkspaceConfig(workspacePath); + validateWorkspaceConfig(workspaceConfig); + return true; + } catch (error) { + return false; + } +}; + +const resolveLastOpenedWorkspacePaths = (lastOpenedWorkspaces, { + defaultWorkspacePath = null, + validateConfig = false +} = {}) => { + const workspacePaths = lastOpenedWorkspaces.getAll(); + const activeWorkspacePath = snapshotManager.getSnapshot()?.activeWorkspacePath; + const validWorkspaces = []; + const invalidPaths = []; + for (const workspacePath of workspacePaths) { + if (defaultWorkspacePath && workspacePath === defaultWorkspacePath) { + continue; + } + + if (isValidWorkspacePathOnDisk(workspacePath, { validateConfig })) { + validWorkspaces.push(workspacePath); + } else { + invalidPaths.push(workspacePath); + } + } + + let prioritizedWorkspaces = prioritizeActiveWorkspacePath(validWorkspaces, activeWorkspacePath); + + if (activeWorkspacePath) { + const normalizedActivePath = normalizeWorkspacePathname(activeWorkspacePath); + const alreadyIncluded = prioritizedWorkspaces.some( + (workspacePath) => normalizeWorkspacePathname(workspacePath) === normalizedActivePath + ); + + if ( + !alreadyIncluded + && normalizedActivePath + && (!defaultWorkspacePath || activeWorkspacePath !== defaultWorkspacePath) + && isValidWorkspacePathOnDisk(activeWorkspacePath, { validateConfig }) + ) { + prioritizedWorkspaces.unshift(activeWorkspacePath); + } + } + + for (const invalidPath of invalidPaths) { + lastOpenedWorkspaces.remove(invalidPath); + } + + return { + validWorkspaces: prioritizedWorkspaces, + invalidPaths + }; +}; + +module.exports = { + normalizeWorkspacePathname, + prioritizeActiveWorkspacePath, + isValidWorkspacePathOnDisk, + resolveLastOpenedWorkspacePaths +}; diff --git a/packages/bruno-electron/tests/utils/workspace-startup.spec.js b/packages/bruno-electron/tests/utils/workspace-startup.spec.js new file mode 100644 index 00000000000..08d6c3b7bb9 --- /dev/null +++ b/packages/bruno-electron/tests/utils/workspace-startup.spec.js @@ -0,0 +1,236 @@ +const path = require('path'); +const fs = require('fs'); +const os = require('os'); + +jest.mock('../../src/services/snapshot', () => ({ + getSnapshot: jest.fn(() => ({ activeWorkspacePath: null })) +})); + +const snapshotManager = require('../../src/services/snapshot'); +const { + normalizeWorkspacePathname, + prioritizeActiveWorkspacePath, + isValidWorkspacePathOnDisk, + resolveLastOpenedWorkspacePaths +} = require('../../src/utils/workspace-startup'); + +const buildWorkspaceYml = (name) => [ + 'opencollection: 1.0.0', + 'info:', + ` name: ${name}`, + ' type: workspace', + 'collections:', + 'specs: []', + 'docs: \'\'', + '' +].join('\n'); + +const createWorkspaceDir = (rootDir, name, { ymlContent = null } = {}) => { + const workspacePath = path.join(rootDir, name); + fs.mkdirSync(workspacePath, { recursive: true }); + + if (ymlContent !== null) { + fs.writeFileSync(path.join(workspacePath, 'workspace.yml'), ymlContent); + } else { + fs.writeFileSync(path.join(workspacePath, 'workspace.yml'), buildWorkspaceYml(name)); + } + + return workspacePath; +}; + +describe('normalizeWorkspacePathname', () => { + test('returns empty string for empty or non-string input', () => { + expect(normalizeWorkspacePathname('')).toBe(''); + expect(normalizeWorkspacePathname(null)).toBe(''); + expect(normalizeWorkspacePathname(undefined)).toBe(''); + expect(normalizeWorkspacePathname(123)).toBe(''); + }); + + test('strips trailing slashes and normalizes paths', () => { + const input = '/tmp/workspace-one/'; + const normalized = normalizeWorkspacePathname(input); + + expect(normalized).toBe(path.normalize('/tmp/workspace-one')); + expect(normalizeWorkspacePathname(`${input}/`)).toBe(normalized); + }); + + test('strips trailing backslashes on Windows-style paths', () => { + const input = 'C:\\workspaces\\demo\\\\'; + const normalized = normalizeWorkspacePathname(input); + + expect(normalized).toBe(path.normalize('C:\\workspaces\\demo')); + }); +}); + +describe('prioritizeActiveWorkspacePath', () => { + const ws1 = '/tmp/ws1'; + const ws2 = '/tmp/ws2'; + const ws3 = '/tmp/ws3'; + const ws4 = '/tmp/ws4'; + const ws5 = '/tmp/ws5'; + + test('returns input unchanged when active path is missing or list is too short', () => { + expect(prioritizeActiveWorkspacePath([ws1], ws2)).toEqual([ws1]); + expect(prioritizeActiveWorkspacePath([], ws2)).toEqual([]); + expect(prioritizeActiveWorkspacePath([ws1, ws2], null)).toEqual([ws1, ws2]); + }); + + test('returns input unchanged when active path is already first', () => { + const paths = [ws4, ws3, ws2, ws1]; + expect(prioritizeActiveWorkspacePath(paths, ws4)).toEqual(paths); + }); + + test('moves active path from later position to front', () => { + const paths = [ws5, ws4, ws3, ws2, ws1]; + expect(prioritizeActiveWorkspacePath(paths, ws4)).toEqual([ws4, ws5, ws3, ws2, ws1]); + expect(prioritizeActiveWorkspacePath(paths, ws2)).toEqual([ws2, ws5, ws4, ws3, ws1]); + }); + + test('returns input unchanged when active path is not in list', () => { + const paths = [ws5, ws4, ws3]; + expect(prioritizeActiveWorkspacePath(paths, '/tmp/missing')).toEqual(paths); + }); + + test('matches paths with trailing slash variants', () => { + const paths = [ws5, ws4, ws3]; + expect(prioritizeActiveWorkspacePath(paths, `${ws4}/`)).toEqual([ws4, ws5, ws3]); + }); +}); + +describe('isValidWorkspacePathOnDisk', () => { + let rootDir; + + beforeEach(() => { + rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bruno-ws-startup-')); + }); + + afterEach(() => { + fs.rmSync(rootDir, { recursive: true, force: true }); + }); + + test('returns false when workspace.yml is missing', () => { + const workspacePath = path.join(rootDir, 'missing-yml'); + fs.mkdirSync(workspacePath, { recursive: true }); + + expect(isValidWorkspacePathOnDisk(workspacePath)).toBe(false); + expect(isValidWorkspacePathOnDisk(workspacePath, { validateConfig: true })).toBe(false); + }); + + test('returns true when workspace.yml exists and config validation is disabled', () => { + const workspacePath = createWorkspaceDir(rootDir, 'exists-only'); + + expect(isValidWorkspacePathOnDisk(workspacePath, { validateConfig: false })).toBe(true); + }); + + test('returns true for valid workspace.yml when config validation is enabled', () => { + const workspacePath = createWorkspaceDir(rootDir, 'valid-config'); + + expect(isValidWorkspacePathOnDisk(workspacePath, { validateConfig: true })).toBe(true); + }); + + test('returns false for malformed workspace.yml when config validation is enabled', () => { + const workspacePath = createWorkspaceDir(rootDir, 'malformed-config', { + ymlContent: 'invalid: yaml: [[[' + }); + + expect(isValidWorkspacePathOnDisk(workspacePath, { validateConfig: true })).toBe(false); + }); +}); + +describe('resolveLastOpenedWorkspacePaths', () => { + let rootDir; + let ws1; + let ws2; + let ws3; + let ws4; + let ws5; + let defaultWorkspacePath; + let lastOpenedWorkspaces; + + beforeEach(() => { + rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bruno-ws-startup-resolve-')); + ws1 = createWorkspaceDir(rootDir, 'workspace-one'); + ws2 = createWorkspaceDir(rootDir, 'workspace-two'); + ws3 = createWorkspaceDir(rootDir, 'workspace-three'); + ws4 = createWorkspaceDir(rootDir, 'workspace-four'); + ws5 = createWorkspaceDir(rootDir, 'workspace-five'); + defaultWorkspacePath = createWorkspaceDir(rootDir, 'default-workspace'); + + lastOpenedWorkspaces = { + getAll: jest.fn(() => [ws5, ws4, ws3, ws2, ws1]), + remove: jest.fn() + }; + + snapshotManager.getSnapshot.mockReturnValue({ activeWorkspacePath: null }); + }); + + afterEach(() => { + fs.rmSync(rootDir, { recursive: true, force: true }); + jest.clearAllMocks(); + }); + + test('prioritizes 4th-position active workspace', () => { + snapshotManager.getSnapshot.mockReturnValue({ activeWorkspacePath: ws4 }); + + const result = resolveLastOpenedWorkspacePaths(lastOpenedWorkspaces, { + validateConfig: true + }); + + expect(lastOpenedWorkspaces.getAll).toHaveBeenCalledTimes(1); + expect(result.validWorkspaces).toEqual([ws4, ws5, ws3, ws2, ws1]); + expect(result.invalidPaths).toEqual([]); + expect(lastOpenedWorkspaces.remove).not.toHaveBeenCalled(); + }); + + test('prioritizes 5th-position active workspace when already MRU-first', () => { + snapshotManager.getSnapshot.mockReturnValue({ activeWorkspacePath: ws5 }); + + const result = resolveLastOpenedWorkspacePaths(lastOpenedWorkspaces, { + validateConfig: true + }); + + expect(result.validWorkspaces).toEqual([ws5, ws4, ws3, ws2, ws1]); + }); + + test('includes active workspace from snapshot when it is valid but not in MRU list', () => { + const externalWorkspace = createWorkspaceDir(rootDir, 'external-active'); + snapshotManager.getSnapshot.mockReturnValue({ activeWorkspacePath: externalWorkspace }); + + const result = resolveLastOpenedWorkspacePaths(lastOpenedWorkspaces, { + validateConfig: true + }); + + expect(result.validWorkspaces).toEqual([externalWorkspace, ws5, ws4, ws3, ws2, ws1]); + }); + + test('does not include malformed active workspace from snapshot', () => { + const malformedWorkspace = createWorkspaceDir(rootDir, 'malformed-active', { + ymlContent: 'invalid: yaml: [[[' + }); + snapshotManager.getSnapshot.mockReturnValue({ activeWorkspacePath: malformedWorkspace }); + + const result = resolveLastOpenedWorkspacePaths(lastOpenedWorkspaces, { + validateConfig: true + }); + + expect(result.validWorkspaces).toEqual([ws5, ws4, ws3, ws2, ws1]); + expect(result.invalidPaths).toEqual([]); + }); + + test('skips default workspace path and removes invalid MRU entries', () => { + const missingYmlPath = path.join(rootDir, 'missing-yml'); + fs.mkdirSync(missingYmlPath, { recursive: true }); + + lastOpenedWorkspaces.getAll.mockReturnValue([ws3, defaultWorkspacePath, missingYmlPath, ws1]); + snapshotManager.getSnapshot.mockReturnValue({ activeWorkspacePath: ws1 }); + + const result = resolveLastOpenedWorkspacePaths(lastOpenedWorkspaces, { + defaultWorkspacePath, + validateConfig: true + }); + + expect(result.validWorkspaces).toEqual([ws1, ws3]); + expect(result.invalidPaths).toEqual([missingYmlPath]); + expect(lastOpenedWorkspaces.remove).toHaveBeenCalledWith(missingYmlPath); + }); +}); diff --git a/tests/snapshots/active-workspace-restore.spec.ts b/tests/snapshots/active-workspace-restore.spec.ts new file mode 100644 index 00000000000..2d08f43c3f1 --- /dev/null +++ b/tests/snapshots/active-workspace-restore.spec.ts @@ -0,0 +1,125 @@ +import path from 'path'; +import fs from 'fs'; +import { test, expect, closeElectronApp } from '../../playwright'; +import { waitForReadyPage } from '../utils/page'; +import { readSnapshot } from '../utils/snapshot'; + +const buildWorkspaceYml = (workspaceName: string) => [ + 'opencollection: 1.0.0', + 'info:', + ` name: ${workspaceName}`, + ' type: workspace', + 'collections:', + 'specs: []', + 'docs: \'\'', + '' +].join('\n'); + +const createWorkspaceDir = async ( + createTmpDir: (tag?: string) => Promise, + tag: string, + workspaceName: string +) => { + const workspacePath = await createTmpDir(tag); + fs.writeFileSync(path.join(workspacePath, 'workspace.yml'), buildWorkspaceYml(workspaceName)); + return workspacePath; +}; + +const seedPreferences = (userDataPath: string, lastOpenedWorkspaces: string[]) => { + fs.writeFileSync( + path.join(userDataPath, 'preferences.json'), + JSON.stringify( + { + preferences: { + onboarding: { + hasLaunchedBefore: true, + hasSeenWelcomeModal: true + } + }, + workspaces: { + lastOpenedWorkspaces + } + }, + null, + 2 + ) + ); +}; + +const seedSnapshot = (userDataPath: string, activeWorkspacePath: string) => { + fs.writeFileSync( + path.join(userDataPath, 'ui-state-snapshot.json'), + JSON.stringify( + { + version: '0.0.1', + activeWorkspacePath, + extras: { + devTools: { + open: false + } + }, + workspaces: [], + collections: [] + }, + null, + 2 + ) + ); +}; + +const setupMultiWorkspaceRestoreFixture = async ( + createTmpDir: (tag?: string) => Promise, + activeWorkspaceIndex: number +) => { + const userDataPath = await createTmpDir('snap-active-ws-restore'); + const workspacePaths = await Promise.all([ + createWorkspaceDir(createTmpDir, 'workspace-one', 'Workspace One'), + createWorkspaceDir(createTmpDir, 'workspace-two', 'Workspace Two'), + createWorkspaceDir(createTmpDir, 'workspace-three', 'Workspace Three'), + createWorkspaceDir(createTmpDir, 'workspace-four', 'Workspace Four'), + createWorkspaceDir(createTmpDir, 'workspace-five', 'Workspace Five') + ]); + + const lastOpenedWorkspaces = [...workspacePaths].reverse(); + const activeWorkspacePath = workspacePaths[activeWorkspaceIndex]; + + seedPreferences(userDataPath, lastOpenedWorkspaces); + seedSnapshot(userDataPath, activeWorkspacePath); + + return { + userDataPath, + activeWorkspacePath, + activeWorkspaceName: ['Workspace One', 'Workspace Two', 'Workspace Three', 'Workspace Four', 'Workspace Five'][activeWorkspaceIndex] + }; +}; + +test.describe('Snapshot: Active Workspace Restore', () => { + test('restores a 4th-position active workspace after restart', async ({ launchElectronApp, createTmpDir }) => { + const { userDataPath, activeWorkspacePath, activeWorkspaceName } = await setupMultiWorkspaceRestoreFixture(createTmpDir, 3); + + expect(readSnapshot(userDataPath)?.activeWorkspacePath).toBe(activeWorkspacePath); + + const app = await launchElectronApp({ userDataPath }); + const page = await waitForReadyPage(app); + + await expect(page.getByTestId('workspace-name')).toHaveText(activeWorkspaceName, { timeout: 10000 }); + + await page.getByTestId('workspace-menu').click(); + await expect(page.locator('.workspace-item.active')).toContainText(activeWorkspaceName); + + await closeElectronApp(app); + }); + + test('restores a 5th-position active workspace after restart', async ({ launchElectronApp, createTmpDir }) => { + const { userDataPath, activeWorkspacePath, activeWorkspaceName } = await setupMultiWorkspaceRestoreFixture(createTmpDir, 4); + + expect(readSnapshot(userDataPath)?.activeWorkspacePath).toBe(activeWorkspacePath); + + const app = await launchElectronApp({ userDataPath }); + const page = await waitForReadyPage(app); + + await expect(page.getByTestId('workspace-name')).toHaveText(activeWorkspaceName, { timeout: 10000 }); + + await closeElectronApp(app); + }); +}); From 090d20a0e65628c52cc8d121e65223e7094ad1e3 Mon Sep 17 00:00:00 2001 From: Sid Date: Mon, 29 Jun 2026 14:14:10 +0530 Subject: [PATCH 02/11] feat(snapshot): refactor snapshot serialization and add environment preservation logic - Moved snapshot serialization logic to a new file for better organization. - Implemented environment preservation for collections during snapshot serialization. - Added utility functions to handle collection environment checks and serialization. - Introduced tests to validate the new serialization behavior and environment preservation. - Enhanced existing tests to cover edge cases for unmounted collections and environment persistence. --- .../middlewares/snapshot/middleware.js | 246 +--------------- .../middlewares/snapshot/serializeSnapshot.js | 268 ++++++++++++++++++ .../snapshot/serializeSnapshot.spec.js | 202 +++++++++++++ .../snapshots/environment/environment.spec.ts | 98 ++++++- tests/utils/snapshot.ts | 27 ++ 5 files changed, 584 insertions(+), 257 deletions(-) create mode 100644 packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js create mode 100644 packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js index cd0766e684e..77337b69052 100644 --- a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js +++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js @@ -5,255 +5,14 @@ * Uses debouncing to prevent excessive disk writes. */ -import { - SAVE_TRIGGERS, - shouldExcludeTab, - serializeTab, - serializeActiveTab, - getCollectionEnvironmentPath, - hydrateSnapshotLookups -} from 'utils/snapshot'; -import { normalizePath } from 'utils/common/path'; -import { TAB_IDENFIERS as DEVTOOL_TABS } from 'providers/ReduxStore/slices/logs'; +import { SAVE_TRIGGERS } from 'utils/snapshot'; +import { serializeSnapshot } from './serializeSnapshot'; const { ipcRenderer } = window; -// Debounce timer reference let saveTimer = null; const DEBOUNCE_MS = 1000; -const COLLECTION_SORT_ORDER_BY_WORKSPACE_SORTING = { - default: 'default', - alphabetical: 'alphabetical', - reverseAlphabetical: 'reverseAlphabetical' -}; - -const normalizeCollectionSortOrder = (sortOrder) => { - return COLLECTION_SORT_ORDER_BY_WORKSPACE_SORTING[sortOrder] || 'default'; -}; - -const normalizeWorkspaceSorting = (sorting) => { - return COLLECTION_SORT_ORDER_BY_WORKSPACE_SORTING[sorting] || 'default'; -}; - -const getWorkspaceCollectionSnapshotKey = (workspacePathname, collectionPathname) => { - const normalizedCollectionPathname = normalizePath(collectionPathname); - if (!normalizedCollectionPathname) { - return ''; - } - - return `${normalizePath(workspacePathname || '')}::${normalizedCollectionPathname}`; -}; - -/** - * Serialize the current app state into a snapshot format - * Persists array-based schema and supports lookup hydration. - */ -const serializeSnapshot = async (state) => { - const { workspaces, collections, tabs, logs, globalEnvironments } = state; - const snapshotHydration = state.app?.snapshotHydration; - const activeWorkspaceCollectionSortOrder = normalizeCollectionSortOrder(collections.collectionSortOrder); - - // Get existing snapshot to preserve data for collections not currently loaded - let existingSnapshot = null; - try { - existingSnapshot = await ipcRenderer.invoke('renderer:snapshot:get'); - } catch (err) { - // Ignore - will create fresh snapshot - } - - const existingSnapshotLookups = hydrateSnapshotLookups(existingSnapshot || {}); - - // Build a set of scratch collection UIDs to exclude - const scratchCollectionUids = new Set( - (workspaces.workspaces || []) - .map((w) => w.scratchCollectionUid) - .filter(Boolean) - ); - - const activeWorkspace = workspaces.workspaces.find( - (w) => w.uid === workspaces.activeWorkspaceUid - ); - - const activeWorkspaceCollectionPaths = new Set( - (activeWorkspace?.collections || []) - .map((collection) => collection?.path) - .filter(Boolean) - .map((collectionPath) => normalizePath(collectionPath)) - ); - - const existingDevTools = existingSnapshot?.extras?.devTools ?? {}; - - const snapshot = { - activeWorkspacePath: activeWorkspace?.pathname || null, - extras: { - devTools: { - open: logs.isConsoleOpen, - activeTab: logs.activeTab ?? existingDevTools.activeTab ?? 'terminal', - tabs: Object.assign(existingDevTools.tabs, { - [logs.activeTab]: {} - }) - } - }, - workspaces: [], - collections: [] - }; - - // Track which workspace+collection entries we've serialized from Redux - const serializedCollectionKeys = new Set(); - - (workspaces.workspaces || []).forEach((workspace) => { - if (!workspace.pathname) return; - - const workspaceCollectionPaths = (workspace.collections || []).map((c) => c.path).filter(Boolean); - const normalizedWorkspacePaths = workspaceCollectionPaths.map((p) => normalizePath(p)); - const isActiveWorkspace = workspace.uid === workspaces.activeWorkspaceUid; - const existingWorkspace = existingSnapshotLookups.workspacesByPath[normalizePath(workspace.pathname)]; - - // Resolve lastActiveCollectionPathname - let lastActiveCollectionPathname = null; - - if (isActiveWorkspace) { - const activeTab = tabs.tabs.find((t) => t.uid === tabs.activeTabUid); - const activeCollection = activeTab - ? (collections.collections || []).find((c) => c.uid === activeTab.collectionUid) - : null; - const normalizedPathname = activeCollection?.pathname ? normalizePath(activeCollection.pathname) : null; - - lastActiveCollectionPathname = normalizedPathname && normalizedWorkspacePaths.includes(normalizedPathname) - ? normalizedPathname - : null; - } else { - // For non-active workspaces, preserve from existing snapshot - lastActiveCollectionPathname = existingWorkspace?.lastActiveCollectionPathname || null; - } - - const workspaceSorting = isActiveWorkspace - ? activeWorkspaceCollectionSortOrder - : normalizeWorkspaceSorting(existingWorkspace?.sorting); - - snapshot.workspaces.push({ - pathname: workspace.pathname, - environment: '', - lastActiveCollectionPathname, - sorting: workspaceSorting, - collections: [...workspaceCollectionPaths] - }); - }); - - (collections.collections || []).forEach((collection) => { - // Skip scratch collections and collections without pathname - if (!collection.pathname || scratchCollectionUids.has(collection.uid)) { - return; - } - - const normalizedPath = normalizePath(collection.pathname); - - // Persist tab state only for the active workspace's collections. - // For non-active workspaces, preserve the last persisted snapshot entries. - if (activeWorkspace && !activeWorkspaceCollectionPaths.has(normalizedPath)) { - return; - } - - const workspacePathname = activeWorkspace?.pathname || ''; - const collectionSnapshotKey = getWorkspaceCollectionSnapshotKey(workspacePathname, collection.pathname); - const existingCollection = (collectionSnapshotKey && existingSnapshotLookups.collectionsByWorkspaceAndPath?.[collectionSnapshotKey]) - || existingSnapshotLookups.collectionsByPath?.[normalizedPath] - || null; - if (collectionSnapshotKey) { - serializedCollectionKeys.add(collectionSnapshotKey); - } - - // Get transient directory for this collection to filter transient tabs - const transientDirectory = collections.tempDirectories?.[collection.uid]; - - // Filter and serialize tabs, excluding transient requests - const collectionTabs = (tabs.tabs || []) - .filter((t) => t.collectionUid === collection.uid && !shouldExcludeTab(t, transientDirectory)) - .map((t) => serializeTab(t, collection)); - - const activeTabInCollection = (tabs.tabs || []).find( - (t) => t.collectionUid === collection.uid && t.uid === tabs.activeTabUid && !shouldExcludeTab(t, transientDirectory) - ); - - const selectedEnvironment = (collection.environments || []).find((env) => env.uid === collection.activeEnvironmentUid); - const environmentPathFromRedux = getCollectionEnvironmentPath(collection, selectedEnvironment, ''); - const selectedEnvironmentFromRedux = selectedEnvironment?.name || ''; - const existingEnvironmentPath = existingCollection?.environment?.collection || existingCollection?.environmentPath || ''; - const existingSelectedEnvironment = existingCollection?.selectedEnvironment || ''; - const shouldPreserveExistingEnvironment = collection.mountStatus !== 'mounted' - && !environmentPathFromRedux - && !selectedEnvironmentFromRedux; - const environmentPath = shouldPreserveExistingEnvironment ? existingEnvironmentPath : environmentPathFromRedux; - const selectedEnvironmentName = shouldPreserveExistingEnvironment - ? existingSelectedEnvironment - : selectedEnvironmentFromRedux; - - snapshot.collections.push({ - pathname: collection.pathname, - workspacePathname, - environment: { - collection: environmentPath, - global: globalEnvironments.activeGlobalEnvironmentUid || '' - }, - environmentPath, - selectedEnvironment: selectedEnvironmentName, - isOpen: !collection.collapsed, - isMounted: collection.mountStatus === 'mounted', - activeTab: serializeActiveTab(activeTabInCollection, collection), - tabs: collectionTabs - }); - }); - - const pendingHydrationPaths = new Set( - (snapshotHydration?.pendingCollectionPathnames || []).map((pathname) => normalizePath(pathname)) - ); - - // Preserve collections from existing snapshot that aren't currently loaded in Redux - // and collections that are still pending hydration during workspace switch. - const existingCollections = Object.values(existingSnapshotLookups.collectionsByWorkspaceAndPath || {}); - const fallbackCollections = Object.values(existingSnapshotLookups.collectionsByPath || {}); - - (existingCollections.length > 0 ? existingCollections : fallbackCollections).forEach((existingCollection) => { - const normalizedPath = normalizePath(existingCollection.pathname || ''); - const workspacePathname = existingCollection.workspacePathname || ''; - const collectionSnapshotKey = getWorkspaceCollectionSnapshotKey(workspacePathname, existingCollection.pathname); - const isSerializedCollection = collectionSnapshotKey && serializedCollectionKeys.has(collectionSnapshotKey); - const shouldPreservePendingHydration = pendingHydrationPaths.has(normalizedPath) - && activeWorkspace?.pathname - && normalizePath(workspacePathname) === normalizePath(activeWorkspace.pathname); - - if (!normalizedPath || (isSerializedCollection && !shouldPreservePendingHydration)) { - return; - } - - const existingTabs = (collectionSnapshotKey && existingSnapshotLookups.tabsByWorkspaceAndCollectionPath?.[collectionSnapshotKey]) - || existingSnapshotLookups.tabsByCollectionPath?.[normalizedPath]; - - snapshot.collections.push({ - pathname: existingCollection.pathname, - workspacePathname, - environment: { - collection: existingCollection.environment?.collection || existingCollection.environmentPath || '', - global: existingCollection.environment?.global || '' - }, - environmentPath: existingCollection.environment?.collection || existingCollection.environmentPath || '', - selectedEnvironment: existingCollection.selectedEnvironment || '', - isOpen: typeof existingCollection.isOpen === 'boolean' ? existingCollection.isOpen : false, - isMounted: typeof existingCollection.isMounted === 'boolean' ? existingCollection.isMounted : false, - activeTab: existingTabs?.activeTab || existingCollection.activeTab || null, - tabs: Array.isArray(existingTabs?.tabs) - ? existingTabs.tabs - : (Array.isArray(existingCollection.tabs) ? existingCollection.tabs : []) - }); - }); - - return snapshot; -}; - -/** - * Schedule a debounced save of the snapshot - */ const scheduleSave = (getState) => { if (saveTimer) { clearTimeout(saveTimer); @@ -305,7 +64,6 @@ export const snapshotMiddleware = ({ getState }) => (next) => (action) => { return result; } - // Only save if snapshot is ready (app has finished initial loading) const state = getState(); if (state.app.snapshotReady && SAVE_TRIGGERS.has(action.type)) { scheduleSave(getState); diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js new file mode 100644 index 00000000000..3531f2a52c2 --- /dev/null +++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js @@ -0,0 +1,268 @@ +import { + shouldExcludeTab, + serializeTab, + serializeActiveTab, + getCollectionEnvironmentPath, + hydrateSnapshotLookups +} from 'utils/snapshot'; +import { normalizePath } from 'utils/common/path'; + +const { ipcRenderer } = window; + +const COLLECTION_SORT_ORDER_BY_WORKSPACE_SORTING = { + default: 'default', + alphabetical: 'alphabetical', + reverseAlphabetical: 'reverseAlphabetical' +}; + +const normalizeCollectionSortOrder = (sortOrder) => { + return COLLECTION_SORT_ORDER_BY_WORKSPACE_SORTING[sortOrder] || 'default'; +}; + +const normalizeWorkspaceSorting = (sorting) => { + return COLLECTION_SORT_ORDER_BY_WORKSPACE_SORTING[sorting] || 'default'; +}; + +const getWorkspaceCollectionSnapshotKey = (workspacePathname, collectionPathname) => { + const normalizedCollectionPathname = normalizePath(collectionPathname); + if (!normalizedCollectionPathname) { + return ''; + } + + return `${normalizePath(workspacePathname || '')}::${normalizedCollectionPathname}`; +}; + +const shouldPreserveCollectionEnvironmentInSnapshot = ({ + collection, + environmentPathFromRedux, + selectedEnvironmentFromRedux, + existingEnvironmentPath, + existingSelectedEnvironment +}) => { + const hasAuthoritativeReduxEnvironment = Boolean( + selectedEnvironmentFromRedux || environmentPathFromRedux + ); + + if (hasAuthoritativeReduxEnvironment) { + return false; + } + + const hasExistingSnapshotEnvironment = Boolean( + existingEnvironmentPath || existingSelectedEnvironment + ); + + if (!hasExistingSnapshotEnvironment) { + return false; + } + + const isCollectionEnvironmentHydrated = collection.mountStatus === 'mounted' + && Array.isArray(collection.environments) + && collection.environments.length > 0; + + return collection.mountStatus !== 'mounted' || !isCollectionEnvironmentHydrated; +}; + +/** + * Serialize the current app state into a snapshot format. + * Persists array-based schema and supports lookup hydration. + */ +export const serializeSnapshot = async (state, options = {}) => { + const { getExistingSnapshot } = options; + const { workspaces, collections, tabs, logs, globalEnvironments } = state; + const snapshotHydration = state.app?.snapshotHydration; + const activeWorkspaceCollectionSortOrder = normalizeCollectionSortOrder(collections.collectionSortOrder); + + let existingSnapshot = null; + try { + if (typeof getExistingSnapshot === 'function') { + existingSnapshot = await getExistingSnapshot(); + } else { + existingSnapshot = await ipcRenderer.invoke('renderer:snapshot:get'); + } + } catch (err) { + // Ignore - will create fresh snapshot + } + + const existingSnapshotLookups = hydrateSnapshotLookups(existingSnapshot || {}); + + const scratchCollectionUids = new Set( + (workspaces.workspaces || []) + .map((w) => w.scratchCollectionUid) + .filter(Boolean) + ); + + const activeWorkspace = workspaces.workspaces.find( + (w) => w.uid === workspaces.activeWorkspaceUid + ); + + const activeWorkspaceCollectionPaths = new Set( + (activeWorkspace?.collections || []) + .map((collection) => collection?.path) + .filter(Boolean) + .map((collectionPath) => normalizePath(collectionPath)) + ); + + const existingDevTools = existingSnapshot?.extras?.devTools ?? {}; + + const snapshot = { + activeWorkspacePath: activeWorkspace?.pathname || null, + extras: { + devTools: { + open: logs.isConsoleOpen, + activeTab: logs.activeTab ?? existingDevTools.activeTab ?? 'terminal', + tabs: Object.assign(existingDevTools.tabs, { + [logs.activeTab]: {} + }) + } + }, + workspaces: [], + collections: [] + }; + + const serializedCollectionKeys = new Set(); + + (workspaces.workspaces || []).forEach((workspace) => { + if (!workspace.pathname) return; + + const workspaceCollectionPaths = (workspace.collections || []).map((c) => c.path).filter(Boolean); + const normalizedWorkspacePaths = workspaceCollectionPaths.map((p) => normalizePath(p)); + const isActiveWorkspace = workspace.uid === workspaces.activeWorkspaceUid; + const existingWorkspace = existingSnapshotLookups.workspacesByPath[normalizePath(workspace.pathname)]; + + let lastActiveCollectionPathname = null; + + if (isActiveWorkspace) { + const activeTab = tabs.tabs.find((t) => t.uid === tabs.activeTabUid); + const activeCollection = activeTab + ? (collections.collections || []).find((c) => c.uid === activeTab.collectionUid) + : null; + const normalizedPathname = activeCollection?.pathname ? normalizePath(activeCollection.pathname) : null; + + lastActiveCollectionPathname = normalizedPathname && normalizedWorkspacePaths.includes(normalizedPathname) + ? normalizedPathname + : null; + } else { + lastActiveCollectionPathname = existingWorkspace?.lastActiveCollectionPathname || null; + } + + const workspaceSorting = isActiveWorkspace + ? activeWorkspaceCollectionSortOrder + : normalizeWorkspaceSorting(existingWorkspace?.sorting); + + snapshot.workspaces.push({ + pathname: workspace.pathname, + environment: '', + lastActiveCollectionPathname, + sorting: workspaceSorting, + collections: [...workspaceCollectionPaths] + }); + }); + + (collections.collections || []).forEach((collection) => { + if (!collection.pathname || scratchCollectionUids.has(collection.uid)) { + return; + } + + const normalizedPath = normalizePath(collection.pathname); + + if (activeWorkspace && !activeWorkspaceCollectionPaths.has(normalizedPath)) { + return; + } + + const workspacePathname = activeWorkspace?.pathname || ''; + const collectionSnapshotKey = getWorkspaceCollectionSnapshotKey(workspacePathname, collection.pathname); + const existingCollection = (collectionSnapshotKey && existingSnapshotLookups.collectionsByWorkspaceAndPath?.[collectionSnapshotKey]) + || existingSnapshotLookups.collectionsByPath?.[normalizedPath] + || null; + if (collectionSnapshotKey) { + serializedCollectionKeys.add(collectionSnapshotKey); + } + + const transientDirectory = collections.tempDirectories?.[collection.uid]; + + const collectionTabs = (tabs.tabs || []) + .filter((t) => t.collectionUid === collection.uid && !shouldExcludeTab(t, transientDirectory)) + .map((t) => serializeTab(t, collection)); + + const activeTabInCollection = (tabs.tabs || []).find( + (t) => t.collectionUid === collection.uid && t.uid === tabs.activeTabUid && !shouldExcludeTab(t, transientDirectory) + ); + + const selectedEnvironment = (collection.environments || []).find((env) => env.uid === collection.activeEnvironmentUid); + const environmentPathFromRedux = getCollectionEnvironmentPath(collection, selectedEnvironment, ''); + const selectedEnvironmentFromRedux = selectedEnvironment?.name || ''; + const existingEnvironmentPath = existingCollection?.environment?.collection || existingCollection?.environmentPath || ''; + const existingSelectedEnvironment = existingCollection?.selectedEnvironment || ''; + const shouldPreserveExistingEnvironment = shouldPreserveCollectionEnvironmentInSnapshot({ + collection, + environmentPathFromRedux, + selectedEnvironmentFromRedux, + existingEnvironmentPath, + existingSelectedEnvironment + }); + const environmentPath = shouldPreserveExistingEnvironment ? existingEnvironmentPath : environmentPathFromRedux; + const selectedEnvironmentName = shouldPreserveExistingEnvironment + ? existingSelectedEnvironment + : selectedEnvironmentFromRedux; + + snapshot.collections.push({ + pathname: collection.pathname, + workspacePathname, + environment: { + collection: environmentPath, + global: globalEnvironments.activeGlobalEnvironmentUid || '' + }, + environmentPath, + selectedEnvironment: selectedEnvironmentName, + isOpen: !collection.collapsed, + isMounted: collection.mountStatus === 'mounted', + activeTab: serializeActiveTab(activeTabInCollection, collection), + tabs: collectionTabs + }); + }); + + const pendingHydrationPaths = new Set( + (snapshotHydration?.pendingCollectionPathnames || []).map((pathname) => normalizePath(pathname)) + ); + + const existingCollections = Object.values(existingSnapshotLookups.collectionsByWorkspaceAndPath || {}); + const fallbackCollections = Object.values(existingSnapshotLookups.collectionsByPath || {}); + + (existingCollections.length > 0 ? existingCollections : fallbackCollections).forEach((existingCollection) => { + const normalizedPath = normalizePath(existingCollection.pathname || ''); + const workspacePathname = existingCollection.workspacePathname || ''; + const collectionSnapshotKey = getWorkspaceCollectionSnapshotKey(workspacePathname, existingCollection.pathname); + const isSerializedCollection = collectionSnapshotKey && serializedCollectionKeys.has(collectionSnapshotKey); + const shouldPreservePendingHydration = pendingHydrationPaths.has(normalizedPath) + && activeWorkspace?.pathname + && normalizePath(workspacePathname) === normalizePath(activeWorkspace.pathname); + + if (!normalizedPath || (isSerializedCollection && !shouldPreservePendingHydration)) { + return; + } + + const existingTabs = (collectionSnapshotKey && existingSnapshotLookups.tabsByWorkspaceAndCollectionPath?.[collectionSnapshotKey]) + || existingSnapshotLookups.tabsByCollectionPath?.[normalizedPath]; + + snapshot.collections.push({ + pathname: existingCollection.pathname, + workspacePathname, + environment: { + collection: existingCollection.environment?.collection || existingCollection.environmentPath || '', + global: existingCollection.environment?.global || '' + }, + environmentPath: existingCollection.environment?.collection || existingCollection.environmentPath || '', + selectedEnvironment: existingCollection.selectedEnvironment || '', + isOpen: typeof existingCollection.isOpen === 'boolean' ? existingCollection.isOpen : false, + isMounted: typeof existingCollection.isMounted === 'boolean' ? existingCollection.isMounted : false, + activeTab: existingTabs?.activeTab || existingCollection.activeTab || null, + tabs: Array.isArray(existingTabs?.tabs) + ? existingTabs.tabs + : (Array.isArray(existingCollection.tabs) ? existingCollection.tabs : []) + }); + }); + + return snapshot; +}; + +export { shouldPreserveCollectionEnvironmentInSnapshot }; diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js new file mode 100644 index 00000000000..69db238d0ce --- /dev/null +++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js @@ -0,0 +1,202 @@ +const { describe, it, expect } = require('@jest/globals'); +const { + serializeSnapshot, + shouldPreserveCollectionEnvironmentInSnapshot +} = require('providers/ReduxStore/middlewares/snapshot/serializeSnapshot'); + +const WORKSPACE_PATH = '/tmp/workspace'; +const COLLECTION_PATH = '/tmp/workspace/collections/api'; +const ENVIRONMENT_PATH = '/tmp/workspace/collections/api/environments/local.yml'; + +const makeExistingSnapshot = () => ({ + version: '0.0.1', + activeWorkspacePath: WORKSPACE_PATH, + extras: { devTools: { open: false, activeTab: 'terminal', tabs: {} } }, + workspaces: [ + { + pathname: WORKSPACE_PATH, + sorting: 'default', + collections: [COLLECTION_PATH] + } + ], + collections: [ + { + pathname: COLLECTION_PATH, + workspacePathname: WORKSPACE_PATH, + environment: { + collection: ENVIRONMENT_PATH, + global: '' + }, + environmentPath: ENVIRONMENT_PATH, + selectedEnvironment: 'local', + isOpen: false, + isMounted: false, + tabs: [] + } + ] +}); + +const makeState = (collectionOverrides = {}) => ({ + app: { + snapshotHydration: { + pendingCollectionPathnames: [] + } + }, + workspaces: { + activeWorkspaceUid: 'ws-1', + workspaces: [ + { + uid: 'ws-1', + pathname: WORKSPACE_PATH, + collections: [{ path: COLLECTION_PATH }] + } + ] + }, + collections: { + collectionSortOrder: 'default', + collections: [ + { + uid: 'col-1', + pathname: COLLECTION_PATH, + mountStatus: 'unmounted', + environments: [], + activeEnvironmentUid: null, + collapsed: true, + ...collectionOverrides + } + ], + tempDirectories: {} + }, + tabs: { + tabs: [], + activeTabUid: null + }, + logs: { + isConsoleOpen: false, + activeTab: 'terminal' + }, + globalEnvironments: { + activeGlobalEnvironmentUid: null + } +}); + +describe('shouldPreserveCollectionEnvironmentInSnapshot', () => { + it('preserves when collection is unmounted and redux has no environment selection', () => { + expect(shouldPreserveCollectionEnvironmentInSnapshot({ + collection: { mountStatus: 'unmounted', environments: [] }, + environmentPathFromRedux: '', + selectedEnvironmentFromRedux: '', + existingEnvironmentPath: ENVIRONMENT_PATH, + existingSelectedEnvironment: 'local' + })).toBe(true); + }); + + it('does not preserve when redux has an authoritative environment selection', () => { + expect(shouldPreserveCollectionEnvironmentInSnapshot({ + collection: { mountStatus: 'unmounted', environments: [] }, + environmentPathFromRedux: ENVIRONMENT_PATH, + selectedEnvironmentFromRedux: 'local', + existingEnvironmentPath: ENVIRONMENT_PATH, + existingSelectedEnvironment: 'local' + })).toBe(false); + }); + + it('preserves when mounted collection has not hydrated environments yet', () => { + expect(shouldPreserveCollectionEnvironmentInSnapshot({ + collection: { mountStatus: 'mounted', environments: [] }, + environmentPathFromRedux: '', + selectedEnvironmentFromRedux: '', + existingEnvironmentPath: ENVIRONMENT_PATH, + existingSelectedEnvironment: 'local' + })).toBe(true); + }); + + it('does not preserve when mounted collection is hydrated and selection was cleared', () => { + expect(shouldPreserveCollectionEnvironmentInSnapshot({ + collection: { + mountStatus: 'mounted', + environments: [{ uid: 'env-1', name: 'local', pathname: ENVIRONMENT_PATH }] + }, + environmentPathFromRedux: '', + selectedEnvironmentFromRedux: '', + existingEnvironmentPath: ENVIRONMENT_PATH, + existingSelectedEnvironment: 'local' + })).toBe(false); + }); +}); + +describe('serializeSnapshot collection environment preservation', () => { + it('preserves existing environment fields for an unmounted collection without loaded environments', async () => { + const snapshot = await serializeSnapshot(makeState(), { + getExistingSnapshot: async () => makeExistingSnapshot() + }); + + expect(snapshot.collections).toHaveLength(1); + expect(snapshot.collections[0]).toMatchObject({ + pathname: COLLECTION_PATH, + workspacePathname: WORKSPACE_PATH, + environmentPath: ENVIRONMENT_PATH, + selectedEnvironment: 'local', + environment: { + collection: ENVIRONMENT_PATH, + global: '' + } + }); + }); + + it('preserves existing environment fields for a mounted but unhydrated collection', async () => { + const snapshot = await serializeSnapshot( + makeState({ mountStatus: 'mounted', environments: [], activeEnvironmentUid: null }), + { getExistingSnapshot: async () => makeExistingSnapshot() } + ); + + expect(snapshot.collections[0]).toMatchObject({ + environmentPath: ENVIRONMENT_PATH, + selectedEnvironment: 'local' + }); + }); + + it('writes redux environment selection when mounted collection is hydrated', async () => { + const snapshot = await serializeSnapshot( + makeState({ + mountStatus: 'mounted', + activeEnvironmentUid: 'env-2', + environments: [ + { + uid: 'env-2', + name: 'staging', + pathname: '/tmp/workspace/collections/api/environments/staging.yml' + } + ] + }), + { getExistingSnapshot: async () => makeExistingSnapshot() } + ); + + expect(snapshot.collections[0]).toMatchObject({ + environmentPath: '/tmp/workspace/collections/api/environments/staging.yml', + selectedEnvironment: 'staging' + }); + }); + + it('writes empty environment when mounted hydrated collection selection was cleared', async () => { + const snapshot = await serializeSnapshot( + makeState({ + mountStatus: 'mounted', + activeEnvironmentUid: null, + environments: [ + { + uid: 'env-1', + name: 'local', + pathname: ENVIRONMENT_PATH + } + ] + }), + { getExistingSnapshot: async () => makeExistingSnapshot() } + ); + + expect(snapshot.collections[0]).toMatchObject({ + environmentPath: '', + selectedEnvironment: '' + }); + }); +}); diff --git a/tests/snapshots/environment/environment.spec.ts b/tests/snapshots/environment/environment.spec.ts index f12a9be8672..27e8c58f6e8 100644 --- a/tests/snapshots/environment/environment.spec.ts +++ b/tests/snapshots/environment/environment.spec.ts @@ -1,23 +1,17 @@ import path from 'path'; -import fs from 'fs'; import { test, expect, closeElectronApp } from '../../../playwright'; import { createCollection, createEnvironment, openCollection, + openCollectionSettings, selectEnvironment, - waitForReadyPage + waitForReadyPage, + readSnapshot, + findSnapshotCollectionEntry, + waitForSnapshotCollectionEnvironment } from '../../utils/page'; -const readSnapshot = (userDataPath: string) => { - const snapshotPath = path.join(userDataPath, 'ui-state-snapshot.json'); - if (!fs.existsSync(snapshotPath)) { - return null; - } - - return JSON.parse(fs.readFileSync(snapshotPath, 'utf-8')); -}; - const legacyPromptVariablesInitUserDataPath = path.join( __dirname, 'init-user-data' @@ -63,8 +57,6 @@ test.describe('Snapshot: Collection Environment Persistence', () => { && path.normalize(collection.pathname) === path.normalize(migrationCollectionPath) ); expect(migratedCollectionEntry).toBeTruthy(); - console.log(JSON.stringify(migratedCollectionEntry)); - expect(migratedCollectionEntry?.selectedEnvironment).toBe('local'); }); }); @@ -98,6 +90,21 @@ test.describe('Snapshot: Collection Environment Persistence', () => { await expect(page.locator('.current-environment')).toContainText('local-b'); }); + await test.step('Trigger snapshot save from active collection and verify both environments remain on disk', async () => { + await openCollectionSettings(page, 'Collection B', { persist: true }); + + await waitForSnapshotCollectionEnvironment(userDataPath, secondCollectionRoot, 'local-b'); + await expect.poll(() => { + const snapshot = readSnapshot(userDataPath); + const firstEntry = findSnapshotCollectionEntry(snapshot, firstCollectionRoot); + const secondEntry = findSnapshotCollectionEntry(snapshot, secondCollectionRoot); + return Boolean( + firstEntry?.selectedEnvironment === 'local-a' + && secondEntry?.selectedEnvironment === 'local-b' + ); + }, { timeout: 15000 }).toBe(true); + }); + await test.step('Close app and assert snapshot stores both environments', async () => { await page.waitForTimeout(2000); await closeElectronApp(app); @@ -122,13 +129,62 @@ test.describe('Snapshot: Collection Environment Persistence', () => { await openCollection(page2, 'Collection A'); await expect(page2.locator('.current-environment')).toContainText('local-a'); + // Wait for debounced snapshot save to flush to verify the snapshot isn't overwritten by the next save + await page2.waitForTimeout(2000); + await openCollection(page2, 'Collection B'); await expect(page2.locator('.current-environment')).toContainText('local-b'); + // Wait for debounced snapshot save to flush to verify the snapshot isn't overwritten by the next save + await page2.waitForTimeout(2000); + await closeElectronApp(app2); }); }); + test('preserves unmounted collection environment after snapshot save from another collection', async ({ launchElectronApp, createTmpDir }) => { + test.setTimeout(60000); + const userDataPath = await createTmpDir('snap-env-unmounted-preserve'); + const firstCollectionPath = await createTmpDir('snap-col-a-unmounted'); + const secondCollectionPath = await createTmpDir('snap-col-b-unmounted'); + const firstCollectionRoot = path.join(firstCollectionPath, 'Collection A'); + const secondCollectionRoot = path.join(secondCollectionPath, 'Collection B'); + + const app = await launchElectronApp({ userDataPath }); + const page = await waitForReadyPage(app); + + await test.step('Create first collection environment and wait for snapshot persistence', async () => { + await createCollection(page, 'Collection A', firstCollectionPath); + await createEnvironment(page, 'local-a', 'collection'); + await selectEnvironment(page, 'local-a', 'collection'); + await waitForSnapshotCollectionEnvironment(userDataPath, firstCollectionRoot, 'local-a'); + }); + + await test.step('Create second collection and make it active', async () => { + await createCollection(page, 'Collection B', secondCollectionPath); + await createEnvironment(page, 'local-b', 'collection'); + await selectEnvironment(page, 'local-b', 'collection'); + await waitForSnapshotCollectionEnvironment(userDataPath, secondCollectionRoot, 'local-b'); + }); + + await test.step('Trigger debounced snapshot save while only second collection is active', async () => { + await openCollectionSettings(page, 'Collection B', { persist: true }); + + await expect.poll(() => { + const snapshot = readSnapshot(userDataPath); + const firstEntry = findSnapshotCollectionEntry(snapshot, firstCollectionRoot); + const secondEntry = findSnapshotCollectionEntry(snapshot, secondCollectionRoot); + return Boolean( + firstEntry?.selectedEnvironment === 'local-a' + && firstEntry?.environmentPath?.includes('local-a') + && secondEntry?.selectedEnvironment === 'local-b' + ); + }, { timeout: 15000 }).toBe(true); + }); + + await closeElectronApp(app); + }); + test('keeps selected environments for three collections across delayed switches and snapshot updates', async ({ launchElectronApp, createTmpDir }) => { // Heavy test: 3 collections, several 2s settle waits, plus a full restart. The default // budget collapses to 30s when the runner doesn't set CI=true, which isn't enough on @@ -173,6 +229,22 @@ test.describe('Snapshot: Collection Environment Persistence', () => { await expect(page.locator('.current-environment')).toContainText('local-c'); }); + await test.step('Trigger snapshot save from active collection and verify all environments remain on disk', async () => { + await openCollectionSettings(page, 'Collection C', { persist: true }); + + await expect.poll(() => { + const snapshot = readSnapshot(userDataPath); + const firstEntry = findSnapshotCollectionEntry(snapshot, firstCollectionRoot); + const secondEntry = findSnapshotCollectionEntry(snapshot, secondCollectionRoot); + const thirdEntry = findSnapshotCollectionEntry(snapshot, thirdCollectionRoot); + return Boolean( + firstEntry?.selectedEnvironment === 'local-a' + && secondEntry?.selectedEnvironment === 'local-b' + && thirdEntry?.selectedEnvironment === 'local-c' + ); + }, { timeout: 15000 }).toBe(true); + }); + await test.step('Close app and assert snapshot stores all three environments', async () => { await closeElectronApp(app); diff --git a/tests/utils/snapshot.ts b/tests/utils/snapshot.ts index 64df1f401d4..bfd882af063 100644 --- a/tests/utils/snapshot.ts +++ b/tests/utils/snapshot.ts @@ -41,3 +41,30 @@ export const findSnapshotCollectionTab = (snapshot: any, collectionPath: string) } return null; }; + +export const findSnapshotCollectionEntry = (snapshot: any, collectionPath: string) => { + if (!snapshot || !Array.isArray(snapshot.collections)) { + return null; + } + + const normalizedTarget = path.normalize(collectionPath); + return snapshot.collections.find( + (collection: any) => typeof collection?.pathname === 'string' + && path.normalize(collection.pathname) === normalizedTarget + ) || null; +}; + +export const waitForSnapshotCollectionEnvironment = async ( + userDataPath: string, + collectionPath: string, + selectedEnvironment: string, + options: { timeout?: number } = {} +) => { + const { timeout = 15000 } = options; + + await expect.poll(() => { + const snapshot = readSnapshot(userDataPath); + const entry = findSnapshotCollectionEntry(snapshot, collectionPath); + return entry?.selectedEnvironment || ''; + }, { timeout }).toBe(selectedEnvironment); +}; From ae61c5f1ef8d39f7c55795a9db11ac97df9b1656 Mon Sep 17 00:00:00 2001 From: Sid Date: Tue, 30 Jun 2026 19:54:35 +0530 Subject: [PATCH 03/11] Add tests for missing and invalid environment files --- .../snapshots/environment/environment.spec.ts | 76 ++++++++++++++++++- 1 file changed, 73 insertions(+), 3 deletions(-) diff --git a/tests/snapshots/environment/environment.spec.ts b/tests/snapshots/environment/environment.spec.ts index 27e8c58f6e8..f5ee18691dd 100644 --- a/tests/snapshots/environment/environment.spec.ts +++ b/tests/snapshots/environment/environment.spec.ts @@ -1,4 +1,5 @@ import path from 'path'; +import fs from 'fs'; import { test, expect, closeElectronApp } from '../../../playwright'; import { createCollection, @@ -246,6 +247,7 @@ test.describe('Snapshot: Collection Environment Persistence', () => { }); await test.step('Close app and assert snapshot stores all three environments', async () => { + await page.waitForTimeout(2000); await closeElectronApp(app); const snapshot = readSnapshot(userDataPath); @@ -269,15 +271,15 @@ test.describe('Snapshot: Collection Environment Persistence', () => { const page2 = await waitForReadyPage(app2); await openCollection(page2, 'Collection A'); - await expect(page2.locator('.current-environment')).toContainText('local-a'); + await expect(page2.locator('.current-environment')).toContainText('local-a', { timeout: 15000 }); await page2.waitForTimeout(2000); await openCollection(page2, 'Collection B'); - await expect(page2.locator('.current-environment')).toContainText('local-b'); + await expect(page2.locator('.current-environment')).toContainText('local-b', { timeout: 15000 }); await page2.waitForTimeout(2000); await openCollection(page2, 'Collection C'); - await expect(page2.locator('.current-environment')).toContainText('local-c'); + await expect(page2.locator('.current-environment')).toContainText('local-c', { timeout: 15000 }); await page2.waitForTimeout(2000); await closeElectronApp(app2); @@ -295,4 +297,72 @@ test.describe('Snapshot: Collection Environment Persistence', () => { expect(thirdUpdatedEntry?.selectedEnvironment).toBe('local-c'); }); }); + + test('preserves snapshot environment when referenced environment file is missing after restart', async ({ launchElectronApp, createTmpDir }) => { + const userDataPath = await createTmpDir('snap-missing-env'); + const collectionPath = await createTmpDir('snap-missing-env-col'); + const collectionRoot = path.join(collectionPath, 'Collection Missing Env'); + + const app = await launchElectronApp({ userDataPath }); + const page = await waitForReadyPage(app); + + await createCollection(page, 'Collection Missing Env', collectionPath); + await openCollection(page, 'Collection Missing Env'); + await createEnvironment(page, 'local-missing', 'collection'); + await selectEnvironment(page, 'local-missing', 'collection'); + await page.waitForTimeout(1500); + await closeElectronApp(app); + + const initialSnapshot = readSnapshot(userDataPath); + const initialEntry = initialSnapshot?.collections?.find((collection: any) => collection?.pathname === collectionRoot); + const envFilePath = initialEntry?.environmentPath || initialEntry?.environment?.collection; + expect(envFilePath).toBeTruthy(); + expect(fs.existsSync(envFilePath)).toBe(true); + fs.rmSync(envFilePath); + + const app2 = await launchElectronApp({ userDataPath }); + const page2 = await waitForReadyPage(app2); + await openCollection(page2, 'Collection Missing Env'); + await page2.waitForTimeout(2000); + await closeElectronApp(app2); + + const snapshot = readSnapshot(userDataPath); + const entry = snapshot?.collections?.find((collection: any) => collection?.pathname === collectionRoot); + expect(entry?.selectedEnvironment).toBe('local-missing'); + expect(entry?.environmentPath).toContain('local-missing'); + }); + + test('preserves snapshot environment when environment file fails to parse after restart', async ({ launchElectronApp, createTmpDir }) => { + const userDataPath = await createTmpDir('snap-bad-env'); + const collectionPath = await createTmpDir('snap-bad-env-col'); + const collectionRoot = path.join(collectionPath, 'Collection Bad Env'); + + const app = await launchElectronApp({ userDataPath }); + const page = await waitForReadyPage(app); + + await createCollection(page, 'Collection Bad Env', collectionPath); + await openCollection(page, 'Collection Bad Env'); + await createEnvironment(page, 'local-bad', 'collection'); + await selectEnvironment(page, 'local-bad', 'collection'); + await page.waitForTimeout(1500); + await closeElectronApp(app); + + const initialSnapshot = readSnapshot(userDataPath); + const initialEntry = initialSnapshot?.collections?.find((collection: any) => collection?.pathname === collectionRoot); + const envFilePath = initialEntry?.environmentPath || initialEntry?.environment?.collection; + expect(envFilePath).toBeTruthy(); + expect(fs.existsSync(envFilePath)).toBe(true); + fs.writeFileSync(envFilePath, 'this is not valid environment syntax {{{'); + + const app2 = await launchElectronApp({ userDataPath }); + const page2 = await waitForReadyPage(app2); + await openCollection(page2, 'Collection Bad Env'); + await page2.waitForTimeout(2000); + await closeElectronApp(app2); + + const snapshot = readSnapshot(userDataPath); + const entry = snapshot?.collections?.find((collection: any) => collection?.pathname === collectionRoot); + expect(entry?.selectedEnvironment).toBe('local-bad'); + expect(entry?.environmentPath).toContain('local-bad'); + }); }); From 76506ebef5fd4ca03d391b9d1d214c0aded34bda Mon Sep 17 00:00:00 2001 From: Sid Date: Tue, 30 Jun 2026 23:00:28 +0530 Subject: [PATCH 04/11] feat(snapshot): refactor devTools normalization and add saveToken to IPC handler --- .../middlewares/snapshot/serializeSnapshot.js | 11 +++++--- .../snapshot/serializeSnapshot.spec.js | 18 ++++++++++++ .../ReduxStore/slices/workspaces/actions.js | 4 +-- packages/bruno-electron/src/ipc/snapshot.js | 4 +-- .../src/services/snapshot/index.js | 7 +++-- .../active-workspace-restore.spec.ts | 23 ++++++++++++--- .../snapshots/environment/environment.spec.ts | 28 ++++++++----------- tests/utils/snapshot.ts | 2 +- 8 files changed, 64 insertions(+), 33 deletions(-) diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js index 3531f2a52c2..ace64c696e4 100644 --- a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js +++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js @@ -103,16 +103,19 @@ export const serializeSnapshot = async (state, options = {}) => { ); const existingDevTools = existingSnapshot?.extras?.devTools ?? {}; + const resolvedDevToolsActiveTab = logs.activeTab ?? existingDevTools.activeTab ?? 'terminal'; + const existingDevToolsTabs = existingDevTools.tabs || {}; const snapshot = { activeWorkspacePath: activeWorkspace?.pathname || null, extras: { devTools: { open: logs.isConsoleOpen, - activeTab: logs.activeTab ?? existingDevTools.activeTab ?? 'terminal', - tabs: Object.assign(existingDevTools.tabs, { - [logs.activeTab]: {} - }) + activeTab: resolvedDevToolsActiveTab, + tabs: { + ...existingDevToolsTabs, + [resolvedDevToolsActiveTab]: existingDevToolsTabs[resolvedDevToolsActiveTab] ?? {} + } } }, workspaces: [], diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js index 69db238d0ce..74bb3ead165 100644 --- a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js +++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js @@ -126,6 +126,24 @@ describe('shouldPreserveCollectionEnvironmentInSnapshot', () => { }); describe('serializeSnapshot collection environment preservation', () => { + it('creates a safe first-run snapshot when no existing snapshot is available', async () => { + const snapshot = await serializeSnapshot(makeState(), { + getExistingSnapshot: async () => null + }); + + expect(snapshot).toMatchObject({ + extras: { + devTools: { + open: false, + activeTab: 'terminal', + tabs: { + terminal: {} + } + } + } + }); + }); + it('preserves existing environment fields for an unmounted collection without loaded environments', async () => { const snapshot = await serializeSnapshot(makeState(), { getExistingSnapshot: async () => makeExistingSnapshot() diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js b/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js index 41aa647d433..015aa126f92 100644 --- a/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js +++ b/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js @@ -835,13 +835,14 @@ export const workspaceOpenedEvent = (workspacePath, workspaceUid, workspaceConfi ...workspaceConfig })); + let snapshot = null; try { await dispatch(loadWorkspaceCollections(workspaceUid)); } catch (error) { } try { - const snapshot = await ipcRenderer.invoke('renderer:snapshot:get'); + snapshot = await ipcRenderer.invoke('renderer:snapshot:get'); const currentState = getState(); if (!currentState.app.snapshotReady && snapshot?.extras?.devTools) { @@ -866,7 +867,6 @@ export const workspaceOpenedEvent = (workspacePath, workspaceUid, workspaceConfi let shouldSwitch = false; try { - const snapshot = await ipcRenderer.invoke('renderer:snapshot:get'); const activeWorkspacePath = snapshot?.activeWorkspacePath; const normalizedWorkspacePath = normalizePath(workspacePath || ''); diff --git a/packages/bruno-electron/src/ipc/snapshot.js b/packages/bruno-electron/src/ipc/snapshot.js index d360e6fe75d..f8d98e052ad 100644 --- a/packages/bruno-electron/src/ipc/snapshot.js +++ b/packages/bruno-electron/src/ipc/snapshot.js @@ -18,8 +18,8 @@ const registerSnapshotIpc = () => { } }); - ipcMain.handle('renderer:snapshot:save', async (event, data) => { - return snapshotManager.saveSnapshot(data); + ipcMain.handle('renderer:snapshot:save', async (event, data, saveToken) => { + return snapshotManager.saveSnapshot(data, saveToken); }); }; diff --git a/packages/bruno-electron/src/services/snapshot/index.js b/packages/bruno-electron/src/services/snapshot/index.js index ea2df8b0b19..86e4bc217cc 100644 --- a/packages/bruno-electron/src/services/snapshot/index.js +++ b/packages/bruno-electron/src/services/snapshot/index.js @@ -291,16 +291,17 @@ class SnapshotManager { 'performance', 'terminal' ]; + const devToolTabs = devTools.tabs || {}; const _snapshotEntry = { open: typeof devTools?.open === 'boolean' ? devTools.open : false, - activeTab: devTools.activeTab, + activeTab: typeof devTools.activeTab === 'string' ? devTools.activeTab : 'terminal', tabs: {} }; devToolKeys.forEach((key) => { - if (key in devTools) { - _snapshotEntry.tabs[key] = devTools.tabs[key]; + if (key in devToolTabs) { + _snapshotEntry.tabs[key] = devToolTabs[key]; } }); diff --git a/tests/snapshots/active-workspace-restore.spec.ts b/tests/snapshots/active-workspace-restore.spec.ts index 2d08f43c3f1..73ce3e60e05 100644 --- a/tests/snapshots/active-workspace-restore.spec.ts +++ b/tests/snapshots/active-workspace-restore.spec.ts @@ -101,11 +101,17 @@ test.describe('Snapshot: Active Workspace Restore', () => { const app = await launchElectronApp({ userDataPath }); const page = await waitForReadyPage(app); + const workspaceNameLocator = page.getByTestId('workspace-name'); + const workspaceMenuLocator = page.getByTestId('workspace-menu'); - await expect(page.getByTestId('workspace-name')).toHaveText(activeWorkspaceName, { timeout: 10000 }); + await test.step('Assert restored workspace is visible', async () => { + await expect(workspaceNameLocator).toHaveText(activeWorkspaceName, { timeout: 10000 }); + }); - await page.getByTestId('workspace-menu').click(); - await expect(page.locator('.workspace-item.active')).toContainText(activeWorkspaceName); + await test.step('Assert restored workspace is active in the menu', async () => { + await workspaceMenuLocator.click(); + await expect(page.locator('.workspace-item.active')).toContainText(activeWorkspaceName); + }); await closeElectronApp(app); }); @@ -117,8 +123,17 @@ test.describe('Snapshot: Active Workspace Restore', () => { const app = await launchElectronApp({ userDataPath }); const page = await waitForReadyPage(app); + const workspaceNameLocator = page.getByTestId('workspace-name'); + const workspaceMenuLocator = page.getByTestId('workspace-menu'); - await expect(page.getByTestId('workspace-name')).toHaveText(activeWorkspaceName, { timeout: 10000 }); + await test.step('Assert restored workspace is visible', async () => { + await expect(workspaceNameLocator).toHaveText(activeWorkspaceName, { timeout: 10000 }); + }); + + await test.step('Assert restored workspace is active in the menu', async () => { + await workspaceMenuLocator.click(); + await expect(page.locator('.workspace-item.active')).toContainText(activeWorkspaceName); + }); await closeElectronApp(app); }); diff --git a/tests/snapshots/environment/environment.spec.ts b/tests/snapshots/environment/environment.spec.ts index f5ee18691dd..0ecf9b1d06a 100644 --- a/tests/snapshots/environment/environment.spec.ts +++ b/tests/snapshots/environment/environment.spec.ts @@ -52,11 +52,7 @@ test.describe('Snapshot: Collection Environment Persistence', () => { expect(Array.isArray(snapshot?.workspaces)).toBe(true); expect(Array.isArray(snapshot?.collections)).toBe(true); - const migratedCollectionEntry = snapshot?.collections?.find( - (collection: any) => - typeof collection?.pathname === 'string' - && path.normalize(collection.pathname) === path.normalize(migrationCollectionPath) - ); + const migratedCollectionEntry = findSnapshotCollectionEntry(snapshot, migrationCollectionPath); expect(migratedCollectionEntry).toBeTruthy(); expect(migratedCollectionEntry?.selectedEnvironment).toBe('local'); }); @@ -112,10 +108,8 @@ test.describe('Snapshot: Collection Environment Persistence', () => { const snapshot = readSnapshot(userDataPath); expect(snapshot).not.toBeNull(); - - const collections = Array.isArray(snapshot?.collections) ? snapshot.collections : []; - const firstEntry = collections.find((collection: any) => collection?.pathname === firstCollectionRoot); - const secondEntry = collections.find((collection: any) => collection?.pathname === secondCollectionRoot); + const firstEntry = findSnapshotCollectionEntry(snapshot, firstCollectionRoot); + const secondEntry = findSnapshotCollectionEntry(snapshot, secondCollectionRoot); expect(firstEntry?.selectedEnvironment).toBe('local-a'); expect(secondEntry?.selectedEnvironment).toBe('local-b'); @@ -252,11 +246,9 @@ test.describe('Snapshot: Collection Environment Persistence', () => { const snapshot = readSnapshot(userDataPath); expect(snapshot).not.toBeNull(); - - const collections = Array.isArray(snapshot?.collections) ? snapshot.collections : []; - const firstEntry = collections.find((collection: any) => collection?.pathname === firstCollectionRoot); - const secondEntry = collections.find((collection: any) => collection?.pathname === secondCollectionRoot); - const thirdEntry = collections.find((collection: any) => collection?.pathname === thirdCollectionRoot); + const firstEntry = findSnapshotCollectionEntry(snapshot, firstCollectionRoot); + const secondEntry = findSnapshotCollectionEntry(snapshot, secondCollectionRoot); + const thirdEntry = findSnapshotCollectionEntry(snapshot, thirdCollectionRoot); expect(firstEntry?.selectedEnvironment).toBe('local-a'); expect(secondEntry?.selectedEnvironment).toBe('local-b'); @@ -314,7 +306,7 @@ test.describe('Snapshot: Collection Environment Persistence', () => { await closeElectronApp(app); const initialSnapshot = readSnapshot(userDataPath); - const initialEntry = initialSnapshot?.collections?.find((collection: any) => collection?.pathname === collectionRoot); + const initialEntry = findSnapshotCollectionEntry(initialSnapshot, collectionRoot); const envFilePath = initialEntry?.environmentPath || initialEntry?.environment?.collection; expect(envFilePath).toBeTruthy(); expect(fs.existsSync(envFilePath)).toBe(true); @@ -323,11 +315,12 @@ test.describe('Snapshot: Collection Environment Persistence', () => { const app2 = await launchElectronApp({ userDataPath }); const page2 = await waitForReadyPage(app2); await openCollection(page2, 'Collection Missing Env'); + await expect(page2.locator('.current-environment')).toContainText('local-missing'); await page2.waitForTimeout(2000); await closeElectronApp(app2); const snapshot = readSnapshot(userDataPath); - const entry = snapshot?.collections?.find((collection: any) => collection?.pathname === collectionRoot); + const entry = findSnapshotCollectionEntry(snapshot, collectionRoot); expect(entry?.selectedEnvironment).toBe('local-missing'); expect(entry?.environmentPath).toContain('local-missing'); }); @@ -357,11 +350,12 @@ test.describe('Snapshot: Collection Environment Persistence', () => { const app2 = await launchElectronApp({ userDataPath }); const page2 = await waitForReadyPage(app2); await openCollection(page2, 'Collection Bad Env'); + await expect(page2.locator('.current-environment')).toContainText('local-bad'); await page2.waitForTimeout(2000); await closeElectronApp(app2); const snapshot = readSnapshot(userDataPath); - const entry = snapshot?.collections?.find((collection: any) => collection?.pathname === collectionRoot); + const entry = findSnapshotCollectionEntry(snapshot, collectionRoot); expect(entry?.selectedEnvironment).toBe('local-bad'); expect(entry?.environmentPath).toContain('local-bad'); }); diff --git a/tests/utils/snapshot.ts b/tests/utils/snapshot.ts index bfd882af063..0cc3d927744 100644 --- a/tests/utils/snapshot.ts +++ b/tests/utils/snapshot.ts @@ -65,6 +65,6 @@ export const waitForSnapshotCollectionEnvironment = async ( await expect.poll(() => { const snapshot = readSnapshot(userDataPath); const entry = findSnapshotCollectionEntry(snapshot, collectionPath); - return entry?.selectedEnvironment || ''; + return entry ? (entry.selectedEnvironment ?? '') : null; }, { timeout }).toBe(selectedEnvironment); }; From 95ae2f28da49ef312e29dbe0b5d50189293b2b88 Mon Sep 17 00:00:00 2001 From: Sid Date: Tue, 30 Jun 2026 23:06:37 +0530 Subject: [PATCH 05/11] refactor(snapshot): remove saveToken from IPC handler for renderer:snapshot:save --- packages/bruno-electron/src/ipc/snapshot.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/bruno-electron/src/ipc/snapshot.js b/packages/bruno-electron/src/ipc/snapshot.js index f8d98e052ad..d360e6fe75d 100644 --- a/packages/bruno-electron/src/ipc/snapshot.js +++ b/packages/bruno-electron/src/ipc/snapshot.js @@ -18,8 +18,8 @@ const registerSnapshotIpc = () => { } }); - ipcMain.handle('renderer:snapshot:save', async (event, data, saveToken) => { - return snapshotManager.saveSnapshot(data, saveToken); + ipcMain.handle('renderer:snapshot:save', async (event, data) => { + return snapshotManager.saveSnapshot(data); }); }; From e9775964cf555403e5499c79aeeee001e8e5f15f Mon Sep 17 00:00:00 2001 From: Sid Date: Wed, 1 Jul 2026 18:21:28 +0530 Subject: [PATCH 06/11] feat(snapshot): implement collection deduplication logic in SnapshotManager and add corresponding tests --- .../src/services/snapshot/index.js | 36 ++++-- tests/snapshots/collection-dedup.spec.ts | 104 ++++++++++++++++++ 2 files changed, 130 insertions(+), 10 deletions(-) create mode 100644 tests/snapshots/collection-dedup.spec.ts diff --git a/packages/bruno-electron/src/services/snapshot/index.js b/packages/bruno-electron/src/services/snapshot/index.js index 86e4bc217cc..543e9e6b3ac 100644 --- a/packages/bruno-electron/src/services/snapshot/index.js +++ b/packages/bruno-electron/src/services/snapshot/index.js @@ -383,23 +383,39 @@ class SnapshotManager { const collectionMap = new Map(); if (Array.isArray(collections)) { + const rawCollectionsByKey = new Map(); + collections.forEach((collection) => { if (!isObject(collection) || typeof collection.pathname !== 'string') { return; } - const normalizedCollection = this._normalizeCollectionEntry(collection.pathname, collection); + const workspacePathname = typeof collection.workspacePathname === 'string' ? collection.workspacePathname : ''; const normalizedPath = normalizeLookupKey(collection.pathname); - const workspaceCollectionKey = buildWorkspaceCollectionLookupKey( - normalizedCollection.workspacePathname, - normalizedCollection.pathname - ); - - if (workspaceCollectionKey) { - collectionMap.set(workspaceCollectionKey, normalizedCollection); - } else if (normalizedPath) { - collectionMap.set(normalizedPath, normalizedCollection); + const key = buildWorkspaceCollectionLookupKey(workspacePathname, collection.pathname) || normalizedPath; + + if (!key) { + return; } + + const existingRaw = rawCollectionsByKey.get(key); + const mergedRaw = existingRaw + ? { + ...existingRaw, + ...collection, + environment: { + ...(isObject(existingRaw.environment) ? existingRaw.environment : {}), + ...(isObject(collection.environment) ? collection.environment : {}) + } + } + : collection; + + rawCollectionsByKey.set(key, mergedRaw); + }); + + rawCollectionsByKey.forEach((mergedRaw, key) => { + const normalizedCollection = this._normalizeCollectionEntry(mergedRaw.pathname, mergedRaw); + collectionMap.set(key, normalizedCollection); }); return [...collectionMap.values()]; diff --git a/tests/snapshots/collection-dedup.spec.ts b/tests/snapshots/collection-dedup.spec.ts new file mode 100644 index 00000000000..8f6cbbc768e --- /dev/null +++ b/tests/snapshots/collection-dedup.spec.ts @@ -0,0 +1,104 @@ +import path from 'path'; +import fs from 'fs'; +import { test, expect, closeElectronApp } from '../../playwright'; +import { waitForReadyPage } from '../utils/page'; +import { readSnapshot, getSnapshotPath, findSnapshotCollectionEntry } from '../utils/snapshot'; + +const seedSnapshotWithDuplicateCollection = (userDataPath: string, collectionPath: string) => { + fs.writeFileSync( + getSnapshotPath(userDataPath), + JSON.stringify( + { + version: '0.0.1', + activeWorkspacePath: null, + extras: { + devTools: { + open: false + } + }, + workspaces: [], + collections: [ + // Older entry: has a selected environment and an open tab, but is not marked open/mounted. + { + pathname: collectionPath, + workspacePathname: '', + environment: { + collection: 'local.yml', + global: '' + }, + environmentPath: 'local.yml', + selectedEnvironment: 'local', + isOpen: false, + isMounted: false, + activeTab: { + accessor: 'pathname', + value: path.join(collectionPath, 'ReqAlpha.bru') + }, + tabs: [ + { + type: 'http-request', + accessor: 'pathname', + pathname: path.join(collectionPath, 'ReqAlpha.bru'), + permanent: true + } + ] + }, + // Newer entry: same pathname, marks the collection open/mounted but omits the environment/tabs + // that the older entry had set. The newer entry should win on the fields it specifies, + // while fields it leaves unspecified should fall back to the older entry. + { + pathname: collectionPath, + workspacePathname: '', + isOpen: true, + isMounted: true + } + ] + }, + null, + 2 + ) + ); +}; + +test.describe('Snapshot: Collection Deduplication', () => { + test('duplicate collection entries for the same pathname are deduplicated, with the latest entry taking precedence', async ({ launchElectronApp, createTmpDir }) => { + const userDataPath = await createTmpDir('snap-collection-dedup'); + const colPath = await createTmpDir('col'); + + fs.writeFileSync(path.join(colPath, 'bruno.json'), JSON.stringify({ version: '1', name: 'TestCol', type: 'collection' }, null, 2)); + + seedSnapshotWithDuplicateCollection(userDataPath, colPath); + + await test.step('Assert seeded snapshot has two entries for the same collection before launch', () => { + const snapshot = readSnapshot(userDataPath); + const entries = snapshot.collections.filter((c: any) => path.normalize(c.pathname) === path.normalize(colPath)); + expect(entries).toHaveLength(2); + }); + + const app = await launchElectronApp({ userDataPath }); + const page = await waitForReadyPage(app); + + await expect(page.getByTestId('workspace-name')).toBeVisible({ timeout: 10000 }); + + await test.step('Close app and verify the snapshot is deduplicated to a single, merged entry', async () => { + await page.waitForTimeout(2000); + await closeElectronApp(app); + + const snapshot = readSnapshot(userDataPath); + const entries = snapshot.collections.filter((c: any) => path.normalize(c.pathname) === path.normalize(colPath)); + expect(entries).toHaveLength(1); + + const entry = findSnapshotCollectionEntry(snapshot, colPath); + + // Fields set by the newer entry win. + expect(entry.isOpen).toBe(true); + expect(entry.isMounted).toBe(true); + + // Fields not touched by the newer entry are preserved from the older entry. + expect(entry.selectedEnvironment).toBe('local'); + expect(entry.environment.collection).toBe('local.yml'); + expect(entry.tabs).toHaveLength(1); + expect(entry.tabs[0].pathname).toBe(path.join(colPath, 'ReqAlpha.bru')); + }); + }); +}); From caf27af691c26b4535b12350d2470163d96c7566 Mon Sep 17 00:00:00 2001 From: Sid Date: Fri, 3 Jul 2026 13:42:25 +0530 Subject: [PATCH 07/11] feat(snapshot): enhance workspace-specific environment handling for shared collections --- .../middlewares/snapshot/serializeSnapshot.js | 3 + .../snapshot/serializeSnapshot.spec.js | 5 + .../ReduxStore/slices/collections/actions.js | 32 +++++- .../ReduxStore/slices/collections/index.js | 19 ---- .../ReduxStore/slices/workspaces/actions.js | 17 ++- .../bruno-app/src/utils/snapshot/index.js | 26 +++++ .../src/utils/snapshot/index.spec.js | 19 +++- .../src/app/collection-watcher.js | 9 +- packages/bruno-electron/src/ipc/collection.js | 4 +- packages/bruno-electron/src/ipc/snapshot.js | 4 + .../src/services/snapshot/index.js | 68 +++++++++-- ...d-collection-workspace-environment.spec.ts | 106 ++++++++++++++++++ tests/utils/page/actions.ts | 57 +++++++--- tests/utils/page/locators.ts | 7 ++ 14 files changed, 317 insertions(+), 59 deletions(-) create mode 100644 tests/snapshots/shared-collection-workspace-environment.spec.ts diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js index ace64c696e4..0db6a0f1617 100644 --- a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js +++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js @@ -211,6 +211,7 @@ export const serializeSnapshot = async (state, options = {}) => { snapshot.collections.push({ pathname: collection.pathname, workspacePathname, + sourceWorkspacePathname: workspacePathname, environment: { collection: environmentPath, global: globalEnvironments.activeGlobalEnvironmentUid || '' @@ -234,6 +235,7 @@ export const serializeSnapshot = async (state, options = {}) => { (existingCollections.length > 0 ? existingCollections : fallbackCollections).forEach((existingCollection) => { const normalizedPath = normalizePath(existingCollection.pathname || ''); const workspacePathname = existingCollection.workspacePathname || ''; + const sourceWorkspacePathname = existingCollection.sourceWorkspacePathname || workspacePathname; const collectionSnapshotKey = getWorkspaceCollectionSnapshotKey(workspacePathname, existingCollection.pathname); const isSerializedCollection = collectionSnapshotKey && serializedCollectionKeys.has(collectionSnapshotKey); const shouldPreservePendingHydration = pendingHydrationPaths.has(normalizedPath) @@ -250,6 +252,7 @@ export const serializeSnapshot = async (state, options = {}) => { snapshot.collections.push({ pathname: existingCollection.pathname, workspacePathname, + sourceWorkspacePathname, environment: { collection: existingCollection.environment?.collection || existingCollection.environmentPath || '', global: existingCollection.environment?.global || '' diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js index 74bb3ead165..b71944f8d2e 100644 --- a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js +++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js @@ -23,6 +23,7 @@ const makeExistingSnapshot = () => ({ { pathname: COLLECTION_PATH, workspacePathname: WORKSPACE_PATH, + sourceWorkspacePathname: WORKSPACE_PATH, environment: { collection: ENVIRONMENT_PATH, global: '' @@ -153,6 +154,7 @@ describe('serializeSnapshot collection environment preservation', () => { expect(snapshot.collections[0]).toMatchObject({ pathname: COLLECTION_PATH, workspacePathname: WORKSPACE_PATH, + sourceWorkspacePathname: WORKSPACE_PATH, environmentPath: ENVIRONMENT_PATH, selectedEnvironment: 'local', environment: { @@ -169,6 +171,7 @@ describe('serializeSnapshot collection environment preservation', () => { ); expect(snapshot.collections[0]).toMatchObject({ + sourceWorkspacePathname: WORKSPACE_PATH, environmentPath: ENVIRONMENT_PATH, selectedEnvironment: 'local' }); @@ -191,6 +194,7 @@ describe('serializeSnapshot collection environment preservation', () => { ); expect(snapshot.collections[0]).toMatchObject({ + sourceWorkspacePathname: WORKSPACE_PATH, environmentPath: '/tmp/workspace/collections/api/environments/staging.yml', selectedEnvironment: 'staging' }); @@ -213,6 +217,7 @@ describe('serializeSnapshot collection environment preservation', () => { ); expect(snapshot.collections[0]).toMatchObject({ + sourceWorkspacePathname: WORKSPACE_PATH, environmentPath: '', selectedEnvironment: '' }); diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js b/packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js index 16b7f2c0a9a..9f1afdbe5e9 100644 --- a/packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js +++ b/packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js @@ -2502,6 +2502,7 @@ export const selectEnvironment = (environmentUid, collectionUid) => (dispatch, g return new Promise((resolve, reject) => { const state = getState(); const collection = findCollectionByUid(state.collections.collections, collectionUid); + const activeWorkspace = state.workspaces.workspaces.find((w) => w.uid === state.workspaces.activeWorkspaceUid); if (!collection) { return reject(new Error('Collection not found')); } @@ -2519,6 +2520,7 @@ export const selectEnvironment = (environmentUid, collectionUid) => (dispatch, g type: 'COLLECTION_ENVIRONMENT', data: { collectionPath: collection?.pathname, + workspacePathname: activeWorkspace?.pathname || null, environmentPath: getCollectionEnvironmentPath(collection, environment), selectedEnvironment: environment?.name || '' } @@ -2951,6 +2953,9 @@ export const collectionAddEnvFileEvent = (payload) => (dispatch, getState) => { return new Promise((resolve, reject) => { const state = getState(); const collection = findCollectionByUid(state.collections.collections, meta.collectionUid); + const activeWorkspace = state.workspaces.workspaces.find((w) => w.uid === state.workspaces.activeWorkspaceUid); + const shouldPersistSelectionFromLastAction = collection?.lastAction?.type === 'ADD_ENVIRONMENT' + && collection?.lastAction?.payload === environment?.name; if (!collection) { return reject(new Error('Collection not found')); } @@ -2973,6 +2978,22 @@ export const collectionAddEnvFileEvent = (payload) => (dispatch, getState) => { }) ) ) + .then(() => { + if (!shouldPersistSelectionFromLastAction) { + return; + } + + const { ipcRenderer } = window; + ipcRenderer.invoke('renderer:update-ui-state-snapshot', { + type: 'COLLECTION_ENVIRONMENT', + data: { + collectionPath: collection?.pathname, + workspacePathname: activeWorkspace?.pathname || null, + environmentPath: getCollectionEnvironmentPath(collection, environment, environment?.pathname), + selectedEnvironment: environment?.name || '' + } + }); + }) .then(resolve) .catch(reject); }); @@ -3240,7 +3261,7 @@ export const mountCollection const fileCacheEnabled = getState().app?.preferences?.cache?.file?.enabled; const channel = fileCacheEnabled ? 'renderer:mount-collection-v2' : 'renderer:mount-collection'; return new Promise(async (resolve, reject) => { - callIpc(channel, { collectionUid, collectionPathname, brunoConfig }) + callIpc(channel, { collectionUid, collectionPathname, brunoConfig, workspacePathname }) .then(async (transientDirPath) => { dispatch(updateCollectionMountStatus({ collectionUid, mountStatus: 'mounted' })); dispatch(addTransientDirectory({ collectionUid, pathname: transientDirPath })); @@ -3248,6 +3269,13 @@ export const mountCollection const collection = getState().collections.collections.find((c) => c.uid === collectionUid); if (!skipTabRestore && collection?.pathname) { await hydrateCollectionTabs(collection, dispatch, restoreTabs, null, workspacePathname); + + const collectionSnapshotState = await window.ipcRenderer + .invoke('renderer:snapshot:get-collection', collection.pathname, workspacePathname) + .catch(() => null); + await dispatch(hydrateCollectionWithUiStateSnapshot( + collectionSnapshotState ? { pathname: collection.pathname, ...collectionSnapshotState } : null + )); } }) .then(resolve) @@ -3536,7 +3564,7 @@ export const migrateCollectionToYml = (collectionUid) => (dispatch, getState) => collectionPathname: collectionPathname, brunoConfig: updatedBrunoConfig })); - } catch (_) {} + } catch (_) { } throw reopenError; } diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js b/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js index 2dc35d5cc4e..4538b6ee35c 100644 --- a/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js +++ b/packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js @@ -24,7 +24,6 @@ import toast from 'react-hot-toast'; import mime from 'mime-types'; import path from 'utils/common/path'; import { getUniqueTagsFromItems } from 'utils/collections/index'; -import { getCollectionEnvironmentPath } from 'utils/snapshot'; import { getDataTypeFromValue } from '@usebruno/common/utils'; import * as exampleReducers from './exampleReducers'; @@ -3043,24 +3042,6 @@ export const collectionsSlice = createSlice({ collection.lastAction = null; if (lastAction.payload === environment.name) { collection.activeEnvironmentUid = environment.uid; - // Persist the selection to the UI state snapshot - const { ipcRenderer } = window; - if (ipcRenderer) { - const extension = collection?.brunoConfig?.version === '1' ? 'bru' : 'yml'; - const environmentPath = environment?.pathname - || (environment?.name && collection?.pathname - ? path.join(collection.pathname, 'environments', `${environment.name}.${extension}`) - : null); - - ipcRenderer.invoke('renderer:update-ui-state-snapshot', { - type: 'COLLECTION_ENVIRONMENT', - data: { - collectionPath: collection?.pathname, - environmentPath: getCollectionEnvironmentPath(collection, environment, environmentPath), - selectedEnvironment: environment?.name || '' - } - }); - } } } } diff --git a/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js b/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js index 015aa126f92..ae2445b9f0d 100644 --- a/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js +++ b/packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js @@ -8,7 +8,7 @@ import { updateWorkspaceLoadingState, setWorkspaceScratchCollection } from '../workspaces'; -import { createCollection, openCollection, openMultipleCollections, openScratchCollectionEvent, mountCollection } from '../collections/actions'; +import { createCollection, openCollection, openMultipleCollections, openScratchCollectionEvent, mountCollection, hydrateCollectionWithUiStateSnapshot } from '../collections/actions'; import { removeCollection, addTransientDirectory, updateCollectionMountStatus, expandCollection, sortCollections } from '../collections'; import { sanitizeName } from 'utils/common/regex'; import { clearCollectionState } from '../openapi-sync'; @@ -22,7 +22,7 @@ import { } from '../app'; import { openConsole, closeConsole, setActiveTab as setActiveDevToolsTab, TAB_IDENFIERS as DEVTOOL_TABS } from '../logs'; import { normalizePath } from 'utils/common/path'; -import { hydrateTabs, getActiveTabFromSnapshot, hydrateSnapshotLookups } from 'utils/snapshot'; +import { hydrateTabs, getActiveTabFromSnapshot, hydrateSnapshotLookups, getCollectionSnapshotFromLookups } from 'utils/snapshot'; import toast from 'react-hot-toast'; const { ipcRenderer } = window; @@ -626,6 +626,19 @@ export const switchWorkspace = (workspaceUid) => { ); await hydrateTabs(collections, dispatch, restoreTabs, snapshotLookups, workspace.pathname || null); + // Restore each collection's workspace-scoped selected environment, so the same + // collection open under two workspaces restores its own environment per workspace. + await Promise.all(collections.map((collection) => { + const collectionSnapshotState = getCollectionSnapshotFromLookups( + collection.pathname, + snapshotLookups, + workspace.pathname || null + ); + return dispatch(hydrateCollectionWithUiStateSnapshot( + collectionSnapshotState ? { pathname: collection.pathname, ...collectionSnapshotState } : null + )); + })); + // Add workspace tabs if (scratchCollection?.uid) { dispatch(addTab({ uid: `${scratchCollection.uid}-overview`, collectionUid: scratchCollection.uid, type: 'workspaceOverview' })); diff --git a/packages/bruno-app/src/utils/snapshot/index.js b/packages/bruno-app/src/utils/snapshot/index.js index 1900424596f..79ab25044c3 100644 --- a/packages/bruno-app/src/utils/snapshot/index.js +++ b/packages/bruno-app/src/utils/snapshot/index.js @@ -119,6 +119,9 @@ const normalizeCollectionSnapshotEntry = (pathname, entry = {}, tabsEntry = {}) return { pathname, workspacePathname: typeof entry.workspacePathname === 'string' ? entry.workspacePathname : '', + sourceWorkspacePathname: typeof entry.sourceWorkspacePathname === 'string' + ? entry.sourceWorkspacePathname + : (typeof entry.workspacePathname === 'string' ? entry.workspacePathname : ''), environment: { collection: collectionEnvironmentPath, global: typeof environment.global === 'string' ? environment.global : '' @@ -174,6 +177,9 @@ export const hydrateSnapshotLookups = (snapshot = {}) => { collectionsByPath[normalizedCollectionPathname] = { pathname: collection.pathname, workspacePathname: typeof collection.workspacePathname === 'string' ? collection.workspacePathname : '', + sourceWorkspacePathname: typeof collection.sourceWorkspacePathname === 'string' + ? collection.sourceWorkspacePathname + : (typeof collection.workspacePathname === 'string' ? collection.workspacePathname : ''), environment: collection.environment, environmentPath: collection.environmentPath, selectedEnvironment: collection.selectedEnvironment, @@ -191,6 +197,9 @@ export const hydrateSnapshotLookups = (snapshot = {}) => { collectionsByWorkspaceAndPath[workspaceCollectionKey] = { pathname: collection.pathname, workspacePathname: typeof collection.workspacePathname === 'string' ? collection.workspacePathname : '', + sourceWorkspacePathname: typeof collection.sourceWorkspacePathname === 'string' + ? collection.sourceWorkspacePathname + : (typeof collection.workspacePathname === 'string' ? collection.workspacePathname : ''), environment: collection.environment, environmentPath: collection.environmentPath, selectedEnvironment: collection.selectedEnvironment, @@ -320,6 +329,23 @@ const getTabsSnapshotFromLookups = ( }; }; +export const getCollectionSnapshotFromLookups = (collectionPathname, snapshotLookups = {}, workspacePathname = null) => { + const normalizedPathname = normalizePath(collectionPathname); + if (!normalizedPathname) { + return null; + } + + if (workspacePathname) { + const workspaceCollectionKey = getWorkspaceCollectionSnapshotKey(workspacePathname, collectionPathname); + const workspaceCollectionEntry = snapshotLookups?.collectionsByWorkspaceAndPath?.[workspaceCollectionKey]; + if (workspaceCollectionEntry) { + return workspaceCollectionEntry; + } + } + + return snapshotLookups?.collectionsByPath?.[normalizedPathname] || null; +}; + export const getCollectionEnvironmentPath = (collection, environment, defaultValue = null) => { if (!environment) { return defaultValue; diff --git a/packages/bruno-app/src/utils/snapshot/index.spec.js b/packages/bruno-app/src/utils/snapshot/index.spec.js index 04cb7f75082..0b44370bec5 100644 --- a/packages/bruno-app/src/utils/snapshot/index.spec.js +++ b/packages/bruno-app/src/utils/snapshot/index.spec.js @@ -16,7 +16,8 @@ const { hydrateSnapshotLookups, hydrateCollectionTabs, isActiveTab, - getActiveTabFromSnapshot + getActiveTabFromSnapshot, + getCollectionSnapshotFromLookups } = require('./index'); describe('hydrateSnapshotLookups', () => { @@ -177,10 +178,10 @@ describe('hydrateSnapshotLookups', () => { pathname: sharedCollectionPath, workspacePathname: workspaceAPath, environment: { - collection: '', + collection: 'env-a', global: '' }, - selectedEnvironment: '', + selectedEnvironment: 'env-a', isOpen: true, isMounted: false, activeTab: { accessor: 'pathname', value: '/collections/shared/ReqA' }, @@ -190,10 +191,10 @@ describe('hydrateSnapshotLookups', () => { pathname: sharedCollectionPath, workspacePathname: workspaceBPath, environment: { - collection: '', + collection: 'env-b', global: '' }, - selectedEnvironment: '', + selectedEnvironment: 'env-b', isOpen: true, isMounted: false, activeTab: { accessor: 'pathname', value: '/collections/shared/ReqB' }, @@ -217,6 +218,14 @@ describe('hydrateSnapshotLookups', () => { }); expect(lookups.hasWorkspaceScopedTabs).toBe(true); + + // Each workspace should resolve to its own selected environment for the shared collection. + expect(getCollectionSnapshotFromLookups(sharedCollectionPath, lookups, workspaceAPath)).toMatchObject({ + selectedEnvironment: 'env-a' + }); + expect(getCollectionSnapshotFromLookups(sharedCollectionPath, lookups, workspaceBPath)).toMatchObject({ + selectedEnvironment: 'env-b' + }); }); it('drops legacy v4 migration tabs from snapshot lookups', () => { diff --git a/packages/bruno-electron/src/app/collection-watcher.js b/packages/bruno-electron/src/app/collection-watcher.js index 217b6832c09..fd7c59ad848 100644 --- a/packages/bruno-electron/src/app/collection-watcher.js +++ b/packages/bruno-electron/src/app/collection-watcher.js @@ -674,15 +674,16 @@ const unlinkDir = async (win, pathname, collectionUid, collectionPath) => { } }; -const onWatcherSetupComplete = (win, watchPath, collectionUid, watcher) => { +const onWatcherSetupComplete = (win, watchPath, collectionUid, watcher, workspacePathname = null) => { // Mark discovery as complete watcher.completeCollectionDiscovery(win, collectionUid); - const collectionSnapshotState = snapshotManager.getCollection(watchPath); + const collectionSnapshotState = snapshotManager.getCollection(watchPath, workspacePathname); const hydratePayload = collectionSnapshotState ? { pathname: watchPath, + workspacePathname: workspacePathname || '', environmentPath: collectionSnapshotState?.environment?.collection || '', selectedEnvironment: collectionSnapshotState?.selectedEnvironment || '' } @@ -772,7 +773,7 @@ class CollectionWatcher { } // v2 already loaded the tree from cache; skip startup scan and stage live edits - const { ignoreInitial = false, fileIndex = null } = options; + const { ignoreInitial = false, fileIndex = null, workspacePathname = null } = options; if (fileIndex) { fileIndexByCollection.set(watchPath, fileIndex); } @@ -823,7 +824,7 @@ class CollectionWatcher { let startedNewWatcher = false; watcher - .on('ready', () => onWatcherSetupComplete(win, watchPath, collectionUid, this)) + .on('ready', () => onWatcherSetupComplete(win, watchPath, collectionUid, this, workspacePathname)) .on('add', (pathname) => add(win, pathname, collectionUid, watchPath, useWorkerThread, this)) .on('addDir', (pathname) => addDirectory(win, pathname, collectionUid, watchPath)) .on('change', (pathname) => change(win, pathname, collectionUid, watchPath)) diff --git a/packages/bruno-electron/src/ipc/collection.js b/packages/bruno-electron/src/ipc/collection.js index bc2b759c60d..0a86745b0c1 100644 --- a/packages/bruno-electron/src/ipc/collection.js +++ b/packages/bruno-electron/src/ipc/collection.js @@ -2149,7 +2149,7 @@ const registerRendererEventHandlers = (mainWindow, watcher) => { } }); - ipcMain.handle('renderer:mount-collection', async (event, { collectionUid, collectionPathname, brunoConfig }) => { + ipcMain.handle('renderer:mount-collection', async (event, { collectionUid, collectionPathname, brunoConfig, workspacePathname }) => { let tempDirectoryPath = null; try { // Ensure the transient base directory exists @@ -2176,7 +2176,7 @@ const registerRendererEventHandlers = (mainWindow, watcher) => { || (filesCount > MAX_COLLECTION_FILES_COUNT) || (maxFileSize > MAX_SINGLE_FILE_SIZE_IN_COLLECTION_IN_MB); - watcher.addWatcher(mainWindow, collectionPathname, collectionUid, brunoConfig, false, shouldLoadCollectionAsync); + watcher.addWatcher(mainWindow, collectionPathname, collectionUid, brunoConfig, false, shouldLoadCollectionAsync, { workspacePathname: workspacePathname || null }); // Add watcher for transient directory watcher.addTempDirectoryWatcher(mainWindow, tempDirectoryPath, collectionUid, collectionPathname); diff --git a/packages/bruno-electron/src/ipc/snapshot.js b/packages/bruno-electron/src/ipc/snapshot.js index d360e6fe75d..5ea442fabdc 100644 --- a/packages/bruno-electron/src/ipc/snapshot.js +++ b/packages/bruno-electron/src/ipc/snapshot.js @@ -10,6 +10,10 @@ const registerSnapshotIpc = () => { return snapshotManager.getTabs(collectionPathname, workspacePathname); }); + ipcMain.handle('renderer:snapshot:get-collection', async (event, collectionPathname, workspacePathname) => { + return snapshotManager.getCollection(collectionPathname, workspacePathname); + }); + ipcMain.on('internal:snapshot:reset', () => { try { snapshotManager.resetSnapshot(); diff --git a/packages/bruno-electron/src/services/snapshot/index.js b/packages/bruno-electron/src/services/snapshot/index.js index 543e9e6b3ac..c35d21fc733 100644 --- a/packages/bruno-electron/src/services/snapshot/index.js +++ b/packages/bruno-electron/src/services/snapshot/index.js @@ -55,6 +55,7 @@ const activeTabSchema = yup.object({ const collectionSchema = yup.object({ pathname: yup.string().required(), workspacePathname: yup.string().optional().default(''), + sourceWorkspacePathname: yup.string().optional().default(''), environment: yup.object({ collection: yup.string(), global: yup.string() @@ -124,14 +125,16 @@ class SnapshotManager { return this._normalizeSnapshot(this.store.store); } - getCollection(pathname) { + getCollection(pathname, workspacePathname = null) { const normalizedPath = normalizeLookupKey(pathname); if (!normalizedPath) { return null; } - const { collectionsByPath } = this._buildLookupMaps(); - const collection = collectionsByPath[normalizedPath]; + const { collectionsByPath, collectionsByWorkspaceAndPath } = this._buildLookupMaps(); + const workspaceCollectionKey = buildWorkspaceCollectionLookupKey(workspacePathname, pathname); + const collection = (workspaceCollectionKey && collectionsByWorkspaceAndPath[workspaceCollectionKey]) + || collectionsByPath[normalizedPath]; if (!collection) { return null; @@ -210,8 +213,23 @@ class SnapshotManager { return; } + const requestedWorkspacePathname = typeof data?.workspacePathname === 'string' + ? data.workspacePathname + : null; + const normalizedRequestedWorkspacePath = normalizeLookupKey(requestedWorkspacePathname || ''); + const snapshot = this._normalizeSnapshot(this.store.store); - const existingCollection = snapshot.collections.find((collection) => normalizeLookupKey(collection.pathname) === normalizedPath); + const existingCollection = snapshot.collections.find((collection) => { + if (normalizeLookupKey(collection.pathname) !== normalizedPath) { + return false; + } + + if (requestedWorkspacePathname === null) { + return true; + } + + return normalizeLookupKey(collection.workspacePathname || '') === normalizedRequestedWorkspacePath; + }); const mergedCollection = { ...(existingCollection || {}), @@ -223,11 +241,25 @@ class SnapshotManager { activeTab: data?.activeTab ?? existingCollection?.activeTab, tabs: data?.tabs ?? existingCollection?.tabs, environmentPath: data?.environmentPath ?? existingCollection?.environmentPath, - selectedEnvironment: data?.selectedEnvironment ?? existingCollection?.selectedEnvironment + selectedEnvironment: data?.selectedEnvironment ?? existingCollection?.selectedEnvironment, + sourceWorkspacePathname: data?.sourceWorkspacePathname + ?? existingCollection?.sourceWorkspacePathname + ?? data?.workspacePathname + ?? existingCollection?.workspacePathname }; const normalizedCollection = this._normalizeCollectionEntry(pathname, mergedCollection); - const collectionIndex = snapshot.collections.findIndex((collection) => normalizeLookupKey(collection.pathname) === normalizedPath); + const collectionIndex = snapshot.collections.findIndex((collection) => { + if (normalizeLookupKey(collection.pathname) !== normalizedPath) { + return false; + } + + if (requestedWorkspacePathname === null) { + return true; + } + + return normalizeLookupKey(collection.workspacePathname || '') === normalizedRequestedWorkspacePath; + }); if (collectionIndex === -1) { snapshot.collections.push(normalizedCollection); @@ -249,18 +281,30 @@ class SnapshotManager { } } - async updateCollectionEnvironment({ collectionPath, environmentPath, selectedEnvironment }) { + async updateCollectionEnvironment({ collectionPath, environmentPath, selectedEnvironment, workspacePathname = null }) { if (!collectionPath) { return; } - const existingCollection = this.getCollection(collectionPath) || {}; + const activeWorkspacePath = typeof this.store.store?.activeWorkspacePath === 'string' + ? this.store.store.activeWorkspacePath + : null; + const resolvedWorkspacePathname = typeof workspacePathname === 'string' && workspacePathname.length > 0 + ? workspacePathname + : activeWorkspacePath; + + const existingCollection = this.getCollection(collectionPath, resolvedWorkspacePathname) || {}; const existingEnvironment = isObject(existingCollection.environment) ? existingCollection.environment : {}; const incomingEnvironmentRef = environmentPath === undefined ? selectedEnvironment : environmentPath; const normalizedEnvironmentPath = await this._normalizeCollectionEnvironmentRefAsync(collectionPath, incomingEnvironmentRef); this.setCollection(collectionPath, { - workspacePathname: typeof existingCollection.workspacePathname === 'string' ? existingCollection.workspacePathname : '', + workspacePathname: typeof resolvedWorkspacePathname === 'string' + ? resolvedWorkspacePathname + : (typeof existingCollection.workspacePathname === 'string' ? existingCollection.workspacePathname : ''), + sourceWorkspacePathname: typeof existingCollection.sourceWorkspacePathname === 'string' + ? existingCollection.sourceWorkspacePathname + : (typeof resolvedWorkspacePathname === 'string' ? resolvedWorkspacePathname : ''), environment: { collection: normalizedEnvironmentPath, global: typeof existingEnvironment.global === 'string' ? existingEnvironment.global : '' @@ -454,6 +498,9 @@ class SnapshotManager { return { pathname, workspacePathname: typeof collection.workspacePathname === 'string' ? collection.workspacePathname : '', + sourceWorkspacePathname: typeof collection.sourceWorkspacePathname === 'string' + ? collection.sourceWorkspacePathname + : (typeof collection.workspacePathname === 'string' ? collection.workspacePathname : ''), environment: { collection: normalizedEnvironmentPath, global: typeof environment.global === 'string' ? environment.global : '' @@ -554,6 +601,7 @@ class SnapshotManager { const normalizedSnapshot = this._normalizeSnapshot(this.store.store); const workspacesByPath = {}; const collectionsByPath = {}; + const collectionsByWorkspaceAndPath = {}; const tabsByCollectionPath = {}; const tabsByWorkspaceAndCollectionPath = {}; @@ -580,6 +628,7 @@ class SnapshotManager { const workspaceCollectionKey = buildWorkspaceCollectionLookupKey(collection.workspacePathname, collection.pathname); if (workspaceCollectionKey) { + collectionsByWorkspaceAndPath[workspaceCollectionKey] = collection; tabsByWorkspaceAndCollectionPath[workspaceCollectionKey] = { activeTab: collection.activeTab, tabs: collection.tabs @@ -590,6 +639,7 @@ class SnapshotManager { this._lookupCache = { workspacesByPath, collectionsByPath, + collectionsByWorkspaceAndPath, tabsByCollectionPath, tabsByWorkspaceAndCollectionPath }; diff --git a/tests/snapshots/shared-collection-workspace-environment.spec.ts b/tests/snapshots/shared-collection-workspace-environment.spec.ts new file mode 100644 index 00000000000..47773ece735 --- /dev/null +++ b/tests/snapshots/shared-collection-workspace-environment.spec.ts @@ -0,0 +1,106 @@ +import path from 'path'; +import fs from 'fs'; +import { test, expect, closeElectronApp } from '../../playwright'; +import { + createRequest, + createEnvironment, + selectEnvironment, + openRequest, + openWorkspaceFromDialog, + waitForReadyPage, + openCollection +} from '../utils/page'; + +const buildWorkspaceYml = (workspaceName: string, collectionPath: string) => [ + 'opencollection: 1.0.0', + 'info:', + ` name: ${workspaceName}`, + ' type: workspace', + 'collections:', + ' - name: SharedCol', + ` path: ${collectionPath.replace(/\\/g, '/')}`, + 'specs: []', + 'docs: \'\'', + '' +].join('\n'); + +test.describe('Snapshot: Shared collection across workspaces restores its own environment', () => { + test('two workspaces sharing a collection each restore their own selected environment', async ({ + launchElectronApp, + createTmpDir + }) => { + const userDataPath = await createTmpDir('snap-shared-col-env-userdata'); + const workspaceAPath = await createTmpDir('snap-shared-col-env-ws-a'); + const workspaceBPath = await createTmpDir('snap-shared-col-env-ws-b'); + const sharedCollectionPath = await createTmpDir('snap-shared-col-env-collection'); + + fs.writeFileSync(path.join(sharedCollectionPath, 'bruno.json'), JSON.stringify({ version: '1', name: 'SharedCol', type: 'collection' }, null, 2)); + fs.writeFileSync(path.join(workspaceAPath, 'workspace.yml'), buildWorkspaceYml('Workspace A', sharedCollectionPath)); + fs.writeFileSync(path.join(workspaceBPath, 'workspace.yml'), buildWorkspaceYml('Workspace B', sharedCollectionPath)); + + const app = await launchElectronApp({ userDataPath }); + const page = await waitForReadyPage(app); + + await test.step('Open Workspace A, create request, and select env-a', async () => { + await openWorkspaceFromDialog(app, page, workspaceAPath); + await expect(page.getByTestId('workspace-name')).toHaveText('Workspace A', { timeout: 10000 }); + await openCollection(page, 'SharedCol'); + await createRequest(page, 'PingA', 'SharedCol', { url: 'https://echo.usebruno.com', method: 'GET' }); + await openRequest(page, 'SharedCol', 'PingA', { persist: true }); + + await createEnvironment(page, 'env-a'); + await selectEnvironment(page, 'env-a'); + await expect(page.locator('.current-environment')).toContainText('env-a'); + }); + + await test.step('Open Workspace B, select env-b for the same shared collection', async () => { + await openWorkspaceFromDialog(app, page, workspaceBPath); + await expect(page.getByTestId('workspace-name')).toHaveText('Workspace B', { timeout: 10000 }); + await openCollection(page, 'SharedCol'); + await openRequest(page, 'SharedCol', 'PingA'); + + await createEnvironment(page, 'env-b'); + await selectEnvironment(page, 'env-b'); + await expect(page.locator('.current-environment')).toContainText('env-b'); + }); + + await test.step('Switch back to Workspace A and verify env-a is still selected', async () => { + await page.getByTestId('workspace-menu').click(); + await page.locator('.workspace-item').filter({ hasText: 'Workspace A' }).click(); + await expect(page.getByTestId('workspace-name')).toHaveText('Workspace A', { timeout: 10000 }); + + await openRequest(page, 'SharedCol', 'PingA'); + await expect(page.locator('.current-environment')).toContainText('env-a', { timeout: 10000 }); + }); + + await test.step('Switch to Workspace B again and verify env-b is still selected', async () => { + await page.getByTestId('workspace-menu').click(); + await page.locator('.workspace-item').filter({ hasText: 'Workspace B' }).click(); + await expect(page.getByTestId('workspace-name')).toHaveText('Workspace B', { timeout: 10000 }); + + await openRequest(page, 'SharedCol', 'PingA'); + await expect(page.locator('.current-environment')).toContainText('env-b', { timeout: 10000 }); + }); + + await test.step('Close and relaunch app: both workspaces still restore their own environment', async () => { + await page.waitForTimeout(2000); + await closeElectronApp(app); + + const app2 = await launchElectronApp({ userDataPath }); + const page2 = await waitForReadyPage(app2); + + await expect(page2.getByTestId('workspace-name')).toHaveText('Workspace B', { timeout: 10000 }); + await openRequest(page2, 'SharedCol', 'PingA'); + await expect(page2.locator('.current-environment')).toContainText('env-b', { timeout: 10000 }); + + await page2.getByTestId('workspace-menu').click(); + await page2.locator('.workspace-item').filter({ hasText: 'Workspace A' }).click(); + await expect(page2.getByTestId('workspace-name')).toHaveText('Workspace A', { timeout: 10000 }); + + await openRequest(page2, 'SharedCol', 'PingA'); + await expect(page2.locator('.current-environment')).toContainText('env-a', { timeout: 10000 }); + + await closeElectronApp(app2); + }); + }); +}); diff --git a/tests/utils/page/actions.ts b/tests/utils/page/actions.ts index bd98f6997cb..a0a2be6e76c 100644 --- a/tests/utils/page/actions.ts +++ b/tests/utils/page/actions.ts @@ -91,7 +91,7 @@ const closeAllCollections = async (page) => { * @param collectionName - The name of the collection to open * @returns void */ -const openCollection = async (page, collectionName: string) => { +const openCollection = async (page: Page, collectionName: string) => { await test.step(`Open collection "${collectionName}"`, async () => { await page.locator('#sidebar-collection-name').filter({ hasText: collectionName }).click(); }); @@ -352,9 +352,14 @@ const createRequest = async ( await locators.sidebar.folder(parentName).hover(); await locators.actions.collectionItemActions(parentName).click(); } else { - await locators.sidebar.collection(parentName).hover(); + const collectionRow = locators.sidebar.collection(parentName); const collectionAction = locators.actions.collectionActions(parentName); - await expect(collectionAction).toBeVisible({ timeout: 2000 }); + // Re-hover on each poll: CSS `:hover` reveals `.collection-actions`, but sidebar + // re-renders (e.g. workspace snapshot hydration) can shift the row out from under a one-shot hover(). + await expect(async () => { + await collectionRow.hover(); + await expect(collectionAction).toBeVisible({ timeout: 1000 }); + }).toPass({ timeout: 10000 }); await collectionAction.click(); } @@ -693,22 +698,42 @@ const createEnvironment = async ( type: EnvironmentType = 'collection' ) => { await test.step(`Create ${type} environment "${environmentName}"`, async () => { + const locators = buildCommonLocators(page); await openEnvironmentSelector(page, type); - await page.locator('button[id="create-env"]').click(); + // Environment selector shows the create button only in empty state. + // If environments already exist, open settings and use the sidebar create action. + const canCreateFromSelectorEmptyState = await locators.environment.createEnvButton().isVisible().catch(() => false); - const nameInput = type === 'collection' - ? page.locator('input[name="name"]') - : page.locator('#environment-name'); - await expect(nameInput).toBeVisible(); - await nameInput.fill(environmentName); - await page.getByRole('button', { name: 'Create' }).click(); + if (canCreateFromSelectorEmptyState) { + await locators.environment.createEnvButton().click(); + + await expect(locators.environment.createModal()).toBeVisible(); + const nameInput = locators.environment.createModalNameInput(); + await expect(nameInput).toBeVisible(); + await nameInput.fill(environmentName); + await locators.environment.createModalCreateButton().click(); + } else { + await locators.environment.configureButton().waitFor({ state: 'visible' }); + await locators.environment.configureButton().dispatchEvent('click'); + + const envTab = type === 'global' + ? locators.environment.globalEnvTab() + : locators.environment.collectionEnvTab(); + await expect(envTab).toBeVisible(); + + await locators.environment.settingsCreateButton().click(); + + const inlineNameInput = locators.environment.settingsCreateNameInput(); + await expect(inlineNameInput).toBeVisible(); + await inlineNameInput.fill(environmentName); + await inlineNameInput.press('Enter'); + } const tabLabel = type === 'collection' ? 'Environments' : 'Global Environments'; await expect(page.locator('.request-tab').filter({ hasText: tabLabel })).toBeVisible(); - const locators = buildCommonLocators(page); - await page.waitForTimeout(200); // @TODO replace with dynamic waiting logic + await expect(locators.environment.selector()).toBeVisible(); await locators.environment.selector().click(); if (type === 'global') { await locators.environment.globalTab().click(); @@ -802,7 +827,7 @@ const deleteAllGlobalEnvironments = async (page: Page) => { const deleteBtn = page.locator('button[title="Delete"]'); const modal = page.locator('.bruno-modal').filter({ hasText: 'Delete Environment' }); - await page.locator('.environments-container').first().waitFor({ state: 'visible' }).catch(() => {}); + await page.locator('.environments-container').first().waitFor({ state: 'visible' }).catch(() => { }); while (true) { if ((await deleteBtn.count()) === 0) { @@ -2195,7 +2220,7 @@ const renameWsMessage = async (page: Page, index: number, name: string) => { */ const scrollVirtuosoRowIntoView = async (page: Page, target: Locator) => { if (await target.count()) { - await target.scrollIntoViewIfNeeded().catch(() => {}); + await target.scrollIntoViewIfNeeded().catch(() => { }); return; } @@ -2213,7 +2238,7 @@ const scrollVirtuosoRowIntoView = async (page: Page, target: Locator) => { await scroll(true); await page.waitForTimeout(120); if (await target.count()) { - await target.scrollIntoViewIfNeeded().catch(() => {}); + await target.scrollIntoViewIfNeeded().catch(() => { }); return; } } @@ -2223,7 +2248,7 @@ const scrollVirtuosoRowIntoView = async (page: Page, target: Locator) => { if (!(await scroll(false))) break; await page.waitForTimeout(120); } - await target.scrollIntoViewIfNeeded().catch(() => {}); + await target.scrollIntoViewIfNeeded().catch(() => { }); }; export { diff --git a/tests/utils/page/locators.ts b/tests/utils/page/locators.ts index 37d1bcc5f5c..9a3372c1c9b 100644 --- a/tests/utils/page/locators.ts +++ b/tests/utils/page/locators.ts @@ -101,6 +101,13 @@ export const buildCommonLocators = (page: Page) => ({ // matching on the wrapper is the only way to get the full concatenated text. variableValue: (name: string) => page.locator('tbody tr').filter({ has: page.locator(`input[value="${name}"]`) }).locator('.CodeMirror').first(), createEnvButton: () => page.locator('button[id="create-env"]'), + settingsCreateButton: () => + page.locator('.environments-container .sidebar button[title="Create environment"]'), + settingsCreateNameInput: () => page.locator('.environment-item.creating .environment-name-input'), + settingsCreateSaveButton: () => page.locator('.environment-item.creating .inline-action-btn.save'), + createModal: () => page.locator('.bruno-modal').filter({ hasText: /Create( Global)? Environment/ }), + createModalNameInput: () => page.locator('.bruno-modal #environment-name'), + createModalCreateButton: () => page.locator('.bruno-modal').getByRole('button', { name: 'Create', exact: true }), envNameInput: () => page.locator('input[name="name"]'), // Variables and secrets each live on their own tab in the environment editor. variablesTab: () => page.getByTestId('responsive-tab-variables'), From 5ab45a0140083c15d9d72930b2961a8ed2b3761c Mon Sep 17 00:00:00 2001 From: Sid Date: Fri, 3 Jul 2026 14:10:28 +0530 Subject: [PATCH 08/11] feat(snapshot): remove sourceWorkspacePathname from snapshot serialization and related tests --- .../ReduxStore/middlewares/snapshot/serializeSnapshot.js | 3 --- .../middlewares/snapshot/serializeSnapshot.spec.js | 5 ----- packages/bruno-app/src/utils/snapshot/index.js | 9 --------- packages/bruno-electron/src/services/snapshot/index.js | 1 - 4 files changed, 18 deletions(-) diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js index 0db6a0f1617..ace64c696e4 100644 --- a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js +++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js @@ -211,7 +211,6 @@ export const serializeSnapshot = async (state, options = {}) => { snapshot.collections.push({ pathname: collection.pathname, workspacePathname, - sourceWorkspacePathname: workspacePathname, environment: { collection: environmentPath, global: globalEnvironments.activeGlobalEnvironmentUid || '' @@ -235,7 +234,6 @@ export const serializeSnapshot = async (state, options = {}) => { (existingCollections.length > 0 ? existingCollections : fallbackCollections).forEach((existingCollection) => { const normalizedPath = normalizePath(existingCollection.pathname || ''); const workspacePathname = existingCollection.workspacePathname || ''; - const sourceWorkspacePathname = existingCollection.sourceWorkspacePathname || workspacePathname; const collectionSnapshotKey = getWorkspaceCollectionSnapshotKey(workspacePathname, existingCollection.pathname); const isSerializedCollection = collectionSnapshotKey && serializedCollectionKeys.has(collectionSnapshotKey); const shouldPreservePendingHydration = pendingHydrationPaths.has(normalizedPath) @@ -252,7 +250,6 @@ export const serializeSnapshot = async (state, options = {}) => { snapshot.collections.push({ pathname: existingCollection.pathname, workspacePathname, - sourceWorkspacePathname, environment: { collection: existingCollection.environment?.collection || existingCollection.environmentPath || '', global: existingCollection.environment?.global || '' diff --git a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js index b71944f8d2e..74bb3ead165 100644 --- a/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js +++ b/packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js @@ -23,7 +23,6 @@ const makeExistingSnapshot = () => ({ { pathname: COLLECTION_PATH, workspacePathname: WORKSPACE_PATH, - sourceWorkspacePathname: WORKSPACE_PATH, environment: { collection: ENVIRONMENT_PATH, global: '' @@ -154,7 +153,6 @@ describe('serializeSnapshot collection environment preservation', () => { expect(snapshot.collections[0]).toMatchObject({ pathname: COLLECTION_PATH, workspacePathname: WORKSPACE_PATH, - sourceWorkspacePathname: WORKSPACE_PATH, environmentPath: ENVIRONMENT_PATH, selectedEnvironment: 'local', environment: { @@ -171,7 +169,6 @@ describe('serializeSnapshot collection environment preservation', () => { ); expect(snapshot.collections[0]).toMatchObject({ - sourceWorkspacePathname: WORKSPACE_PATH, environmentPath: ENVIRONMENT_PATH, selectedEnvironment: 'local' }); @@ -194,7 +191,6 @@ describe('serializeSnapshot collection environment preservation', () => { ); expect(snapshot.collections[0]).toMatchObject({ - sourceWorkspacePathname: WORKSPACE_PATH, environmentPath: '/tmp/workspace/collections/api/environments/staging.yml', selectedEnvironment: 'staging' }); @@ -217,7 +213,6 @@ describe('serializeSnapshot collection environment preservation', () => { ); expect(snapshot.collections[0]).toMatchObject({ - sourceWorkspacePathname: WORKSPACE_PATH, environmentPath: '', selectedEnvironment: '' }); diff --git a/packages/bruno-app/src/utils/snapshot/index.js b/packages/bruno-app/src/utils/snapshot/index.js index 79ab25044c3..8a8a9cd77a3 100644 --- a/packages/bruno-app/src/utils/snapshot/index.js +++ b/packages/bruno-app/src/utils/snapshot/index.js @@ -119,9 +119,6 @@ const normalizeCollectionSnapshotEntry = (pathname, entry = {}, tabsEntry = {}) return { pathname, workspacePathname: typeof entry.workspacePathname === 'string' ? entry.workspacePathname : '', - sourceWorkspacePathname: typeof entry.sourceWorkspacePathname === 'string' - ? entry.sourceWorkspacePathname - : (typeof entry.workspacePathname === 'string' ? entry.workspacePathname : ''), environment: { collection: collectionEnvironmentPath, global: typeof environment.global === 'string' ? environment.global : '' @@ -177,9 +174,6 @@ export const hydrateSnapshotLookups = (snapshot = {}) => { collectionsByPath[normalizedCollectionPathname] = { pathname: collection.pathname, workspacePathname: typeof collection.workspacePathname === 'string' ? collection.workspacePathname : '', - sourceWorkspacePathname: typeof collection.sourceWorkspacePathname === 'string' - ? collection.sourceWorkspacePathname - : (typeof collection.workspacePathname === 'string' ? collection.workspacePathname : ''), environment: collection.environment, environmentPath: collection.environmentPath, selectedEnvironment: collection.selectedEnvironment, @@ -197,9 +191,6 @@ export const hydrateSnapshotLookups = (snapshot = {}) => { collectionsByWorkspaceAndPath[workspaceCollectionKey] = { pathname: collection.pathname, workspacePathname: typeof collection.workspacePathname === 'string' ? collection.workspacePathname : '', - sourceWorkspacePathname: typeof collection.sourceWorkspacePathname === 'string' - ? collection.sourceWorkspacePathname - : (typeof collection.workspacePathname === 'string' ? collection.workspacePathname : ''), environment: collection.environment, environmentPath: collection.environmentPath, selectedEnvironment: collection.selectedEnvironment, diff --git a/packages/bruno-electron/src/services/snapshot/index.js b/packages/bruno-electron/src/services/snapshot/index.js index c35d21fc733..49c24d90b9d 100644 --- a/packages/bruno-electron/src/services/snapshot/index.js +++ b/packages/bruno-electron/src/services/snapshot/index.js @@ -55,7 +55,6 @@ const activeTabSchema = yup.object({ const collectionSchema = yup.object({ pathname: yup.string().required(), workspacePathname: yup.string().optional().default(''), - sourceWorkspacePathname: yup.string().optional().default(''), environment: yup.object({ collection: yup.string(), global: yup.string() From c8e5205b143495ed5caecb41722e91c2cea0c39e Mon Sep 17 00:00:00 2001 From: Sid Date: Fri, 3 Jul 2026 14:15:18 +0530 Subject: [PATCH 09/11] feat(snapshot): remove sourceWorkspacePathname from SnapshotManager and add tests for shared collection environment restoration --- .../bruno-electron/src/services/snapshot/index.js | 12 +----------- .../shared-collection-workspace-environment.spec.ts | 4 ++-- 2 files changed, 3 insertions(+), 13 deletions(-) rename tests/snapshots/{ => environment}/shared-collection-workspace-environment.spec.ts (98%) diff --git a/packages/bruno-electron/src/services/snapshot/index.js b/packages/bruno-electron/src/services/snapshot/index.js index 49c24d90b9d..8cac57a7ee0 100644 --- a/packages/bruno-electron/src/services/snapshot/index.js +++ b/packages/bruno-electron/src/services/snapshot/index.js @@ -240,11 +240,7 @@ class SnapshotManager { activeTab: data?.activeTab ?? existingCollection?.activeTab, tabs: data?.tabs ?? existingCollection?.tabs, environmentPath: data?.environmentPath ?? existingCollection?.environmentPath, - selectedEnvironment: data?.selectedEnvironment ?? existingCollection?.selectedEnvironment, - sourceWorkspacePathname: data?.sourceWorkspacePathname - ?? existingCollection?.sourceWorkspacePathname - ?? data?.workspacePathname - ?? existingCollection?.workspacePathname + selectedEnvironment: data?.selectedEnvironment ?? existingCollection?.selectedEnvironment }; const normalizedCollection = this._normalizeCollectionEntry(pathname, mergedCollection); @@ -301,9 +297,6 @@ class SnapshotManager { workspacePathname: typeof resolvedWorkspacePathname === 'string' ? resolvedWorkspacePathname : (typeof existingCollection.workspacePathname === 'string' ? existingCollection.workspacePathname : ''), - sourceWorkspacePathname: typeof existingCollection.sourceWorkspacePathname === 'string' - ? existingCollection.sourceWorkspacePathname - : (typeof resolvedWorkspacePathname === 'string' ? resolvedWorkspacePathname : ''), environment: { collection: normalizedEnvironmentPath, global: typeof existingEnvironment.global === 'string' ? existingEnvironment.global : '' @@ -497,9 +490,6 @@ class SnapshotManager { return { pathname, workspacePathname: typeof collection.workspacePathname === 'string' ? collection.workspacePathname : '', - sourceWorkspacePathname: typeof collection.sourceWorkspacePathname === 'string' - ? collection.sourceWorkspacePathname - : (typeof collection.workspacePathname === 'string' ? collection.workspacePathname : ''), environment: { collection: normalizedEnvironmentPath, global: typeof environment.global === 'string' ? environment.global : '' diff --git a/tests/snapshots/shared-collection-workspace-environment.spec.ts b/tests/snapshots/environment/shared-collection-workspace-environment.spec.ts similarity index 98% rename from tests/snapshots/shared-collection-workspace-environment.spec.ts rename to tests/snapshots/environment/shared-collection-workspace-environment.spec.ts index 47773ece735..dfa99546be0 100644 --- a/tests/snapshots/shared-collection-workspace-environment.spec.ts +++ b/tests/snapshots/environment/shared-collection-workspace-environment.spec.ts @@ -1,6 +1,6 @@ import path from 'path'; import fs from 'fs'; -import { test, expect, closeElectronApp } from '../../playwright'; +import { test, expect, closeElectronApp } from '../../../playwright'; import { createRequest, createEnvironment, @@ -9,7 +9,7 @@ import { openWorkspaceFromDialog, waitForReadyPage, openCollection -} from '../utils/page'; +} from '../../utils/page'; const buildWorkspaceYml = (workspaceName: string, collectionPath: string) => [ 'opencollection: 1.0.0', From e9399d3dc2c6527606db8b2a6689ce6536c259e0 Mon Sep 17 00:00:00 2001 From: Sid Date: Fri, 3 Jul 2026 14:32:50 +0530 Subject: [PATCH 10/11] feat(snapshot): refactor collection deduplication tests and enhance snapshot seeding utility --- tests/snapshots/collection-dedup.spec.ts | 154 +++++++++++------- .../snapshots/environment/environment.spec.ts | 2 +- tests/utils/snapshot.ts | 33 +++- 3 files changed, 129 insertions(+), 60 deletions(-) diff --git a/tests/snapshots/collection-dedup.spec.ts b/tests/snapshots/collection-dedup.spec.ts index 8f6cbbc768e..ab62e2d72b2 100644 --- a/tests/snapshots/collection-dedup.spec.ts +++ b/tests/snapshots/collection-dedup.spec.ts @@ -2,63 +2,7 @@ import path from 'path'; import fs from 'fs'; import { test, expect, closeElectronApp } from '../../playwright'; import { waitForReadyPage } from '../utils/page'; -import { readSnapshot, getSnapshotPath, findSnapshotCollectionEntry } from '../utils/snapshot'; - -const seedSnapshotWithDuplicateCollection = (userDataPath: string, collectionPath: string) => { - fs.writeFileSync( - getSnapshotPath(userDataPath), - JSON.stringify( - { - version: '0.0.1', - activeWorkspacePath: null, - extras: { - devTools: { - open: false - } - }, - workspaces: [], - collections: [ - // Older entry: has a selected environment and an open tab, but is not marked open/mounted. - { - pathname: collectionPath, - workspacePathname: '', - environment: { - collection: 'local.yml', - global: '' - }, - environmentPath: 'local.yml', - selectedEnvironment: 'local', - isOpen: false, - isMounted: false, - activeTab: { - accessor: 'pathname', - value: path.join(collectionPath, 'ReqAlpha.bru') - }, - tabs: [ - { - type: 'http-request', - accessor: 'pathname', - pathname: path.join(collectionPath, 'ReqAlpha.bru'), - permanent: true - } - ] - }, - // Newer entry: same pathname, marks the collection open/mounted but omits the environment/tabs - // that the older entry had set. The newer entry should win on the fields it specifies, - // while fields it leaves unspecified should fall back to the older entry. - { - pathname: collectionPath, - workspacePathname: '', - isOpen: true, - isMounted: true - } - ] - }, - null, - 2 - ) - ); -}; +import { readSnapshot, findSnapshotCollectionEntry, seedSnapshotWithCollections } from '../utils/snapshot'; test.describe('Snapshot: Collection Deduplication', () => { test('duplicate collection entries for the same pathname are deduplicated, with the latest entry taking precedence', async ({ launchElectronApp, createTmpDir }) => { @@ -67,7 +11,42 @@ test.describe('Snapshot: Collection Deduplication', () => { fs.writeFileSync(path.join(colPath, 'bruno.json'), JSON.stringify({ version: '1', name: 'TestCol', type: 'collection' }, null, 2)); - seedSnapshotWithDuplicateCollection(userDataPath, colPath); + seedSnapshotWithCollections(userDataPath, [ + // Older entry: has a selected environment and an open tab, but is not marked open/mounted. + { + pathname: colPath, + workspacePathname: '', + environment: { + collection: 'local.yml', + global: '' + }, + environmentPath: 'local.yml', + selectedEnvironment: 'local', + isOpen: false, + isMounted: false, + activeTab: { + accessor: 'pathname', + value: path.join(colPath, 'ReqAlpha.bru') + }, + tabs: [ + { + type: 'http-request', + accessor: 'pathname', + pathname: path.join(colPath, 'ReqAlpha.bru'), + permanent: true + } + ] + }, + // Newer entry: same pathname, marks the collection open/mounted but omits the environment/tabs + // that the older entry had set. The newer entry should win on the fields it specifies, + // while fields it leaves unspecified should fall back to the older entry. + { + pathname: colPath, + workspacePathname: '', + isOpen: true, + isMounted: true + } + ]); await test.step('Assert seeded snapshot has two entries for the same collection before launch', () => { const snapshot = readSnapshot(userDataPath); @@ -101,4 +80,63 @@ test.describe('Snapshot: Collection Deduplication', () => { expect(entry.tabs[0].pathname).toBe(path.join(colPath, 'ReqAlpha.bru')); }); }); + + test('collection entries with the same pathname but different workspacePathname are not deduplicated', async ({ launchElectronApp, createTmpDir }) => { + const userDataPath = await createTmpDir('snap-collection-dedup-diff-workspace'); + const colPath = await createTmpDir('col'); + const workspaceAPath = await createTmpDir('workspace-a'); + const workspaceBPath = await createTmpDir('workspace-b'); + + fs.writeFileSync(path.join(colPath, 'bruno.json'), JSON.stringify({ version: '1', name: 'TestCol', type: 'collection' }, null, 2)); + + seedSnapshotWithCollections( + userDataPath, + [ + // Same collection pathname, but scoped to workspace A. + { + pathname: colPath, + workspacePathname: workspaceAPath, + isOpen: true, + isMounted: true + }, + // Same collection pathname, but scoped to workspace B. Distinct entry since the + // workspacePathname differs - it should NOT be merged/removed by dedup. + { + pathname: colPath, + workspacePathname: workspaceBPath, + isOpen: false, + isMounted: false + } + ], + { workspaces: [{ pathname: workspaceAPath }, { pathname: workspaceBPath }] } + ); + + await test.step('Assert seeded snapshot has two entries for the same collection pathname before launch', () => { + const snapshot = readSnapshot(userDataPath); + const entries = snapshot.collections.filter((c: any) => path.normalize(c.pathname) === path.normalize(colPath)); + expect(entries).toHaveLength(2); + }); + + const app = await launchElectronApp({ userDataPath }); + const page = await waitForReadyPage(app); + + await expect(page.getByTestId('workspace-name')).toBeVisible({ timeout: 10000 }); + + await test.step('Close app and verify both workspace-scoped entries are preserved', async () => { + await page.waitForTimeout(2000); + await closeElectronApp(app); + + const snapshot = readSnapshot(userDataPath); + const entries = snapshot.collections.filter((c: any) => path.normalize(c.pathname) === path.normalize(colPath)); + expect(entries).toHaveLength(2); + + const entryA = findSnapshotCollectionEntry(snapshot, colPath, workspaceAPath); + const entryB = findSnapshotCollectionEntry(snapshot, colPath, workspaceBPath); + + expect(entryA).not.toBeNull(); + expect(entryB).not.toBeNull(); + expect(entryA.isOpen).toBe(true); + expect(entryB.isOpen).toBe(false); + }); + }); }); diff --git a/tests/snapshots/environment/environment.spec.ts b/tests/snapshots/environment/environment.spec.ts index 0ecf9b1d06a..ab80ad9bf7f 100644 --- a/tests/snapshots/environment/environment.spec.ts +++ b/tests/snapshots/environment/environment.spec.ts @@ -315,7 +315,7 @@ test.describe('Snapshot: Collection Environment Persistence', () => { const app2 = await launchElectronApp({ userDataPath }); const page2 = await waitForReadyPage(app2); await openCollection(page2, 'Collection Missing Env'); - await expect(page2.locator('.current-environment')).toContainText('local-missing'); + await expect(page2.locator('.current-environment')).toContainText('No Environment'); await page2.waitForTimeout(2000); await closeElectronApp(app2); diff --git a/tests/utils/snapshot.ts b/tests/utils/snapshot.ts index 0cc3d927744..e78e72d4d4d 100644 --- a/tests/utils/snapshot.ts +++ b/tests/utils/snapshot.ts @@ -5,6 +5,36 @@ import { expect } from '../../playwright'; export const getSnapshotPath = (userDataPath: string) => path.join(userDataPath, 'ui-state-snapshot.json'); +/** + * Write a snapshot file seeded with the given collection entries (and, optionally, + * workspace entries). Useful for asserting on snapshot normalization/dedup behavior + * that runs on app launch. + */ +export const seedSnapshotWithCollections = ( + userDataPath: string, + collections: any[], + options: { workspaces?: any[] } = {} +) => { + fs.writeFileSync( + getSnapshotPath(userDataPath), + JSON.stringify( + { + version: '0.0.1', + activeWorkspacePath: null, + extras: { + devTools: { + open: false + } + }, + workspaces: options.workspaces ?? [], + collections + }, + null, + 2 + ) + ); +}; + /** * Read the snapshot JSON from the user data directory. * electron-store saves it as `ui-state-snapshot.json`. @@ -42,7 +72,7 @@ export const findSnapshotCollectionTab = (snapshot: any, collectionPath: string) return null; }; -export const findSnapshotCollectionEntry = (snapshot: any, collectionPath: string) => { +export const findSnapshotCollectionEntry = (snapshot: any, collectionPath: string, workspacePathname?: string) => { if (!snapshot || !Array.isArray(snapshot.collections)) { return null; } @@ -51,6 +81,7 @@ export const findSnapshotCollectionEntry = (snapshot: any, collectionPath: strin return snapshot.collections.find( (collection: any) => typeof collection?.pathname === 'string' && path.normalize(collection.pathname) === normalizedTarget + && (workspacePathname === undefined || (collection?.workspacePathname ?? '') === workspacePathname) ) || null; }; From 2c34323a5b8f949ac501a78993df0e1c9660c3aa Mon Sep 17 00:00:00 2001 From: Sid Date: Fri, 3 Jul 2026 15:03:29 +0530 Subject: [PATCH 11/11] feat(snapshot): enhance workspace path normalization and improve snapshot environment tests --- .../src/services/snapshot/index.js | 2 +- .../src/utils/workspace-startup.js | 5 ++-- .../snapshots/environment/environment.spec.ts | 23 +++++++++---------- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/bruno-electron/src/services/snapshot/index.js b/packages/bruno-electron/src/services/snapshot/index.js index 8cac57a7ee0..ee1c8836153 100644 --- a/packages/bruno-electron/src/services/snapshot/index.js +++ b/packages/bruno-electron/src/services/snapshot/index.js @@ -327,7 +327,7 @@ class SnapshotManager { 'performance', 'terminal' ]; - const devToolTabs = devTools.tabs || {}; + const devToolTabs = isObject(devTools.tabs) ? devTools.tabs : {}; const _snapshotEntry = { open: typeof devTools?.open === 'boolean' ? devTools.open : false, diff --git a/packages/bruno-electron/src/utils/workspace-startup.js b/packages/bruno-electron/src/utils/workspace-startup.js index 693e0f39001..3a1392c304d 100644 --- a/packages/bruno-electron/src/utils/workspace-startup.js +++ b/packages/bruno-electron/src/utils/workspace-startup.js @@ -61,10 +61,11 @@ const resolveLastOpenedWorkspacePaths = (lastOpenedWorkspaces, { } = {}) => { const workspacePaths = lastOpenedWorkspaces.getAll(); const activeWorkspacePath = snapshotManager.getSnapshot()?.activeWorkspacePath; + const normalizedDefaultWorkspacePath = defaultWorkspacePath ? normalizeWorkspacePathname(defaultWorkspacePath) : null; const validWorkspaces = []; const invalidPaths = []; for (const workspacePath of workspacePaths) { - if (defaultWorkspacePath && workspacePath === defaultWorkspacePath) { + if (normalizedDefaultWorkspacePath && normalizeWorkspacePathname(workspacePath) === normalizedDefaultWorkspacePath) { continue; } @@ -86,7 +87,7 @@ const resolveLastOpenedWorkspacePaths = (lastOpenedWorkspaces, { if ( !alreadyIncluded && normalizedActivePath - && (!defaultWorkspacePath || activeWorkspacePath !== defaultWorkspacePath) + && (!normalizedDefaultWorkspacePath || normalizedActivePath !== normalizedDefaultWorkspacePath) && isValidWorkspacePathOnDisk(activeWorkspacePath, { validateConfig }) ) { prioritizedWorkspaces.unshift(activeWorkspacePath); diff --git a/tests/snapshots/environment/environment.spec.ts b/tests/snapshots/environment/environment.spec.ts index ab80ad9bf7f..cdc70837d9e 100644 --- a/tests/snapshots/environment/environment.spec.ts +++ b/tests/snapshots/environment/environment.spec.ts @@ -125,13 +125,13 @@ test.describe('Snapshot: Collection Environment Persistence', () => { await expect(page2.locator('.current-environment')).toContainText('local-a'); // Wait for debounced snapshot save to flush to verify the snapshot isn't overwritten by the next save - await page2.waitForTimeout(2000); + await waitForSnapshotCollectionEnvironment(userDataPath, firstCollectionRoot, 'local-a'); await openCollection(page2, 'Collection B'); await expect(page2.locator('.current-environment')).toContainText('local-b'); // Wait for debounced snapshot save to flush to verify the snapshot isn't overwritten by the next save - await page2.waitForTimeout(2000); + await waitForSnapshotCollectionEnvironment(userDataPath, secondCollectionRoot, 'local-b'); await closeElectronApp(app2); }); @@ -264,25 +264,24 @@ test.describe('Snapshot: Collection Environment Persistence', () => { await openCollection(page2, 'Collection A'); await expect(page2.locator('.current-environment')).toContainText('local-a', { timeout: 15000 }); - await page2.waitForTimeout(2000); + await waitForSnapshotCollectionEnvironment(userDataPath, firstCollectionRoot, 'local-a'); await openCollection(page2, 'Collection B'); await expect(page2.locator('.current-environment')).toContainText('local-b', { timeout: 15000 }); - await page2.waitForTimeout(2000); + await waitForSnapshotCollectionEnvironment(userDataPath, secondCollectionRoot, 'local-b'); await openCollection(page2, 'Collection C'); await expect(page2.locator('.current-environment')).toContainText('local-c', { timeout: 15000 }); - await page2.waitForTimeout(2000); + await waitForSnapshotCollectionEnvironment(userDataPath, thirdCollectionRoot, 'local-c'); await closeElectronApp(app2); const updatedSnapshot = readSnapshot(userDataPath); expect(updatedSnapshot).not.toBeNull(); - const updatedCollections = Array.isArray(updatedSnapshot?.collections) ? updatedSnapshot.collections : []; - const firstUpdatedEntry = updatedCollections.find((collection: any) => collection?.pathname === firstCollectionRoot); - const secondUpdatedEntry = updatedCollections.find((collection: any) => collection?.pathname === secondCollectionRoot); - const thirdUpdatedEntry = updatedCollections.find((collection: any) => collection?.pathname === thirdCollectionRoot); + const firstUpdatedEntry = findSnapshotCollectionEntry(updatedSnapshot, firstCollectionRoot); + const secondUpdatedEntry = findSnapshotCollectionEntry(updatedSnapshot, secondCollectionRoot); + const thirdUpdatedEntry = findSnapshotCollectionEntry(updatedSnapshot, thirdCollectionRoot); expect(firstUpdatedEntry?.selectedEnvironment).toBe('local-a'); expect(secondUpdatedEntry?.selectedEnvironment).toBe('local-b'); @@ -316,7 +315,7 @@ test.describe('Snapshot: Collection Environment Persistence', () => { const page2 = await waitForReadyPage(app2); await openCollection(page2, 'Collection Missing Env'); await expect(page2.locator('.current-environment')).toContainText('No Environment'); - await page2.waitForTimeout(2000); + await waitForSnapshotCollectionEnvironment(userDataPath, collectionRoot, 'local-missing'); await closeElectronApp(app2); const snapshot = readSnapshot(userDataPath); @@ -341,7 +340,7 @@ test.describe('Snapshot: Collection Environment Persistence', () => { await closeElectronApp(app); const initialSnapshot = readSnapshot(userDataPath); - const initialEntry = initialSnapshot?.collections?.find((collection: any) => collection?.pathname === collectionRoot); + const initialEntry = findSnapshotCollectionEntry(initialSnapshot, collectionRoot); const envFilePath = initialEntry?.environmentPath || initialEntry?.environment?.collection; expect(envFilePath).toBeTruthy(); expect(fs.existsSync(envFilePath)).toBe(true); @@ -351,7 +350,7 @@ test.describe('Snapshot: Collection Environment Persistence', () => { const page2 = await waitForReadyPage(app2); await openCollection(page2, 'Collection Bad Env'); await expect(page2.locator('.current-environment')).toContainText('local-bad'); - await page2.waitForTimeout(2000); + await waitForSnapshotCollectionEnvironment(userDataPath, collectionRoot, 'local-bad'); await closeElectronApp(app2); const snapshot = readSnapshot(userDataPath);