Skip to content

fix(migration): reattach mountv2 watcher after yml migration - #8567

Merged
bijin-bruno merged 2 commits into
usebruno:mainfrom
chirag-bruno:fix/mountv2-reattach-watcher-after-yaml-migration
Jul 13, 2026
Merged

bijin-bruno merged 2 commits into
usebruno:mainfrom
chirag-bruno:fix/mountv2-reattach-watcher-after-yaml-migration

Conversation

@chirag-bruno

@chirag-bruno chirag-bruno commented Jul 10, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

When a collection is migrated from .bru to .yml via the migrate-to-yml action, the renderer:migrate-collection-to-yml handler tears down the collection watcher and re-attaches it the v1 way — without a fileIndex and without a temp-directory watcher.

For a collection mounted via mountv2 (file cache enabled), this breaks live sync: file changes no longer write through to the cache, and the cache keeps stale .bru entries while the new .yml files are never indexed (the watcher re-attaches with ignoreInitial: true).

Fix

  • Add MountManager.remount(...), which re-reconciles the file-index cache against disk (evicting stale .bru entries, indexing the new .yml files), re-emits the tree, and re-attaches the watcher through the shared cold-load path — preserving the existing transient directory so the renderer's tracked path stays valid.
  • Extract the cold-mount tail into a private #coldLoad reused by both mount and remount.
  • The migrate handler now delegates to remount when the collection is v2-mounted, and falls back to the v1 watcher otherwise. The v1/v2 branch is driven by whether the collection is present in MountManager's mount map, so it can't drift from the cache.file.enabled preference.

Notes

Reload fast-path in mount() is unchanged; only the cold path is shared.

Summary by CodeRabbit

  • Bug Fixes
    • Improved collection migration from .bru to .yml to more reliably restore live synchronization.
    • Enhanced remount behavior so live updates reattach correctly after migration or reload.
    • Added a resilient fallback watching strategy when remount isn’t available.
    • When live sync can’t be restored, the app now displays a clearer error message prompting users to reopen the collection.
    • Remount now consistently refreshes file indexing and the collection tree, including temp directory handling.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

Failed to post review comments.

We encountered an issue with GitHub. Use @coderabbitai full review to retry the review.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fab20b37-c2c5-4f15-85ad-da05ca813e2e

📥 Commits

Reviewing files that changed from the base of the PR and between 32515dd and 4daf0ff.

📒 Files selected for processing (4)
  • packages/bruno-electron/src/ipc/collection.js
  • packages/bruno-electron/src/ipc/mount.js
  • packages/bruno-electron/src/services/mount/manager.js
  • packages/bruno-electron/src/services/mount/manager.spec.js
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/bruno-electron/src/ipc/mount.js
  • packages/bruno-electron/src/services/mount/manager.spec.js
  • packages/bruno-electron/src/services/mount/manager.js
⏰ Context from checks skipped due to timeout. (6)
  • GitHub Check: Lint Check
  • GitHub Check: CLI Tests (Linux)
  • GitHub Check: OAuth 1.0 Auth Tests (Linux)
  • GitHub Check: Playwright E2E Tests (Linux)
  • GitHub Check: SSL Tests (Linux)
  • GitHub Check: Unit Tests (Linux)
⚠️ CI failures not shown inline (1)

Commit Status: security/snyk (Bruno): security/snyk (Bruno)

Conclusion: failure

You have used your limit of private tests
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (CODING_STANDARDS.md)

**/*.{js,jsx,ts,tsx}: Keep code changes minimal and avoid unnecessary whitespace-only diffs.
Use two spaces for indentation and never tabs.
Use single-quoted strings, except JSX/TSX attributes, which use double quotes.
Terminate statements with semicolons.
Do not use trailing commas.
Always use parentheses around arrow-function parameters.
Place opening braces on the same line for multiline constructs and use multiline formatting only when there are at least two elements.
Do not add newlines inside function parentheses.
Put spaces before and after arrow operators, and no space between a function name and its parentheses.
Avoid abstractions unless identical code is used in more than three places.
Use concise, descriptive function names and meaningful comments for complex code flow.
Avoid single-line abstractions that only add a call-stack frame.

Files:

  • packages/bruno-electron/src/ipc/collection.js
**

⚙️ CodeRabbit configuration file

**: # Bruno Coding Standards

  • No diffs unless an actual change is made, the code changes need to be as minimal as possible, avoid making un-necessary whitespace diffs. This is already handled by eslint but make sure you check your code changes before commiting and raising a PR.

General Style Rules

  • Use 2 spaces for indentation. No tabs, just spaces – keeps everything neat and uniform.

  • Stick to single quotes for strings. For JSX/TSX attributes, use double quotes (e.g., ) to follow React conventions.

  • Always add semicolons at the end of statements. It's like putting a period at the end of a sentence – clarity matters.

  • JSX is enabled, so feel free to use it where it makes sense.

Punctuation and Spacing

  • No trailing commas. Keep it clean, no extra commas hanging around.

  • Always use parentheses around parameters in arrow functions. Even for single params – consistency is key.

  • For multiline constructs, put opening braces on the same line, and ensure consistency. Minimum 2 elements for multiline.

  • No newlines inside function parentheses. Keep 'em tight.

  • 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.

  • No strict max length – write readable code, not cramped lines.

  • Multiple expressions per line in JSX are fine – flexibility is nice.

Remember, these rules are here to make our codebase harmonious. If something doesn't fit perfectly, let's chat about it. Happy coding! 🚀

Tests

  • Add tests for any new functionality or meaningful changes. If code is added, removed, or significantly modified, corresponding tests should be updated or created.

  • Prioritise high-value tests over maximum coverage. Focus on testing behaviour that is critical, complex, or likely to break—don’t chase coverage numbers for their own sake.

  • Write behaviour-driven tests, n...

Files:

  • packages/bruno-electron/src/ipc/collection.js
**/*

⚙️ CodeRabbit configuration file

**/*: Bruno is a cross-platform Electron desktop app that runs on macOS, Windows, and Linux. Ensure that all code is OS-agnostic:

  • File paths must use path.join() or path.resolve() instead of hardcoded / or \\ separators
  • Never assume case-sensitive or case-insensitive filesystems
  • Use os.homedir(), app.getPath(), or environment-appropriate APIs instead of hardcoded paths like /home/, C:\\Users\\, or ~/
  • Line endings should be handled consistently (be aware of CRLF vs LF issues)
  • Use path.sep or path.posix/path.win32 when platform-specific separators are needed
  • Shell commands or child_process calls must account for platform differences (e.g., which vs where, /bin/sh vs cmd.exe)
  • File permissions (e.g., fs.chmod, fs.access) should account for Windows not supporting Unix-style permission bits
  • Avoid relying on Unix-only signals (e.g., SIGKILL) without Windows fallbacks
  • Use os.tmpdir() instead of hardcoding /tmp
  • Environment variable access should handle platform differences (e.g., HOME vs USERPROFILE)

Files:

  • packages/bruno-electron/src/ipc/collection.js
🧠 Learnings (2)
📚 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/ipc/collection.js
📚 Learning: 2026-06-26T21:24:02.726Z
Learnt from: sanish-bruno
Repo: usebruno/bruno PR: 8387
File: packages/bruno-cli/src/utils/persist-variables.js:330-337
Timestamp: 2026-06-26T21:24:02.726Z
Learning: In the usebruno/bruno repository, the codebase is standardized to LF line endings. During code review, do not flag CRLF-preservation/line-ending change concerns for these text-based source/config files unless the file format or an explicit workflow/tooling requirement requires preserving CRLF (e.g., a Windows-specific file type or a mandated EOL rule).

Applied to files:

  • packages/bruno-electron/src/ipc/collection.js
🪛 ast-grep (0.44.1)
packages/bruno-electron/src/ipc/collection.js

[warning] 2814-2814: Filesystem path is not a string literal; a request-/variable-derived path can enable path traversal. Validate and normalize the path before use.
Context: fs.readFileSync(path.join(collectionPathname, 'bruno.json'), 'utf8')
Note: [CWE-22] Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal').

(detect-non-literal-fs-filename)

Walkthrough

Collection migration now remounts existing collections through the mount manager. Mount startup and remounting share a centralized cold-load flow that rebuilds state, reconciles files, emits the tree, and restores watchers.

Changes

Collection remount lifecycle

Layer / File(s) Summary
Centralized mount lifecycle and validation
packages/bruno-electron/src/services/mount/manager.js, packages/bruno-electron/src/services/mount/manager.spec.js
Mount startup delegates to #coldLoad; remounting updates metadata, removes the prior watcher, reloads state, reconciles files, emits the tree, and restores watchers. Tests cover success, missing mounts, and watcher-removal failures.
IPC remount integration
packages/bruno-electron/src/ipc/mount.js, packages/bruno-electron/src/ipc/collection.js
The mount IPC exports remount, and collection migration invokes it before conditionally falling back to direct watcher attachment or displaying an error.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CollectionIPC
  participant MountIPC
  participant MountManager
  participant Watcher
  CollectionIPC->>MountIPC: remount migrated collection
  MountIPC->>MountManager: delegate remount(params)
  MountManager->>Watcher: remove and reattach watchers
  MountManager-->>CollectionIPC: return remount result
  CollectionIPC->>Watcher: fallback watcher attachment when needed
Loading

Possibly related PRs

  • usebruno/bruno#8424: Both modify the YML collection migration flow and migrated brunoConfig handling.
  • usebruno/bruno#8514: Both modify the MountManager mount pipeline and reconciliation behavior exercised by remounting.
  • usebruno/bruno#8553: Both modify the end-to-end YML collection migration flow.

Suggested reviewers: helloanoop, lohit-bruno, naman-bruno, bijin-bruno, sid-bruno

Poem

A watcher sleeps, then wakes anew,
The mount path finds its rhythm too.
Files reconcile, trees arise,
Live sync returns beneath bright skies.
Remount flows where old paths flew.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: reattaching the mountv2 watcher after YML migration.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@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

🧹 Nitpick comments (1)
packages/bruno-electron/src/services/mount/manager.js (1)

104-118: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

remount updates entry.win but never refreshes entry.emit.

entry.emit (used inside #coldLoad for loading/tree events) is only ever set once, at initial mount() time, and its callbacks are closures bound to the window/webContents captured at that point (see ipc/mount.js's mount-collection-v2 handler). remount({ win, ... }) updates entry.win but has no way to update entry.emit — so if a caller ever passes a win different from the one the collection was originally mounted with (e.g. after a window reload/recreate), tree/loading events would keep firing against a stale/possibly-destroyed window while entry.win (used for the actual fs watcher) points to the new one.

Currently the single call site (collection.js migration handler) reuses the same mainWindow for both, so this isn't user-visible today, but the API shape invites future misuse. Consider either accepting/refreshing emit alongside win, or dropping the win param from remount if it's never expected to differ from the mount-time window.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/bruno-electron/src/services/mount/manager.js` around lines 104 -
118, Update remount() and its callers so entry.emit is refreshed whenever a new
win is supplied, ensuring `#coldLoad` emits through the current window rather than
stale mount-time callbacks; alternatively remove the win parameter if remount
must always reuse the original window. Keep entry.win and entry.emit
synchronized across remounts, including the mount-collection-v2 callback setup.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/bruno-electron/src/ipc/collection.js`:
- Around line 2783-2793: Ensure the remount failure path in the migration
handler also attempts watcher recovery when appropriate: in the catch around
remountCollectionV2, distinguish genuine remount errors from an unavailable
remount and invoke watcher.addWatcher with the same arguments and ignoreInitial
option used by the !remounted branch when safe. Preserve the error logging and
user notification for genuine failures, and coordinate with
remountCollectionV2’s removeWatcher error handling so recovery does not mask the
original error.

In `@packages/bruno-electron/src/services/mount/manager.js`:
- Around line 104-136: Add tests covering the new remount lifecycle in
MountManager: verify successful remount tears down and reattaches watchers while
reconciling and emitting the tree, unknown collectionUid returns false without
lifecycle work, and errors from collectionWatcher.removeWatcher are propagated
with loading state restored. Use the remount and `#coldLoad` methods with mocked
watcher, index, reconciliation, and emit dependencies.

---

Nitpick comments:
In `@packages/bruno-electron/src/services/mount/manager.js`:
- Around line 104-118: Update remount() and its callers so entry.emit is
refreshed whenever a new win is supplied, ensuring `#coldLoad` emits through the
current window rather than stale mount-time callbacks; alternatively remove the
win parameter if remount must always reuse the original window. Keep entry.win
and entry.emit synchronized across remounts, including the mount-collection-v2
callback setup.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f2d9f384-4be5-4f67-a0f0-7d0a6f049e39

📥 Commits

Reviewing files that changed from the base of the PR and between 68945db and 32515dd.

📒 Files selected for processing (3)
  • packages/bruno-electron/src/ipc/collection.js
  • packages/bruno-electron/src/ipc/mount.js
  • packages/bruno-electron/src/services/mount/manager.js

cchirag added 2 commits July 13, 2026 16:24
The migrate-to-yml handler tore down the collection watcher and
re-attached it the v1 way (no fileIndex, no temp-dir watcher), so a
collection mounted via mountv2 lost cache-backed live sync after
migration and the file cache kept stale .bru entries.

Add MountManager.remount, which re-reconciles the cache against disk
and re-attaches the watcher through the shared cold-load path while
preserving the existing transient directory. The migrate handler now
delegates to it when the collection is v2-mounted and falls back to
the v1 watcher otherwise.
- Drop the unused win param from MountManager.remount; it always reuses
  the mount-time win/emit (a real window swap goes through mount()'s
  reload branch, which refreshes both).
- Migration success path now falls back to a plain watcher when remount
  throws, not only when it returns false; the reopen-collection toast is
  the last resort.
- Migration rollback path prefers remount for v2-mounted collections too,
  falling back to the v1 watcher.
- Add unit tests for remount: successful reattach + tree re-emit,
  unknown collection returns false, watcher-removal failure propagates.
@chirag-bruno
chirag-bruno force-pushed the fix/mountv2-reattach-watcher-after-yaml-migration branch from 2febdb6 to 4daf0ff Compare July 13, 2026 10:54

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/bruno-electron/src/ipc/collection.js`:
- Around line 2814-2822: Update the rollback handling around remountCollectionV2
so a remount failure still re-attaches the watcher via watcher.addWatcher when
available. Make the parsed bruno.json configuration accessible to the catch
block by hoisting its declaration or otherwise preserving/reusing it, and ensure
the fallback does not depend on rereading a file that may have been deleted
during migration.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fab20b37-c2c5-4f15-85ad-da05ca813e2e

📥 Commits

Reviewing files that changed from the base of the PR and between 32515dd and 4daf0ff.

📒 Files selected for processing (4)
  • packages/bruno-electron/src/ipc/collection.js
  • packages/bruno-electron/src/ipc/mount.js
  • packages/bruno-electron/src/services/mount/manager.js
  • packages/bruno-electron/src/services/mount/manager.spec.js
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/bruno-electron/src/ipc/mount.js
  • packages/bruno-electron/src/services/mount/manager.spec.js
  • packages/bruno-electron/src/services/mount/manager.js

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.

5 participants