Repository navigation
fix(snapshot): active workspace restoration from snapshot - #8392
Conversation
- 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.
|
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 snapshot-driven active workspace restore on startup: a new ChangesSnapshot-driven workspace restore
Sequence DiagramsequenceDiagram
rect rgba(100, 120, 200, 0.5)
Note over ElectronMain,workspacesActions: Startup Restore Flow
end
participant ElectronMain as Electron Main
participant useIpcEvents as useIpcEvents (Renderer)
participant workspacesActions as workspaces/actions.js
participant snapshotService as Snapshot Service
ElectronMain->>ElectronMain: resolveLastOpenedWorkspacePaths()
ElectronMain->>ElectronMain: load each workspace (workspaceOpenedEvent dispatched)
Note over workspacesActions: startupWorkspaceRestorePending=true → early-return, no switch
ElectronMain->>useIpcEvents: send('main:workspaces-ready')
useIpcEvents->>workspacesActions: dispatch(restoreActiveWorkspaceFromSnapshot)
workspacesActions->>workspacesActions: clear startupWorkspaceRestorePending
workspacesActions->>snapshotService: ipcRenderer.invoke('renderer:snapshot:get')
snapshotService-->>workspacesActions: snapshot { activeWorkspacePath }
workspacesActions->>workspacesActions: match path → switchWorkspace or fallback to default
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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.
🧹 Nitpick comments (2)
tests/snapshots/active-workspace-restore.spec.ts (1)
97-124: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winWrap actions in
test.stepand extract locators.Per the e2e path instructions, structure each test with
test.step(Arrange/Act/Assert) for readable reports, and assign reused locators (e.g.workspace-name,workspace-menu) to variables. The second test also skips the active-item assertion the first one makes — worth mirroring for parity.As per path instructions: "Promote the use of
test.stepas much as possible" and "Use locator variables for locators".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/snapshots/active-workspace-restore.spec.ts` around lines 97 - 124, Wrap both workspace restore tests in test.step blocks for clear Arrange/Act/Assert reporting, and extract repeated locators such as workspace-name and workspace-menu into local variables before reuse. Update the 5th-position restore test to mirror the active-item assertion used in the 4th-position test so both cases validate the restored active workspace consistently. Use the existing test functions and helper calls in active-workspace-restore.spec.ts to keep the structure aligned.Source: Path instructions
packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js (1)
843-881: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueOptional: fold the two
renderer:snapshot:getcalls into one.
workspaceOpenedEventinvokesrenderer:snapshot:gettwice per event (Line 844 for devtools, Line 869 for the switch decision). Reusing a single fetch trims an IPC round-trip on every workspace-opened.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js` around lines 843 - 881, `workspaceOpenedEvent` is calling `ipcRenderer.invoke('renderer:snapshot:get')` twice in the same flow, once for devtools state and again for the workspace switch decision. Fetch the snapshot once near the start of the function, reuse that value for both the devtools handling and the `shouldSwitch` calculation, and keep the existing fallback behavior in the `catch` path when the snapshot lookup fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js`:
- Around line 843-881: `workspaceOpenedEvent` is calling
`ipcRenderer.invoke('renderer:snapshot:get')` twice in the same flow, once for
devtools state and again for the workspace switch decision. Fetch the snapshot
once near the start of the function, reuse that value for both the devtools
handling and the `shouldSwitch` calculation, and keep the existing fallback
behavior in the `catch` path when the snapshot lookup fails.
In `@tests/snapshots/active-workspace-restore.spec.ts`:
- Around line 97-124: Wrap both workspace restore tests in test.step blocks for
clear Arrange/Act/Assert reporting, and extract repeated locators such as
workspace-name and workspace-menu into local variables before reuse. Update the
5th-position restore test to mirror the active-item assertion used in the
4th-position test so both cases validate the restored active workspace
consistently. Use the existing test functions and helper calls in
active-workspace-restore.spec.ts to keep the structure aligned.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: a09db041-762d-4e56-9602-39a09ccdc92d
📒 Files selected for processing (6)
packages/bruno-app/src/providers/App/useIpcEvents.jspackages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.jspackages/bruno-electron/src/ipc/workspace.jspackages/bruno-electron/src/utils/workspace-startup.jspackages/bruno-electron/tests/utils/workspace-startup.spec.jstests/snapshots/active-workspace-restore.spec.ts
…reservation 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.
There was a problem hiding this comment.
Actionable comments posted: 4
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/middlewares/snapshot/middleware.js (1)
57-64: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winInvalidate in-flight debounced saves before flushing.
clearTimeout(saveTimer)only stops a callback that has not started yet. If the debounced save is already insideserializeSnapshot()oripcRenderer.invoke(),flushSnapshotNow()can write the fresh snapshot and the older callback can still finish afterwards, overwriting it with stale state. Track a save generation or in-flight promise so older writes bail before persisting.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js` around lines 57 - 64, The snapshot middleware’s `handleAction` path for `app/setSnapshotReady` only cancels the pending timeout, so an already-running debounced save can still complete after `flushSnapshotNow(getState)` and overwrite the newer snapshot with stale data. Update the snapshot save flow in the middleware to track an in-flight save generation or promise state around `serializeSnapshot()` and `ipcRenderer.invoke()` so older saves detect they are stale and exit before persisting; use the existing `saveTimer`, `flushSnapshotNow`, and snapshot write logic to gate writes by the latest generation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js`:
- Around line 105-115: `serializeSnapshot` can throw during fresh snapshot
creation because `existingDevTools.tabs` may be undefined when no prior snapshot
exists. Update the snapshot-building logic in `serializeSnapshot` to fall back
to a safe empty object before calling `Object.assign`, and use the resolved
active tab value consistently for both `activeTab` and the `tabs` entry so the
initial snapshot can be saved without crashing.
In
`@packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js`:
- Around line 128-202: Add coverage for the first-run path in serializeSnapshot
by including a test where getExistingSnapshot returns null, since all current
cases assume an existing snapshot. Update the serializeSnapshot collection
environment preservation spec to verify behavior when bootstrap starts with no
prior snapshot, using the existing serializeSnapshot and makeState helpers, so
regressions in extras.devTools are caught.
In `@tests/snapshots/environment/environment.spec.ts`:
- Around line 132-139: The restart test uses fixed sleeps in the snapshot
persistence flow, which is both slow and flaky. In environment.spec.ts, replace
the two page2.waitForTimeout(2000) calls with an event-driven wait tied to
snapshot persistence, reusing waitForSnapshotCollectionEnvironment() or
expect.poll() around the openCollection/page2 assertions so the test waits for
the expected environment state instead of an arbitrary delay.
In `@tests/utils/snapshot.ts`:
- Around line 65-69: The polling logic in
findSnapshotCollectionEntry/readSnapshot handling currently returns an empty
string for both a missing snapshot entry and a deliberately cleared
selectedEnvironment, so waits for an empty selection can succeed too early.
Update the snapshot polling in snapshot.ts to return a distinct sentinel value
until the collection entry exists, and only return '' once the entry is actually
present and cleared. Keep the change localized around the expect.poll callback
that reads snapshot entries so callers waiting on selectedEnvironment behave
correctly.
---
Outside diff comments:
In
`@packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js`:
- Around line 57-64: The snapshot middleware’s `handleAction` path for
`app/setSnapshotReady` only cancels the pending timeout, so an already-running
debounced save can still complete after `flushSnapshotNow(getState)` and
overwrite the newer snapshot with stale data. Update the snapshot save flow in
the middleware to track an in-flight save generation or promise state around
`serializeSnapshot()` and `ipcRenderer.invoke()` so older saves detect they are
stale and exit before persisting; use the existing `saveTimer`,
`flushSnapshotNow`, and snapshot write logic to gate writes by the latest
generation.
🪄 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: b7b61888-8e7e-4d0f-8d87-e73e3cc99874
📒 Files selected for processing (5)
packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.jspackages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.jspackages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.jstests/snapshots/environment/environment.spec.tstests/utils/snapshot.ts
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/snapshots/environment/environment.spec.ts`:
- Around line 323-327: The restart flow in the environment snapshot tests only
checks persistence via ui-state-snapshot.json and does not assert the
user-visible restored state. In the relaunch block around launchElectronApp,
waitForReadyPage, and openCollection, add an assertion on the visible
environment selection or degraded-mode UI state before closeElectronApp(app2),
so the test follows Arrange-Act-Assert-Cleanup and verifies what the user
actually sees; keep the snapshot assertion as a secondary check.
- Around line 316-318: The snapshot restart assertions are bypassing the shared
normalized-path matcher and using raw pathname equality, which can break
OS-agnostic behavior. Update the lookup logic in environment.spec.ts to use
findSnapshotCollectionEntry() (from tests/utils/snapshot.ts) when locating the
relevant collection entry, and then read environmentPath/environment from that
matched entry instead of comparing collection.pathname directly. Apply the same
helper-based lookup to all affected assertions in the restart coverage block so
the test follows the same normalized-path contract as the rest of the snapshot
tests.
🪄 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: d6bd0ab8-d1f7-42c4-b1d6-d2a35d938a1f
📒 Files selected for processing (1)
tests/snapshots/environment/environment.spec.ts
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/bruno-electron/src/ipc/snapshot.js`:
- Around line 21-22: The new saveToken IPC argument is not propagated
end-to-end, so stale-save protection never takes effect. Update the renderer
call site in snapshot middleware to pass the token when invoking the
renderer:snapshot:save channel, and update snapshotManager.saveSnapshot in
packages/bruno-electron/src/services/snapshot/index.js to accept and use
saveToken so the persisted snapshot state is actually gated by it.
In `@packages/bruno-electron/src/services/snapshot/index.js`:
- Around line 294-304: `devTools.tabs` is only defaulted with `|| {}`, so
non-object truthy values can still reach the `key in devToolTabs` check and
throw during snapshot normalization. Update the normalization logic in the
snapshot service around `_snapshotEntry` and `devToolKeys.forEach` to coerce
`devTools.tabs` to a plain object only when it is actually an object, otherwise
fall back to `{}` before using `in`.
🪄 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: dc3c817f-8a03-4749-a0b0-c04f6b771a49
📒 Files selected for processing (8)
packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.jspackages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.jspackages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.jspackages/bruno-electron/src/ipc/snapshot.jspackages/bruno-electron/src/services/snapshot/index.jstests/snapshots/active-workspace-restore.spec.tstests/snapshots/environment/environment.spec.tstests/utils/snapshot.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- tests/utils/snapshot.ts
- tests/snapshots/active-workspace-restore.spec.ts
- packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js
- packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js
- packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js
- tests/snapshots/environment/environment.spec.ts
…anager and add corresponding tests
…hared collections
There was a problem hiding this comment.
Pull request overview
Improves snapshot-driven startup restoration by (1) restoring the previously active workspace, and (2) scoping collection snapshot state (notably selected environments) to the workspace so the same collection can retain different environment selections per workspace. The PR also refactors snapshot serialization/persistence to preserve environment fields for unmounted/unhydrated collections and adds extensive test coverage around these scenarios.
Changes:
- Add active-workspace restore flow using a new
main:workspaces-readyIPC signal + renderer action to switch to the snapshot’s active workspace (fallback to default). - Make snapshot collection state workspace-aware (lookup keys, hydration, IPC getters, watcher hydration payload), and preserve environment fields when collections are unmounted or not yet hydrated.
- Add new Playwright + Jest test suites to cover active workspace restore, shared-collection environment isolation, collection deduplication, and snapshot environment preservation.
Reviewed changes
Copilot reviewed 23 out of 23 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/utils/snapshot.ts | Adds snapshot helpers to find collection entries and poll for persisted selected environment. |
| tests/utils/page/locators.ts | Adds locators for environment creation via settings sidebar and modal flows. |
| tests/utils/page/actions.ts | Improves test robustness (hover re-polling, environment creation via empty-state vs settings). |
| tests/snapshots/shared-collection-workspace-environment.spec.ts | New Playwright test ensuring shared collection restores per-workspace selected environment. |
| tests/snapshots/environment/environment.spec.ts | Refactors snapshot assertions + adds new persistence/regression scenarios. |
| tests/snapshots/collection-dedup.spec.ts | New Playwright test for deduplicating/merging duplicate snapshot collection entries. |
| tests/snapshots/active-workspace-restore.spec.ts | New Playwright test ensuring active workspace restores from snapshot after restart. |
| packages/bruno-electron/tests/utils/workspace-startup.spec.js | New Jest unit tests for workspace startup path normalization/validation/prioritization. |
| packages/bruno-electron/src/utils/workspace-startup.js | New utility to resolve/validate MRU workspaces and prioritize snapshot active workspace. |
| packages/bruno-electron/src/services/snapshot/index.js | Adds workspace-scoped collection lookups + merge/dedup behavior + devtools normalization tweaks. |
| packages/bruno-electron/src/ipc/workspace.js | Uses workspace-startup resolver; emits main:workspaces-ready after initialization. |
| packages/bruno-electron/src/ipc/snapshot.js | Adds IPC to fetch a collection snapshot entry scoped by workspace. |
| packages/bruno-electron/src/ipc/collection.js | Passes workspacePathname through mount-collection IPC into watcher setup. |
| packages/bruno-electron/src/app/collection-watcher.js | Hydrates collection environment state using workspace-scoped snapshot lookup. |
| packages/bruno-app/src/utils/snapshot/index.spec.js | Extends snapshot lookup tests for workspace-scoped collection environment resolution. |
| packages/bruno-app/src/utils/snapshot/index.js | Adds sourceWorkspacePathname + getCollectionSnapshotFromLookups helper. |
| packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js | Adds restoreActiveWorkspaceFromSnapshot and gates startup switching until workspaces are ready. |
| packages/bruno-app/src/providers/ReduxStore/slices/collections/index.js | Removes inline snapshot persistence from reducer (moved to action/event-driven flows). |
| packages/bruno-app/src/providers/ReduxStore/slices/collections/actions.js | Persists collection environment selections with workspacePathname; hydrates env snapshot on mount. |
| packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.spec.js | New Jest tests for snapshot environment preservation rules and devtools defaults. |
| packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/serializeSnapshot.js | New snapshot serializer with environment-preservation logic and safer devtools tab handling. |
| packages/bruno-app/src/providers/ReduxStore/middlewares/snapshot/middleware.js | Refactors middleware to call shared serializeSnapshot module. |
| packages/bruno-app/src/providers/App/useIpcEvents.js | Listens for main:workspaces-ready to trigger active-workspace restoration from snapshot. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
…ation and related tests
…nd add tests for shared collection environment restoration
…napshot seeding utility
Description
JIRA
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