Repository navigation
feat: ui state snapshots - #7794
Conversation
- Add snapshot middleware to persist UI state (tabs, workspaces, environments) - Add SnapshotManager service in electron for atomic snapshot storage - Add accessor-based tab serialization using pathname for reliable restoration - Add loading states for tabs while collections are mounting - Add hydrateTabs to restore tabs from snapshots on app load - Add devTools state persistence (console open/height/tab)
Make serializeSnapshot async to fetch existing snapshot before saving, ensuring collections not currently loaded in Redux are preserved. Fix activeTab serialization to pass collection object instead of just UID.
… IPC Replace array-based snapshot storage with key-value maps keyed by pathname for O(1) lookups. Separate tabs into their own top-level map, decoupled from collections. - Rewrite SnapshotManager with map-based schema and granular read/write methods (getWorkspace, getTabs, setCollection, removeWorkspace, etc.) - Add 12 granular IPC handlers (renderer:snapshot:*) replacing 4 coarse ones - Update middleware serialization to produce maps; remove activeCollectionUidCache in favor of lastActiveCollectionPathname on workspace objects - Fix mountCollection passing collectionUid instead of collection to restoreTabs - Preserve non-active workspace state from existing snapshot on save
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds end-to-end UI snapshot persistence: new SnapshotManager service and IPC handlers, snapshot utilities, Redux snapshot middleware and slice changes, UI loading/fallbacks, tab payload enhancements (pathname/exampleName), and tests for snapshot hydration and persistence. Changes
Sequence Diagram(s)sequenceDiagram
participant App as Frontend App
participant Redux as Redux Store
participant Middleware as Snapshot Middleware
participant IPC as Electron IPC
participant SnapshotMgr as SnapshotManager
participant Store as electron-store
App->>Redux: dispatch(action)
activate Redux
Redux->>Redux: reduce state
deactivate Redux
Redux->>Middleware: middleware intercepts action
activate Middleware
alt action in SAVE_TRIGGERS && state.app.snapshotReady
Middleware->>Middleware: debounce serializeSnapshot(state)
Middleware->>IPC: ipcRenderer.invoke('renderer:snapshot:save', data)
end
deactivate Middleware
IPC->>SnapshotMgr: snapshotManager.saveSnapshot(data)
activate SnapshotMgr
SnapshotMgr->>SnapshotMgr: normalize & validate
SnapshotMgr->>Store: store.set('ui-state-snapshot', snapshot)
Store-->>SnapshotMgr: persisted
deactivate SnapshotMgr
IPC-->>Middleware: result
sequenceDiagram
participant User as User
participant Panel as RequestTabPanel
participant Redux as Redux (collection state)
participant Utils as snapshot utils
participant IPC as Electron IPC
User->>Panel: open tab (uid or pathname)
activate Panel
Panel->>Redux: find item by uid
alt item found
Panel->>Panel: render item UI
else not found
Panel->>Redux: check collection.mountStatus / areItemsLoading
alt collection mounting && displayName exists
Panel->>Panel: render RequestTabPanelLoading
Panel->>Utils: optionally request snapshot tabs
Utils->>IPC: ipcRenderer.invoke('renderer:snapshot:get-tabs', collectionPath)
IPC-->>Utils: snapshot tabs
Utils-->>Panel: resolved tab state
else collection ready
Panel->>Panel: render NotFound / ExampleNotFound / FolderNotFound
end
end
deactivate Panel
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
Adds a new UI state snapshot pipeline to persist/restore workspace, collection, tab, and DevTools state across app restarts, including migrations from the legacy collection-array snapshot format.
Changes:
- Introduces an Electron-side
SnapshotManager(electron-store + yup schema) and IPC surface for snapshot read/write. - Adds a renderer snapshot middleware + snapshot (de)serialization helpers to persist/restore tabs, workspace selection, collection state, environments, and DevTools state.
- Updates UI/tab rendering to support pathname/exampleName-based restoration with loading placeholders, and adds Playwright coverage for snapshot persistence.
Reviewed changes
Copilot reviewed 26 out of 26 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/workspace/snapshot-persistence.spec.ts | Adds end-to-end coverage for snapshot persistence/restoration scenarios. |
| packages/bruno-electron/src/store/ui-state-snapshot.js | Removes legacy UI snapshot store implementation. |
| packages/bruno-electron/src/services/snapshot/index.js | Adds centralized snapshot manager with schema validation + legacy migration. |
| packages/bruno-electron/src/ipc/snapshot.js | Adds IPC handlers for snapshot CRUD operations. |
| packages/bruno-electron/src/ipc/collection.js | Routes snapshot updates through the new snapshot manager. |
| packages/bruno-electron/src/index.js | Registers snapshot IPC on app startup. |
| packages/bruno-electron/src/app/collection-watcher.js | Hydrates renderer with snapshot-derived collection environment info. |
| packages/bruno-app/src/utils/snapshot/index.js | Adds snapshot serialization/deserialization + hydration helpers. |
| packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js | Restores workspace/collection/tab/devtools state on workspace load/switch; gates saving via snapshotReady. |
| packages/bruno-app/src/providers/ReduxStore/slices/tabs.js | Adds pathname/exampleName support, tab restoration, and example UID syncing. |
| packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js | Adds expandCollection, persists environment pathname, updates snapshot payload shape. |
| packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js | Persists env selection via environment path; hydrates tabs after mount. |
| packages/bruno-app/src/providers/ReduxStore/slices/app.js | Adds snapshotReady flag and setter action. |
| packages/bruno-app/src/providers/ReduxStore/middlewares/tasks/middleware.js | Updates example-tab opening to include pathname/exampleName. |
| packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js | Adds debounced snapshot persistence middleware. |
| packages/bruno-app/src/providers/ReduxStore/index.js | Registers snapshot middleware. |
| packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.js | Ensures opened tabs include type + pathname for restoration. |
| packages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/ExampleItem/index.js | Ensures example tabs include pathname + exampleName. |
| packages/bruno-app/src/components/RequestTabs/RequestTab/index.js | Adds pathname fallback lookup and loading placeholder handling. |
| packages/bruno-app/src/components/RequestTabs/RequestTab/StyledWrapper.js | Adds tab label ellipsis styling. |
| packages/bruno-app/src/components/RequestTabs/RequestTab/RequestTabLoading.js | Adds tab placeholder component for loading/mounting collections. |
| packages/bruno-app/src/components/RequestTabs/ExampleTab/index.js | Adds pathname/exampleName fallback, placeholder state, and UID syncing. |
| packages/bruno-app/src/components/RequestTabPanel/index.js | Adds pathname/exampleName fallback rendering and panel loading placeholder. |
| packages/bruno-app/src/components/RequestTabPanel/RequestTabPanelLoading/index.js | Adds panel loading placeholder component. |
| packages/bruno-app/src/components/RequestTabPanel/RequestNotFound/index.js | Fixes delayed error UI timer cleanup. |
| packages/bruno-app/src/components/GlobalSearchModal/index.js | Ensures tabs opened from search include type + pathname. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (9)
packages/bruno-electron/src/ipc/collection.js (1)
1632-1638: Nit: rethrowing loses the original stack.
throw new Error(error.message)strips the original error's stack trace, which makes debugging snapshot failures harder. Consider rethrowingerrordirectly (or usingPromise.reject(error)to stay consistent with the other handlers in this file).♻️ Suggested change
ipcMain.handle('renderer:update-ui-state-snapshot', (event, { type, data }) => { try { snapshotManager.update({ type, data }); } catch (error) { - throw new Error(error.message); + return Promise.reject(error); } });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-electron/src/ipc/collection.js` around lines 1632 - 1638, The IPC handler for 'renderer:update-ui-state-snapshot' currently catches errors and rethrows a new Error which loses the original stack; change the catch to rethrow the original error (e.g., throw error) or return Promise.reject(error) so the original stack and error details from snapshotManager.update are preserved, updating the handler that wraps snapshotManager.update({ type, data }) accordingly.packages/bruno-app/src/utils/snapshot/index.js (3)
82-98: Matching a normalized path againstuidandnameconflates identifiers.Lines 89 and 93 reuse
normalizedEnvironmentPath(a pathname with trailing-slash stripped and backslashes flipped) as the comparison key for bothenvironment.uidandenvironment.name. A real pathname like/users/foo/envs/dev.bruwill never equal a uid or a name, so these branches only fire when the caller passed a non-path (e.g., a raw name) viaenvironmentPath. That's a semantic smell — either the field is a path or it's an identifier.Either (a) accept a separate
environmentUid/environmentNameinsnapshotDataand match each against its corresponding field, or (b) document thatenvironmentPathis deliberately a "best-effort reference" and rename it accordingly. Today's behavior works but is easy to break on future refactors.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/utils/snapshot/index.js` around lines 82 - 98, The current matcher conflates path vs identifier by comparing normalizedEnvironmentPath (from normalizeSnapshotPathRef(environment?.pathname)) against environment.uid and environment.name; change the logic to accept and check distinct keys: use snapshotData.environmentPath (normalized via normalizeSnapshotPathRef on environment?.pathname) only to compare against environment?.pathname, and add/accept snapshotData.environmentUid and snapshotData.environmentName and compare those against environment?.uid and environment?.name respectively inside the collection.environments.find callback (fall back to selectedEnvironment for legacy name matching if needed); update any callers to pass environmentUid/environmentName when available or keep environmentPath for path-only matching and add a clear comment on the new behavior.
15-40:SAVE_TRIGGERSshould be aSet, not aMap<string, null>.No value is ever read from the map — every entry is
nulland the only access pattern will beSAVE_TRIGGERS.has(action.type). ASet<string>conveys intent, halves the memory footprint, and avoids misleading future readers into thinking thenullslot is meaningful.♻️ Proposed refactor
-export const SAVE_TRIGGERS = new Map([ - ['app/setSnapshotReady', null], - ['tabs/addTab', null], +export const SAVE_TRIGGERS = new Set([ + 'app/setSnapshotReady', + 'tabs/addTab', ... - ['logs/setActiveTab', null] -]); + 'logs/setActiveTab' +]);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/utils/snapshot/index.js` around lines 15 - 40, SAVE_TRIGGERS is defined as a Map filled with string keys and null values but only ever used with SAVE_TRIGGERS.has(action.type); change it to a Set<string> to convey intent and reduce memory: replace the Map construction with a Set containing the same action type strings (keep the same symbol SAVE_TRIGGERS) and ensure all current usages (e.g., SAVE_TRIGGERS.has(...)) continue to work unchanged.
201-209: Default pane values applied unconditionally — dead fields on non-request tabs.
requestPaneTab: 'params',responsePaneTab: 'response', etc. are set for every tab type, including singletons likevariablesorcollection-runnerwhereserializeTabnever writesrequest/responseblocks. Harmless today, but it inflates the tab object and muddies the shape. Consider gating these defaults behindisRequestTab(type):♻️ Proposed refactor
const tab = { collectionUid: collection.uid, type, preview: !snapshotTab.permanent, name: snapshotTab.name || null, - pathname: pathname || null, - requestPaneTab: snapshotTab.request?.tab || 'params', - requestPaneWidth: snapshotTab.request?.width || null, - requestPaneHeight: snapshotTab.request?.height || null, - responsePaneTab: snapshotTab.response?.tab || 'response', - responseFormat: snapshotTab.response?.format || null, - responseViewTab: snapshotTab.response?.viewTab || null, - responsePaneScrollPosition: null, - scriptPaneTab: null + pathname: pathname || null, + ...(isRequestTab(type) ? { + requestPaneTab: snapshotTab.request?.tab || 'params', + requestPaneWidth: snapshotTab.request?.width || null, + requestPaneHeight: snapshotTab.request?.height || null, + responsePaneTab: snapshotTab.response?.tab || 'response', + responseFormat: snapshotTab.response?.format || null, + responseViewTab: snapshotTab.response?.viewTab || null, + responsePaneScrollPosition: null, + scriptPaneTab: null + } : {}) };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/utils/snapshot/index.js` around lines 201 - 209, The code unconditionally assigns request/response pane defaults (requestPaneTab, requestPaneWidth, requestPaneHeight, responsePaneTab, responseFormat, responseViewTab) from snapshotTab even for non-request tabs, producing dead fields; change the object construction so these properties are only added when the tab is a request-type (use or add an isRequestTab(type) check) or when snapshotTab.request/response exist (refer to snapshotTab, requestPaneTab, responsePaneTab and serializeTab in your change), i.e., wrap or conditionally spread the request/response defaults into the returned tab snapshot only when isRequestTab(type) is true so non-request singletons like variables/collection-runner keep a minimal shape.tests/workspace/snapshot-persistence.spec.ts (5)
179-182: Request-pane active-tab assertion couples to layout classes.
page2.locator('.request-pane > .px-4')(Line 179) and the/active/class regex (Line 182) depend on Tailwind spacing (px-4) and an internal className pattern. A Tailwind v4 migration or any style refactor will silently break this test. Route throughgetByTestId+getByRole('tab', { selected: true })ortoHaveAttribute('aria-selected', 'true')instead.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/workspace/snapshot-persistence.spec.ts` around lines 179 - 182, The test is brittle due to CSS-dependent selectors and class checks: replace the DOM queries that use page2.locator('.request-pane > .px-4') and the class-regex check on headersTab with semantic/test-id and ARIA assertions; locate the request pane via a test id (e.g., getByTestId('request-pane') or similar), find the tab using getByRole('tab', { name: 'Headers' }) and assert selected state via getByRole(..., { selected: true }) or toHaveAttribute('aria-selected', 'true') on the headersTab element instead of checking for the /active/ class.
28-34: Per-test boilerplate duplication — extract alaunchAndWaitForLoadedhelper.The three-liner
launchElectronApp→firstWindow→waitFor('[data-app-state="loaded"]', 30000)shows up 14 times in this file. A single helper (e.g.,await launchLoadedApp({ userDataPath })returning{ app, page }) would cut ~40 lines and make the tests read like specs.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/workspace/snapshot-persistence.spec.ts` around lines 28 - 34, Extract the repeated three-line startup sequence into a helper (e.g., launchLoadedApp) so tests call something like await launchLoadedApp({ userDataPath }) and get back { app, page }; specifically, factor out the launchElectronApp call, app.firstWindow(), and await page.locator('[data-app-state="loaded"]').waitFor({ timeout: 30000 }) into a single async function (referencing launchElectronApp, firstWindow, and the locator waitFor) and replace the 14 duplicated occurrences in the spec with calls to that helper to reduce boilerplate and improve readability.
61-62: Brittle DOM selectors — preferdata-testid.
.request-tab .tab-label(Line 61),.console-header/.console-tab(Lines 448, 450, 467, 470),.dropdown-item(Lines 220, 278, 392),.request-pane > .px-4(Line 179) are all CSS/Tailwind-class selectors that will break on any styling refactor. Adddata-testidhooks on the corresponding components and usegetByTestIdhere.As per coding guidelines: "Add
data-testidto testable elements for Playwright."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/workspace/snapshot-persistence.spec.ts` around lines 61 - 62, Replace brittle CSS/Tailwind selectors with data-testid hooks: add descriptive data-testid attributes to the UI components that render the elements currently targeted by selectors '.request-tab .tab-label', '.console-header', '.console-tab', '.dropdown-item', and '.request-pane > .px-4'; then update the tests (e.g., where you call page2.locator('.request-tab .tab-label') and other occurrences) to use Playwright's getByTestId or locator('[data-testid="..."]') with those test IDs instead of class-based selectors so tests no longer break on styling refactors.
195-205: DuplicateWORKSPACE_YML+ dialog-stub block across 3 tests.The same 10-line YAML literal and the
dialog.showOpenDialogmonkey-patch repeat verbatim at Lines 195–221, 247–279, and 361–393. Extract a shared helper (e.g.,createWorkspaceFixture(createTmpDir, name)andopenWorkspaceViaDialog(app, page, path)) intests/utils/page/to keep these tests focused on the actual assertions.As per coding guidelines: "Use consistent patterns and helper utilities where they improve clarity. Prefer shared test utilities over copy-pasted setup code, but only when it actually reduces complexity."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/workspace/snapshot-persistence.spec.ts` around lines 195 - 205, The tests duplicate the same WORKSPACE_YML literal and dialog.showOpenDialog monkey-patch across multiple specs; create a shared helper in tests/utils/page/, e.g., add createWorkspaceFixture(createTmpDir, name) that writes WORKSPACE_YML (or builds it from name) to the tmp dir and returns the path, and add openWorkspaceViaDialog(app, page, workspacePath) that applies the dialog.showOpenDialog monkey-patch and triggers the UI open action; then replace the repeated blocks in the spec files with calls to createWorkspaceFixture and openWorkspaceViaDialog so WORKSPACE_YML and the dialog stub live only in the new helpers.
44-48: Debounce flushes rely on fixedwaitForTimeout(2000)— fragile and slow.This pattern repeats 7+ times across the suite (Lines 46, 92, 129, 163, 226, 290, 300, 334, 402, 457, 536). If the debounce window ever grows, every test flakes; if it shrinks, we're wasting CI minutes. Per coding guidelines,
page.waitForTimeoutshould be avoided unless unavoidable.Prefer a deterministic signal — e.g., have the renderer flip a
data-snapshot-savedattribute (or emit an IPC ack) after each flush, thenawait expect(page.locator('[data-snapshot-state="idle"]')).toBeVisible(). Fallback: pollreadSnapshot(userDataPath)for the expected mutation with Playwright'sexpect.poll.As per coding guidelines: "Try to reduce usage of
page.waitForTimeout();in code unless absolutely necessary and the locator cannot be found using existingexpect()playwright calls".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/workspace/snapshot-persistence.spec.ts` around lines 44 - 48, The test uses a fragile fixed delay via page.waitForTimeout(2000) before calling closeElectronApp(app); replace this with a deterministic wait for the snapshot-flush signal: have the renderer set a DOM attribute (e.g., data-snapshot-saved or data-snapshot-state="idle") or emit an IPC ack when the debounce flush completes, then in the test await that signal (e.g., await expect(page.locator('[data-snapshot-state="idle"]')).toBeVisible()) instead of waitForTimeout; alternatively use Playwright's expect.poll to poll readSnapshot(userDataPath) for the expected mutation before calling closeElectronApp(app) — update all occurrences of page.waitForTimeout in this spec to use one of these deterministic approaches.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js`:
- Around line 3008-3015: Move the call to hydrateCollectionTabs so tabs are
restored before any snapshot-triggering mount state is saved: call
hydrateCollectionTabs(collection, dispatch, restoreTabs) (using the same
collection detection logic) before dispatching updateCollectionMountStatus and
addTransientDirectory, because updateCollectionMountStatus triggers a snapshot
save and could persist a mounted collection with no tabs if restoreTabs runs
after the debounce window.
In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js`:
- Around line 2923-2933: The code derives the environment file extension using
collection?.brunoConfig?.version which is unreliable; change the discriminator
to use collection.format or collection?.brunoConfig?.opencollection to determine
whether to use 'bru' or 'yml' (e.g., treat opencollection or format === 'open'
as YAML/open collection -> 'yml', else 'bru'), update the const extension and
ensure the subsequent environmentPath and the getCollectionEnvironmentPath call
use that corrected logic (symbols: extension, environmentPath,
getCollectionEnvironmentPath, collection?.brunoConfig).
In `@packages/bruno-app/src/utils/snapshot/index.js`:
- Around line 230-241: The current hydrateCollectionTabs function swallows IPC
errors via .catch(() => null); replace that catch with one that logs the error
and collection context (e.g., capture the thrown error from
ipcRenderer.invoke('renderer:snapshot:get-tabs', collection.pathname) and call
console.error or your app logger with a message like "Failed to get tabs
snapshot for" plus collection.pathname and the error, then return null) so
failures are visible; apply the same pattern to the other similar IPC
invocation(s) in this file (the other .catch(() => null) occurrence) and keep
the existing dispatch(restoreTabs({...})) flow unchanged.
In `@packages/bruno-electron/src/services/snapshot/index.js`:
- Around line 416-458: _getByPathWithNormalizedFallback and
_deleteByPathWithNormalizedFallback only normalize separators but still compare
case-sensitively; update the matching logic to compare normalized paths in a
case-insensitive way by lowercasing both sides (e.g. const normalizedPath =
path.normalize(pathname).toLowerCase(); and compare with
path.normalize(key).toLowerCase()). Keep the rest of the flow the same (use
this._escapeKey for store keys and this.store.get/delete for rootKey and
matchingKey) so lookups and deletes will match entries that only differ by case.
In `@tests/workspace/snapshot-persistence.spec.ts`:
- Around line 505-512: The test currently only checks that workspace-name
renders and may pass even if SnapshotManager didn't rewrite the corrupt file;
after launching the app (launchElectronApp / page.waitFor), call the
readSnapshot helper for the ui-state-snapshot.json (e.g.,
readSnapshot(userDataPath)) and assert it returns a valid object containing the
expected top-level keys used by SnapshotManager (for example the keys present in
the default snapshot structure), ensuring the corrupt file was rewritten rather
than simply ignored; reference SnapshotManager and ui-state-snapshot.json to
locate the related behavior.
---
Nitpick comments:
In `@packages/bruno-app/src/utils/snapshot/index.js`:
- Around line 82-98: The current matcher conflates path vs identifier by
comparing normalizedEnvironmentPath (from
normalizeSnapshotPathRef(environment?.pathname)) against environment.uid and
environment.name; change the logic to accept and check distinct keys: use
snapshotData.environmentPath (normalized via normalizeSnapshotPathRef on
environment?.pathname) only to compare against environment?.pathname, and
add/accept snapshotData.environmentUid and snapshotData.environmentName and
compare those against environment?.uid and environment?.name respectively inside
the collection.environments.find callback (fall back to selectedEnvironment for
legacy name matching if needed); update any callers to pass
environmentUid/environmentName when available or keep environmentPath for
path-only matching and add a clear comment on the new behavior.
- Around line 15-40: SAVE_TRIGGERS is defined as a Map filled with string keys
and null values but only ever used with SAVE_TRIGGERS.has(action.type); change
it to a Set<string> to convey intent and reduce memory: replace the Map
construction with a Set containing the same action type strings (keep the same
symbol SAVE_TRIGGERS) and ensure all current usages (e.g.,
SAVE_TRIGGERS.has(...)) continue to work unchanged.
- Around line 201-209: The code unconditionally assigns request/response pane
defaults (requestPaneTab, requestPaneWidth, requestPaneHeight, responsePaneTab,
responseFormat, responseViewTab) from snapshotTab even for non-request tabs,
producing dead fields; change the object construction so these properties are
only added when the tab is a request-type (use or add an isRequestTab(type)
check) or when snapshotTab.request/response exist (refer to snapshotTab,
requestPaneTab, responsePaneTab and serializeTab in your change), i.e., wrap or
conditionally spread the request/response defaults into the returned tab
snapshot only when isRequestTab(type) is true so non-request singletons like
variables/collection-runner keep a minimal shape.
In `@packages/bruno-electron/src/ipc/collection.js`:
- Around line 1632-1638: The IPC handler for 'renderer:update-ui-state-snapshot'
currently catches errors and rethrows a new Error which loses the original
stack; change the catch to rethrow the original error (e.g., throw error) or
return Promise.reject(error) so the original stack and error details from
snapshotManager.update are preserved, updating the handler that wraps
snapshotManager.update({ type, data }) accordingly.
In `@tests/workspace/snapshot-persistence.spec.ts`:
- Around line 179-182: The test is brittle due to CSS-dependent selectors and
class checks: replace the DOM queries that use page2.locator('.request-pane >
.px-4') and the class-regex check on headersTab with semantic/test-id and ARIA
assertions; locate the request pane via a test id (e.g.,
getByTestId('request-pane') or similar), find the tab using getByRole('tab', {
name: 'Headers' }) and assert selected state via getByRole(..., { selected: true
}) or toHaveAttribute('aria-selected', 'true') on the headersTab element instead
of checking for the /active/ class.
- Around line 28-34: Extract the repeated three-line startup sequence into a
helper (e.g., launchLoadedApp) so tests call something like await
launchLoadedApp({ userDataPath }) and get back { app, page }; specifically,
factor out the launchElectronApp call, app.firstWindow(), and await
page.locator('[data-app-state="loaded"]').waitFor({ timeout: 30000 }) into a
single async function (referencing launchElectronApp, firstWindow, and the
locator waitFor) and replace the 14 duplicated occurrences in the spec with
calls to that helper to reduce boilerplate and improve readability.
- Around line 61-62: Replace brittle CSS/Tailwind selectors with data-testid
hooks: add descriptive data-testid attributes to the UI components that render
the elements currently targeted by selectors '.request-tab .tab-label',
'.console-header', '.console-tab', '.dropdown-item', and '.request-pane >
.px-4'; then update the tests (e.g., where you call page2.locator('.request-tab
.tab-label') and other occurrences) to use Playwright's getByTestId or
locator('[data-testid="..."]') with those test IDs instead of class-based
selectors so tests no longer break on styling refactors.
- Around line 195-205: The tests duplicate the same WORKSPACE_YML literal and
dialog.showOpenDialog monkey-patch across multiple specs; create a shared helper
in tests/utils/page/, e.g., add createWorkspaceFixture(createTmpDir, name) that
writes WORKSPACE_YML (or builds it from name) to the tmp dir and returns the
path, and add openWorkspaceViaDialog(app, page, workspacePath) that applies the
dialog.showOpenDialog monkey-patch and triggers the UI open action; then replace
the repeated blocks in the spec files with calls to createWorkspaceFixture and
openWorkspaceViaDialog so WORKSPACE_YML and the dialog stub live only in the new
helpers.
- Around line 44-48: The test uses a fragile fixed delay via
page.waitForTimeout(2000) before calling closeElectronApp(app); replace this
with a deterministic wait for the snapshot-flush signal: have the renderer set a
DOM attribute (e.g., data-snapshot-saved or data-snapshot-state="idle") or emit
an IPC ack when the debounce flush completes, then in the test await that signal
(e.g., await expect(page.locator('[data-snapshot-state="idle"]')).toBeVisible())
instead of waitForTimeout; alternatively use Playwright's expect.poll to poll
readSnapshot(userDataPath) for the expected mutation before calling
closeElectronApp(app) — update all occurrences of page.waitForTimeout in this
spec to use one of these deterministic approaches.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a5584c3e-cb27-47a0-87c3-ea4f14142b5b
📒 Files selected for processing (26)
packages/bruno-app/src/components/GlobalSearchModal/index.jspackages/bruno-app/src/components/RequestTabPanel/RequestNotFound/index.jspackages/bruno-app/src/components/RequestTabPanel/RequestTabPanelLoading/index.jspackages/bruno-app/src/components/RequestTabPanel/index.jspackages/bruno-app/src/components/RequestTabs/ExampleTab/index.jspackages/bruno-app/src/components/RequestTabs/RequestTab/RequestTabLoading.jspackages/bruno-app/src/components/RequestTabs/RequestTab/StyledWrapper.jspackages/bruno-app/src/components/RequestTabs/RequestTab/index.jspackages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/ExampleItem/index.jspackages/bruno-app/src/components/Sidebar/Collections/Collection/CollectionItem/index.jspackages/bruno-app/src/providers/ReduxStore/index.jspackages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.jspackages/bruno-app/src/providers/ReduxStore/middlewares/tasks/middleware.jspackages/bruno-app/src/providers/ReduxStore/slices/app.jspackages/bruno-app/src/providers/ReduxStore/slices/collections/actions.jspackages/bruno-app/src/providers/ReduxStore/slices/collections/index.jspackages/bruno-app/src/providers/ReduxStore/slices/tabs.jspackages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.jspackages/bruno-app/src/utils/snapshot/index.jspackages/bruno-electron/src/app/collection-watcher.jspackages/bruno-electron/src/index.jspackages/bruno-electron/src/ipc/collection.jspackages/bruno-electron/src/ipc/snapshot.jspackages/bruno-electron/src/services/snapshot/index.jspackages/bruno-electron/src/store/ui-state-snapshot.jstests/workspace/snapshot-persistence.spec.ts
💤 Files with no reviewable changes (1)
- packages/bruno-electron/src/store/ui-state-snapshot.js
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js (1)
2890-2910:⚠️ Potential issue | 🟡 Minor
existingEnv.pathname = environment.pathnamecan clobber withundefined.If an event payload is missing
pathnamefor any reason, we'd stampundefinedover a valid cached value, and the next snapshot write would then emit a broken path. Cheap guard:- existingEnv.pathname = environment.pathname; + if (environment.pathname) { + existingEnv.pathname = environment.pathname; + }Low likelihood today given upstream always sets it, but it's a one-liner of insurance for a field you're now using in the persisted snapshot.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js` around lines 2890 - 2910, Avoid overwriting a valid cached pathname with undefined by guarding the assignment to existingEnv.pathname; instead of unconditional existingEnv.pathname = environment.pathname, only assign when environment.pathname is defined (e.g., check environment.pathname !== undefined and/or environment.pathname != null) so existingEnv.pathname stays intact if the incoming payload omits pathname; apply this guard in the block that updates existingEnv (where existingEnv.pathname and existingEnv.name are set).
♻️ Duplicate comments (3)
packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js (1)
2921-2937:⚠️ Potential issue | 🟠 MajorSame
brunoConfig.versionformat-sniffing issue as previously flagged. 🐇Line 2923 still keys the extension off
brunoConfig?.version === '1', which isn't a reliable format discriminator — YAML/opencollection workspaces can also carryversion, so the fallback path will happily construct a.brupath for a.ymlcollection. Usecollection.format(already set increateCollectionat Lines 173-177 based onopencollection) orbrunoConfig?.opencollectiondirectly.Note: the exact same bug lives downstream in
getCollectionEnvironmentPath(packages/bruno-app/src/utils/snapshot/index.jsLines 252-266). Fixing only this site leaves the helper's fallback path broken whenenvironment.pathnameis empty andenvironment.nameis set — worth fixing at the root.Suggested fix
- const extension = collection?.brunoConfig?.version === '1' ? 'bru' : 'yml'; + const extension = collection?.format === 'yml' || collection?.brunoConfig?.opencollection ? 'yml' : 'bru'; 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 || '' - } + data: { + collectionPath: collection?.pathname, + environmentPath, + selectedEnvironment: environment?.name || '' + } });Based on learning: "the Redux reducer determines collection format by checking for the
opencollectionproperty in brunoConfig. Theversionproperty is not used for format detection".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js` around lines 2921 - 2937, The code is incorrectly detecting file extension via brunoConfig.version; update the extension logic in the block using ipcRenderer (and the helper getCollectionEnvironmentPath) to derive format from collection.format or brunoConfig?.opencollection instead of brunoConfig?.version === '1' so YAML/opencollection collections produce '.yml' and legacy Bruno collections produce '.bru'; specifically modify the extension assignment in the Redux slice (inside the ipcRenderer.invoke payload) to use collection.format || (collection?.brunoConfig?.opencollection ? 'yml' : 'bru') and also fix the same detection in the getCollectionEnvironmentPath function so its fallback path constructs the correct .yml/.bru filename when environment.pathname is empty but environment.name exists.packages/bruno-app/src/utils/snapshot/index.js (1)
429-430:⚠️ Potential issue | 🟡 MinorLog snapshot IPC hydration failures.
These catches still turn snapshot read failures into silent no-ops, leaving tab-loss reports with no diagnostic trail.
Suggested fix
const tabsSnapshot = getTabsSnapshotFromLookups(collection.pathname, snapshotLookups) - || await ipcRenderer.invoke('renderer:snapshot:get-tabs', collection.pathname).catch(() => null); + || await ipcRenderer.invoke('renderer:snapshot:get-tabs', collection.pathname).catch((err) => { + console.error(`[snapshot] Failed to hydrate tabs for ${collection.pathname}:`, err); + return null; + });const tabsSnapshot = getTabsSnapshotFromLookups(collectionPathname, snapshotLookups) - || await ipcRenderer.invoke('renderer:snapshot:get-tabs', collectionPathname).catch(() => null); + || await ipcRenderer.invoke('renderer:snapshot:get-tabs', collectionPathname).catch((err) => { + console.error(`[snapshot] Failed to get active tab for ${collectionPathname}:`, err); + return null; + });Also applies to: 450-451
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/utils/snapshot/index.js` around lines 429 - 430, The current silent catches around the IPC snapshot fetch hide diagnostic info; update the await ipcRenderer.invoke('renderer:snapshot:get-tabs', collection.pathname).catch(() => null) calls (and the similar catch at the other occurrence) to log the caught error via the existing logging facility (or console.error) including context (collection.pathname and that it's a tabs snapshot IPC/hydration failure) before returning null; locate the occurrences around getTabsSnapshotFromLookups and replace the empty catch handlers with ones that capture the error and emit a clear diagnostic message.packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js (1)
3009-3016:⚠️ Potential issue | 🟠 MajorHydrate tabs before marking the collection as mounted.
Line 3010 can trigger snapshot persistence before Line 3015 restores tabs, so a slow snapshot read can overwrite the saved tab state with an empty mounted collection state.
Suggested fix
callIpc('renderer:mount-collection', { collectionUid, collectionPathname, brunoConfig }) .then(async (transientDirPath) => { - dispatch(updateCollectionMountStatus({ collectionUid, mountStatus: 'mounted' })); dispatch(addTransientDirectory({ collectionUid, pathname: transientDirPath })); const collection = getState().collections.collections.find((c) => c.uid === collectionUid); if (collection?.pathname) { await hydrateCollectionTabs(collection, dispatch, restoreTabs); } + + dispatch(updateCollectionMountStatus({ collectionUid, mountStatus: 'mounted' })); })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js` around lines 3009 - 3016, The code marks the collection as mounted before restoring tabs, which can let snapshot persistence overwrite restored tab state; move the call to hydrateCollectionTabs (await hydrateCollectionTabs(collection, dispatch, restoreTabs)) to occur before dispatch(updateCollectionMountStatus({ collectionUid, mountStatus: 'mounted' })) and dispatch(addTransientDirectory(...)); locate the block that finds collection via getState().collections.collections.find((c) => c.uid === collectionUid) and ensure you await hydrateCollectionTabs for that collection first, then dispatch addTransientDirectory and updateCollectionMountStatus so the persisted snapshot reflects the restored tabs.
🧹 Nitpick comments (4)
packages/bruno-app/src/utils/snapshot/index.spec.js (2)
63-140: Windows-path test is a stowaway inside the map-based schema test. 🕵️The block at Lines 117-139 exercises array-based snapshots with Windows paths, but lives inside a test titled "builds lookup maps from map-based schema for backward compatibility". If either assertion set fails, the failure message points at the wrong concern. Split it into its own
it(...)so failures tell a clear story.♻️ Proposed split
expect(Array.isArray(tabs.tabs)).toBe(true); expect(tabs.tabs).toHaveLength(1); - - const windowsSnapshot = { + }); + + it('normalizes Windows-style paths for lookup keys', () => { + const windowsSnapshot = { workspaces: [ { pathname: 'C:\\workspace', sorting: 'az', collections: ['C:\\workspace\\collection'] } ], collections: [ { pathname: 'C:\\workspace\\collection', selectedEnvironment: 'Prod', isOpen: true, isMounted: true } ] }; const windowsLookups = hydrateSnapshotLookups(windowsSnapshot); expect(windowsLookups.collectionsByPath['C:/workspace/collection']).toMatchObject({ workspacePathname: 'C:\\workspace', selectedEnvironment: 'Prod' }); });Based on the coding guideline "Name tests descriptively, keep setup minimal, and avoid unnecessary abstraction."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/utils/snapshot/index.spec.js` around lines 63 - 140, The current test "builds lookup maps from map-based schema for backward compatibility" mixes a separate Windows/array-based snapshot assertion (windowsSnapshot -> windowsLookups via hydrateSnapshotLookups) into the map-based test; extract the Windows path assertions (the windowsSnapshot, windowsLookups, and the expect on windowsLookups.collectionsByPath['C:/workspace/collection']) into a new it(...) with a descriptive name like "handles array-based Windows paths when hydrating lookups", keep the original map-based test focused on map schema and remove the Windows block from it, and ensure the new test calls hydrateSnapshotLookups and asserts the workspacePathname and selectedEnvironment as before.
5-141: Missing degraded-path coverage.Happy paths look solid, but
hydrateSnapshotLookupshas defensive branches (non-object entries, missingpathname,snapshot = {}default, workspace entries pointing at collections that aren't in the snapshot, etc.) that have no tests. Per the "realistically problematic paths" guideline, consider adding at least:
hydrateSnapshotLookups()/hydrateSnapshotLookups({})returns empty maps- array entries missing
pathnameare skipped- workspace
collectionPathnamesreferencing unknown collections don't explode and don't pollutecollectionsByPathBased on the coding guideline "Cover both the 'happy path' and the realistically problematic paths."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/utils/snapshot/index.spec.js` around lines 5 - 141, Add tests covering degraded paths for hydrateSnapshotLookups: verify hydrateSnapshotLookups() and hydrateSnapshotLookups({}) return empty maps; add a snapshot array entry (in workspaces/collections/tabs) missing pathname and assert it's skipped (no entry in workspacesByPath/collectionsByPath/tabsByCollectionPath and no throw); add a workspace whose collectionPathnames includes an unknown collection and assert hydrateSnapshotLookups still returns the workspace (in workspacesByPath) but does not add any entry for the unknown path into collectionsByPath and does not throw. Reference the hydrateSnapshotLookups function and the existing index.spec.js tests when adding these assertions.tests/workspace/snapshot-persistence.spec.ts (2)
61-66: Tests lean on Tailwind/implementation CSS instead of testids.Several assertions bind to implementation details that UI refactors will silently break:
- Line 61:
.request-tab .tab-label- Line 179:
.request-pane > .px-4(a Tailwind class, especially fragile)- Line 181:
.tabs+ role=tab combo- Lines 446, 448, 450:
button[data-trigger="dev-tools"],.console-header,.console-tabPrefer
data-testidhooks (or extendbuildCommonLocatorswithdevTools,requestPane.subTab(name), etc.) so the e2e layer is decoupled from styling/layout.Based on the coding guideline "Add
data-testidto testable elements for Playwright."Also applies to: 179-182, 446-452
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/workspace/snapshot-persistence.spec.ts` around lines 61 - 66, The tests are using fragile implementation CSS selectors (e.g., '.request-tab .tab-label', '.request-pane > .px-4', '.tabs' + role=tab, 'button[data-trigger="dev-tools"]', '.console-header', '.console-tab') which will break on styling refactors; add stable data-testid attributes to the corresponding UI elements (for request tabs, request pane sub-tabs, tabs/role=tab combo, dev-tools button, console header/tabs) and update the spec to use those testids or the shared locator helpers (extend buildCommonLocators with e.g. devTools, requestPane.subTab(name), requestTab.label(name)) and replace usages of the fragile selectors in snapshot-persistence.spec.ts with the new data-testid-based locators.
44-48:page.waitForTimeout(2000)for debounced save — eleven times.The pattern
await page.waitForTimeout(2000); await closeElectronApp(app);(and variants) repeats at Lines 46, 92, 129, 163, 226, 290, 300, 334, 402, 457, 536. These are racy on slow CI and wasteful on fast machines. Two cleaner options:
- Poll the snapshot file (you already have
readSnapshot): wait until it exists and contains the just-created entity, e.g.expect.poll(() => readSnapshot(userDataPath)?.collections?.length).toBeGreaterThan(0).- Expose a flush IPC used only in test mode to force an immediate persist (best for determinism).
At minimum, wrap the wait in a single helper like
waitForSnapshotFlush(page, userDataPath, predicate)to centralize the timeout and make it easy to tighten later.Based on the coding guideline "Try to reduce usage of
page.waitForTimeout()in code unless absolutely necessary and the locator cannot be found using existingexpect()playwright calls."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/workspace/snapshot-persistence.spec.ts` around lines 44 - 48, Replace the repeated ad-hoc page.waitForTimeout(2000) + closeElectronApp(app) pattern with a deterministic helper that polls the persisted snapshot (use existing readSnapshot) or an explicit test-only IPC flush: add a waitForSnapshotFlush(page, userDataPath, predicate) helper that uses expect.poll(() => readSnapshot(userDataPath)...) to wait until the snapshot contains the expected entity, then call closeElectronApp(app); alternatively implement a test-only IPC method (e.g., forceSnapshotFlush) that the test can invoke before closing; update all occurrences (the tests that call page.waitForTimeout and closeElectronApp) to use this helper or the IPC flush to remove flaky timeouts and centralize the wait logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/bruno-app/src/utils/snapshot/index.js`:
- Around line 432-437: tabsSnapshot currently contains serialized records but
restoreTabs expects real tab objects (with uid/collectionUid) and activeTab as
an object with uid; before calling dispatch(restoreTabs(...)) deserialize the
snapshot entries: map tabsSnapshot.tabs into full tab objects (recreating uid,
collectionUid and any other runtime fields) and resolve tabsSnapshot.activeTab
to the corresponding deserialized tab (or extract its uid) so you pass tabs:
deserializedTabs and activeTab: deserializedActiveTab (or activeTab.uid) into
restoreTabs; update the call site that uses tabsSnapshot.tabs and
tabsSnapshot.activeTab to use these deserialized values.
- Around line 265-266: The code currently infers the environment file extension
from collection.brunoConfig?.version which is incorrect; update the logic that
sets extension (the const extension and the return that joins
collection.pathname with environment.name) to detect format the same way reducer
does — prefer collection.brunoConfig?.opencollection (or the collection's
resolved format property if present, e.g., collection.format) instead of version
— so choose 'yml' for Open Collection and 'bru' otherwise, then return the
normalized path as before.
- Around line 46-48: The current shouldExcludeTab uses startsWith which can
false-positive match sibling paths; change it to a path-boundary check using
Node's path utilities: import path and, inside shouldExcludeTab(tab,
transientDirectory), normalize/resolve both transientDirectory and tab.pathname
then compute path.relative(transientDirectoryResolved, pathnameResolved) and
return true only if the relative path is '' or does not start with '..' (i.e.
the pathname is the same or inside the transientDirectory). Reference:
shouldExcludeTab, tab.pathname, transientDirectory.
- Around line 419-421: The current assignment "if (accessor === 'type') tab.uid
= type" is wrong for singleton tabs and causes cross-collection collisions;
change the reconstruction logic to set tab.uid per type: when type is
"collection-settings" restore tab.uid to the containing collection's uid (use
the tab.collection or collection uid field used elsewhere), but for
non-replaceable singletons ("collection-runner", "variables", "openapi-sync",
"openapi-spec") generate a new unique id (same behavior as callers that use
uuid()); keep addTab's deduplication (which checks uid first) intact by ensuring
these uids follow that convention. Ensure you update the accessor==='type'
branch that sets tab.uid and reference the types list and addTab dedup check
when making the change.
In `@packages/bruno-electron/src/app/collection-watcher.js`:
- Around line 639-649: The code builds hydratePayload from
collectionSnapshotState but reads environment.collection; instead use the
top-level field exported by snapshotManager.getCollection — replace
collectionSnapshotState?.environment?.collection with
collectionSnapshotState?.environmentPath (keep selectedEnvironment fallback
as-is) when constructing hydratePayload so it matches the getCollection() shape
and avoids unnecessary nesting; then send that hydratePayload via
win.webContents.send('main:hydrate-app-with-ui-state-snapshot', hydratePayload)
as before.
---
Outside diff comments:
In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js`:
- Around line 2890-2910: Avoid overwriting a valid cached pathname with
undefined by guarding the assignment to existingEnv.pathname; instead of
unconditional existingEnv.pathname = environment.pathname, only assign when
environment.pathname is defined (e.g., check environment.pathname !== undefined
and/or environment.pathname != null) so existingEnv.pathname stays intact if the
incoming payload omits pathname; apply this guard in the block that updates
existingEnv (where existingEnv.pathname and existingEnv.name are set).
---
Duplicate comments:
In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js`:
- Around line 3009-3016: The code marks the collection as mounted before
restoring tabs, which can let snapshot persistence overwrite restored tab state;
move the call to hydrateCollectionTabs (await hydrateCollectionTabs(collection,
dispatch, restoreTabs)) to occur before dispatch(updateCollectionMountStatus({
collectionUid, mountStatus: 'mounted' })) and
dispatch(addTransientDirectory(...)); locate the block that finds collection via
getState().collections.collections.find((c) => c.uid === collectionUid) and
ensure you await hydrateCollectionTabs for that collection first, then dispatch
addTransientDirectory and updateCollectionMountStatus so the persisted snapshot
reflects the restored tabs.
In `@packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js`:
- Around line 2921-2937: The code is incorrectly detecting file extension via
brunoConfig.version; update the extension logic in the block using ipcRenderer
(and the helper getCollectionEnvironmentPath) to derive format from
collection.format or brunoConfig?.opencollection instead of brunoConfig?.version
=== '1' so YAML/opencollection collections produce '.yml' and legacy Bruno
collections produce '.bru'; specifically modify the extension assignment in the
Redux slice (inside the ipcRenderer.invoke payload) to use collection.format ||
(collection?.brunoConfig?.opencollection ? 'yml' : 'bru') and also fix the same
detection in the getCollectionEnvironmentPath function so its fallback path
constructs the correct .yml/.bru filename when environment.pathname is empty but
environment.name exists.
In `@packages/bruno-app/src/utils/snapshot/index.js`:
- Around line 429-430: The current silent catches around the IPC snapshot fetch
hide diagnostic info; update the await
ipcRenderer.invoke('renderer:snapshot:get-tabs', collection.pathname).catch(()
=> null) calls (and the similar catch at the other occurrence) to log the caught
error via the existing logging facility (or console.error) including context
(collection.pathname and that it's a tabs snapshot IPC/hydration failure) before
returning null; locate the occurrences around getTabsSnapshotFromLookups and
replace the empty catch handlers with ones that capture the error and emit a
clear diagnostic message.
---
Nitpick comments:
In `@packages/bruno-app/src/utils/snapshot/index.spec.js`:
- Around line 63-140: The current test "builds lookup maps from map-based schema
for backward compatibility" mixes a separate Windows/array-based snapshot
assertion (windowsSnapshot -> windowsLookups via hydrateSnapshotLookups) into
the map-based test; extract the Windows path assertions (the windowsSnapshot,
windowsLookups, and the expect on
windowsLookups.collectionsByPath['C:/workspace/collection']) into a new it(...)
with a descriptive name like "handles array-based Windows paths when hydrating
lookups", keep the original map-based test focused on map schema and remove the
Windows block from it, and ensure the new test calls hydrateSnapshotLookups and
asserts the workspacePathname and selectedEnvironment as before.
- Around line 5-141: Add tests covering degraded paths for
hydrateSnapshotLookups: verify hydrateSnapshotLookups() and
hydrateSnapshotLookups({}) return empty maps; add a snapshot array entry (in
workspaces/collections/tabs) missing pathname and assert it's skipped (no entry
in workspacesByPath/collectionsByPath/tabsByCollectionPath and no throw); add a
workspace whose collectionPathnames includes an unknown collection and assert
hydrateSnapshotLookups still returns the workspace (in workspacesByPath) but
does not add any entry for the unknown path into collectionsByPath and does not
throw. Reference the hydrateSnapshotLookups function and the existing
index.spec.js tests when adding these assertions.
In `@tests/workspace/snapshot-persistence.spec.ts`:
- Around line 61-66: The tests are using fragile implementation CSS selectors
(e.g., '.request-tab .tab-label', '.request-pane > .px-4', '.tabs' + role=tab,
'button[data-trigger="dev-tools"]', '.console-header', '.console-tab') which
will break on styling refactors; add stable data-testid attributes to the
corresponding UI elements (for request tabs, request pane sub-tabs,
tabs/role=tab combo, dev-tools button, console header/tabs) and update the spec
to use those testids or the shared locator helpers (extend buildCommonLocators
with e.g. devTools, requestPane.subTab(name), requestTab.label(name)) and
replace usages of the fragile selectors in snapshot-persistence.spec.ts with the
new data-testid-based locators.
- Around line 44-48: Replace the repeated ad-hoc page.waitForTimeout(2000) +
closeElectronApp(app) pattern with a deterministic helper that polls the
persisted snapshot (use existing readSnapshot) or an explicit test-only IPC
flush: add a waitForSnapshotFlush(page, userDataPath, predicate) helper that
uses expect.poll(() => readSnapshot(userDataPath)...) to wait until the snapshot
contains the expected entity, then call closeElectronApp(app); alternatively
implement a test-only IPC method (e.g., forceSnapshotFlush) that the test can
invoke before closing; update all occurrences (the tests that call
page.waitForTimeout and closeElectronApp) to use this helper or the IPC flush to
remove flaky timeouts and centralize the wait logic.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 019df361-376a-47f6-bd51-05b182f59d50
📒 Files selected for processing (9)
packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.jspackages/bruno-app/src/providers/ReduxStore/slices/collections/actions.jspackages/bruno-app/src/providers/ReduxStore/slices/collections/index.jspackages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.jspackages/bruno-app/src/utils/snapshot/index.jspackages/bruno-app/src/utils/snapshot/index.spec.jspackages/bruno-electron/src/app/collection-watcher.jspackages/bruno-electron/src/services/snapshot/index.jstests/workspace/snapshot-persistence.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js
- packages/bruno-electron/src/services/snapshot/index.js
- packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (5)
packages/bruno-electron/src/services/snapshot/index.js (3)
302-310:updatedispatcher silently ignores unknown types.The
default: breakis fine for forward-compat, but during development an unknowntypeends up as a silent no-op that's hard to debug. Consider aconsole.warn(or at least a dev-only log) when an unrecognized update type is dispatched.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-electron/src/services/snapshot/index.js` around lines 302 - 310, The update({ type, data }) dispatcher currently swallows unknown types in its switch default; modify the default branch in the update method to emit a dev-time warning (e.g., console.warn or a debug logger) that includes the unrecognized type and the provided data to aid debugging—keep the existing case for 'COLLECTION_ENVIRONMENT' and the call to this.updateCollectionEnvironment(data || {}) but add the warning in default so unexpected dispatches are visible during development.
335-346: Migration rewrite triggers on every launch due to stringify compare.
JSON.stringify(currentSnapshot) !== JSON.stringify(normalizedSnapshot)will often betrueeven for already-valid snapshots, because key ordering fromelectron-storeneed not match the order produced by_normalizeSnapshotobject literals, and any added default (e.g., missingextras.devTools.tabData: {}) forces a rewrite. Harmless functionally, but it means every startup performs a disk write. Consider a cheaper "needs migration" detection (e.g., presence of top-leveltabskey, or non-arraycollections) instead of full-snapshot stringify compare.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-electron/src/services/snapshot/index.js` around lines 335 - 346, The stringify comparison in _migrateLegacySnapshot causes unnecessary writes; replace it with a lightweight "needs migration" check that inspects this.store.store for known legacy shapes (e.g., missing top-level "tabs", "collections" not an array, missing extras.devTools.tabData or other default fields), and only call this._normalizeSnapshot(currentSnapshot) and assign this.store.store = normalizedSnapshot when one of those quick checks returns true. Update _migrateLegacySnapshot to perform these targeted checks (and fall back to normalization if ambiguous), keeping _normalizeSnapshot unchanged but only invoked when migration is required.
184-194:saveSnapshotruns validation after normalization — validation is effectively a no-op.
_normalizeSnapshotalready coerces every field to its schema-valid shape (booleans default tofalse, arrays default to[], etc.), sosnapshotSchema.validateSyncon the normalized output will essentially never throw. If the intent is to reject invalid inputs, validatedata(or at least the not-yet-coerced pieces) before normalizing; otherwise the yup schema is dead weight on the write path and the catch block is unreachable for validation failures.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-electron/src/services/snapshot/index.js` around lines 184 - 194, saveSnapshot currently normalizes first so snapshotSchema.validateSync never fails; change the order to validate the raw input before coercion: call snapshotSchema.validateSync(data, { strict: true }) (or validateSync on the not-yet-coerced pieces) before calling this._normalizeSnapshot(data), then proceed to set this.store.store = normalizedSnapshot; keep the try/catch but ensure you validate the original data (not normalizedSnapshot) so validation errors are catchable and logged.tests/snapshots/basic.spec.ts (2)
195-205: DRY: extract theWORKSPACE_YMLfixture.The same inline YAML is repeated across three tests. Either lift it into a module-level constant in this file, or — better — move it into
tests/snapshots/fixtures/workspace-b/workspace.ymlper the repo's fixture convention and read it once, which also keeps the fixture discoverable alongside the spec.As per coding guidelines: "Ensure that the
fixtureslike the collections are nested inside thefixturesfolder".Also applies to: 247-257, 361-371
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/snapshots/basic.spec.ts` around lines 195 - 205, Extract the repeated WORKSPACE_YML string into a shared fixture: create a file at tests/snapshots/fixtures/workspace-b/workspace.yml containing the YAML, and update usages of the WORKSPACE_YML variable (and the fs.writeFileSync(path.join(workspaceBPath, 'workspace.yml'), WORKSPACE_YML) calls) to read that file once (e.g., fs.readFileSync or a module-level constant import) instead of inlining the YAML in each test; alternatively, if you prefer not to add a fixture file, declare WORKSPACE_YML as a module-level constant at the top of tests/snapshots/basic.spec.ts and reuse it in the three places referenced (lines around WORKSPACE_YML, 247-257, 361-371).
61-66: Preferdata-testidover structural CSS selectors.Selectors like
.request-tab .tab-label,.request-pane > .px-4,.console-header,.console-tab, andbutton[data-trigger="dev-tools"]will break on innocuous markup/Tailwind refactors. Recommend addingdata-testidhooks on the tab labels, request pane, console header, and devtools tabs, and switching these assertions togetByTestId/locators.*.As per coding guidelines: "Add
data-testidto testable elements for Playwright".Also applies to: 179-182, 446-452, 470-471
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/snapshots/basic.spec.ts` around lines 61 - 66, The test uses brittle structural selectors (e.g., the locator '.request-tab .tab-label' and variables tabs/tabTexts/alphaIndex/betaIndex) which can break on markup or Tailwind changes; add stable data-testid attributes to the UI elements (tab labels, request pane, console header, console tabs, devtools button) and update the test to query by those IDs (e.g., getByTestId or page.locator('[data-testid="..."]')) to find the alpha and beta tabs and assert their ordering using the new test IDs instead of structural CSS selectors.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/bruno-electron/src/services/snapshot/index.js`:
- Around line 505-545: The current implementation repeatedly calls fs.existsSync
from _normalizeCollectionEnvironmentRef → _resolveEnvironmentPathByName during
reads; change this so resolution happens once and reads are fast: either resolve
and store the absolute environment path when selectEnvironment is dispatched
(store on the collection snapshot or workspace state) or implement an
instance-level cache keyed by (collectionPath, environmentName) in the snapshot
service that _resolveEnvironmentPathByName consults and populates on first
successful resolution; update _normalizeCollectionEnvironmentRef to return the
cached/stored absolute path when available and remove per-read fs.existsSync
checks.
- Around line 459-477: The code assumes collections and tabs are arrays but
legacy snapshots provide plain objects, causing the spread to throw; update the
logic where collectionEntries, tabsEntries and collectionPathnames are derived
so they work for both shapes: if collections (or tabs) is an array, use it
as-is, otherwise use Object.keys(collections) (and Object.keys(tabs) or empty
array) so collectionPathnames becomes a Set of keys; keep the subsequent calls
to this._normalizeCollectionEntry(collectionPathname,
collectionEntries[collectionPathname], tabsEntries[collectionPathname]) and
normalizeLookupKey(collectionPathname) intact and ensure this change is applied
in the migration path used by _migrateLegacySnapshot so legacy object-shaped
snapshots are properly iterated and normalized.
In `@tests/snapshots/basic.spec.ts`:
- Around line 535-541: The test has a race where waitForTimeout(2000) may be
reset by later activity so closeElectronApp(app) can exit before snapshot is
flushed; update the test using closeElectronApp/readSnapshot by either (A)
replacing the fixed wait with a poll assertion that the snapshot file exists
(e.g., expect.poll(() => fs.existsSync(snapshotPath)).toBe(true)) after closing
the app, or (B) add and call an IPC/test-hook to force-flush snapshots from the
renderer/main before calling closeElectronApp(app); locate usages around
waitForTimeout, closeElectronApp, readSnapshot and snapshotPath and apply the
polling or flush-hook pattern consistently for all similar sites.
---
Nitpick comments:
In `@packages/bruno-electron/src/services/snapshot/index.js`:
- Around line 302-310: The update({ type, data }) dispatcher currently swallows
unknown types in its switch default; modify the default branch in the update
method to emit a dev-time warning (e.g., console.warn or a debug logger) that
includes the unrecognized type and the provided data to aid debugging—keep the
existing case for 'COLLECTION_ENVIRONMENT' and the call to
this.updateCollectionEnvironment(data || {}) but add the warning in default so
unexpected dispatches are visible during development.
- Around line 335-346: The stringify comparison in _migrateLegacySnapshot causes
unnecessary writes; replace it with a lightweight "needs migration" check that
inspects this.store.store for known legacy shapes (e.g., missing top-level
"tabs", "collections" not an array, missing extras.devTools.tabData or other
default fields), and only call this._normalizeSnapshot(currentSnapshot) and
assign this.store.store = normalizedSnapshot when one of those quick checks
returns true. Update _migrateLegacySnapshot to perform these targeted checks
(and fall back to normalization if ambiguous), keeping _normalizeSnapshot
unchanged but only invoked when migration is required.
- Around line 184-194: saveSnapshot currently normalizes first so
snapshotSchema.validateSync never fails; change the order to validate the raw
input before coercion: call snapshotSchema.validateSync(data, { strict: true })
(or validateSync on the not-yet-coerced pieces) before calling
this._normalizeSnapshot(data), then proceed to set this.store.store =
normalizedSnapshot; keep the try/catch but ensure you validate the original data
(not normalizedSnapshot) so validation errors are catchable and logged.
In `@tests/snapshots/basic.spec.ts`:
- Around line 195-205: Extract the repeated WORKSPACE_YML string into a shared
fixture: create a file at tests/snapshots/fixtures/workspace-b/workspace.yml
containing the YAML, and update usages of the WORKSPACE_YML variable (and the
fs.writeFileSync(path.join(workspaceBPath, 'workspace.yml'), WORKSPACE_YML)
calls) to read that file once (e.g., fs.readFileSync or a module-level constant
import) instead of inlining the YAML in each test; alternatively, if you prefer
not to add a fixture file, declare WORKSPACE_YML as a module-level constant at
the top of tests/snapshots/basic.spec.ts and reuse it in the three places
referenced (lines around WORKSPACE_YML, 247-257, 361-371).
- Around line 61-66: The test uses brittle structural selectors (e.g., the
locator '.request-tab .tab-label' and variables
tabs/tabTexts/alphaIndex/betaIndex) which can break on markup or Tailwind
changes; add stable data-testid attributes to the UI elements (tab labels,
request pane, console header, console tabs, devtools button) and update the test
to query by those IDs (e.g., getByTestId or page.locator('[data-testid="..."]'))
to find the alpha and beta tabs and assert their ordering using the new test IDs
instead of structural CSS selectors.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 83dbc2d9-eb01-466f-a5ec-a894416c820f
📒 Files selected for processing (5)
packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.jspackages/bruno-app/src/utils/snapshot/index.jspackages/bruno-app/src/utils/snapshot/index.spec.jspackages/bruno-electron/src/services/snapshot/index.jstests/snapshots/basic.spec.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/bruno-app/src/utils/snapshot/index.spec.js
- packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js
- packages/bruno-app/src/utils/snapshot/index.js
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js (1)
390-425: RedundantworkspaceOverviewdispatches in fallback branches.Lines 392-393 unconditionally add the overview and environments tabs for the scratch collection. The fallback dispatches at lines 420 and 424 re-add the same
${scratchCollection.uid}-overviewtab — harmless if the reducer treatsaddTabas idempotent onuid, but it's dead work and obscures intent. If the goal is to focus the overview tab when there's no active tab to restore, that should be afocusTab/setActiveTabdispatch, not anotheraddTab.♻️ Suggested cleanup
if (activeTab) { dispatch(addTab(activeTab)); - } else if (scratchCollection?.uid) { - dispatch(addTab({ uid: `${scratchCollection.uid}-overview`, collectionUid: scratchCollection.uid, type: 'workspaceOverview' })); } - } else if (scratchCollection?.uid) { - // No active collection, focus the workspace overview tab - dispatch(addTab({ uid: `${scratchCollection.uid}-overview`, collectionUid: scratchCollection.uid, type: 'workspaceOverview' })); }If focusing the overview is actually desired in these branches, replace with an explicit
setActiveTabfor that uid.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js` around lines 390 - 425, The code currently unconditionally dispatches addTab for the scratchCollection overview and environments (addTab) and then later may dispatch addTab again to "focus" the overview, causing redundant work; change those fallback addTab calls (the ones after getActiveTabFromSnapshot and in the else branch) to dispatch an explicit focus/set-active action instead of addTab — e.g., replace dispatch(addTab({ uid: `${scratchCollection.uid}-overview`, ... })) with dispatch(setActiveTab({ uid: `${scratchCollection.uid}-overview` })) or dispatch(focusTab({ uid: `${scratchCollection.uid}-overview` })); keep the initial addTab for creating tabs (and keep addTab for environments), but ensure you reference the existing action creators addTab, setActiveTab or focusTab and the scratchCollection.uid and activeTab/getActiveTabFromSnapshot logic when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js`:
- Around line 301-303: The current dedupe uses new Set(collectionPaths) which
compares raw strings and loses normalization; change the logic that builds
uniqueCollectionPaths to key by normalizePath(p) (like the
workspaceConfigUpdatedEvent code) — e.g. build a Map where the key is
normalizePath(path) and the value is the original path (or first seen canonical
form), then set uniqueCollectionPaths = Array.from(yourMap.values()) so paths
differing only by case/sep/trailing slash are coalesced; update the block that
references collectionPaths/uniqueCollectionPaths accordingly to mirror the
normalizePath + Map pattern used elsewhere.
---
Nitpick comments:
In `@packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js`:
- Around line 390-425: The code currently unconditionally dispatches addTab for
the scratchCollection overview and environments (addTab) and then later may
dispatch addTab again to "focus" the overview, causing redundant work; change
those fallback addTab calls (the ones after getActiveTabFromSnapshot and in the
else branch) to dispatch an explicit focus/set-active action instead of addTab —
e.g., replace dispatch(addTab({ uid: `${scratchCollection.uid}-overview`, ...
})) with dispatch(setActiveTab({ uid: `${scratchCollection.uid}-overview` })) or
dispatch(focusTab({ uid: `${scratchCollection.uid}-overview` })); keep the
initial addTab for creating tabs (and keep addTab for environments), but ensure
you reference the existing action creators addTab, setActiveTab or focusTab and
the scratchCollection.uid and activeTab/getActiveTabFromSnapshot logic when
making the change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1e7a94e6-ec8f-488f-a2aa-8ddb4a319a40
📒 Files selected for processing (1)
packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js (2)
302-343:requestedCollectionPathsis computed and returned but nobody reads it.
switchWorkspaceonly destructuresupdatedWorkspacefrom the return (line 526). Either drop the second field or have the caller consume it (e.g., to seedpendingCollectionPathnameswithout re-deriving from workspace state at lines 529–592). Right now it's just noise on both the happy path and the catch branch.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js` around lines 302 - 343, The PR returns requestedCollectionPaths from the action but the caller switchWorkspace only uses updatedWorkspace, so requestedCollectionPaths is unused noise; either remove requestedCollectionPaths from the returned object in the action (the function that computes it around requestedCollectionPaths, uniqueCollectionPaths, openCollectionsFunction and loadWorkspaceCollections) and from the catch branch, or update the switchWorkspace caller to destructure and consume requestedCollectionPaths (e.g., seed pendingCollectionPathnames instead of re-deriving them) so the computed list is actually used; pick one approach and apply consistently to the action and switchWorkspace caller (and any related logic that expects pendingCollectionPathnames).
431-452: ThreadsnapshotLookupsinto on-demand hydration too.
hydrateTabsandgetActiveTabFromSnapshotboth accept asnapshotLookupsargument and fall back to IPC (renderer:snapshot:get-tabs) when it's missing. InswitchWorkspaceyou rightly pass the lookups; here each opened collection will incur 1–2 extra IPC round-trips. Cache the lookups (e.g., fetch once per session or hang them off the hydration session state) and pass them through.🛠️ Sketch
- await hydrateTabs([collection], dispatch, restoreTabs); + await hydrateTabs([collection], dispatch, restoreTabs, snapshotLookups); ... - const activeTab = await getActiveTabFromSnapshot(collection.pathname, collection); + const activeTab = await getActiveTabFromSnapshot(collection.pathname, collection, snapshotLookups);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js` around lines 431 - 452, The on-demand hydration in this block should reuse a cached snapshotLookups and pass it into hydrateTabs and getActiveTabFromSnapshot to avoid repeated IPC; locate the snapshotLookups source (e.g., from snapshotHydration or the hydration session state used in switchWorkspace) and thread that value into the calls to hydrateTabs([collection], dispatch, restoreTabs) and getActiveTabFromSnapshot(collection.pathname, collection) so they become hydrateTabs([collection], dispatch, restoreTabs, snapshotLookups) and getActiveTabFromSnapshot(collection.pathname, collection, snapshotLookups) (and ensure any upstream callers propagate the same cached snapshotLookups).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js`:
- Around line 720-745: The comparison that sets shouldSwitch uses a raw string
equality (workspacePath === activeWorkspacePath); update it to normalize both
sides before comparing using the existing normalizePath utility (e.g.,
normalizePath(workspacePath) === normalizePath(activeWorkspacePath)) and ensure
you guard for undefined/null activeWorkspacePath; keep the fallback behavior
unchanged. Locate the comparison in the block that awaits
ipcRenderer.invoke('renderer:snapshot:get') and modify that conditional only,
reusing the same normalizePath function used elsewhere in this file.
- Around line 395-458: In hydrateSnapshotForOpenedCollection, when no matching
collection is found in state.collections.collections (the branch that currently
returns early), dispatch markSnapshotCollectionHydrated for that pathname (use
the incoming collectionPathname/normalizedCollectionPath) so the pathname is
removed from pendingCollectionPathnames and then call
maybeCompleteSnapshotHydrationSession(dispatch, getState) (optionally log a
warning) before returning; update references in the function
(hydrateSnapshotForOpenedCollection, markSnapshotCollectionHydrated,
maybeCompleteSnapshotHydrationSession, state.collections.collections)
accordingly.
---
Nitpick comments:
In `@packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js`:
- Around line 302-343: The PR returns requestedCollectionPaths from the action
but the caller switchWorkspace only uses updatedWorkspace, so
requestedCollectionPaths is unused noise; either remove requestedCollectionPaths
from the returned object in the action (the function that computes it around
requestedCollectionPaths, uniqueCollectionPaths, openCollectionsFunction and
loadWorkspaceCollections) and from the catch branch, or update the
switchWorkspace caller to destructure and consume requestedCollectionPaths
(e.g., seed pendingCollectionPathnames instead of re-deriving them) so the
computed list is actually used; pick one approach and apply consistently to the
action and switchWorkspace caller (and any related logic that expects
pendingCollectionPathnames).
- Around line 431-452: The on-demand hydration in this block should reuse a
cached snapshotLookups and pass it into hydrateTabs and getActiveTabFromSnapshot
to avoid repeated IPC; locate the snapshotLookups source (e.g., from
snapshotHydration or the hydration session state used in switchWorkspace) and
thread that value into the calls to hydrateTabs([collection], dispatch,
restoreTabs) and getActiveTabFromSnapshot(collection.pathname, collection) so
they become hydrateTabs([collection], dispatch, restoreTabs, snapshotLookups)
and getActiveTabFromSnapshot(collection.pathname, collection, snapshotLookups)
(and ensure any upstream callers propagate the same cached snapshotLookups).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 124d7466-ecfd-4a5f-9b68-f73216047f45
📒 Files selected for processing (4)
packages/bruno-app/src/providers/App/useIpcEvents.jspackages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.jspackages/bruno-app/src/providers/ReduxStore/slices/app.jspackages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js
- packages/bruno-app/src/providers/ReduxStore/slices/app.js
* feat(snapshot): add session snapshot persistence and restoration - Add snapshot middleware to persist UI state (tabs, workspaces, environments) - Add SnapshotManager service in electron for atomic snapshot storage - Add accessor-based tab serialization using pathname for reliable restoration - Add loading states for tabs while collections are mounting - Add hydrateTabs to restore tabs from snapshots on app load - Add devTools state persistence (console open/height/tab) * fix(snapshot): preserve unloaded collections and fix async serialization Make serializeSnapshot async to fetch existing snapshot before saving, ensuring collections not currently loaded in Redux are preserved. Fix activeTab serialization to pass collection object instead of just UID. * refactor(snapshot): rewrite storage to map-based schema with granular IPC Replace array-based snapshot storage with key-value maps keyed by pathname for O(1) lookups. Separate tabs into their own top-level map, decoupled from collections. - Rewrite SnapshotManager with map-based schema and granular read/write methods (getWorkspace, getTabs, setCollection, removeWorkspace, etc.) - Add 12 granular IPC handlers (renderer:snapshot:*) replacing 4 coarse ones - Update middleware serialization to produce maps; remove activeCollectionUidCache in favor of lastActiveCollectionPathname on workspace objects - Fix mountCollection passing collectionUid instead of collection to restoreTabs - Preserve non-active workspace state from existing snapshot on save * wip * refactor: allow migration of old snapshot * refactor: trim down redundancy * fix: for workspace state * feat: fix for finalised schema * fix: schema cleanup * chore: simplify * chore: wait on hydration to finish * chore: snapshot changes to schema * chore: fix typo * fix: switch schema for saving and restoring extras * chore: correctness changes * chore: add active in the schema check * chore: fix lint * chore: comments * chore: make writes async * fix: sorting and cross workspace shared collection fixes * chore: add version * fix: wait on hydration * chore: fix backward compat for ui-snapshots * chore: dead code removal * Fix optional chaining in snapshot lookup --------- Co-authored-by: Chirag Chandrashekhar <[email protected]>
* feat: implement proxy-aware API fetching using axios instance (usebruno#7767) * fix(cli): skip headers with empty name when building request (usebruno#7869) * Revert "feat: ws multi message (usebruno#7719)" (usebruno#7921) This reverts commit a305b41. * fix: remove dragbar z-index that was bleeding through modals (usebruno#7924) * feat: ui state snapshots (usebruno#7794) * feat(snapshot): add session snapshot persistence and restoration - Add snapshot middleware to persist UI state (tabs, workspaces, environments) - Add SnapshotManager service in electron for atomic snapshot storage - Add accessor-based tab serialization using pathname for reliable restoration - Add loading states for tabs while collections are mounting - Add hydrateTabs to restore tabs from snapshots on app load - Add devTools state persistence (console open/height/tab) * fix(snapshot): preserve unloaded collections and fix async serialization Make serializeSnapshot async to fetch existing snapshot before saving, ensuring collections not currently loaded in Redux are preserved. Fix activeTab serialization to pass collection object instead of just UID. * refactor(snapshot): rewrite storage to map-based schema with granular IPC Replace array-based snapshot storage with key-value maps keyed by pathname for O(1) lookups. Separate tabs into their own top-level map, decoupled from collections. - Rewrite SnapshotManager with map-based schema and granular read/write methods (getWorkspace, getTabs, setCollection, removeWorkspace, etc.) - Add 12 granular IPC handlers (renderer:snapshot:*) replacing 4 coarse ones - Update middleware serialization to produce maps; remove activeCollectionUidCache in favor of lastActiveCollectionPathname on workspace objects - Fix mountCollection passing collectionUid instead of collection to restoreTabs - Preserve non-active workspace state from existing snapshot on save * wip * refactor: allow migration of old snapshot * refactor: trim down redundancy * fix: for workspace state * feat: fix for finalised schema * fix: schema cleanup * chore: simplify * chore: wait on hydration to finish * chore: snapshot changes to schema * chore: fix typo * fix: switch schema for saving and restoring extras * chore: correctness changes * chore: add active in the schema check * chore: fix lint * chore: comments * chore: make writes async * fix: sorting and cross workspace shared collection fixes * chore: add version * fix: wait on hydration * chore: fix backward compat for ui-snapshots * chore: dead code removal * Fix optional chaining in snapshot lookup --------- Co-authored-by: Chirag Chandrashekhar <[email protected]> * fix: scrollbar restoration (usebruno#7926) * fix: restore scrollbar * chore: remove comments --------- Co-authored-by: shubh-bruno <[email protected]> * fix: message in ConnectGitRemote and RemoveGitRemote (usebruno#7929) * fix: allow empty header names in CLI and gRPC request preparation (usebruno#7925) * refactor: remove idx from HeaderList, extend ReadOnlyPropertyList, add positional method translations (usebruno#7917) * refactor: remove 'idx' method from headerList and update related tests - Eliminated the 'idx' method from both req.headerList and res.headerList to streamline header management. - Updated associated tests and documentation to reflect the removal, ensuring clarity in the API usage and maintaining consistency across the header management system. * refactor: block unimplemented HeaderList methods with error messages - Added error handling for unimplemented methods in HeaderList, including idx, add, upsert, remove, each, prepend, insert, and insertAfter. - Each method now throws a descriptive error indicating the appropriate alternative methods to use, enhancing clarity in the API and guiding users towards correct usage. * refactor: update error message in idx() method of HeaderList for clarity - Modified the error message in the idx() method to guide users towards using all()[index] or get(name) instead of the unsupported idx() method, enhancing the clarity of the API documentation. * refactor: update HeaderList to extend ReadOnlyPropertyList and remove unimplemented methods - Changed HeaderList to extend ReadOnlyPropertyList instead of PropertyList, streamlining its functionality. - Removed unimplemented methods (prepend, insert, insertAfter) from HeaderList, clarifying the API and guiding users towards using supported methods. - Updated related tests to reflect these changes, ensuring consistency and accuracy in header management. * test: add translations for pm.request.headers methods in request tests - Introduced new tests to validate the translation of pm.request.headers methods (prepend, insert, insertAfter) to their corresponding req.headerList.append method. - Enhanced existing tests to ensure accurate conversion and functionality of header management in the Bruno converters. * feat: enhance header translation methods for pm.request.headers - Added translations for additional pm.request.headers methods (get, has, one, all, count, indexOf, find, filter, each, map, reduce, toObject, clear) to their corresponding req.headerList methods. - Updated tests to validate the new translations and ensure accurate header management functionality in the Bruno converters. --------- Co-authored-by: Pragadesh-45 <[email protected]> Co-authored-by: Sid <[email protected]> Co-authored-by: gopu-bruno <[email protected]> Co-authored-by: Chirag Chandrashekhar <[email protected]> Co-authored-by: shubh-bruno <[email protected]> Co-authored-by: shubh-bruno <[email protected]> Co-authored-by: naman-bruno <[email protected]> Co-authored-by: sanish chirayath <[email protected]>
Description
Extends #7494 with a few changes before finalising them in the original PR
Contribution Checklist:
Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.
Publishing to New Package Managers
Please see here for more information.
Summary by CodeRabbit
New Features
Bug Fixes
Style
Tests