Skip to content

fix: default workspace error checking - #6379

Merged
bijin-bruno merged 10 commits into
usebruno:mainfrom
naman-bruno:bugfix/default-workspace
Dec 15, 2025
Merged

bijin-bruno merged 10 commits into
usebruno:mainfrom
naman-bruno:bugfix/default-workspace

Conversation

@naman-bruno

@naman-bruno naman-bruno commented Dec 11, 2025 •

Copy link
Copy Markdown
Collaborator

Description

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

    • Improved default workspace initialization, validation, recovery and error logging.
    • Prunes invalid previously opened workspaces and makes persistence more reliable across restarts.
    • More robust handling when workspace configuration is missing, corrupted, or mismatched.
  • New Features

    • App consistently recognizes a canonical default workspace UID and includes an explicit workspace type in workspace events and payloads.
    • Startup now loads and validates the default and previously opened workspaces, removing invalid entries.
  • Tests

    • Added end-to-end tests for default workspace creation, persistence, recovery and migration; adjusted UI action timing for stability.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 11, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Centralized workspace UID logic via new getWorkspaceUid; default workspace now has a constant UID/type. Workspace config read/validation centralized; IPC and watcher payloads include an explicit type. Default-workspace initialization/validation behavior changed and Playwright tests for default workspace and migration were added.

Changes

Cohort / File(s) Summary
Default Workspace Initialization & Validation
packages/bruno-electron/src/store/default-workspace.js
Added WORKSPACE_TYPE and DEFAULT_WORKSPACE_UID; getDefaultWorkspaceUid() returns constant; added isValidDefaultWorkspace(); initializeDefaultWorkspace(options) now computes default path under userData, uses fs.mkdirSync(..., { recursive: true }), integrates readWorkspaceConfig/validation, and adjusted migration wiring.
Workspace UID & Config Utilities
packages/bruno-electron/src/utils/workspace-config.js
Added and exported getWorkspaceUid(workspacePath) — returns 'default' for default path, otherwise uses hash-based UID via generateUidBasedOnHash.
IPC: Workspace Flows & Payloads
packages/bruno-electron/src/ipc/workspace.js
Replaced generateUidBasedOnHash with getWorkspaceUid; centralized config reads via readWorkspaceConfig(); IPC payloads include explicit type (coerced to 'default' when applicable); improved error logging; renderer-ready loads default then other workspaces and prunes invalid entries.
Watcher: UID & Type Propagation
packages/bruno-electron/src/app/workspace-watcher.js
Switched to getWorkspaceUid(workspacePath) and derived isDefault; adjusted handleWorkspaceFileChange and addWatcher to emit main:workspace-config-updated with coerced type ('default' when UID === 'default').
API Specs Adapter
packages/bruno-electron/src/app/apiSpecs.js
Replaced path-hash UID generation with getWorkspaceUid(options.workspacePath) and coerced emitted type to 'default' when appropriate while preserving normalized config.
Playwright Tests — Default Workspace
tests/workspace/default-workspace/default-workspace.spec.ts
New tests for first-launch default workspace creation, persistence across restarts, recovery from corrupted/missing workspace states, UI assertions (dropdown, absence of pin), and filesystem manipulations to trigger recovery paths.
Playwright Tests — Migration
tests/workspace/default-workspace/migration.spec.ts
New tests validating migration from legacy lastOpenedCollections (single/multiple), skipping sample collections when appropriate, reusing existing workspace, and clean-install behavior.
Test Utilities Update
tests/utils/page/actions.ts
After creating a collection, wait for modal detach with extended timeout (15000 ms) and add a 200 ms delay before proceeding.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Main as Main Process
    participant Prefs as Preferences (FS)
    participant FS as Filesystem
    participant Config as workspace-config
    participant Watcher as WorkspaceWatcher
    participant IPC as IPC/Emitter
    participant Renderer as Renderer

    Main->>Prefs: read preferences.lastOpenedWorkspaces
    Main->>Config: readWorkspaceConfig(defaultPath)
    Config->>FS: read workspace.yml (default)
    FS-->>Config: file contents / error
    Config->>Main: validated default config (type:'default'), uid:'default'
    Main->>IPC: emit main:workspace-opened (default config, uid:'default')
    Main->>Watcher: addWatcher(defaultPath, uid:'default')

    loop for each path in lastOpenedWorkspaces
        Main->>FS: stat(path)
        FS-->>Main: exists / missing
        alt exists
            Main->>Config: readWorkspaceConfig(path)
            Config->>FS: read workspace.yml
            FS-->>Config: contents / invalid
            alt valid
                Config->>Main: validated config (type preserved), uid=hash(path)
                Main->>IPC: emit main:workspace-opened (config, uid)
                Main->>Watcher: addWatcher(path, uid)
            else invalid
                Main->>Prefs: remove path from lastOpenedWorkspaces
                Main->>Console: log error
            end
        else missing
            Main->>Prefs: remove path from lastOpenedWorkspaces
            Main->>Console: log error
        end
    end

    IPC->>Renderer: notify renderer about opened workspaces
    Main->>Prefs: write pruned preferences
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Files warranting extra attention:
    • packages/bruno-electron/src/store/default-workspace.js — path derivation, sync mkdir usage, and signature/behavior changes for initialization.
    • packages/bruno-electron/src/ipc/workspace.js — multiple IPC flows and payload shape changes (addition of type).
    • packages/bruno-electron/src/app/workspace-watcher.js — UID/keying and emitted event payload adjustments.
    • New Playwright tests — reliability of setup/teardown and timeouts.

Possibly related PRs

Suggested labels

size/XXL

Suggested reviewers

  • lohit-bruno
  • helloanoop

Poem

🌱 A default UID planted, steady and round,
Paths read and validated, no surprises found.
Watchers hum and IPCs sing, configs unfold,
Tests stand guard where recoveries are told.
Cheers to clean starts and workspaces bold. 🚀

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title describes default workspace error checking, which aligns with core changes to default workspace validation, error handling, and config retrieval across multiple files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@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: 0

🧹 Nitpick comments (9)
tests/workspace/default-workspace/migration.spec.ts (4)

47-52: Conditional assertion may silently pass if file doesn't exist.

The if (fs.existsSync(workspaceYmlPath)) pattern could cause the test to pass silently without verifying the workspace.yml contents if the file doesn't exist for some reason. Consider asserting that the file exists unconditionally first.

-      // Verify workspace.yml exists and contains the migrated collection
-      const workspaceYmlPath = path.join(workspacePath, 'workspace.yml');
-      if (fs.existsSync(workspaceYmlPath)) {
-        const workspaceYml = fs.readFileSync(workspaceYmlPath, 'utf8');
-        expect(workspaceYml).toContain('collections:');
-        // Collection should be referenced
-        expect(workspaceYml).toContain('my-old-collection');
-      }
+      // Verify workspace.yml exists and contains the migrated collection
+      const workspaceYmlPath = path.join(workspacePath, 'workspace.yml');
+      expect(fs.existsSync(workspaceYmlPath)).toBe(true);
+      const workspaceYml = fs.readFileSync(workspaceYmlPath, 'utf8');
+      expect(workspaceYml).toContain('collections:');
+      // Collection should be referenced
+      expect(workspaceYml).toContain('my-old-collection');

94-98: Same conditional assertion concern as above.

This if block could silently skip assertions. Apply the same fix to make the file existence check an unconditional assertion.

-      if (fs.existsSync(workspaceYmlPath)) {
-        const workspaceYml = fs.readFileSync(workspaceYmlPath, 'utf8');
-        expect(workspaceYml).toContain('collection-1');
-        expect(workspaceYml).toContain('collection-2');
-      }
+      expect(fs.existsSync(workspaceYmlPath)).toBe(true);
+      const workspaceYml = fs.readFileSync(workspaceYmlPath, 'utf8');
+      expect(workspaceYml).toContain('collection-1');
+      expect(workspaceYml).toContain('collection-2');

11-55: Consider wrapping test steps with test.step for improved report readability.

Per coding guidelines, test.step usage is encouraged for better Playwright report structure. The test has distinct phases (setup, launch, verify UI, verify filesystem) that would benefit from this.

Example structure:

await test.step('Setup test collection and preferences', async () => {
  // fs operations here
});

await test.step('Launch app and verify UI', async () => {
  const app = await launchElectronApp({ userDataPath });
  // ...
});

await test.step('Verify workspace filesystem state', async () => {
  // filesystem assertions
});

195-199: Conditional assertion pattern in clean installation test.

Same issue here—the conditional if could silently skip the regex assertion.

-      if (fs.existsSync(workspaceYmlPath)) {
-        const workspaceYml = fs.readFileSync(workspaceYmlPath, 'utf8');
-        // Collections should be empty (just the key)
-        expect(workspaceYml).toMatch(/collections:\s*\n/);
-      }
+      expect(fs.existsSync(workspaceYmlPath)).toBe(true);
+      const workspaceYml = fs.readFileSync(workspaceYmlPath, 'utf8');
+      // Collections should be empty (just the key)
+      expect(workspaceYml).toMatch(/collections:\s*\n/);
tests/workspace/default-workspace/default-workspace.spec.ts (3)

125-132: Consider extracting YAML content to a constant or helper.

The inline multi-line YAML string is functional but could be clearer with a named constant or helper function, especially if similar YAML structures are needed in other tests.


199-201: Using .first() may mask unintended duplicates.

If the dropdown unexpectedly contains multiple items matching "My Workspace", this assertion would still pass. Consider asserting count if uniqueness is expected.

// If only one workspace should exist, assert count first
await expect(workspaceItem).toHaveCount(1);
await expect(workspaceItem).toBeVisible();

188-221: Consider adding test.step for UI behavior tests.

Per coding guidelines, test.step improves report readability. The UI tests have distinct setup/action/assertion phases that would benefit from this structure.

packages/bruno-electron/src/store/default-workspace.js (2)

107-112: Consider adding an upper bound to prevent potential infinite loop.

While extremely unlikely in practice, the while loop has no termination guard if many default-workspace-N directories exist. A reasonable limit would prevent unexpected behavior.

     let workspacePath = baseWorkspacePath;
     let counter = 1;
+    const MAX_ATTEMPTS = 100;
     while (fs.existsSync(workspacePath)) {
+      if (counter >= MAX_ATTEMPTS) {
+        throw new Error('Unable to create default workspace: too many existing workspace directories');
+      }
       workspacePath = `${baseWorkspacePath}-${counter}`;
       counter++;
     }

114-116: Synchronous fs operations may block the main Electron process.

Using fs.mkdirSync on the main process could cause UI freeze during initialization, though the impact is minimal for directory creation. Consider using fs.promises.mkdir for consistency with the async nature of this method.

-    fs.mkdirSync(workspacePath, { recursive: true });
-    fs.mkdirSync(path.join(workspacePath, 'collections'), { recursive: true });
-    fs.mkdirSync(path.join(workspacePath, 'environments'), { recursive: true });
+    await fs.promises.mkdir(workspacePath, { recursive: true });
+    await fs.promises.mkdir(path.join(workspacePath, 'collections'), { recursive: true });
+    await fs.promises.mkdir(path.join(workspacePath, 'environments'), { recursive: true });
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 079eb49 and 2690c32.

📒 Files selected for processing (3)
  • packages/bruno-electron/src/store/default-workspace.js (5 hunks)
  • tests/workspace/default-workspace/default-workspace.spec.ts (1 hunks)
  • tests/workspace/default-workspace/migration.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • tests/workspace/default-workspace/default-workspace.spec.ts
  • tests/workspace/default-workspace/migration.spec.ts
  • packages/bruno-electron/src/store/default-workspace.js
tests/**/**.*

⚙️ CodeRabbit configuration file

tests/**/**.*: Review the following e2e test code written using the Playwright test library. Ensure that:

  • Follow best practices for Playwright code and e2e automation

  • Try to reduce usage of page.waitForTimeout(); in code unless absolutely necessary and the locator cannot be found using existing expect() playwright calls

  • Avoid using page.pause() in code

  • Use locator variables for locators

  • Avoid using test.only

  • Use multiple assertions

  • Promote the use of test.step as much as possible so the generated reports are easier to read

  • Ensure that the fixtures like the collections are nested inside the fixtures folder

    Fixture Example*: Here's an example of possible fixture and test pair

    .
    ├── fixtures
    │   └── collection
    │       ├── base.bru
    │       ├── bruno.json
    │       ├── collection.bru
    │       ├── ws-test-request-with-headers.bru
    │       ├── ws-test-request-with-subproto.bru
    │       └── ws-test-request.bru
    ├── connection.spec.ts # <- Depends on the collection in ./fixtures/collection
    ├── headers.spec.ts
    ├── persistence.spec.ts
    ├── variable-interpolation
    │   ├── fixtures
    │   │   └── collection
    │   │       ├── environments
    │   │       ├── bruno.json
    │   │       └── ws-interpolation-test.bru
    │   ├── init-user-data
    │   └── variable-interpolation.spec.ts # <- Depends on the collection in ./variable-interpolation/fixtures/collection
    └── subproto.spec.ts
    

Files:

  • tests/workspace/default-workspace/default-workspace.spec.ts
  • tests/workspace/default-workspace/migration.spec.ts
🧠 Learnings (1)
📚 Learning: 2025-12-05T20:31:33.005Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-05T20:31:33.005Z
Learning: Applies to **/*.test.{js,jsx,ts,tsx} : Add tests for any new functionality or meaningful changes. If code is added, removed, or significantly modified, corresponding tests should be updated or created

Applied to files:

  • tests/workspace/default-workspace/default-workspace.spec.ts
  • tests/workspace/default-workspace/migration.spec.ts
🧬 Code graph analysis (2)
tests/workspace/default-workspace/migration.spec.ts (3)
packages/bruno-electron/src/store/default-workspace.js (1)
  • path (2-2)
packages/bruno-tests/src/index.js (1)
  • app (13-13)
packages/bruno-electron/src/app/onboarding.js (1)
  • sampleCollection (41-41)
packages/bruno-electron/src/store/default-workspace.js (1)
packages/bruno-electron/src/utils/workspace-config.js (15)
  • OPENCOLLECTION_VERSION (7-7)
  • WORKSPACE_TYPE (6-6)
  • fs (1-1)
  • path (2-2)
  • config (184-184)
  • config (194-194)
  • config (201-201)
  • config (229-229)
  • config (269-269)
  • config (284-284)
  • config (299-299)
  • config (325-325)
  • readWorkspaceConfig (85-100)
  • validateWorkspaceConfig (165-181)
  • workspaceConfig (93-93)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: CLI Tests
  • GitHub Check: Unit Tests
🔇 Additional comments (8)
tests/workspace/default-workspace/default-workspace.spec.ts (3)

1-19: LGTM!

First launch test is well-structured with clear assertions and proper cleanup.


22-42: LGTM!

Persistence test properly validates workspace state across app restarts using the same userDataPath.


44-81: Good coverage of recovery scenario.

Test correctly validates that a new workspace is created when workspace.yml is missing, and that the old directory is preserved. The assertion that default-workspace-1 is created demonstrates proper counter-based naming.

packages/bruno-electron/src/store/default-workspace.js (5)

10-12: LGTM on constants definition.

Centralizing WORKSPACE_TYPE and DEFAULT_WORKSPACE_UID as constants improves maintainability and ensures consistency across the codebase.


47-64: Validation method is well-structured.

The isValidDefaultWorkspace method properly chains existence checks before attempting config validation. Swallowing the exception and returning false is appropriate here since this is a validation check.


141-199: Migration logic looks solid.

The migrateFromPreferences method properly handles collection paths, global environments, and docs migration. Error handling wraps the entire operation, and the global environment store is cleared after successful migration to prevent duplicate migrations.


90-92: Null handling is already implemented at call sites.

Both callers of ensureDefaultWorkspaceExists() properly check the return value before accessing properties (lines 428 and 453 in packages/bruno-electron/src/ipc/workspace.js). No action needed.


30-32: Default workspace UID change is safe—no backward compatibility risk.

The getDefaultWorkspaceUid() returning the constant 'default' introduces a new feature rather than replacing an existing UID scheme. The default workspace itself is a new workspace type created once during initialization or migrated from old lastOpenedCollections preferences. Subsequent app launches reuse the same workspace, and other workspaces continue using generateUidBasedOnHash() for their UIDs. Comprehensive test coverage validates migration from legacy preferences, workspace reuse on restart, and clean installations.

bijin-bruno
bijin-bruno previously approved these changes Dec 11, 2025
@bijin-bruno
bijin-bruno force-pushed the bugfix/default-workspace branch from a5f1158 to 013c128 Compare December 11, 2025 14:23

@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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/bruno-electron/src/ipc/workspace.js (2)

85-110: Inconsistent UID generation in open-workspace handlers.

Lines 92, 130 use generateUidBasedOnHash directly instead of the new getWorkspaceUid helper. This creates an inconsistency: if a user opens the default workspace via the file dialog, it receives a hash-based UID instead of the constant 'default' UID.

Apply this fix:

-      const workspaceUid = generateUidBasedOnHash(workspacePath);
+      const workspaceUid = getWorkspaceUid(workspacePath);

Apply the same change at line 130.


459-510: Inconsistent UID generation in workspace initialization.

Line 488 uses generateUidBasedOnHash directly instead of getWorkspaceUid. This creates the same inconsistency noted in the open-workspace handlers.

Apply this fix:

-            const workspaceUid = generateUidBasedOnHash(workspacePath);
+            const workspaceUid = getWorkspaceUid(workspacePath);

The rest of the changes look excellent - enhanced validation, error logging, and pruning of invalid paths improve robustness.

🧹 Nitpick comments (9)
tests/workspace/default-workspace/migration.spec.ts (5)

11-55: Improve test readability with test.step and locator variables.

The test logic is sound, but readability and reporting can be improved by:

  1. Using test.step to break down the test into logical phases (setup, launch, verify).
  2. Extracting locators into variables for reusability and clarity.

Apply this pattern:

-    test('should migrate collections from lastOpenedCollections to new workspace', async ({ launchElectronApp, createTmpDir }) => {
+    test('should migrate collections from lastOpenedCollections to new workspace', async ({ launchElectronApp, createTmpDir }) => {
+      await test.step('Setup old collection structure', async () => {
-      const userDataPath = await createTmpDir('default-workspace-migration');
+        const userDataPath = await createTmpDir('default-workspace-migration');
-
-      // Create a test collection that would have been opened before
-      const testCollectionPath = path.join(userDataPath, 'my-old-collection');
-      fs.mkdirSync(testCollectionPath, { recursive: true });
-      fs.writeFileSync(
-        path.join(testCollectionPath, 'bruno.json'),
-        JSON.stringify({
-          version: '1',
-          name: 'My Old Collection',
-          type: 'collection'
-        })
-      );
+        // Create a test collection that would have been opened before
+        const testCollectionPath = path.join(userDataPath, 'my-old-collection');
+        fs.mkdirSync(testCollectionPath, { recursive: true });
+        fs.writeFileSync(
+          path.join(testCollectionPath, 'bruno.json'),
+          JSON.stringify({
+            version: '1',
+            name: 'My Old Collection',
+            type: 'collection'
+          })
+        );
+
+        fs.writeFileSync(
+          path.join(userDataPath, 'preferences.json'),
+          JSON.stringify({
+            lastOpenedCollections: [testCollectionPath]
+          })
+        );
+      });
+
+      await test.step('Launch app and verify migration', async () => {
+        const app = await launchElectronApp({ userDataPath });
+        const page = await app.firstWindow();
+        
+        const loadedStateLocator = page.locator('[data-app-state="loaded"]');
+        const workspaceNameLocator = page.locator('.workspace-name');
+        
+        await loadedStateLocator.waitFor({ timeout: 30000 });
+        await expect(workspaceNameLocator).toContainText('My Workspace');
+        
+        // ... rest of verification
+      });
+    });

Based on coding guidelines, test.step promotes better report readability.


57-101: Apply test.step pattern consistently.

Similar to the first test, this test would benefit from test.step for better reporting structure. Consider grouping setup, execution, and verification phases.


105-141: Apply test.step pattern consistently.

Consider using test.step to structure the test into logical phases (setup, launch, verification) for improved test reporting.


145-176: Apply test.step pattern consistently.

This test verifies workspace reuse behavior. Using test.step for the first and second launch phases would make the test flow clearer in reports.


194-199: Strengthen empty collections assertion.

The regex pattern /collections:\s*\n/ is fragile and may break with YAML formatting changes or additional whitespace.

Consider a more robust check:

-        expect(workspaceYml).toMatch(/collections:\s*\n/);
+        const parsed = yaml.load(workspaceYml);
+        expect(parsed.collections).toEqual([]);

Import yaml at the top of the file if not already imported.

packages/bruno-electron/src/store/default-workspace.js (2)

47-64: Consider logging validation errors for debugging.

The method silently returns false on validation errors, which may make debugging difficult when workspace validation fails unexpectedly.

Add optional debug logging:

     } catch (error) {
+      console.debug('Workspace validation failed:', error.message);
       return false;
     }

114-116: Sync filesystem operations may block event loop.

Using synchronous fs.mkdirSync in the main process can block the event loop during workspace initialization. Since this runs at startup, the impact is limited, but it's worth noting.

If startup performance becomes an issue, consider reverting to async operations with Promise.all:

-    fs.mkdirSync(workspacePath, { recursive: true });
-    fs.mkdirSync(path.join(workspacePath, 'collections'), { recursive: true });
-    fs.mkdirSync(path.join(workspacePath, 'environments'), { recursive: true });
+    await Promise.all([
+      createDirectory(workspacePath),
+      createDirectory(path.join(workspacePath, 'collections')),
+      createDirectory(path.join(workspacePath, 'environments'))
+    ]);
packages/bruno-electron/src/ipc/workspace.js (2)

41-83: Consider using getWorkspaceUid for consistency.

Line 62 uses generateUidBasedOnHash directly. While likely correct for new workspaces, using getWorkspaceUid would ensure consistent UID generation logic across all handlers.

-      const workspaceUid = generateUidBasedOnHash(dirPath);
+      const workspaceUid = getWorkspaceUid(dirPath);

163-198: Consider using readWorkspaceConfig for consistency.

This handler still uses manual YAML parsing (lines 169-176) while other handlers now use readWorkspaceConfig. For consistency and to centralize error handling, consider updating this handler as well.

-      const workspaceFilePath = path.join(workspacePath, 'workspace.yml');
-
-      if (!fs.existsSync(workspaceFilePath)) {
-        throw new Error('Invalid workspace: workspace.yml not found');
-      }
-
-      const yamlContent = fs.readFileSync(workspaceFilePath, 'utf8');
-      const workspaceConfig = yaml.load(yamlContent);
-
-      if (!workspaceConfig || typeof workspaceConfig !== 'object') {
-        return [];
-      }
+      const workspaceConfig = readWorkspaceConfig(workspacePath);
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a5f1158 and 013c128.

📒 Files selected for processing (4)
  • packages/bruno-electron/src/ipc/workspace.js (5 hunks)
  • packages/bruno-electron/src/store/default-workspace.js (5 hunks)
  • tests/workspace/default-workspace/default-workspace.spec.ts (1 hunks)
  • tests/workspace/default-workspace/migration.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/workspace/default-workspace/default-workspace.spec.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-electron/src/store/default-workspace.js
  • tests/workspace/default-workspace/migration.spec.ts
  • packages/bruno-electron/src/ipc/workspace.js
tests/**/**.*

⚙️ CodeRabbit configuration file

tests/**/**.*: Review the following e2e test code written using the Playwright test library. Ensure that:

  • Follow best practices for Playwright code and e2e automation

  • Try to reduce usage of page.waitForTimeout(); in code unless absolutely necessary and the locator cannot be found using existing expect() playwright calls

  • Avoid using page.pause() in code

  • Use locator variables for locators

  • Avoid using test.only

  • Use multiple assertions

  • Promote the use of test.step as much as possible so the generated reports are easier to read

  • Ensure that the fixtures like the collections are nested inside the fixtures folder

    Fixture Example*: Here's an example of possible fixture and test pair

    .
    ├── fixtures
    │   └── collection
    │       ├── base.bru
    │       ├── bruno.json
    │       ├── collection.bru
    │       ├── ws-test-request-with-headers.bru
    │       ├── ws-test-request-with-subproto.bru
    │       └── ws-test-request.bru
    ├── connection.spec.ts # <- Depends on the collection in ./fixtures/collection
    ├── headers.spec.ts
    ├── persistence.spec.ts
    ├── variable-interpolation
    │   ├── fixtures
    │   │   └── collection
    │   │       ├── environments
    │   │       ├── bruno.json
    │   │       └── ws-interpolation-test.bru
    │   ├── init-user-data
    │   └── variable-interpolation.spec.ts # <- Depends on the collection in ./variable-interpolation/fixtures/collection
    └── subproto.spec.ts
    

Files:

  • tests/workspace/default-workspace/migration.spec.ts
🧠 Learnings (1)
📚 Learning: 2025-12-05T20:31:33.005Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-05T20:31:33.005Z
Learning: Applies to **/*.test.{js,jsx,ts,tsx} : Add tests for any new functionality or meaningful changes. If code is added, removed, or significantly modified, corresponding tests should be updated or created

Applied to files:

  • tests/workspace/default-workspace/migration.spec.ts
🧬 Code graph analysis (2)
packages/bruno-electron/src/store/default-workspace.js (1)
packages/bruno-electron/src/utils/workspace-config.js (16)
  • require (4-4)
  • OPENCOLLECTION_VERSION (7-7)
  • WORKSPACE_TYPE (6-6)
  • fs (1-1)
  • path (2-2)
  • config (184-184)
  • config (194-194)
  • config (201-201)
  • config (229-229)
  • config (269-269)
  • config (284-284)
  • config (299-299)
  • config (325-325)
  • readWorkspaceConfig (85-100)
  • validateWorkspaceConfig (165-181)
  • workspaceConfig (93-93)
tests/workspace/default-workspace/migration.spec.ts (3)
packages/bruno-electron/src/store/default-workspace.js (1)
  • path (2-2)
packages/bruno-tests/src/index.js (1)
  • app (13-13)
packages/bruno-electron/src/app/onboarding.js (1)
  • sampleCollection (41-41)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Unit Tests
  • GitHub Check: CLI Tests
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - macOS
🔇 Additional comments (5)
packages/bruno-electron/src/store/default-workspace.js (3)

66-99: LGTM!

The enhanced validation via isValidDefaultWorkspace improves reliability, and error logging provides useful debugging information. The return structure is consistent with the IPC expectations.


30-32: No action needed.

The method correctly returns a constant UID for the default workspace, which is the intended design. Both the frontend (packages/bruno-app/src/providers/ReduxStore/slices/workspaces/index.js) and backend use the same constant 'default' to identify the default workspace consistently. All usages throughout the codebase handle this constant UID correctly.


101-139: The single call site at line 84 already uses the current signature { migrateFromPreferences: shouldMigrate }, which matches the method definition at line 101. No outdated callers were found.

packages/bruno-electron/src/ipc/workspace.js (2)

31-39: LGTM! Well-designed helper function.

Centralizing the workspace UID logic is excellent practice. The path normalization prevents bugs from differing path separators.

If this logic is needed elsewhere, consider extracting to a shared utility module.


435-457: LGTM! Improved error handling and consistency.

Using readWorkspaceConfig centralizes config reading and the added error logging will aid debugging. The null return provides safe error handling for callers.

const { generateYamlContent, readWorkspaceConfig, validateWorkspaceConfig } = require('../utils/workspace-config');

const OPENCOLLECTION_VERSION = '1.0.0';
const WORKSPACE_TYPE = 'workspace';

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.

🛠️ Refactor suggestion | 🟠 Major

WORKSPACE_TYPE constant is duplicated.

This constant is defined both here and in workspace-config.js (line 6). Duplication creates a maintenance risk.

Import it instead:

+const { generateYamlContent, readWorkspaceConfig, validateWorkspaceConfig, WORKSPACE_TYPE } = require('../utils/workspace-config');
-const WORKSPACE_TYPE = 'workspace';

Ensure WORKSPACE_TYPE is exported from workspace-config.js.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/bruno-electron/src/store/default-workspace.js around line 11, the
WORKSPACE_TYPE constant is duplicated (also defined in workspace-config.js);
remove the local definition and import WORKSPACE_TYPE from workspace-config.js
instead, and if not already exported, add an export for WORKSPACE_TYPE in
workspace-config.js so the module can be imported here.

@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: 0

♻️ Duplicate comments (5)
tests/import/insomnia/import-insomnia-v4-environments.spec.ts (1)

33-35: Apply the same locator-based readiness pattern here

Same pattern as the v5 environments spec: instead of a fixed waitForTimeout(500), prefer an assertion on a concrete readiness signal (e.g. await expect(page.locator('input[type="file"]')).toBeAttached();) before setInputFiles. The increased timeout: 30000 on the location modal is fine and consistent with other tests.

Also applies to: 39-39

tests/import/openapi/duplicate-operation-names-fix.spec.ts (1)

22-24: Avoid fixed sleep; wait on a concrete readiness condition

Here too, the 500ms sleep stabilizes the test but is weaker than asserting on something like the hidden file input being attached:

// After the modal is visible
await expect(page.locator('input[type="file"]')).toBeAttached();
await page.setInputFiles('input[type="file"]', openApiFile);

Consider this (or a shared helper) to replace waitForTimeout(500) across the OpenAPI import specs, while keeping the longer 30s modal timeout.

Also applies to: 30-30

tests/import/openapi/path-based-grouping.spec.ts (1)

22-24: Same note on replacing waitForTimeout(500) with a locator-based wait

As with the other OpenAPI import specs, it would be more robust to wait for the hidden file input (or another specific readiness signal) instead of a hard-coded 500ms delay, while keeping the 30s location-modal timeout.

Also applies to: 30-30

tests/import/openapi/operation-name-with-newlines-fix.spec.ts (1)

22-24: Reuse the import‑modal readiness approach from other specs

Same situation as the other OpenAPI tests: replace waitForTimeout(500) with a readiness assertion on a specific locator (e.g. hidden file input) or a shared helper, and keep the extended 30s timeout for the location modal.

Also applies to: 30-30

tests/import/postman/import-postman-with-examples.spec.ts (1)

49-51: Align Postman import test with locator-based readiness used elsewhere

Here too, the fixed 500ms sleep before setInputFiles can be swapped for a more explicit readiness check (e.g. expect(page.locator('input[type="file"]')).toBeAttached()), matching the suggested pattern for the other import specs, while preserving the 30s timeout for the location modal.

Also applies to: 57-57

🧹 Nitpick comments (7)
tests/import/insomnia/import-insomnia-v5-environments.spec.ts (1)

33-35: Prefer locator-based readiness over fixed 500ms sleep

The extra delay likely stabilizes the import flow, but a fixed waitForTimeout(500) is brittle and goes against our Playwright guidelines. Instead, consider waiting on the actual readiness signal (e.g. the hidden file input being attached/enabled) and keep the longer modal timeout as-is:

-      // Small delay to ensure modal is fully ready
-      await page.waitForTimeout(500);
+      // Wait for the hidden file input to be attached instead of a fixed timeout
+      await expect(page.locator('input[type="file"]')).toBeAttached();

You can apply the same pattern to similar import tests in this PR.

Also applies to: 40-40

tests/import/openapi/import-openapi-with-examples.spec.ts (1)

49-51: Deduplicate and replace the repeated 500ms sleeps with a reusable readiness helper

Both import flows in this file add the same 500ms delay before setInputFiles and extend the location modal timeout to 30s. The longer timeout is fine, but instead of duplicating waitForTimeout(500) twice, consider a small helper that waits for the hidden file input (or other stable signal) to be ready:

async function waitForImportFileInput(page: Page) {
  await expect(page.locator('input[type="file"]')).toBeAttached();
}

Then call await waitForImportFileInput(page); in each step instead of the fixed sleep. This keeps tests less flaky and DRY.

Also applies to: 57-57, 169-171, 176-176

tests/import/bruno/import-bruno-with-examples.spec.ts (1)

25-27: Tighten readiness logic instead of static sleep before Promise.race

The pattern here matches the other import tests:

  • The 500ms waitForTimeout before starting the Promise.race is a generic guard; prefer waiting for something concrete like input[type="file"] being attached/enabled.
  • Bumping both branches of the Promise.race to timeout: 30000 is consistent, but be aware it doubles how long this step can block on a real failure.

Consider:

-      // Small delay to ensure modal is fully ready
-      await page.waitForTimeout(500);
+      // Wait for the hidden file input to be attached instead of a fixed timeout
+      await expect(page.locator('input[type="file"]')).toBeAttached();

and keep the 30s timeouts if they match the app’s worst‑case import time.

Also applies to: 34-35

tests/import/wsdl/import-wsdl.spec.ts (2)

24-33: Avoid fixed waitForTimeout when a locator-based wait can work

The added 500ms sleep is a pragmatic stabilizer, but it would be better to wait on a specific condition (e.g., file input visible+enabled, or some “ready” marker in the import modal) instead of a hard timeout. That keeps the test fast on healthy runs and still robust on slower ones. The 30s timeout on the location modal looks fine; if you keep it, consider aligning this with a shared constant used by other import tests for consistency.

Example direction (adjust to what actually flaked):

const fileInput = page.locator('input[type="file"]');
await expect(fileInput).toBeVisible();
await expect(fileInput).toBeEnabled();
await fileInput.setInputFiles(wsdlFile);

As per coding guidelines, please prefer condition-based waits over page.waitForTimeout, especially in tests.


85-94: Mirror the XML flow fix but still prefer condition-based waits over static sleeps

Same comments as for the XML path: if the extra 500ms is masking a race, it’s worth trying to express that race via a locator-based wait (visibility, enabled state, or a spinner disappearing) rather than a fixed timeout. Since both XML and JSON imports now share identical timing behavior, you might also consider extracting a small helper like chooseWsdlFileAndWaitForLocationModal(wsdlFile) so the synchronization logic is defined in one place.

As per coding guidelines, it’s better to rely on Playwright’s locator/expect waits instead of page.waitForTimeout wherever possible.

tests/collection/moving-requests/cross-collection-drag-drop-folder.spec.ts (2)

11-106: Good move on dynamic collection naming; consider removing fixed sleeps and tightening locators

The overall flow and the use of testId-based sourceCollectionName / targetCollectionName look solid and will help avoid cross-run collisions.

A few Playwright-focused improvements to reduce flakiness and align with the test guidelines:

  1. Replace fixed waitForTimeout(500) with locator-based waits where possible

Most of the new waits in this test can likely be dropped in favor of relying on expect’s auto-wait. Examples:

  • Folder creation (Lines 30-32):
-    // Wait for the folder to be created and appear in the sidebar
-    await page.waitForTimeout(500);
-    await expect(page.locator('.collection-item-name').filter({ hasText: 'test-folder' })).toBeVisible();
+    // Wait for the folder to be created and appear in the sidebar
+    await expect(page.locator('.collection-item-name').filter({ hasText: 'test-folder' })).toBeVisible();
  • Request creation + expansion (Lines 43-49):
-    // Wait for the request to be created
-    await page.waitForTimeout(500);
-
-    // Expand the folder to see the request inside
-    await page.locator('.collection-item-name').filter({ hasText: 'test-folder' }).click();
-    await page.waitForTimeout(500);
-    await expect(page.locator('.collection-item-name').filter({ hasText: 'test-request-in-folder' })).toBeVisible();
+    // Expand the folder to see the request inside
+    await page.locator('.collection-item-name').filter({ hasText: 'test-folder' }).click();
+    await expect(page.locator('.collection-item-name').filter({ hasText: 'test-request-in-folder' })).toBeVisible();
  • Post–drag-and-drop verification (Lines 69-76, 87-91):
-    // Wait for the operation to complete
-    await page.waitForTimeout(500);
-
-    // Verify the folder has been moved to the target collection
-    // Click on target collection to expand it if needed
-    await page.locator('#sidebar-collection-name').filter({ hasText: targetCollectionName }).click();
-    await page.waitForTimeout(500);
+    // Verify the folder has been moved to the target collection
+    // Click on target collection to expand it if needed
+    await page.locator('#sidebar-collection-name').filter({ hasText: targetCollectionName }).click();
-    // Expand the moved folder to verify the request inside is also moved
-    await targetCollectionContainer.locator('.collection-item-name').filter({ hasText: 'test-folder' }).click();
-    await page.waitForTimeout(500);
-    await expect(
-      targetCollectionContainer.locator('.collection-item-name').filter({ hasText: 'test-request-in-folder' })
-    ).toBeVisible();
+    // Expand the moved folder to verify the request inside is also moved
+    await targetCollectionContainer.locator('.collection-item-name').filter({ hasText: 'test-folder' }).click();
+    await expect(
+      targetCollectionContainer.locator('.collection-item-name').filter({ hasText: 'test-request-in-folder' })
+    ).toBeVisible();

expect(...).toBeVisible() will wait for the DOM state change and is generally more robust than a fixed 500ms sleep. If there’s a UI transition that truly lacks a reliable locator signal, keeping a targeted timeout with a short comment explaining why would help future maintainers.

  1. Extract repeated locators into variables

You already do this for a few things (sourceCollectionContainer1, sourceFolder, targetCollection). To go a bit further and match the “use locator variables” guideline, consider extracting the frequently repeated selectors:

  • .collection-item-name with 'test-folder'
  • .collection-item-name with 'test-request-in-folder'
  • page.locator('#sidebar-collection-name').filter({ hasText: targetCollectionName })

For example:

const folderInSource = page.locator('.collection-item-name').filter({ hasText: 'test-folder' });
const requestInFolder = page.locator('.collection-item-name').filter({ hasText: 'test-request-in-folder' });
const targetCollectionSidebar = page.locator('#sidebar-collection-name').filter({ hasText: targetCollectionName });

Then reuse these in the steps. This keeps the test intent clearer and makes selector changes easier.

  1. Optional: wrap logical phases in test.step

This test has clear phases (“create source collection”, “create folder + request”, “create target collection”, “drag-and-drop”, “assert post-conditions”). Wrapping them in test.step would make Playwright reports more readable without changing behavior.


112-215: Duplicate-folder scenario looks well covered; consider tightening waits and locator reuse

The scenario and assertions here are strong: you validate the error toast and that both source and target collections remain in the expected state.

A few improvements in line with the Playwright/test guidelines:

  1. Drop fixed sleeps in favor of expect auto-wait

Similar to the first test, the explicit await page.waitForTimeout(500); calls at folder/request creation time can almost certainly be removed:

  • After creating folder-1 in the source (Lines 135-139):
-    await page.getByRole('button', { name: 'Create' }).click();
-    await page.waitForTimeout(500);
-
-    await expect(page.locator('.collection-item-name').filter({ hasText: 'folder-1' })).toBeVisible();
+    await page.getByRole('button', { name: 'Create' }).click();
+    await expect(page.locator('.collection-item-name').filter({ hasText: 'folder-1' })).toBeVisible();
  • After creating http-request in the source (Lines 143-152):
-    await page.locator('.dropdown-item').filter({ hasText: 'New Request' }).click();
-    await page.getByPlaceholder('Request Name').fill('http-request');
-    await page.locator('#new-request-url .CodeMirror').click();
-    await page.locator('textarea').fill('https://echo.usebruno.com');
-    await page.getByRole('button', { name: 'Create' }).click();
-    await page.waitForTimeout(500);
-
-    // Expand the folder to see the request inside
-    await page.locator('.collection-item-name').filter({ hasText: 'folder-1' }).click();
-    await expect(page.locator('.collection-item-name').filter({ hasText: 'http-request' })).toBeVisible();
+    await page.locator('.dropdown-item').filter({ hasText: 'New Request' }).click();
+    await page.getByPlaceholder('Request Name').fill('http-request');
+    await page.locator('#new-request-url .CodeMirror').click();
+    await page.locator('textarea').fill('https://echo.usebruno.com');
+    await page.getByRole('button', { name: 'Create' }).click();
+
+    // Expand the folder to see the request inside
+    await page.locator('.collection-item-name').filter({ hasText: 'folder-1' }).click();
+    await expect(page.locator('.collection-item-name').filter({ hasText: 'http-request' })).toBeVisible();
  • After creating the duplicate folder-1 in the target (Lines 170-175):
-    await page.locator('.dropdown-item').filter({ hasText: 'New Folder' }).click();
-    await expect(page.locator('#folder-name')).toBeVisible();
-    await page.locator('#folder-name').fill('folder-1');
-    await page.getByRole('button', { name: 'Create' }).click();
-    await page.waitForTimeout(500);
+    await page.locator('.dropdown-item').filter({ hasText: 'New Folder' }).click();
+    await expect(page.locator('#folder-name')).toBeVisible();
+    await page.locator('#folder-name').fill('folder-1');
+    await page.getByRole('button', { name: 'Create' }).click();

The error toast assertion (await expect(page.getByText(/Error: Cannot copy.*already exists/i)).toBeVisible();) already provides a natural wait point after the drag-and-drop.

If any of these sleeps were added to work around a specific race, it’d be helpful to either keep them very targeted with a short comment, or consider raising the timeout on the relevant expect instead.

  1. Factor common locators into variables

You reuse:

  • page.locator('.collection-name').filter({ hasText: sourceCollectionName }).locator('..')
  • page.locator('.collection-name').filter({ hasText: targetCollectionName }).locator('..')

in multiple places. Defining them once makes the test clearer and easier to maintain:

const sourceCollection = page.locator('.collection-name').filter({ hasText: sourceCollectionName });
const sourceCollectionContainer = sourceCollection.locator('..');

const targetCollection = page.locator('.collection-name').filter({ hasText: targetCollectionName });
const targetCollectionContainer = targetCollection.locator('..');

Then reuse those in the hover/click and final assertions instead of rebuilding the locator chain each time.

  1. Optional: use test.step for clearer reporting

This test naturally splits into steps:

  • “Create source collection with folder+request”
  • “Create target collection with duplicate folder”
  • “Drag folder and assert error toast”
  • “Verify source/target collections unchanged”

Wrapping these with test.step would make debugging failures easier in CI reports.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 013c128 and 917a3e0.

📒 Files selected for processing (11)
  • tests/collection/moving-requests/cross-collection-drag-drop-folder.spec.ts (7 hunks)
  • tests/collection/moving-requests/tag-persistence.spec.ts (1 hunks)
  • tests/import/bruno/import-bruno-with-examples.spec.ts (1 hunks)
  • tests/import/insomnia/import-insomnia-v4-environments.spec.ts (1 hunks)
  • tests/import/insomnia/import-insomnia-v5-environments.spec.ts (1 hunks)
  • tests/import/openapi/duplicate-operation-names-fix.spec.ts (1 hunks)
  • tests/import/openapi/import-openapi-with-examples.spec.ts (2 hunks)
  • tests/import/openapi/operation-name-with-newlines-fix.spec.ts (1 hunks)
  • tests/import/openapi/path-based-grouping.spec.ts (1 hunks)
  • tests/import/postman/import-postman-with-examples.spec.ts (1 hunks)
  • tests/import/wsdl/import-wsdl.spec.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • tests/collection/moving-requests/tag-persistence.spec.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • tests/import/postman/import-postman-with-examples.spec.ts
  • tests/import/openapi/import-openapi-with-examples.spec.ts
  • tests/import/openapi/operation-name-with-newlines-fix.spec.ts
  • tests/import/bruno/import-bruno-with-examples.spec.ts
  • tests/import/wsdl/import-wsdl.spec.ts
  • tests/import/openapi/duplicate-operation-names-fix.spec.ts
  • tests/import/insomnia/import-insomnia-v5-environments.spec.ts
  • tests/collection/moving-requests/cross-collection-drag-drop-folder.spec.ts
  • tests/import/insomnia/import-insomnia-v4-environments.spec.ts
  • tests/import/openapi/path-based-grouping.spec.ts
tests/**/**.*

⚙️ CodeRabbit configuration file

tests/**/**.*: Review the following e2e test code written using the Playwright test library. Ensure that:

  • Follow best practices for Playwright code and e2e automation

  • Try to reduce usage of page.waitForTimeout(); in code unless absolutely necessary and the locator cannot be found using existing expect() playwright calls

  • Avoid using page.pause() in code

  • Use locator variables for locators

  • Avoid using test.only

  • Use multiple assertions

  • Promote the use of test.step as much as possible so the generated reports are easier to read

  • Ensure that the fixtures like the collections are nested inside the fixtures folder

    Fixture Example*: Here's an example of possible fixture and test pair

    .
    ├── fixtures
    │   └── collection
    │       ├── base.bru
    │       ├── bruno.json
    │       ├── collection.bru
    │       ├── ws-test-request-with-headers.bru
    │       ├── ws-test-request-with-subproto.bru
    │       └── ws-test-request.bru
    ├── connection.spec.ts # <- Depends on the collection in ./fixtures/collection
    ├── headers.spec.ts
    ├── persistence.spec.ts
    ├── variable-interpolation
    │   ├── fixtures
    │   │   └── collection
    │   │       ├── environments
    │   │       ├── bruno.json
    │   │       └── ws-interpolation-test.bru
    │   ├── init-user-data
    │   └── variable-interpolation.spec.ts # <- Depends on the collection in ./variable-interpolation/fixtures/collection
    └── subproto.spec.ts
    

Files:

  • tests/import/postman/import-postman-with-examples.spec.ts
  • tests/import/openapi/import-openapi-with-examples.spec.ts
  • tests/import/openapi/operation-name-with-newlines-fix.spec.ts
  • tests/import/bruno/import-bruno-with-examples.spec.ts
  • tests/import/wsdl/import-wsdl.spec.ts
  • tests/import/openapi/duplicate-operation-names-fix.spec.ts
  • tests/import/insomnia/import-insomnia-v5-environments.spec.ts
  • tests/collection/moving-requests/cross-collection-drag-drop-folder.spec.ts
  • tests/import/insomnia/import-insomnia-v4-environments.spec.ts
  • tests/import/openapi/path-based-grouping.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: Unit Tests
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - Linux

@naman-bruno
naman-bruno force-pushed the bugfix/default-workspace branch from 917a3e0 to 013c128 Compare December 11, 2025 16:43

@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

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 917a3e0 and 72dccdb.

📒 Files selected for processing (1)
  • tests/utils/page/actions.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • tests/utils/page/actions.ts
tests/**/**.*

⚙️ CodeRabbit configuration file

tests/**/**.*: Review the following e2e test code written using the Playwright test library. Ensure that:

  • Follow best practices for Playwright code and e2e automation

  • Try to reduce usage of page.waitForTimeout(); in code unless absolutely necessary and the locator cannot be found using existing expect() playwright calls

  • Avoid using page.pause() in code

  • Use locator variables for locators

  • Avoid using test.only

  • Use multiple assertions

  • Promote the use of test.step as much as possible so the generated reports are easier to read

  • Ensure that the fixtures like the collections are nested inside the fixtures folder

    Fixture Example*: Here's an example of possible fixture and test pair

    .
    ├── fixtures
    │   └── collection
    │       ├── base.bru
    │       ├── bruno.json
    │       ├── collection.bru
    │       ├── ws-test-request-with-headers.bru
    │       ├── ws-test-request-with-subproto.bru
    │       └── ws-test-request.bru
    ├── connection.spec.ts # <- Depends on the collection in ./fixtures/collection
    ├── headers.spec.ts
    ├── persistence.spec.ts
    ├── variable-interpolation
    │   ├── fixtures
    │   │   └── collection
    │   │       ├── environments
    │   │       ├── bruno.json
    │   │       └── ws-interpolation-test.bru
    │   ├── init-user-data
    │   └── variable-interpolation.spec.ts # <- Depends on the collection in ./variable-interpolation/fixtures/collection
    └── subproto.spec.ts
    

Files:

  • tests/utils/page/actions.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: Unit Tests
  • GitHub Check: CLI Tests

Comment on lines +79 to +80
await createCollectionModal.waitFor({ state: 'detached', timeout: 15000 });
await page.waitForTimeout(200);

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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

cd /tmp && find . -name "actions.ts" -path "*/tests/*" 2>/dev/null | head -5

Repository: usebruno/bruno

Length of output: 40


🏁 Script executed:

wc -l tests/utils/page/actions.ts

Repository: usebruno/bruno

Length of output: 89


🏁 Script executed:

sed -n '70,90p' tests/utils/page/actions.ts

Repository: usebruno/bruno

Length of output: 857


🏁 Script executed:

sed -n '1,100p' tests/utils/page/actions.ts | head -100

Repository: usebruno/bruno

Length of output: 4089


Remove the fixed timeout and use locator-based waits instead.

Line 80's await page.waitForTimeout(200) violates the coding guidelines. Rather than a fixed delay, verify that the collection appears in the sidebar when it will be used immediately after:

 await createCollectionModal.waitFor({ state: 'detached', timeout: 15000 });
-await page.waitForTimeout(200);

 if (options.openWithSandboxMode != undefined) {
+  // Wait for collection to appear in sidebar before opening
+  await expect(page.getByTestId('collections').locator('.collection-name').filter({ hasText: collectionName })).toBeVisible({ timeout: 5000 });
   await openCollectionAndAcceptSandbox(page, collectionName, options.openWithSandboxMode);
 }

If the collection is not always immediately opened, move the wait only where it's needed to avoid unnecessary delays.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In tests/utils/page/actions.ts around lines 79 to 80, remove the fixed await
page.waitForTimeout(200) and replace it with a locator-based wait that asserts
the collection appears in the sidebar (or the specific element used immediately
after) — e.g., waitFor a sidebar collection locator to be visible/attached with
a sensible timeout; if the collection is not always immediately opened, only add
this locator wait at the call sites where the sidebar item is required so you
avoid unnecessary delays.

@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: 0

🧹 Nitpick comments (2)
packages/bruno-electron/src/app/workspace-watcher.js (2)

10-20: Consider sharing getWorkspaceUid logic to avoid drift across modules

This helper cleanly encapsulates the default-vs-hash UID behavior. If similar getWorkspaceUid logic is now used in other files (e.g., IPC layer), consider moving this into a shared util (or defaultWorkspaceManager) so there is a single source of truth for workspace UID computation and future changes don’t need to be duplicated.


54-56: Keep workspaceUid stable per watcher by passing it into handleWorkspaceFileChange

Right now workspaceUid is:

  • Computed once in addWatcher and captured by the env watchers, but
  • Recomputed inside handleWorkspaceFileChange via getWorkspaceUid(workspacePath).

If the default workspace path/UID changes while a watcher is alive, config events (main:workspace-config-updated) could start emitting a different UID than env events (main:global-environment-*), which may confuse consumers relying on a stable workspace UID.

You can avoid this by passing the already computed workspaceUid into handleWorkspaceFileChange and not recomputing it there:

-const handleWorkspaceFileChange = (win, workspacePath) => {
+const handleWorkspaceFileChange = (win, workspacePath, workspaceUid) => {
@@
-    const workspaceConfig = normalizeWorkspaceConfig(rawConfig);
+    const workspaceConfig = normalizeWorkspaceConfig(rawConfig);
@@
-    const type = workspaceConfig.info?.type || workspaceConfig.type;
+    const type = workspaceConfig.info?.type || workspaceConfig.type;
@@
-    if (type !== 'workspace') {
+    if (type !== 'workspace') {
       return;
     }
 
-    const workspaceUid = getWorkspaceUid(workspacePath);
-
     win.webContents.send('main:workspace-config-updated', workspacePath, workspaceUid, workspaceConfig);

And in addWatcher:

-      watcher.on('change', () => handleWorkspaceFileChange(win, workspacePath));
-      watcher.on('add', () => handleWorkspaceFileChange(win, workspacePath));
+      watcher.on('change', () => handleWorkspaceFileChange(win, workspacePath, workspaceUid));
+      watcher.on('add', () => handleWorkspaceFileChange(win, workspacePath, workspaceUid));

This keeps all events for a given watcher path using a single, consistent UID for its lifetime.

Also applies to: 135-188

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 72dccdb and b82b308.

📒 Files selected for processing (1)
  • packages/bruno-electron/src/app/workspace-watcher.js (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-electron/src/app/workspace-watcher.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Unit Tests
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - Linux

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/bruno-electron/src/ipc/workspace.js (1)

463-510: Potential duplicate workspace opening.

If the default workspace path is also stored in lastOpenedWorkspaces, it will be opened twice (once at line 471 and again in the loop at line 495). Consider filtering the default path from workspacePaths.

      // Load other workspaces
      const workspacePaths = lastOpenedWorkspaces.getAll();
+     const defaultPath = defaultResult?.workspacePath;
      const invalidPaths = [];

      for (const workspacePath of workspacePaths) {
+       if (defaultPath && path.normalize(workspacePath) === path.normalize(defaultPath)) {
+         continue; // Already opened as default workspace
+       }
        const workspaceYmlPath = path.join(workspacePath, 'workspace.yml');
♻️ Duplicate comments (1)
packages/bruno-electron/src/store/default-workspace.js (1)

11-12: WORKSPACE_TYPE duplication noted in past review.

As flagged previously, WORKSPACE_TYPE is duplicated from workspace-config.js. Consider importing it to maintain a single source of truth.

🧹 Nitpick comments (1)
packages/bruno-electron/src/store/default-workspace.js (1)

107-112: Consider adding a max iteration guard.

The while loop could theoretically run indefinitely if fs.existsSync keeps returning true. While unlikely in practice, a safeguard would be defensive.

     let workspacePath = baseWorkspacePath;
     let counter = 1;
+    const maxAttempts = 100;
     while (fs.existsSync(workspacePath)) {
+      if (counter > maxAttempts) {
+        throw new Error('Unable to find available default workspace path');
+      }
       workspacePath = `${baseWorkspacePath}-${counter}`;
       counter++;
     }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b82b308 and 0c62ead.

📒 Files selected for processing (5)
  • packages/bruno-electron/src/app/apiSpecs.js (2 hunks)
  • packages/bruno-electron/src/app/workspace-watcher.js (3 hunks)
  • packages/bruno-electron/src/ipc/workspace.js (9 hunks)
  • packages/bruno-electron/src/store/default-workspace.js (5 hunks)
  • packages/bruno-electron/src/utils/workspace-config.js (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • packages/bruno-electron/src/app/workspace-watcher.js
  • packages/bruno-electron/src/store/default-workspace.js
  • packages/bruno-electron/src/utils/workspace-config.js
  • packages/bruno-electron/src/ipc/workspace.js
  • packages/bruno-electron/src/app/apiSpecs.js
🧬 Code graph analysis (5)
packages/bruno-electron/src/app/workspace-watcher.js (1)
packages/bruno-electron/src/utils/workspace-config.js (1)
  • getWorkspaceUid (359-365)
packages/bruno-electron/src/store/default-workspace.js (1)
packages/bruno-electron/src/utils/workspace-config.js (15)
  • OPENCOLLECTION_VERSION (9-9)
  • WORKSPACE_TYPE (8-8)
  • fs (1-1)
  • path (2-2)
  • config (186-186)
  • config (196-196)
  • config (203-203)
  • config (231-231)
  • config (271-271)
  • config (286-286)
  • config (301-301)
  • config (327-327)
  • readWorkspaceConfig (87-102)
  • validateWorkspaceConfig (167-183)
  • workspaceConfig (95-95)
packages/bruno-electron/src/utils/workspace-config.js (2)
packages/bruno-electron/src/app/workspace-watcher.js (4)
  • require (6-6)
  • require (7-7)
  • require (8-8)
  • require (10-10)
packages/bruno-electron/src/store/default-workspace.js (3)
  • require (3-3)
  • require (4-4)
  • require (5-5)
packages/bruno-electron/src/ipc/workspace.js (1)
packages/bruno-electron/src/utils/workspace-config.js (4)
  • getWorkspaceUid (359-365)
  • createWorkspaceConfig (66-75)
  • writeWorkspaceConfig (162-165)
  • readWorkspaceConfig (87-102)
packages/bruno-electron/src/app/apiSpecs.js (2)
packages/bruno-electron/src/app/workspace-watcher.js (6)
  • require (6-6)
  • require (7-7)
  • require (8-8)
  • require (10-10)
  • workspaceUid (46-46)
  • isDefault (47-47)
packages/bruno-electron/src/utils/workspace-config.js (4)
  • require (4-4)
  • require (5-5)
  • require (6-6)
  • getWorkspaceUid (359-365)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: Unit Tests
  • GitHub Check: CLI Tests
  • GitHub Check: Playwright E2E Tests
🔇 Additional comments (17)
packages/bruno-electron/src/app/apiSpecs.js (2)

78-83: LGTM - Consistent UID and type handling.

The workspace UID logic aligns with the centralized getWorkspaceUid pattern used across other files. The type override for default workspaces is correctly applied before sending the IPC message.


3-4: Imports are correct.

Both generateUidBasedOnHash (for API spec paths at line 33) and getWorkspaceUid (for workspace paths at line 78) are needed.

packages/bruno-electron/src/utils/workspace-config.js (1)

359-365: LGTM - Clean UID resolution logic.

The null check on defaultWorkspacePath before comparison and the use of path.normalize for cross-platform path matching are good practices.

packages/bruno-electron/src/app/workspace-watcher.js (3)

6-7: Both imports are needed.

generateUidBasedOnHash is still used at line 73 for environment file UIDs, while getWorkspaceUid handles workspace-level UID resolution.


46-52: Consistent type derivation pattern.

The isDefault flag and conditional type assignment align with the approach in apiSpecs.js and workspace.js.


128-131: LGTM - Centralized UID for watcher registration.

The workspace UID is correctly computed once and passed to environment handlers for consistency.

packages/bruno-electron/src/ipc/workspace.js (7)

23-24: Imports are correctly updated.

Both validateWorkspaceDirectory and getWorkspaceUid are used in this file.


51-72: LGTM - Create workspace handler updated correctly.

The workspace UID and type derivation are correctly applied to both the IPC message and the return value.


85-101: LGTM - Open workspace handler consistent.


125-141: LGTM - Dialog handler consistent.


348-353: LGTM - Collection add handler updated.


384-397: Good defensive approach.

Recalculating the workspace UID as correctWorkspaceUid rather than trusting the passed parameter ensures consistency, especially if the caller has stale data.


447-460: LGTM - Centralized config reading.

Using readWorkspaceConfig instead of inline YAML parsing is cleaner. The hardcoded type: 'default' is correct since this handler specifically deals with the default workspace.

packages/bruno-electron/src/store/default-workspace.js (4)

30-32: LGTM - Simplified UID getter.

Returning the constant DEFAULT_WORKSPACE_UID directly is cleaner and ensures consistency.


47-64: LGTM - Robust validation helper.

The three-tier validation (path exists, workspace.yml exists, config is valid) with proper error handling provides a clean boolean API.


66-99: LGTM - Cleaner initialization flow.

Using isValidDefaultWorkspace simplifies the check. The null return on error is appropriate for graceful degradation.


114-116: Synchronous mkdir is acceptable here.

For one-time initialization during app startup, synchronous operations are fine.

@bijin-bruno bijin-bruno left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@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/workspace/default-workspace/migration.spec.ts (1)

36-39: Store locators in variables for better readability.

The coding guidelines recommend using locator variables instead of inline locators. This improves readability and makes the test intent clearer.

Example refactor for the first test:

   const app = await launchElectronApp({ userDataPath });
   const page = await app.firstWindow();
-  await page.locator('[data-app-state="loaded"]').waitFor({ timeout: 30000 });
+  
+  const appLoadedLocator = page.locator('[data-app-state="loaded"]');
+  const workspaceNameLocator = page.locator('.workspace-name');
+  
+  await appLoadedLocator.waitFor({ timeout: 30000 });
   
-  await expect(page.locator('.workspace-name')).toContainText('My Workspace');
+  await expect(workspaceNameLocator).toContainText('My Workspace');

Apply similar refactoring to all tests in the file for consistency.

Also applies to: 85-87, 128-131, 148-149, 161-162, 182-184

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 90a4f82 and 4c2dcea.

📒 Files selected for processing (1)
  • tests/workspace/default-workspace/migration.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • tests/workspace/default-workspace/migration.spec.ts
tests/**/**.*

⚙️ CodeRabbit configuration file

tests/**/**.*: Review the following e2e test code written using the Playwright test library. Ensure that:

  • Follow best practices for Playwright code and e2e automation

  • Try to reduce usage of page.waitForTimeout(); in code unless absolutely necessary and the locator cannot be found using existing expect() playwright calls

  • Avoid using page.pause() in code

  • Use locator variables for locators

  • Avoid using test.only

  • Use multiple assertions

  • Promote the use of test.step as much as possible so the generated reports are easier to read

  • Ensure that the fixtures like the collections are nested inside the fixtures folder

    Fixture Example*: Here's an example of possible fixture and test pair

    .
    ├── fixtures
    │   └── collection
    │       ├── base.bru
    │       ├── bruno.json
    │       ├── collection.bru
    │       ├── ws-test-request-with-headers.bru
    │       ├── ws-test-request-with-subproto.bru
    │       └── ws-test-request.bru
    ├── connection.spec.ts # <- Depends on the collection in ./fixtures/collection
    ├── headers.spec.ts
    ├── persistence.spec.ts
    ├── variable-interpolation
    │   ├── fixtures
    │   │   └── collection
    │   │       ├── environments
    │   │       ├── bruno.json
    │   │       └── ws-interpolation-test.bru
    │   ├── init-user-data
    │   └── variable-interpolation.spec.ts # <- Depends on the collection in ./variable-interpolation/fixtures/collection
    └── subproto.spec.ts
    

Files:

  • tests/workspace/default-workspace/migration.spec.ts
🧠 Learnings (2)
📚 Learning: 2025-12-05T20:31:33.005Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-05T20:31:33.005Z
Learning: Applies to **/*.test.{js,jsx,ts,tsx} : Add tests for any new functionality or meaningful changes. If code is added, removed, or significantly modified, corresponding tests should be updated or created

Applied to files:

  • tests/workspace/default-workspace/migration.spec.ts
📚 Learning: 2025-12-05T20:31:33.005Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-05T20:31:33.005Z
Learning: 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

Applied to files:

  • tests/workspace/default-workspace/migration.spec.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - macOS
  • GitHub Check: CLI Tests
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: Unit Tests
🔇 Additional comments (1)
tests/workspace/default-workspace/migration.spec.ts (1)

47-50: Past review comment addressed correctly.

The conditional checks that could mask test failures have been replaced with explicit assertions. All instances now properly assert file existence before reading, which will fail the test if workspace.yml is not created as expected.

Also applies to: 92-95, 192-195

@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: 0

🧹 Nitpick comments (3)
tests/workspace/default-workspace/migration.spec.ts (1)

109-139: Assert existing user collection visibility to harden regression signal

Right now this test only asserts that the sample collection is not visible; it doesn’t confirm that the existing user collection actually shows up, which would better validate the migration path for real users.

You could add an assertion like this:

-      // Sample collection should NOT be created (because user has existing collections)
-      const sampleCollection = page.locator('#sidebar-collection-name').getByText('Sample API Collection');
-      await expect(sampleCollection).not.toBeVisible();
+      // Existing user collection should be visible
+      const existingCollection = page.locator('#sidebar-collection-name').getByText('Old User Collection');
+      await expect(existingCollection).toBeVisible();
+
+      // Sample collection should NOT be created (because user has existing collections)
+      const sampleCollection = page.locator('#sidebar-collection-name').getByText('Sample API Collection');
+      await expect(sampleCollection).not.toBeVisible();

This makes the test assert both “no regression” (existing collection still there) and “no unwanted sample import”.

tests/workspace/default-workspace/default-workspace.spec.ts (2)

24-43: Tighten persistence test with filesystem assertions and consistent cleanup

The persistence test currently only checks the UI name and closes app1 without explicitly closing its context, while other tests do both.

Consider:

-      // First launch
+      // First launch
       const app1 = await launchElectronApp({ userDataPath });
       const page1 = await app1.firstWindow();
       await page1.locator('[data-app-state="loaded"]').waitFor({ timeout: 30000 });
       await expect(page1.locator('.workspace-name')).toContainText('My Workspace');
-
-      await app1.close();
+      await app1.context().close();
+      await app1.close();
@@
-      // Second launch - same workspace should be loaded
+      // Second launch - same workspace should be loaded, and no duplicate directory created
       const app2 = await launchElectronApp({ userDataPath });
       const page2 = await app2.firstWindow();
       await page2.locator('[data-app-state="loaded"]').waitFor({ timeout: 30000 });
       await expect(page2.locator('.workspace-name')).toContainText('My Workspace');
+
+      const workspacePath = path.join(userDataPath, 'default-workspace');
+      expect(fs.existsSync(workspacePath)).toBe(true);
+      expect(fs.existsSync(path.join(userDataPath, 'default-workspace-1'))).toBe(false);

This aligns the cleanup pattern with other tests and makes the persistence behavior more strictly validated.


46-191: Consider structuring these longer flows with test.step and a shared “wait for app loaded” helper

The recovery and UI tests have clear phases (filesystem setup, app launch, UI assertions, filesystem assertions, cleanup). Following the guidelines, you could:

  • Wrap those phases in test.step blocks for clearer Playwright reports
  • Extract the repeated await page.locator('[data-app-state="loaded"]').waitFor({ timeout: 30000 }); into a small helper (e.g., await waitForAppLoaded(page);) in a shared test utility

This would reduce duplication across this file and migration.spec.ts and make failures easier to interpret. Based on learnings, using shared helpers where they simplify tests is preferred.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f0627e1 and 591ddf8.

📒 Files selected for processing (2)
  • tests/workspace/default-workspace/default-workspace.spec.ts (1 hunks)
  • tests/workspace/default-workspace/migration.spec.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Use 2 spaces for indentation. No tabs, just spaces
Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., )
Always add semicolons at the end of statements
No trailing commas
Always use parentheses around parameters in arrow functions, even for single params
For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline
No newlines inside function parentheses
Space before and after the arrow in arrow functions. () => {} is good
No space between function name and parentheses. func() not func ()
Semicolons go at the end of the line, not on a new line
Names for functions need to be concise and descriptive
Add in JSDoc comments to add more details to the abstractions if needed
Add in meaningful comments instead of obvious ones where complex code flow is explained properly

Files:

  • tests/workspace/default-workspace/migration.spec.ts
  • tests/workspace/default-workspace/default-workspace.spec.ts
tests/**/**.*

⚙️ CodeRabbit configuration file

tests/**/**.*: Review the following e2e test code written using the Playwright test library. Ensure that:

  • Follow best practices for Playwright code and e2e automation

  • Try to reduce usage of page.waitForTimeout(); in code unless absolutely necessary and the locator cannot be found using existing expect() playwright calls

  • Avoid using page.pause() in code

  • Use locator variables for locators

  • Avoid using test.only

  • Use multiple assertions

  • Promote the use of test.step as much as possible so the generated reports are easier to read

  • Ensure that the fixtures like the collections are nested inside the fixtures folder

    Fixture Example*: Here's an example of possible fixture and test pair

    .
    ├── fixtures
    │   └── collection
    │       ├── base.bru
    │       ├── bruno.json
    │       ├── collection.bru
    │       ├── ws-test-request-with-headers.bru
    │       ├── ws-test-request-with-subproto.bru
    │       └── ws-test-request.bru
    ├── connection.spec.ts # <- Depends on the collection in ./fixtures/collection
    ├── headers.spec.ts
    ├── persistence.spec.ts
    ├── variable-interpolation
    │   ├── fixtures
    │   │   └── collection
    │   │       ├── environments
    │   │       ├── bruno.json
    │   │       └── ws-interpolation-test.bru
    │   ├── init-user-data
    │   └── variable-interpolation.spec.ts # <- Depends on the collection in ./variable-interpolation/fixtures/collection
    └── subproto.spec.ts
    

Files:

  • tests/workspace/default-workspace/migration.spec.ts
  • tests/workspace/default-workspace/default-workspace.spec.ts
🧠 Learnings (2)
📚 Learning: 2025-12-05T20:31:33.005Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-05T20:31:33.005Z
Learning: Applies to **/*.test.{js,jsx,ts,tsx} : Add tests for any new functionality or meaningful changes. If code is added, removed, or significantly modified, corresponding tests should be updated or created

Applied to files:

  • tests/workspace/default-workspace/migration.spec.ts
  • tests/workspace/default-workspace/default-workspace.spec.ts
📚 Learning: 2025-12-05T20:31:33.005Z
Learnt from: CR
Repo: usebruno/bruno PR: 0
File: CODING_STANDARDS.md:0-0
Timestamp: 2025-12-05T20:31:33.005Z
Learning: 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

Applied to files:

  • tests/workspace/default-workspace/migration.spec.ts
🧬 Code graph analysis (1)
tests/workspace/default-workspace/default-workspace.spec.ts (3)
packages/bruno-tests/src/index.js (1)
  • app (13-13)
packages/bruno-electron/src/utils/workspace-config.js (1)
  • defaultWorkspacePath (360-360)
packages/bruno-electron/src/store/default-workspace.js (2)
  • path (2-2)
  • fs (1-1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Playwright E2E Tests
  • GitHub Check: Unit Tests
  • GitHub Check: CLI Tests
  • GitHub Check: SSL Tests - Windows
  • GitHub Check: SSL Tests - Linux
  • GitHub Check: SSL Tests - macOS
🔇 Additional comments (2)
tests/workspace/default-workspace/migration.spec.ts (1)

11-55: Solid coverage of primary migration path

This test wires up old-style preferences, launches the app, and asserts both UI state and workspace.yml contents; behavior and assertions look correct for the single-collection migration case.

Please keep an eye on CI runs for this spec across platforms, in case workspace.yml formatting or timing differences surface.

tests/workspace/default-workspace/default-workspace.spec.ts (1)

7-20: First‑launch default workspace behavior looks correct

The test cleanly exercises a fresh user data directory and asserts the default workspace name via the title area; this matches the intended first‑launch behavior.

@bijin-bruno
bijin-bruno merged commit 8b0f41e into usebruno:main Dec 15, 2025
maxenceleblanc pushed a commit to maxenceleblanc/curly_cats2 that referenced this pull request Jul 20, 2026
* fix: default workspace error checking

* add: tests

* fixes

* fix

* fixes

* fixes

* fix

* fixes

* fix

* chore: close app context in tests

---------

Co-authored-by: Bijin A B <[email protected]>
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.

2 participants