Skip to content

Watch files handled by runtime plugin onLoad - #30608

Closed
robobun wants to merge 5 commits into
mainfrom
farm/a861bd7c/watch-plugin-onload
Closed

robobun wants to merge 5 commits into
mainfrom
farm/a861bd7c/watch-plugin-onload

Conversation

@robobun

@robobun robobun commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes #17270
Fixes #19496
Fixes #5844
Fixes #4790
Fixes #5431

When a runtime plugin's onLoad handler matches an imported file under --watch / --hot, edits to that file never trigger a reload. This happens both when the plugin throws (the reported case — e.g. a transpiler plugin hitting a parse error) and when it succeeds.

Repro

# bunfig.toml
preload = ["./plugin.js"]
// plugin.js
import { plugin, file } from "bun";
await plugin({
  name: "repro",
  setup(b) {
    b.onLoad({ filter: /foo\.js$/ }, async ({ path }) => {
      const contents = await file(path).text();
      if (contents.includes("BAD")) throw new Error("bad");
      return { contents, loader: "js" };
    });
  },
});
// entry.js
import "./foo.js";
bun --watch entry.js
# edit foo.js → nothing happens

Cause

The watcher is populated inside transpileSourceCode after the transpiler opens the source file (input_file_fd). When a plugin's onLoad matches, Bun__runVirtualModule returns the plugin result and the C++ side either rejects immediately (throw case) or calls Bun__transpileVirtualModule with a virtual_source (success case). In both paths the transpiler never opens the real file, so input_file_fd stays invalid and bun_watcher.addFile is never called.

The entry-point file happened to be covered anyway by a separate addMainToWatcherIfNeeded fallback, which masked the bug for single-file repros.

Fix

In Bun__runVirtualModule, whenever a plugin matches (returns a value or throws), register the specifier with the watcher via addFileByPathSlow — for absolute paths in the default/file namespace, skipping node_modules (same filter the normal path uses). When no plugin matches we fall through to the existing transpile path unchanged.

How did you verify your code works?

New regression test test/regression/issue/17270.test.ts covers:

  • onLoad throws → fix file → reload → edit again → reload
  • onLoad succeeds → edit → reload → break → reload → fix → reload

Both tests time out on main and pass with this change.

Also ran test/cli/hot/watch.test.ts, test/cli/watch/watch.test.ts, and test/js/bun/plugin/plugins.test.ts — all green.

When a runtime plugin's onLoad handler matches an imported file, the
normal transpile path that registers the file with the watcher is
bypassed — the transpiler never opens the file because the source
comes from the plugin. As a result, edits to that file never trigger
a reload under --watch or --hot, whether the plugin succeeded or
threw.

Register the specifier with the watcher in Bun__runVirtualModule
whenever a plugin matches (returns a result or throws), for absolute
paths in the default/file namespace.

Fixes #17270
@robobun

robobun commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:04 AM PT - May 13th, 2026

❌ @robobun, your commit 5efdb23 has 1 failures in Build #53978 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 30608

That installs a local version of the PR into your bun-30608 executable, so you can run:

bun-30608 --bun

@coderabbitai

coderabbitai Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 46e3163d-90df-4b5e-a396-b3642b386317

📥 Commits

Reviewing files that changed from the base of the PR and between fac27ce and 6693745.

📒 Files selected for processing (1)
  • test/regression/issue/17270.test.ts

Walkthrough

Registers plugin-handled on-disk files with Bun’s watcher and updates plugin execution to notify the watcher on both throw and success paths; adds regression tests exercising bun --watch across plugin onLoad throw/succeed transitions.

Changes

Plugin Watch Mode File Tracking

Layer / File(s) Summary
Watcher registration helper
src/jsc/ModuleLoader.zig
addPluginHandledPathToWatcher validates and registers absolute, non-node_modules files with the file watcher for the default file namespace, selecting loader by extension.
Plugin execution with watcher integration
src/jsc/ModuleLoader.zig
Bun__runVirtualModule caches the VM locally and updates runOnLoadPlugins handling to register plugin-handled paths with the watcher on both throw and success, returning plugin results or falling through when no plugin matches.
Watch mode regression tests
test/regression/issue/17270.test.ts
Adds an inline preload runtime plugin, an async stdout line-matching helper, and two tests verifying bun --watch keeps detecting file edits after onLoad throws and across throw/succeed transitions.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and concisely describes the main change: ensuring files handled by runtime plugin onLoad are watched.
Description check ✅ Passed Description includes both required sections: clear explanation of what the PR does with issue references and linked repro, and verification details including new test and existing test runs.
Linked Issues check ✅ Passed Code changes directly address all linked issues (#17270, #19496, #5844, #4790, #5431) by registering plugin-matched files with the watcher via addFileByPathSlow.
Out of Scope Changes check ✅ Passed All changes are directly in scope: ModuleLoader.zig implements the watcher registration fix and test file adds regression coverage for the addressed issues.

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


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

@github-actions

Copy link
Copy Markdown
Contributor

Found 5 issues this PR may fix:

  1. File watch not working anymore with 1.2.10+ #19496 - File watch stopped working with plugins in 1.2.10+; same root cause of plugin onLoad files not registered with watcher
  2. bun --watch does not reload when custom loader file changes #5844 - bun --watch does not reload when custom loader (.scss plugin onLoad) file changes
  3. Bun fails to reload on file changes on --watch when preload present; Only preload file changes triggers refresh #4790 - bun --watch fails to reload on file changes when preload plugin with onLoad is present
  4. Fix hot reloading for modules imported via custom loaders #5431 - Hot reloading broken for modules imported via custom loaders
  5. Implement watchFiles and watchDirs in plugin API #4689 - build.onLoad prevents watching/reloading filtered files (partially fixed; the watchFiles/watchDirs API enhancement is not addressed)

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #19496
Fixes #5844
Fixes #4790
Fixes #5431
Fixes #4689

🤖 Generated with Claude Code

@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

🤖 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 `@src/jsc/ModuleLoader.zig`:
- Around line 1133-1136: Replace the call to std.fs.path.isAbsolute(path) with
the repo convention bun.path.Platform.auto.isAbsolute(path) in the ModuleLoader
logic that checks the path before skipping node_modules; keep
std.fs.path.extension(path) as-is. Update the conditional in the block that
references the local variable path and the jsc_vm/transpiler loader call (the
lines around the use of jsc_vm.transpiler.options.loader and
jsc_vm.bun_watcher.addFileByPathSlow) so it uses
bun.path.Platform.auto.isAbsolute(...) instead of std.fs.path.isAbsolute(...).

In `@test/regression/issue/17270.test.ts`:
- Line 40: Add an explicit 15000ms timeout to the tests that spawn a `bun
--watch` subprocess and call `nextMatching()` to avoid CI flakiness; locate the
test definition for test("after onLoad throws", ...) and the other sibling test
in the same file that also uses `--watch`/`nextMatching()` and pass 15000 as the
timeout argument to the test function (i.e., use the test(name, fn, 15000)
signature) so the watch startup, initial compile, and file-change detection have
enough time.
🪄 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: ASSERTIVE

Plan: Pro

Run ID: 3ba4d222-7872-44f9-b46c-6c1fce84b517

📥 Commits

Reviewing files that changed from the base of the PR and between 3bf4b33 and e531685.

📒 Files selected for processing (2)
  • src/jsc/ModuleLoader.zig
  • test/regression/issue/17270.test.ts

Comment thread src/jsc/ModuleLoader.zig Resolved
Comment thread test/regression/issue/17270.test.ts Resolved

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

♻️ Duplicate comments (1)
test/regression/issue/17270.test.ts (1)

42-74: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add explicit timeouts to both watch-process tests.

Line 42 and Line 76 run long-lived bun --watch subprocess flows and await multiple nextMatching() transitions; with the default 5000ms timeout these are prone to CI flakes. Please set an explicit timeout (e.g. 15_000) on both tests.

⏱️ Proposed fix
-    test("after onLoad throws", async () => {
+    test("after onLoad throws", async () => {
       using dir = tempDir("watch-plugin-throw", {
         "bunfig.toml": `preload = ["./plugin.js"]\n`,
         "plugin.js": plugin,
         "entry.js": `import "./foo.js";\n`,
         "foo.js": `BAD; console.log("hello v1");\n`,
       });
@@
       proc.kill();
       await proc.exited;
-    });
+    }, 15_000);

-    test("after onLoad succeeds", async () => {
+    test("after onLoad succeeds", async () => {
       using dir = tempDir("watch-plugin-ok", {
         "bunfig.toml": `preload = ["./plugin.js"]\n`,
         "plugin.js": plugin,
         "entry.js": `import "./foo.js";\n`,
         "foo.js": `console.log("hello v1");\n`,
       });
@@
       proc.kill();
       await proc.exited;
-    });
+    }, 15_000);

Based on learnings: In IPC-related tests that spawn parent/child processes, set explicit test timeouts (e.g., 15000ms) because the default 5000ms is often insufficient.

Also applies to: 76-109

🤖 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 `@test/regression/issue/17270.test.ts` around lines 42 - 74, Add an explicit
15_000ms timeout to the long-lived watch-process tests so CI flakes stop
occurring: update the test() call for "after onLoad throws" (the test that
spawns bun with --watch and uses nextMatching/forEachLine) to include a 15000
timeout argument, and do the same for the second watch-test around lines 76-109
(the other test that spawns a watch subprocess). This ensures the async
spawn/nextMatching flows have a longer timeout than the default 5000ms.
🤖 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.

Duplicate comments:
In `@test/regression/issue/17270.test.ts`:
- Around line 42-74: Add an explicit 15_000ms timeout to the long-lived
watch-process tests so CI flakes stop occurring: update the test() call for
"after onLoad throws" (the test that spawns bun with --watch and uses
nextMatching/forEachLine) to include a 15000 timeout argument, and do the same
for the second watch-test around lines 76-109 (the other test that spawns a
watch subprocess). This ensures the async spawn/nextMatching flows have a longer
timeout than the default 5000ms.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 20fcebd5-2f25-4aa4-87a0-4c767fabe03d

📥 Commits

Reviewing files that changed from the base of the PR and between e531685 and 153f417.

📒 Files selected for processing (1)
  • test/regression/issue/17270.test.ts

Comment thread test/regression/issue/17270.test.ts Resolved
@robobun

robobun commented May 13, 2026

Copy link
Copy Markdown
Collaborator Author

CI status: the diff is green — test/regression/issue/17270.test.ts passes on every lane it ran on, and the ModuleLoader.zig change doesn't appear in any failure annotation.

Remaining red is unrelated flake, all on Windows and none touching the watcher/plugin path:

Build Lane Test Failure
53970 debian x64-asan fetch-http2-client.test.ts WebKit AtomStringImpl::remove assertion in HTTP/2 fetch
53978 win x64 / x64-baseline / aarch64 test-http-should-emit-close-when-connection-is-aborted.ts timeout
53978 (flaky-tagged) win x64 jsc-stress.test.ts mprotect failed: 487 in Wasm JIT
53978 (flaky-tagged) win x64 hot.test.ts sourcemap reload counter 45 vs 50 (timing)
53978 (flaky-tagged) win x64-baseline bun-install-registry.test.ts peer hoist version

I've already re-rolled once (5efdb23). Needs a maintainer to retry/merge.

@robobun

robobun commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: this PR's implementation lives entirely in Zig source files that have since been removed from the tree as part of the Rust migration. The change can no longer merge cleanly and the files it edits no longer exist on main.

If the underlying issue is still present, it will need a fresh fix against the Rust implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

1 participant