* feat: implement app.getApplicationInfoForProtocol() on Linux
* refactor: move xdg spec helpers to spec/lib/xdg-helpers.ts
test: add Linux test coverage for app.getApplicationInfoForProtocol()
* chore: make gncheck happy
* fixup! refactor: move xdg spec helpers to spec/lib/xdg-helpers.ts
fix accidental clobber of XDG_DATA_DIRS
feat: add http cache support to requests from utility process
Add `session` and `partition` options to `utilityProcess.fork()` to
allow utility processes to use a session-specific network context
instead of the system network context. This enables HTTP caching,
cookie isolation, and webRequest interception for utility process
network requests.
When `respondToAuthRequestsFromMainProcess` is true and a session is
provided, HTTP 401/407 auth challenges now emit a `login` event on
the UtilityProcess instance rather than on `app`. Without a session,
auth challenges continue to emit on `app` for backward compatibility.
Added Browser::Get()->is_ready() guards to all contentTracing API functions (startRecording, stopRecording, getCategories, getTraceBufferUsage) so they reject their returned Promises with a clear error message instead of crashing when called before app.whenReady().
Added a crash-case fixture test that validates all four APIs reject properly before readiness and work normally after.
* test: add Linux-specific test for getApplicationNameForProtocol()
On Linux, use XDG env vars to inject a mock that we can use
to test app.getApplicationNameForProtocol().
* fixup! test: add Linux-specific test for getApplicationNameForProtocol()
better system mocks
fix: prevent use-after-free when destroying guest WebContents during event emission
Multiple event emission sites in WebContents destroy the underlying C++
object via a JavaScript event handler calling webContents.destroy(), then
continue to dereference the freed `this` pointer. This is exploitable
through <webview> guest WebContents because Destroy() calls `delete this`
synchronously for guests, unlike non-guests which safely defer deletion.
The fix has two layers:
1. A new `is_emitting_event_` flag is checked in Destroy() — when true,
guest deletion is deferred to a posted task instead of executing
synchronously. This is separate from `is_safe_to_delete_` (which
gates LoadURL re-entrancy) to avoid rejecting legitimate loadURL
calls from event handlers.
2. AutoReset<bool> guards on `is_emitting_event_` are added to
CloseContents, RenderViewDeleted, DidFinishNavigation, and
SetContentsBounds, preventing synchronous destruction while their
Emit() calls are on the stack.
Destroy() now requires both `is_safe_to_delete_` (navigation re-entrancy)
and `!is_emitting_event_` (event emission) to allow synchronous guest
deletion. The existing AutoReset guards on `is_safe_to_delete_` in
DidStartNavigation, DidRedirectNavigation, and ReadyToCommitNavigation
are also now effective for guests.
* fix: nodeIntegrationInWorker not working in AudioWorklet
* fix: deadlock on Windows when destroying non-AudioWorklet worker contexts
The previous change kept the WebWorkerObserver alive across
ContextWillDestroy so the worker thread could be reused for the next
context (AudioWorklet thread pooling, Chromium CL:5270028). This is
correct for AudioWorklet but wrong for PaintWorklet and other worker
types, which Blink does not pool — each teardown destroys the thread.
For those worker types, ~NodeBindings was deferred to the thread-exit
TLS callback. By that point set_uv_env(nullptr) had already run, so on
Windows the embed thread was parked in GetQueuedCompletionStatus with a
stale async_sent latch that swallowed the eventual WakeupEmbedThread()
from ~NodeBindings. uv_thread_join then blocked forever, deadlocking
renderer navigation. The worker-multiple-destroy crash case timed out
on win-x64/x86/arm64 as a result. macOS/Linux (epoll/kqueue) don't have
the latch and were unaffected.
Plumb is_audio_worklet from WillDestroyWorkerContextOnWorkerThread into
ContextWillDestroy. For non-AudioWorklet contexts, restore the
pre-existing behavior of calling lazy_tls->Set(nullptr) at the end of
the last-context cleanup so ~NodeBindings runs while the worker thread
is still healthy. AudioWorklet continues to keep the observer alive so
the next pooled context can share NodeBindings.
* chore: address review feedback
* fix: stop embed thread before destroying environments in worker teardown
FreeEnvironment (called via environments_.clear()) runs uv_run to drain
handle close callbacks. On Windows, both that uv_run and the embed
thread's PollEvents call GetQueuedCompletionStatus on the same IOCP
handle. IOCP completions are consumed by exactly one waiter, so the
embed thread can steal completions that FreeEnvironment needs, causing
uv_run to block indefinitely. On Linux/Mac epoll_wait/kevent can wake
multiple waiters for the same event so the race doesn't manifest.
Add NodeBindings::StopPolling() which cleanly joins the embed thread
without destroying handles or the loop, and allows PrepareEmbedThread +
StartPolling to restart it later. Call StopPolling() in
WebWorkerObserver::ContextWillDestroy before environments_.clear() so
FreeEnvironment's uv_run is the only thread touching the IOCP.
Split PrepareEmbedThread's handle initialization (uv_async_init,
uv_sem_init) from thread creation via a new embed_thread_prepared_ flag
so the handles survive across stop/restart cycles for pooled worklets
while the embed thread itself can be recreated.
* chore: address outstanding feedback
* build: add oxfmt for code formatting and import sorting
Adds oxfmt as a devDependency alongside oxlint and wires it into the
lint pipeline. The .oxfmtrc.json config matches Electron's current JS
style (single quotes, semicolons, 2-space indent, trailing commas off,
printWidth 100) and configures sortImports with custom groups that
mirror the import/order pathGroups previously enforced by ESLint:
@electron/internal, @electron/*, and {electron,electron/**} each get
their own ordered group ahead of external modules.
- `yarn lint:fmt` runs `oxfmt --check` over JS/TS sources and is
chained into `yarn lint` so CI enforces it automatically.
- `yarn format` runs `oxfmt --write` for local fix-up.
- lint-staged invokes `oxfmt --write` on staged .js/.ts/.mjs/.cjs
files before oxlint, so formatting is applied at commit time.
The next commit applies the formatter to the existing codebase so the
check actually passes.
* chore: apply oxfmt formatting to JS and TS sources
Runs `yarn format` across lib/, spec/, script/, build/, default_app/,
and npm/ to bring the codebase in line with the .oxfmtrc.json settings
added in the previous commit. This is a pure formatting pass: import
statements are sorted into the groups defined by the config, method
chains longer than printWidth are broken, single-quoted strings
containing apostrophes are switched to double quotes, and a handful of
single-statement `if` bodies are re-wrapped and get braces added by
`oxlint --fix` to satisfy the `curly: multi-line` rule.
No behavior changes.
* feat: capture JS stack trace on renderer OOM
When a renderer process approaches its V8 heap limit, capture the
JavaScript stack trace and write it to both a Crashpad crash key
("js-oom-stack") and stderr.
The stack trace is captured via RequestInterrupt rather than directly
inside the NearHeapLimitCallback because CurrentStackTrace is unsafe
to call during OOM — V8 FATALs on optimized (TurboFan) frames that
have had their deoptimization data garbage-collected. RequestInterrupt
defers the capture to the next V8 safe point, where all frames are
guaranteed to have deopt data available. This matches Node.js's
approach of never capturing JS stacks inside the heap limit callback.
The callback is registered once per isolate via an atomic guard in
RendererClientBase::DidCreateScriptContext, preventing the CHECK
failure V8 raises on duplicate AddNearHeapLimitCallback registrations
(which would otherwise occur on page navigations or multiple contexts).
Refs: #46078
Made-with: Cursor
* Update shell/renderer/oom_stack_trace.cc
Co-authored-by: Niklas Wenzel <dev@nikwen.de>
* Update shell/renderer/oom_stack_trace.cc
Co-authored-by: Niklas Wenzel <dev@nikwen.de>
* test: add crash reporter test for OOM JS stack trace
Add a test that verifies the `electron.v8-oom.stack` crash key contains
the JS stack trace (including function names) when a renderer process
runs out of memory. Also deduplicate the heap info formatting in
oom_stack_trace.cc.
Refs: #46078
Made-with: Cursor
* fix: lint formatting in oom_stack_trace.cc
Made-with: Cursor
* fix: use proper logger API instead of cstdio
* fix: check heap headroom before capturing OOM stack trace
deepak1556: "Should there be check for available heap size [for]
CurrentStackTrace and formatting"
CurrentStackTrace allocates StackTraceInfo + StackFrameInfo on the V8
heap. If the 20 MB bump is partially consumed by the time the interrupt
fires, these allocations trigger a secondary OOM. Guard with a 2 MB
headroom check.
Made-with: Cursor
* fix: handle V8 cage limit when bumping heap for OOM stack capture
deepak1556: "Does this bumping work when we are at the cage limit of
4GB"
V8's pointer compression cage caps the heap at ~4 GB. When
current_heap_limit is already near the ceiling, our 20 MB bump gets
clamped to zero and the interrupt never fires. Detect this and record
heap info as the final crash key instead of waiting for a stack trace
that won't arrive.
Made-with: Cursor
* feat: add V8 heap statistics as OOM crash keys
deepak1556: "V8 seems to capture heap stats as crash keys but it gets
missed today due to the OOM callback override... wonder if we can
include that to get some more heuristics in the dump."
Record heap used/total/limit/available, per-space stats for old_space
and large_object_space, native/detached context counts, and utilization
percentage as crash keys. Also add heap stats in the V8OOMErrorCallback
in node_bindings.cc for the final OOM crash report.
Made-with: Cursor
* feat: support worker thread isolates for OOM stack trace
deepak1556: "You need a separate registration for worker threads via
WorkerScriptReadyForEvaluationOnWorkerThread but that also means the
process global g_registered_isolate would break."
Chromium has one V8 isolate per thread (main + one per web worker), so
thread_local is equivalent to per-isolate storage. Replace the global
atomic + mutex/set with a constinit thread_local OomState* that holds
the isolate pointer and per-isolate is_in_oom flag. The void* data
parameter on AddNearHeapLimitCallback delivers OomState* directly into
callbacks, so the hot path needs no TLS lookup.
Add WorkerScriptReadyForEvaluationOnWorkerThread and
WillDestroyWorkerContextOnWorkerThread overrides to RendererClientBase
so both ElectronRendererClient and ElectronSandboxedRendererClient get
worker OOM registration. Update ElectronRendererClient to call the base
class in both worker lifecycle methods.
Add a web worker OOM test that spawns a dedicated Worker with a memory
leak and verifies the stack trace captures the worker function name.
Made-with: Cursor
* fix: register OOM callback for all script contexts
When context isolation is enabled, ShouldNotifyClient skips
DidCreateScriptContext for the main world, but user JS still runs there
and can OOM. Register in DidInstallConditionalFeatures which fires for
every script context. The TLS dedup guard prevents double-registration
on the same isolate.
Made-with: Cursor
* fix: guard against division by zero and cage size changes in OOM handler
Add a zero-guard on heap_size_limit before computing utilization
percentage — maximizes robustness in an OOM code path.
Add static_assert on kPtrComprCageReservationSize to catch any
upstream V8 change to the cage size at compile time.
Made-with: Cursor
* fix: address review feedback on OOM stack trace PR
- Remove redundant RegisterOomStackTraceCallback from
electron_render_frame_observer.cc; DidCreateScriptContext is sufficient
since main world and isolated world share the same isolate
- Replace thread_local OomState* with base::ThreadLocalOwnedPointer
wrapped in base::NoDestructor per Chromium style for non-trivially
destructible types
- Change heap-headroom and cage-limit logs from ERROR to INFO since
users cannot act on these diagnostics
- Add comment explaining why base class is called last in
WillDestroyWorkerContextOnWorkerThread (OOM deregistration ordering)
Made-with: Cursor
* fix: skip OOM stack trace registration for worklet contexts
Worklets can share a thread and isolate via WorkletThreadHolder's
per-process singleton pattern. With per-thread OOM state, the first
worklet to be destroyed would prematurely remove the callback for
any remaining worklets on the same thread. Skip worklets entirely
to avoid this; can be revisited with ref-counting if needed.
Made-with: Cursor
* fix: prevent dangling raw_ptr<v8::Isolate> in OOM state
The OomState held a raw_ptr<v8::Isolate> that outlived the isolate on
the main thread: gin::IsolateHolder destroyed the isolate during
shutdown, but the OomState (stored in thread-local storage) was only
released later in JavascriptEnvironment::~JavascriptEnvironment. This
triggers a dangling pointer check when building with
enable_dangling_raw_ptr_checks.
Register OomState as a gin::PerIsolateData::DisposeObserver so it
clears the raw_ptr and removes the NearHeapLimitCallback before the
isolate is destroyed, regardless of destructor ordering.
Suggested-by: Deepak Mohan
Made-with: Cursor
* test: verify OOM crash keys end-to-end via crash reporter
Replace stderr-based OOM tests with end-to-end crash dump validation.
Instead of parsing log output, start a crash reporter server, trigger
renderer OOM, and verify the uploaded crash dump contains the expected
`electron.v8-oom.*` annotations — the same code path production crash
reports take.
Consolidate all OOM test scenarios (basic heap leak, JSON.stringify,
web worker) into a single `describe('OOM crash keys')` block inside
api-crash-reporter-spec using the existing crash fixture app with new
renderer-oom-json and renderer-oom-worker crash types.
The web worker test verifies that OOM crash keys are present but does
not assert on the JS function name: the 20 MB heap bump may be
exhausted before V8 reaches a safe point to fire the stack-capture
interrupt, leaving the crash key at "(stack pending)". Increasing the
bump or switching to a synchronous capture strategy would fix this but
is left for a follow-up.
Remove the standalone oom-stack-trace-spec.ts and its fixture app.
Made-with: Cursor
---------
Co-authored-by: Niklas Wenzel <dev@nikwen.de>
#47171 migrated `std::deque` to `base::circular_deque` in
`shell/common/crash_keys.cc`. However, `CrashKeyString` wraps a
`crashpad::Annotation` that holds self-referential pointers and
registers itself in a process-global linked list. `circular_deque`
relocates elements on growth (via `VectorBuffer::MoveConstructRange`),
leaving those pointers dangling — causing missing crash keys or a hung
crashpad handler (especially on macOS). The `base/containers/README.md`
warns: "Since `base::deque` does not have stable iterators and it will
move the objects it contains, it may not be appropriate for all uses."
Reverts to `std::deque`, whose block-based layout never relocates
existing elements. Adds a regression test that registers 50 dynamic
crash keys and verifies they all survive a renderer crash.
Notes: Fixed crash keys being lost and the crash reporter hanging on
macOS when many dynamic crash keys were registered.
Made-with: Cursor
Consolidates the root .eslintrc.json and five nested configs (build,
script, docs, default_app, spec) into a single .oxlintrc.json at the
repo root. script/lint.js now shells out to the oxlint binary from
node_modules/.bin instead of using the ESLint Node API, and emits
GitHub Actions annotations directly via --format=github in CI
(replacing the deleted eslint-stylish problem matcher).
Oxlint has no markdown processor, so the ESLint-based lint of JS code
blocks in docs/**/*.md is replaced with an inline regex check for bare
Node.js builtin imports. This preserves the rule docs/.eslintrc.json
was originally added for in #42113; the rest of the standard ruleset on
docs code blocks was already being enforced in parallel by
lint-roller-markdown-standard.
V8's second-pass weak callbacks run inside a
DisallowJavascriptExecutionScope: they may touch the V8 API but must
not invoke JS, directly or indirectly. Several Electron Wrappables
(WebContents in particular) emit JS events from their destructors,
so deleting synchronously inside SecondWeakCallback can crash with
"Invoke in DisallowJavascriptExecutionScope" when GC happens to
collect the JS wrapper during a foreground GC task — typically during
shutdown's uv_run drain after a leaked WebContentsView.
This was previously latent and timing-dependent (electron/electron#47420,
electron/electron#45416, podman-desktop/podman-desktop#12409). The
esbuild migration's keepNames option (which wraps every function/class
with an Object.defineProperty call) shifted heap layout enough to make
the spec/fixtures/crash-cases/webcontentsview-create-leak-exit case
reliably reproduce it on every run, giving a clean signal for the fix.
Both WrappableBase and DeprecatedWrappableBase SecondWeakCallback now
post the deletion via base::SequencedTaskRunner::GetCurrentDefault()
so the destructor (and any Emit it does) runs once V8 has left the GC
scope. Falls back to synchronous deletion if no task runner is
available (early/late process lifetime).
Fixeselectron/electron#47420.
fix: preserve staged update dir when pruning orphaned update dirs on macOS
The previous squirrel.mac patch cleaned up all staged update directories
before starting a new download. This kept disk usage bounded but broke
quitAndInstall() if called while a subsequent checkForUpdates() was in
flight — the already-staged bundle would be deleted out from under it.
This reworks the patch to read ShipItState.plist and preserve the
directory it references, deleting only truly orphaned update.XXXXXXX
directories. Disk footprint stays bounded (at most 2 dirs: staged +
in-progress) and quitAndInstall() remains safe mid-check.
Also adds test coverage for the quitAndInstall/checkForUpdates race and
a triple-stack scenario where 3 updates arrive without a restart.
Refs https://github.com/electron/electron/issues/50200
* fix: continue to run ProxyingURLLoaderFactory for intercepted protocols
* test: webRequest handlers when loading browser windows
* fix: wrap special URL loaders factories with ProxyingURLLoaderFactory
* test: webRequest handlers when using net.fetch
* refactor: remove redundant intercepted protocol handling
AsarURLLoaderFactory is now intercepted by ProxyingURLLoaderFactory, which already handles when the file:// scheme is intercepted.
* fix: check before using saved headers in OnReceiveResponse
* fix: run webRequest handlers when loading file service workers
* test: handlers when loading file service workers
* refactor: add shared CreateURLLoaderFactoryBuilder method
---------
Co-authored-by: John Kleinschmidt <jkleinsc@electronjs.org>
* feat: add support for `long-animation-frame` script attribution
* docs: document `AlwaysLogLOAFURL`
* chore: add test
* docs: adjust docs as per PR comment
* fix: test failures
* chore: simplify test
* fix: tests on Windows and Linux
* fix: create directory for singleton test in `temp` instead of `home`
* fix: remove directory for singleton test at test end
* refactor: avoid extraneous declarations in singleton test
* refactor: reintroduce `userDataFolder` declaration in singleton test
* refactor: move cleanup before app exit in singleton test
* style: add missing semicolon
* refactor: set the user data path after pre-test cleanup in singleton test
* fix: release lock before cleanup in singleton test
trap handlers will be initialized once the user script starts
but before app#ready. Wasm compilation before that phase will
break trap handler registeration due to the check in
v8::internal::wasm::UpdateComputedInformation. For some reason
this issue was only visible in <= 39-x-y when pdf-reader.mjs
was being loaded, maybe some module loading logic changed in >= 40-x-y
which are based on Node.js v24.x. In either case, it is best to
align the loading of wasm module required for the tests in light
of changes to how we are registering the trap handlers for the
main process.
* feat: enable innerWidth and innerHeight for window open
* update comment for added special innerWidth and innerHeight
* update 100 min spec requirement handling
* update testing to include getContentSize
* update macOS min requirement handling
* adjust refactored consts
* update const values from nativewindowviews