Skip to content

fix(snapshot): normalize renderer:get-last-opened-workspaces output to avoid reactivating a deleted workspace - #8033

Merged
bijin-bruno merged 3 commits into
usebruno:mainfrom
sid-bruno:fix/workspace-switch
May 18, 2026
Merged

bijin-bruno merged 3 commits into
usebruno:mainfrom
sid-bruno:fix/workspace-switch

Conversation

@sid-bruno

@sid-bruno sid-bruno commented May 18, 2026 •

Copy link
Copy Markdown
Collaborator

Description

JIRA

Contribution Checklist:

  • I've used AI significantly to create this pull request
  • The pull request only addresses one issue or adds one feature.
  • The pull request does not introduce any breaking changes
  • I have added screenshots or gifs to help explain the change if applicable.
  • I have read the contribution guidelines.
  • Create an issue and link to the pull request.

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

  • Bug Fixes

    • Normalize workspace paths before comparison so the app reliably detects and switches to the correct workspace.
    • Avoid restoring stale/in-memory active workspace; fall back to the default or last-opened workspace when appropriate.
  • Tests

    • Expanded snapshot/e2e coverage with five scenarios verifying deleted/malformed workspace recovery, fallback to “My Workspace,” and prevention of stale UI restoration.
    • Added a test utility to simulate opening a workspace via the system dialog.

Review Change Stack

Copilot AI review requested due to automatic review settings May 18, 2026 13:29
@coderabbitai

coderabbitai Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR normalizes workspace paths when handling snapshot-driven opens, adjusts switch logic for default workspaces by consulting the last-opened workspaces list, and adds E2E snapshot tests covering deleted/missing/malformed workspace.yml recovery plus a test helper to open workspaces via a stubbed dialog.

Changes

Stale Workspace Snapshot Restoration

Layer / File(s) Summary
Stale workspace detection and restoration logic
packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js
workspaceOpenedEvent now normalizes workspace paths for equality checks. If the snapshot's activeWorkspacePath doesn't match the opened workspace and the workspace config type is default, it calls renderer:get-last-opened-workspaces and sets shouldSwitch based on whether the snapshot path exists in that last-opened list.
Snapshot: Deleted Workspace Restoration tests
tests/snapshots/workspace.spec.ts
Adds a buildWorkspaceYml helper and five Playwright/Electron tests that cover deleted, missing, and malformed workspace.yml cases, stale-tab prevention, and active workspace/tab recovery; tests assert fallback to "My Workspace", preservation of default workspace data, and removal of the deleted/malformed workspace from the list.
Test helper: openWorkspaceFromDialog
tests/utils/page/actions.ts
Adds openWorkspaceFromDialog which stubs dialog.showOpenDialog via app.evaluate, clicks UI to trigger "Open workspace", and exports the helper for tests.

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly Related PRs

  • usebruno/bruno#6343: Related changes to last-opened workspaces storage/lookup semantics (path-based).
  • usebruno/bruno#6456: Related workspace open/switch flow and tab initialization after workspace switch.

Suggested Reviewers

  • helloanoop
  • lohit-bruno
  • naman-bruno
  • bijin-bruno

📦 Workspaces deleted, snapshots gone stale,
Paths normalized now to steady the sail.
Last-opened lists guide the switch with grace,
A default restored, deleted workspace erased. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: normalizing workspace output to prevent reactivating deleted workspaces, which aligns with the core fix in the actions.js file.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sid-bruno
sid-bruno marked this pull request as draft May 18, 2026 13:29

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
tests/snapshots/workspace.spec.ts (1)

55-58: ⚡ Quick win

Prefer event-driven waits over hardcoded timeouts.

page.waitForTimeout(2000) is a magic sleep. Per guidelines, replace brittle timeouts with event-driven waits. If the intent is to ensure snapshot persistence before closing, consider waiting for a specific IPC completion or a UI indicator.

