Repository navigation
improve: migration & default workspace handling - #6707
Conversation
WalkthroughThe pull request adds workspace recovery and backup capabilities to the default workspace manager. New methods discover existing workspaces, recover collections and environments from broken workspaces, and back up global environments. Migration logic is enhanced to merge recovered data, preserve active environment UIDs, and create backup files. Changes
Sequence DiagramsequenceDiagram
actor App as App Launch
participant DWM as DefaultWorkspaceManager
participant Prefs as Preferences
participant FS as File System
participant WS as Workspace Config
App->>DWM: ensureDefaultWorkspaceExists()
alt Has stored workspace path
DWM->>WS: isValidDefaultWorkspace(path)
alt Valid
DWM->>Prefs: Return existing path
else Invalid/Broken
rect rgb(255, 223, 186)
Note over DWM,FS: Recovery Path
DWM->>DWM: findExistingDefaultWorkspaces()
DWM->>FS: Scan for numbered workspaces
DWM->>DWM: findLatestValidWorkspace()
DWM->>DWM: recoverDataFromWorkspace(broken path)
DWM->>FS: Read workspace config & environments/
DWM->>Prefs: Store recovered path
end
end
else No stored path
rect rgb(220, 240, 255)
Note over DWM,FS: Discovery Path
DWM->>DWM: findExistingDefaultWorkspaces()
DWM->>DWM: findLatestValidWorkspace()
DWM->>Prefs: Store discovered path
end
end
alt Needs migration
rect rgb(230, 255, 230)
Note over DWM,FS: Migration & Backup
DWM->>DWM: backupGlobalEnvironments()
DWM->>FS: Write global-environments-backup.json
DWM->>DWM: migrateFromPreferences(path, config)
DWM->>WS: Merge recovered data into workspace
end
end
DWM->>DWM: initializeDefaultWorkspace(options)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
tests/workspace/default-workspace/recovery-and-backup.spec.ts (3)
7-66: Consider usingtest.step()for better test organization.Breaking this test into steps (e.g., "Setup global environments", "Launch app and trigger migration", "Verify backup file") would improve readability and generate more informative test reports.
Example refactoring with test.step
test('should create backup file for global environments during migration', async ({ launchElectronApp, createTmpDir }) => { - const userDataPath = await createTmpDir('global-env-backup'); - - // Setup: Create global-environments.json - const globalEnvData = { - environments: [ - { - uid: 'env1abcdefghijk123456', - name: 'Production', - variables: [ - { uid: 'var1abcdefghijk123456', name: 'API_URL', value: 'https://api.prod.com', secret: false, type: 'text', enabled: true } - ] - }, - ... - ], - activeGlobalEnvironmentUid: 'env1abcdefghijk123456' - }; - fs.writeFileSync( - path.join(userDataPath, 'global-environments.json'), - JSON.stringify(globalEnvData) - ); - ... - - // Launch app - should trigger migration and create backup - const app = await launchElectronApp({ userDataPath }); - const page = await app.firstWindow(); - await page.locator('[data-app-state="loaded"]').waitFor({ timeout: 30000 }); - - // Verify backup file was created - const backupPath = path.join(userDataPath, 'global-environments-backup.json'); - expect(fs.existsSync(backupPath)).toBe(true); - ... + await test.step('Setup global environments and collection', async () => { + const userDataPath = await createTmpDir('global-env-backup'); + const globalEnvData = { ... }; + fs.writeFileSync(...); + }); + + await test.step('Launch app and trigger migration', async () => { + const app = await launchElectronApp({ userDataPath }); + const page = await app.firstWindow(); + await page.locator('[data-app-state="loaded"]').waitFor({ timeout: 30000 }); + }); + + await test.step('Verify backup file was created with correct content', async () => { + const backupPath = path.join(userDataPath, 'global-environments-backup.json'); + expect(fs.existsSync(backupPath)).toBe(true); + const backup = JSON.parse(fs.readFileSync(backupPath, 'utf8')); + expect(backup.environments).toHaveLength(2); + ... + });
50-50: Consider extracting repeated locators to variables.The pattern
page.locator('[data-app-state="loaded"]').waitFor({ timeout: 30000 })appears throughout the test file. Extracting this to a locator variable would improve maintainability and follow best practices.Example refactoring
test('should create backup file for global environments during migration', async ({ launchElectronApp, createTmpDir }) => { const userDataPath = await createTmpDir('global-env-backup'); // ... setup code ... 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"]'); + await appLoadedLocator.waitFor({ timeout: 30000 });Also applies to: 98-98, 109-109, 142-142, 183-183
473-474: Consider parsing YAML for more robust verification.While
toContain('fallback-collection')works, parsing the YAML and checking the collections array would be more robust against formatting changes.More robust verification
+ const yaml = require('js-yaml'); const workspaceYml = fs.readFileSync(path.join(newWorkspace, 'workspace.yml'), 'utf8'); - expect(workspaceYml).toContain('fallback-collection'); + const config = yaml.load(workspaceYml); + expect(config.collections).toEqual( + expect.arrayContaining([ + expect.objectContaining({ path: expect.stringContaining('fallback-collection') }) + ]) + );packages/bruno-electron/src/store/default-workspace.js (1)
205-208: Consider explicit handling for empty workspace discovery.Line 207:
this.findExistingDefaultWorkspaces()[0]could beundefinedif no workspaces exist. WhilerecoverDataFromWorkspace(undefined)handles this gracefully by catching errors, making this explicit would improve code clarity.More explicit handling
const hasExistingPath = existingPath && fs.existsSync(existingPath); -const recoverySource = hasExistingPath ? existingPath : this.findExistingDefaultWorkspaces()[0]; +const existingWorkspaces = this.findExistingDefaultWorkspaces(); +const recoverySource = hasExistingPath ? existingPath : (existingWorkspaces.length > 0 ? existingWorkspaces[0] : null); const recoveredData = recoverySource ? this.recoverDataFromWorkspace(recoverySource) : null;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/bruno-electron/src/store/default-workspace.jspackages/bruno-electron/src/store/preferences.jstests/workspace/default-workspace/recovery-and-backup.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()notfunc ()
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/preferences.jstests/workspace/default-workspace/recovery-and-backup.spec.tspackages/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 existingexpect()playwright callsAvoid using
page.pause()in codeUse locator variables for locators
Avoid using test.only
Use multiple assertions
Promote the use of
test.stepas much as possible so the generated reports are easier to readEnsure that the
fixtureslike the collections are nested inside thefixturesfolderFixture 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/recovery-and-backup.spec.ts
🧠 Learnings (3)
📚 Learning: 2025-12-17T21:41:24.730Z
Learnt from: naman-bruno
Repo: usebruno/bruno PR: 6407
File: packages/bruno-app/src/components/Environments/ConfirmCloseEnvironment/index.js:5-41
Timestamp: 2025-12-17T21:41:24.730Z
Learning: Do not suggest PropTypes validation for React components in the Bruno codebase. The project does not use PropTypes, so reviews should avoid proposing PropTypes and rely on the existing typing/validation approach (e.g., TypeScript or alternative runtime checks) if applicable. This guideline applies broadly to all JavaScript/JSX components in the repo.
Applied to files:
packages/bruno-electron/src/store/preferences.jspackages/bruno-electron/src/store/default-workspace.js
📚 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/recovery-and-backup.spec.ts
📚 Learning: 2025-12-16T07:16:23.647Z
Learnt from: sanish-bruno
Repo: usebruno/bruno PR: 6090
File: tests/scripting/hooks/init-user-data/ui-state-snapshot.json:1-8
Timestamp: 2025-12-16T07:16:23.647Z
Learning: For e2e tests in the bruno repository: Collections that are shared between CLI and UI tests (comprehensive test suites testing core functionality) should be placed in `packages/bruno-tests/` to avoid duplication. The `tests/**/fixtures/collection` pattern should be used for test-specific collections that test particular UI behaviors or are specific to a single test file.
Applied to files:
tests/workspace/default-workspace/recovery-and-backup.spec.ts
🧬 Code graph analysis (1)
packages/bruno-electron/src/store/default-workspace.js (2)
packages/bruno-electron/src/utils/workspace-config.js (11)
path(2-2)fs(1-1)config(395-395)config(426-426)readWorkspaceConfig(201-216)isValidCollectionEntry(51-65)workspaceConfig(209-209)yamlContent(208-208)generateYamlContent(218-274)collections(229-229)collections(396-396)packages/bruno-electron/src/utils/filesystem.js (3)
path(1-1)fs(2-2)isValidCollectionDirectory(41-48)
⏰ 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: SSL Tests - Linux
- GitHub Check: Playwright E2E Tests
- GitHub Check: CLI Tests
- GitHub Check: Unit Tests
🔇 Additional comments (12)
packages/bruno-electron/src/store/preferences.js (2)
53-54: LGTM: defaultWorkspacePath preference added consistently.The new
defaultWorkspacePathproperty follows the same pattern asdefaultCollectionLocationand integrates cleanly with the existing structure.
107-108: LGTM: Schema validation is appropriate.The validation for
defaultWorkspacePathmatches the existingdefaultCollectionLocationvalidation, ensuring consistency across path preferences.packages/bruno-electron/src/store/default-workspace.js (10)
19-19: LGTM: Backup file constant added.The
GLOBAL_ENV_BACKUP_FILEconstant is well-named and properly scoped at the module level.
27-50: LGTM: Workspace discovery logic is sound.The method correctly discovers base and numbered workspace paths and sorts them by recency (latest first). Note that this method only checks existence; validity checking is delegated to
findLatestValidWorkspace(), which is the appropriate separation of concerns.
52-63: LGTM: Latest valid workspace selection is correct.The method appropriately iterates through workspaces (already sorted latest-first) and returns the first valid one. Returning
nullwhen none are found is appropriate for the caller to handle.
65-103: LGTM: Recovery logic is comprehensive and well-protected.The method attempts to recover both collections and environments with appropriate error handling. The separation of collection config recovery and environment file recovery allows partial recovery if one fails.
105-126: LGTM: Backup logic is well-implemented.The method appropriately backs up global environments with a timestamp, only when data exists. Using synchronous file write is acceptable here as this is called during initialization/migration.
148-154: Verify intended behavior when preference save fails.The method updates
this.defaultWorkspacePatheven ifsavePreferencesfails. This creates a divergence between in-memory state and persisted state. Consider:
- Should the method throw/return false on failure?
- Should it skip updating in-memory state if persistence fails?
- Is the current optimistic update intentional to allow the app to continue in the current session?
The current behavior allows the app to function in the current session but might cause unexpected behavior on restart. Please verify this is the intended fallback strategy.
264-284: LGTM: Recovery data is properly integrated.The method correctly applies recovered environments and collections before migration. The ordering ensures recovered data takes precedence, and the
activeEnvironmentUidfrom recovered data is preserved (migration only sets it if not already present).
306-336: LGTM: Collection merging with proper deduplication.The method correctly deduplicates collections between recovered and preference sources using normalized paths. The ordering (recovered first, then preferences) is appropriate and well-implemented.
339-340: Excellent preservation of recovered data during migration.The migration logic properly:
- Creates a backup before making changes (line 340)
- Avoids overwriting recovered environments (lines 367-370)
- Preserves recovered
activeEnvironmentUid(lines 377-379)This ensures that recovered data takes precedence over potentially conflicting global environment data.
Also applies to: 349-370, 377-379
393-397: Improved validation in needsMigration.Changing from existence check to validity check (using
isValidDefaultWorkspace) is a significant improvement. Migration will now trigger for broken/invalid workspaces, not just missing ones, enabling the recovery scenarios tested in the test suite.
…ration improve: migration & default workspace handling
Description
Contribution Checklist:
Note: Keeping the PR small and focused helps make it easier to review and merge. If you have multiple changes you want to make, please consider submitting them as separate pull requests.
Publishing to New Package Managers
Please see here for more information.
Summary by CodeRabbit
New Features
Bug Fixes
✏️ Tip: You can customize this high-level summary in your review settings.