🤖 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/workspace.spec.ts` around lines 55 - 58, The test currently
uses a brittle sleep (page.waitForTimeout(2000)) inside the test.step before
calling closeElectronApp; replace this with an event-driven wait that confirms
snapshot persistence (e.g., wait for a specific IPC completion event, a
network/IPC response, or a UI indicator) instead of a fixed timeout. Update the
test.step to remove page.waitForTimeout and instead await a durable signal such
as page.waitForSelector(...) for a saved indicator, page.waitForFunction(...)
that checks the app state, or an IPC event listener that resolves when the
snapshot save completes, then call closeElectronApp(app).
🤖 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/workspace.spec.ts`:
- Line 12: The test in tests/snapshots/workspace.spec.ts uses an empty
description (the call to test('', async ({ launchElectronApp, createTmpDir }) =>
{ ... })) which makes reports unreadable; replace the empty string with a
concise, meaningful description summarizing what the test asserts (e.g., "opens
workspace and matches snapshot" or similar) so test runner output is clear—edit
the test(...) invocation in that file to provide the new description string.

---

Nitpick comments:
In `@tests/snapshots/workspace.spec.ts`:
- Around line 55-58: The test currently uses a brittle sleep
(page.waitForTimeout(2000)) inside the test.step before calling
closeElectronApp; replace this with an event-driven wait that confirms snapshot
persistence (e.g., wait for a specific IPC completion event, a network/IPC
response, or a UI indicator) instead of a fixed timeout. Update the test.step to
remove page.waitForTimeout and instead await a durable signal such as
page.waitForSelector(...) for a saved indicator, page.waitForFunction(...) that
checks the app state, or an IPC event listener that resolves when the snapshot
save completes, then call closeElectronApp(app).
🪄 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: 644b27bd-dd82-4fae-85dc-e2cceca4d591

📥 Commits

Reviewing files that changed from the base of the PR and between e8468ac and 97bafd7.

📒 Files selected for processing (2)
  • packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js
  • tests/snapshots/workspace.spec.ts

Comment thread tests/snapshots/workspace.spec.ts Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR aims to prevent Bruno from reactivating a workspace that has been deleted from disk by normalizing workspace path comparisons during snapshot hydration, and it adds an end-to-end snapshot test to cover the “deleted workspace” restoration scenario.

Changes:

  • Normalize workspacePath vs snapshot.activeWorkspacePath comparisons when deciding whether to switch workspaces on workspaceOpenedEvent.
  • When opening the default workspace, fall back to it if the snapshot’s active workspace path is no longer present in the persisted “last opened workspaces” list.
  • Add a new Playwright Electron snapshot spec that deletes a workspace directory and asserts the app restores the default workspace state after restart.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
tests/snapshots/workspace.spec.ts Adds an e2e snapshot test to validate default workspace restoration when the previously active workspace has been deleted.
packages/bruno-app/src/providers/ReduxStore/slices/workspaces/actions.js Normalizes workspace path comparisons and adds logic to avoid switching to a stale/deleted workspace referenced by snapshot state.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/snapshots/workspace.spec.ts Resolved
@sid-bruno sid-bruno changed the title fix: normalize renderer:get-last-opened-workspaces output to avoid reactivating a deleted workspace fix(snapshot): normalize renderer:get-last-opened-workspaces output to avoid reactivating a deleted workspace May 18, 2026
@sid-bruno
sid-bruno marked this pull request as ready for review May 18, 2026 13:48
@pull-request-size pull-request-size Bot added size/L and removed size/M labels May 18, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
tests/utils/page/actions.ts (1)

1435-1446: ⚡ Quick win

Use typed parameters and wrap in test.step for better reporting.

The function uses any types for app and page, reducing type safety. ElectronApplication and Page types are imported and available. Additionally, per coding guidelines, test.step should be used extensively for better report readability—similar helpers in this file wrap their logic in test.step.

♻️ Refactor for type safety and reporting
-const openWorkspaceFromDialog = async (app: any, page: any, targetPath: string) => {
-  await app.evaluate(
-    ({ dialog }: { dialog: DialogOptions }, workspacePath: string) => {
-      dialog.showOpenDialog = () =>
-        Promise.resolve({ canceled: false, filePaths: [workspacePath] });
-    },
-    targetPath
-  );
-
-  await page.getByTestId('workspace-menu').click();
-  await page.locator('.dropdown-item').filter({ hasText: 'Open workspace' }).click();
-};
+const openWorkspaceFromDialog = async (app: ElectronApplication, page: Page, targetPath: string) => {
+  await test.step(`Open workspace from dialog: ${targetPath}`, async () => {
+    await app.evaluate(
+      ({ dialog }: { dialog: DialogOptions }, workspacePath: string) => {
+        dialog.showOpenDialog = () =>
+          Promise.resolve({ canceled: false, filePaths: [workspacePath] });
+      },
+      targetPath
+    );
+
+    await page.getByTestId('workspace-menu').click();
+    await page.locator('.dropdown-item').filter({ hasText: 'Open workspace' }).click();
+  });
+};

As per coding guidelines, promote the use of test.step as much as possible so the generated reports are easier to read.

🤖 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/utils/page/actions.ts` around lines 1435 - 1446, The helper
openWorkspaceFromDialog uses untyped parameters and lacks test.step wrappers;
change its signature to use ElectronApplication and Page (instead of any), and
wrap each logical action (stubbing dialog.showOpenDialog via app.evaluate and
the UI clicks via page.getByTestId/locator) in test.step calls for clearer
reporting; update references inside the evaluate callback to match the typed
invocation and ensure the Promise.resolve stub remains unchanged while
preserving the passed targetPath argument.
tests/snapshots/workspace.spec.ts (1)

50-50: ⚡ Quick win

Document the waitForTimeout usage or replace with event-driven wait.

Each test uses page.waitForTimeout(2000) before closing the app without explanation. Per coding guidelines, waitForTimeout should be reduced unless absolutely necessary. If the wait is necessary to allow workspace snapshot writes to complete, add a comment explaining this; otherwise, consider using an event-driven alternative (e.g., app.evaluate to verify the snapshot file has been written).

📝 Example: Add explanatory comment
+    // Wait for workspace snapshot to be persisted to disk before closing
     await page.waitForTimeout(2000);
     await closeElectronApp(app);

Higher-effort alternative: Use app.evaluate to poll for snapshot file modification time or expose an IPC event when snapshot writes complete.

As per coding guidelines, try to reduce usage of page.waitForTimeout(); in code unless absolutely necessary and the locator cannot be found using existing expect() playwright calls.

Also applies to: 94-94, 138-138, 193-193, 243-243

🤖 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/workspace.spec.ts` at line 50, Replace the blind sleeps
(calls to page.waitForTimeout(2000)) with either a short explanatory comment if
the delay is truly required for async snapshot writes, or—preferably—an
event-driven wait: have the test use app.evaluate / page.evaluate to poll for
the workspace snapshot file modification or expose/listen to an IPC/event like
"snapshot-saved" so the test waits for that signal (replace occurrences of
page.waitForTimeout at the spots in tests/snapshots/workspace.spec.ts). If you
keep the wait, add a concise comment explaining why 2000ms is necessary and
reference the snapshot write operation; otherwise implement the file-existence
or IPC-based check to deterministically wait for snapshot completion.
🤖 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 `@tests/snapshots/workspace.spec.ts`:
- Line 50: Replace the blind sleeps (calls to page.waitForTimeout(2000)) with
either a short explanatory comment if the delay is truly required for async
snapshot writes, or—preferably—an event-driven wait: have the test use
app.evaluate / page.evaluate to poll for the workspace snapshot file
modification or expose/listen to an IPC/event like "snapshot-saved" so the test
waits for that signal (replace occurrences of page.waitForTimeout at the spots
in tests/snapshots/workspace.spec.ts). If you keep the wait, add a concise
comment explaining why 2000ms is necessary and reference the snapshot write
operation; otherwise implement the file-existence or IPC-based check to
deterministically wait for snapshot completion.

In `@tests/utils/page/actions.ts`:
- Around line 1435-1446: The helper openWorkspaceFromDialog uses untyped
parameters and lacks test.step wrappers; change its signature to use
ElectronApplication and Page (instead of any), and wrap each logical action
(stubbing dialog.showOpenDialog via app.evaluate and the UI clicks via
page.getByTestId/locator) in test.step calls for clearer reporting; update
references inside the evaluate callback to match the typed invocation and ensure
the Promise.resolve stub remains unchanged while preserving the passed
targetPath argument.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4deb18ba-ec0c-484a-9436-fca762650d25

📥 Commits

Reviewing files that changed from the base of the PR and between f015c74 and 5f2669f.

📒 Files selected for processing (2)
  • tests/snapshots/workspace.spec.ts
  • tests/utils/page/actions.ts

@bijin-bruno
bijin-bruno merged commit cea883e into usebruno:main May 18, 2026
19 of 20 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request May 20, 2026
6 tasks
lyh543 pushed a commit to lyh543/bruno that referenced this pull request May 22, 2026
… to avoid reactivating a deleted workspace (usebruno#8033)

* fix: normalize workspace paths during workspace switch to prevent stale state

* chore: test text

* tests(snapshot): more workspace coverage
sharan-bruno pushed a commit to sharan-bruno/bruno that referenced this pull request Jun 4, 2026
… to avoid reactivating a deleted workspace (usebruno#8033)

* fix: normalize workspace paths during workspace switch to prevent stale state

* chore: test text

* tests(snapshot): more workspace coverage
@coderabbitai coderabbitai Bot mentioned this pull request Jul 6, 2026
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants