- extensions.spec.ts: the two 'does not take precedence over Electron
webRequest' tests use an async IIFE inside new Promise(). onBeforeRequest/
onBeforeSendHeaders fires on the navigation itself, so the outer promise
resolves (and the load is cancelled/aborted by teardown) before the IIFE's
awaited loadURL settles; the IIFE then rejects unhandled. .catch() the IIFE.
- api-service-worker-main.spec.ts: loadWorkerScript() wraps wc.loadURL and all
24 call sites are fire-and-forget; wrap the helper's return in
dangerouslyIgnoreWebContentsLoadResult. Also .catch() the once(ipcMain,'ping',
{signal}).then() chain so abortController.abort() in finally doesn't surface
an AbortError.
- serial/chromium-focus-and-clipboard.spec.ts: executeJavaScript returned the
WindowProxy from window.open(), which can't be structured-cloned over IPC;
append '; null' so the result is serializable.
vitest's fork worker patches process.exit to throw. Our worker-entry
uncaughtException handler called process.exit(1), which then threw inside
the handler, so Node exited with code 7 ('exception handler threw') and the
original error was hidden. Scope the handler to bootstrap only and remove it
once workers/forks.js is loaded.
Also fix the crash diagnostic: WorkerRequest carries files at
message.context.files (FileSpecification[]), not message.files.
split-tests now buckets spec/*.spec.ts and spec/serial/*.spec.ts as two
independent sets (each sorted by test count, round-robined) so every shard
gets a proportional slice of both. run.js already routes spec/serial/* to
the --no-file-parallelism phase, so within a shard serial files still run
one-at-a-time. This also fixes the serial phase never running on CI — it
was skipped because split-tests only emitted parallel positionals.
- api-subframe: 'should not crash when changing subframe src' never closed w
- api-view: 'can be added as a child of another View' declared a local const w
shadowing the describe-level one the afterEach closes
- api-web-frame / api-web-utils: defer(() => w.close()) and afterAll win.close()
don't await 'closed', so windows were still in getAllWindows() when the
global leak check fired; use closeWindow() which awaits
ElectronPoolWorker now tracks the last 'files' payload sent to the child and
prints it (with pid, code, signal) if the child exits non-zero outside stop().
closeWindow's assertNotWindows path tried to assert 'this was the only
window' one tick after closing, which only worked if the next-tick fired
after the outer afterEach(closeAllWindows) — a race that mostly held under
mocha and doesn't under vitest.
Replace it with assertNoWindowsLeaked() registered as a setupFiles-level
afterAll — it runs once per file after every test-file afterAll, so suites
that share a window across tests (useRemoteContext, the api-context-bridge
reuse, etc.) aren't flagged on every test. Verified ordering with probe
files: a describe-level afterAll(closeWindow) runs before the global check,
and a file that never cleans up is flagged.
closeWindow is now a plain awaited close; the assertNotWindows option and
its 7 call-site opt-outs are removed. useRemoteContext's afterAll now awaits
'closed' so the shared window is actually gone before the leak check fires.
api-net's shared-utility-process commit changed api-net-spec.js to post a
ready handshake and wait for an explicit shutdown instead of exiting after
each message. This test forks the same fixture and was still assuming the
old one-shot protocol, so it read 'ready' as the result (data.ok undefined).
The assertion passed an async function to .to.not.throw(), which only checks
sync throws, so it was always green and the unawaited body leaked the
'data:text/html,hello there' loadURL rejection as unhandled. Invoke the IIFE
and await expect(p).to.not.be.rejected() instead.
The 'focus handling' describe in chromium.spec.ts (w.focus() + sendInputEvent
TAB cycling) and the three darwin 'emits show and close events' Notification
tests both depend on OS-singleton state (window focus, Notification Center).
macos-arm64 tests run on the 4-vCPU / 7 GB macos-15 runner; three concurrent
Electron main processes (cpus-1 default) plus their GPU/network-service
children exhausted it and several workers missed the 90s start window.
macos-x64 uses macos-15-large (12-vCPU / 30 GB); cap at 6 for headroom.
closeWindow's assertNotWindows path scheduled a detached setTimeout that
asserted BaseWindow.getAllWindows().length === 0; by the time the timer
fired the next test's beforeEach had created windows, so the assertion
rejected unhandled. Now it's an inline awaited check so the failure is
attributed to the right test.
no-unawaited-load flags loadURL()/loadFile() calls whose promise isn't
awaited, returned, assigned, .then/.catch'd, passed as an argument, or
explicitly voided. 393 warnings across spec/ — set to 'warn' for now.
crash.spec spawns child Electrons that defaulted to the shared userData
profile; under parallel workers that contended with other test-spawned
Electrons (autoupdater etc.). Each child now gets a mkdtemp --user-data-dir
that afterEach removes (even on timeout, since the kill+rmSync runs in the
hook).
api-autoupdater-darwin: 'import * as express' under vite SSR gives a
namespace object, so express() fails with '__vite_ssr_import_N__ is not a
function'. Use 'import = require()' for express and psList which are
called directly as functions.
search: passes the path raw and os.tmpdir() may not be the right tmp inside
the CI container; query: {out} URL-encodes properly and userData is the
per-worker mkdtemp we control.
The 'does not crash when closed via window.close()' test (added in #47933)
listens for 'blur' during WebContents destruction; on macOS that Emit runs
a microtask checkpoint after weak_factory_ is already torn down, so any
re-entrant Destroy() -> GetWeakPtr() DCHECKs at base/memory/weak_ptr.h:298.
Skipped with a TODO until the native lifecycle is fixed.
Also rewrites the 'accepts existing webContents object' count assertion to
compare id sets so still-closing contents from prior tests don't skew it.
- api-in-app-purchase: wrap in ifdescribe(darwin) instead of early-return,
which left an empty suite that vitest treats as an error
- api-browser-view: custom afterEach nulls w before defer() callbacks run;
call runCleanupFunctions() first so defer(() => w.removeBrowserView(...))
sees a live window
- api-web-contents-view: afterEach used contents.close() without awaiting
destruction, so the next test's getAllWebContents() count included
still-closing leftovers; use cleanupWebContents() which awaits 'destroyed'
- modules/esm: run the ESM-vs-CJS key comparison in a child Electron (outside
vite's alias) via a .mjs fixture, sort both lists, and filter Node's
CJS-interop 'default'/'module.exports' keys before comparing
makeBindingWindow now lazily creates one window per describe and swaps
preloads via session.registerPreloadScript/unregisterPreloadScript instead
of constructing a fresh BrowserWindow per test. ~21s -> ~9s for 144 tests.
no-locals is stricter than plain @remote: closures may not reference
ANY identifier declared in the file (imports from anywhere, or file-scope
const/let/var/function/class). JS/DOM globals are fine. Applied to
callWithBindings in api-context-bridge.spec.ts, whose closures are
executeJavaScript'd in a page world with no __rt shim and no require.
makeBindingWindow stringifies its bindingCreator closure into a preload
script; under vite the captured 'contextBridge' import becomes
__vite_ssr_import_N__.contextBridge. Tag makeBindingWindow /** @remote */,
run rewriteForRemoteEval on the closure, and declare 'const __rt = renderer_1'
in the preload so __rt.contextBridge resolves.
remote-tools.ts re-exports contextBridge/ipcRenderer/webFrame from
electron/renderer — undefined at runtime in the main process, but typed
correctly for closures that only ever execute in a preload.
callWithBindings closures only reference their 'root' param, so no change
needed there. 144/144 pass.
Lazy-fork once, await a 'ready' handshake, then post each test body to the
same long-lived child. The fixture no longer exits after each message; it
posts {ok:false} on failure and keeps running, and exits cleanly on a
{type:'shutdown'} message sent from afterAll.
Functions declared with a /** @remote */ JSDoc (or const/for-of bindings
so tagged) are treated like itremote/remotely: any closure passed to them
is checked for imports that don't come from ./lib/remote-tools.
api-net.spec.ts's itUtility stringifies its closure and posts it to a
utility-process fixture, so it's the same __vite_ssr_import_ problem.
- itUtility now runs rewriteForRemoteEval(fn) before posting
- the fixture declares a local __rt spreading net-helpers + electron/main
- the for-of loop that aliases itUtility as 'test' is tagged @remote
- remote-tools.ts re-exports net, session, http, defer, and the net-helpers
- api-net.spec.ts imports those via remote-tools (closure bodies unchanged)
api-net: 252 passed / 2 todo.
Both passed without actually waiting for the condition; now that waitUntil
takes ctx.signal they at least stopped on abort, but the assertions were
still never gating the test.
Same ESM-vs-CJS stub issue as release-notes: sinon.stub on
require('node:child_process') doesn't intercept the ESM import that
version-bumper.ts uses under vite. vi.mock('node:child_process', {spy:true})
does. sinon is no longer used anywhere in spec/.
Under vite, notes.ts imports spawnSync via ESM; sinon.stub on the CJS
require() object doesn't intercept that binding. vi.mock('node:child_process',
{spy: true}) replaces the module in vite's graph so vi.mocked(cp.spawnSync)
.mockImplementation() applies to the import notes.ts sees.
close.html and unload.html previously wrote to __dirname + '/close'|'/unload'
inside spec/fixtures/api/ itself. Pass the output path via ?out= query param
and use a pid+timestamp tmp file so parallel workers and retries never race.
16 inner it() calls in api-browser-window.spec.ts were wrapped in an outer
it() or ifit() where the author meant describe()/ifdescribe(). Under mocha
these inner tests were registered as siblings at collection time; under
vitest they throw. Also removes two unused chai imports in api-safe-storage
left over from moving chai.use() to setup.ts.
Mocha silently tolerated it() inside another it()/ifit() body; vitest does
not. The rule tracks test-call nesting depth and flags any inner definition.
Swaps expect/setTimeout/BrowserWindow imports in the 5 files flagged by
remote-tools-imports/no-foreign-imports-in-remote-closure so their
stringified closures resolve via the __rt shim. Import-line changes only.
remote-tools-imports/no-foreign-imports-in-remote-closure flags any
identifier inside an itremote()/remotely() closure that is bound to an
import from somewhere other than spec/lib/remote-tools. Those bindings
get rewritten to __vite_ssr_import_N__ by vite's SSR transform and fail
when the closure is stringified and eval'd in a remote context.
Skips type-only imports and type-annotation positions. Currently flags
50 sites across 5 files (node, webview, chromium, fuses, api-native-image).
vite's SSR transform rewrites import bindings to __vite_ssr_import_N__,
which breaks closures that are stringified and eval'd in a remote context.
remote-tools.ts re-exports the common modules (path, fs, url, expect, ...)
so spec files can 'import { path, expect } from ./lib/remote-tools' and
closure bodies stay unchanged. runRemote/remotely regex-replace every
__vite_ssr_import_N__ with __rt (a renderer-side object whose keys mirror
the remote-tools export names), so __rt.path.join(...) etc. resolve with
no property-name ambiguity.
asar.spec.ts: 170 failing itremote tests -> 0, import-line changes only.
vitest's onTestFinished runs *after* afterEach (contrary to the earlier
assumption), so defer() callbacks saw windows already destroyed by
afterEach(closeAllWindows). And runCleanupFunctions didn't clear its
queue on throw, so one bad defer cascaded into every subsequent test.
- runCleanupFunctions now splices the queue before iterating and wraps
each cleanup in try/catch, aggregating errors.
- closeAllWindows runs runCleanupFunctions() first, so the 190+ existing
afterEach(closeAllWindows) call sites get mocha's ordering (defers run,
then windows close) without modification. setup.ts's onTestFinished
remains as a fallback for tests that defer() without closeAllWindows.
- cleanupWebContents guards against already-destroyed contents.
vitest passes a context object as the first arg to hook callbacks, so
afterEach(closeAllWindows) effectively called closeAllWindows(ctx) - a
truthy value that triggered the unused assert-no-windows-remain path,
producing unhandled rejections. afterAll(closeAllWindows) failed outright
with a FixtureParseError because vitest parses the param list.
No caller ever passed the argument explicitly, so the param is removed.
Await each CDP step in sequence and use Runtime.evaluate on the attached
session after Debugger.enable is acknowledged, so Debugger.scriptParsed is
guaranteed to fire regardless of page-load timing. 0/10 flakes (was ~3/5).
The closure at spec/api-app.spec.ts:2282 is stringified and eval'd inside
a utility-process fixture. Under vite's SSR transform the captured import
bindings become __vite_ssr_import_N__ refs that don't exist in the fixture.
Inline require() calls survive toString() intact.
- spec/_vitest_runner/package.json: name/productName match spec/package.json
so app.name assertions hold
- worker-entry: userData is <mkdtemp>/<app.name>/ so getPath('userData')
still includes the app name
- net-helpers: import defer from defer-helpers and own listen() directly,
so the utility-process fixture (which ts-node-requires net-helpers) no
longer pulls in spec-helpers -> vitest
vite's resolve.alias in object form matched the bare 'electron' specifier
but not 'electron/main' etc. The array-with-regex form matches all four.
Also extract defer/runCleanupFunctions into spec/lib/defer-helpers.ts so
setup.ts doesn't transitively import 'electron/main' (setupFiles go
through a slightly different SSR load path than test files).
- refresh-page fixture served mocha.js as a 'large JS file' over a custom
protocol; point it at chai.js instead since mocha is no longer a dep
- drop descriptive 'mocha' mentions from comments
This was a win-arm64 workaround for the mocha runner: process.exit() could
hang in the single Electron process, so the suite SIGTERMed itself after
printing the failure count to stdout for script/spec-runner.js to scrape.
Under vitest, the process that decides and reports the exit code is the
plain-Node vitest CLI; Electron instances are pool workers that the pool
tears down. The workaround no longer applies.
- allowOnly: !CI matches mocha's forbidOnly
- retry: 3 on CI matches mocha's CI retries
- runCleanupFunctions via ctx.onTestFinished so defer()-ed cleanups run
before test-file afterEach hooks, matching the per-suite hook ordering
in spec/index.js
Adds spec/_vitest_runner/, a custom vitest pool that spawns each worker
as a full Electron main process (not a node-mode fork) so tests can use
real Electron APIs. Each worker gets a pool-owned mkdtemp userData dir
that is cleaned up on worker stop. File-level parallelism is enabled;
intra-file concurrency stays off to match current mocha behaviour.
Run with: yarn test:vitest
fix: simpleFullScreen exits when web content calls requestFullscreen
SetHtmlApiFullscreen only checked IsFullscreen() to detect that the
window was already fullscreen, missing the simple-fullscreen case on
macOS. When web content triggered requestFullscreen the code fell
through to SetFullScreen(true) which toggled simple fullscreen off.
Include IsSimpleFullScreen() in the guard so the HTML-API fullscreen
state is updated without touching the window's fullscreen mode.
* 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.
Adds a new skill mirroring the Chromium upgrade skill, adapted for
Node.js rolls. Covers patch conflict resolution, build fix workflow,
commit guidelines, and documents high-churn patches and major version
upgrade patterns (V8 bridge patch deletions, BoringSSL complexity).
* chore: use emplace and use it correctly
* chore: redundant cast to the same type [google-readability-casting]
* chore: do not create objects with +new [google-objc-avoid-nsobject-new]
* chore: default arguments on virtual or override methods are prohibited [google-default-arguments]
* chore: warning: C-style casts are discouraged; use static_cast [google-readability-casting]
CFLocaleGetValue already returns CFTypeRef so that redundant static_cast was removed
* chore: refactor block to avoid use after move warning from clang-tidy
Looks like clang-tidy couldn't tell these were two mutually exclusive
branches so there was no actual issue, but refactoring is cleaner
anyway since it makes it more DRY.
* chore: C-style casts are discouraged; use static_cast [google-readability-casting]
No cast needed here, everything is already the correct type
* chore: C-style casts are discouraged; use static_cast/const_cast/reinterpret_cast [google-readability-casting]
* chore: use '= default' to define a trivial destructor [modernize-use-equals-default]
* chore: use range-based for loop instead [modernize-loop-convert]
* chore: redundant void argument list [modernize-redundant-void-arg]
* chore: address code review feedback
* chore: use auto
Co-authored-by: Charles Kerr <charles@charleskerr.com>
---------
Co-authored-by: Charles Kerr <charles@charleskerr.com>
* 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>
chore: address blink gc plugin errors
Key fixes:
- Replace `base::WeakPtrFactory` with `gin::WeakCellFactory` in
MenuMac, MenuViews, and NetLog, since weak pointers to cppgc-managed
objects must go through weak cells
- Replace `v8::Global<v8::Value>` with `cppgc::Persistent<Menu>` for
the menu reference in BaseWindow
- Stop using `gin_helper::Handle<T>` with cppgc types; use raw `T*`
and add a `static_assert` to prevent future misuse
- Add proper `Trace()` overrides for Menu, MenuMac, MenuViews, and
NetLog to ensure cppgc members are visited during garbage collection
- Replace `SelfKeepAlive` prevent-GC mechanism in Menu with a
`cppgc::Persistent` prevent-GC captured in `BindSelfToClosure`
- Introduce `GC_PLUGIN_IGNORE` macro to suppress
known-safe violations: mojo::Remote fields, ObjC bridging pointers,
and intentional persistent self-references
- Mark `ArgumentHolder` as `CPPGC_STACK_ALLOCATED()` in both Electron's
and gin's function_template.h to silence raw-pointer-to-GC-type
warnings
* feat: allow to set id and groupId
* feat: use Id's without hash but check length
* feat: adds visual grouping via groupTitle
* test: tests added for id, groupId and groupTitle
* fix: unused vars on Mac and Linux
* fix: remove redundant parameter
* fix: add doc links for id and group
* fix: throw if groupId is missing
* fix: test
fix: guard permission handlers in File System API tests
Manual port of #50865 for `main` due to code shear.
1. Chromium can fire unrelated permission checks (e.g. 'background-sync')
on the default session. Copy a safeguard `permission === 'fileSystem'` from
"calls twice when trying to query a read/write file handle permissions".
2. add afterEach cleanup, reset setPermissionCheckHandler(null).
fix: return numeric `blksize` and `blocks` from asar `fs.stat`
Previously, `fs.stat` on files inside `.asar` archives returned
`undefined` for `blksize` and `blocks`, violating the Node.js API
contract where these fields must be `number | bigint`.
Use `4096` for `blksize` (matching the convention used by `memfs` and
the proposed `node:vfs` module in nodejs/node#61478) and compute
`blocks` as `ceil(size / 512)` (standard 512-byte block units).
Fixes#42686
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
fix: pass root_gen_dir from GN to generate_node_headers.py
PR #50828 replaced a local get_out_dir() (defaulting to 'Testing') with
the shared one from script/lib/util.py (defaulting to 'Default').
Neither default is correct because the actual output directory depends
on the active build config. Pass $root_gen_dir from the GN action so
the script always uses the correct path.
* fix: remove Electron links from default help menu
* fix: remove help menu entirely from default menu
* fix: move Electron help menu links to default app
* docs: update default menu items list in menu.md
fix: webContents.print() ignoring mediaSize when silent
PR #49523 moved the default media size fallback into OnGetDeviceNameToUse,
but the new code unconditionally writes kSettingMediaSize — clobbering
any mediaSize the caller had already set in WebContents::Print() from
options.mediaSize / pageSize. As a result, silent prints with an
explicit pageSize (e.g. "Letter") fell back to A4 with tiny content.
Only populate the default/printer media size when the caller hasn't
already supplied one, preserving the precedence:
1. user-supplied mediaSize / pageSize
2. printer default (when usePrinterDefaultPageSize is true)
3. A4 fallback
fix: avoid crash in window.print() when prefilling native print dialog
When UpdatePrinterSettings() fails (e.g. the printer rejects the
requested resolution), OnError() nullifies print_info_ via
ReleaseContext(). The return value was not checked, so
AskUserForSettings() passed nil to [NSPrintPanel runModalWithPrintInfo:],
crashing in PJCSessionHasApplicationSetPrinter with a null PMPrintSession.
Check the return value and fall back to UseDefaultSettings() on failure
so the dialog opens with defaults instead of crashing.
The needs-signed-commits label was previously added by the lightweight
synchronize workflow but only removed by a job in build.yml gated on
`gha-done`, which requires every macOS/Linux/Windows build to finish
green. That made label removal both slow (waits on the full pipeline)
and fragile (any unrelated build failure leaves the label pinned even
after commits are properly signed).
Drop the `if` guard on the synchronize job so it re-evaluates signing
on every push, and add a removal step that runs on success when the
label is present. Force-pushing signed commits now clears the label as
soon as the check completes, with no dependency on the build pipeline.
* fix: use proper OOPIF PDF check in `StreamsPrivateAPI`
* fix: add `ShouldEnableSubframeZoom` override to `ElectronBrowserClient` for upstream parity
* fix: add `MaybeOverrideLocalURLCrossOriginEmbedderPolicy` override to `ElectronBrowserClient` for upstream parity
* fix: add `DoesSiteRequireDedicatedProcess` override to `ElectronBrowserClient` for upstream parity
* style: move `DoesSiteRequireDedicatedProcess` to correct override section
* chore: remove window enlargement revert patch
Chromium removed the `window_enlargement_` system from
DesktopWindowTreeHostWin (1771dbae), which was a workaround for an AMD
driver bug from 2013 (crbug.com/286609) where translucent HWNDs smaller
than 64x64 caused graphical glitches. Chromium confirmed this is no
longer needed and shipped the removal.
This removes the revert patch and all Electron-side code that depended
on the `kEnableTransparentHwndEnlargement` feature flag, including the
`GetExpandedWindowSize` helper and max size constraint expansion in
`NativeWindow::GetContentMaximumSize`.
* test: remove obsolete <64x64 transparent window test
The test was added in 2018 (#12904) to verify the AMD driver
workaround that artificially enlarged translucent HWNDs smaller than
64x64 (crbug.com/286609). The workaround set the real HWND to 64x64
and subtracted a stored window_enlargement_ from every client/window
bounds query, so getContentSize() reported the originally-requested
size even though the actual HWND was larger.
With both the Chromium window_enlargement_ system and Electron's
GetExpandedWindowSize gone, setContentSize on a transparent
thickFrame window calls SetWindowPos directly. WS_THICKFRAME windows
are subject to DefWindowProc's MINMAXINFO.ptMinTrackSize clamp on
programmatic resizes (Chromium's OnGetMinMaxInfo ends with
SetMsgHandled(FALSE), so DefWindowProc overwrites the zeroed
min-track with system defaults), which on Windows Server 2025
floors at 32x39 — hence the failing [32, 39] vs [30, 30].
The removed feature_list.cc comment explicitly flagged this test as
the blocker for retiring kEnableTransparentHwndEnlargement, so
delete it alongside the workaround it was validating.
#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
The local get_out_dir() defaulted to 'Testing' instead of 'Default',
causing e test to fail when using a non-Testing build config. Replace
it with the canonical version from script/lib/util.py.
Menu was holding a SelfKeepAlive to itself from construction, so any
Menu that was never opened (e.g. an application menu replaced before
being shown) stayed pinned in cppgc forever. Repeated calls to
Menu.setApplicationMenu leaked every prior Menu along with its model
and items.
Restore the original Pin/Unpin lifecycle: start keep_alive_ empty and
only assign `this` in OnMenuWillShow. OnMenuWillClose already clears
it.
* chore: testing of desktopCapturer can run on arm
* fix: DesktopMediaListCaptureThread crash
Fixed a crash when Windows calls ::CoCreateInstance() in the
DesktopMediaListCaptureThread before COM is initialized.
* test: added test for desktopCapturer fetchWindowIcons
* chore: updating Chromium patch hash
---------
Co-authored-by: Charles Kerr <charles@charleskerr.com>
PR #50646 added a dock state allowlist in SetDockState() that collapsed any
non-matching value to "right". WebContents::OpenDevTools passes an empty
string when no `mode` option is given, which is the sentinel LoadCompleted()
uses to restore `currentDockState` from prefs. The allowlist clobbered that
sentinel to "right", so previously-undocked devtools would flash detached
and then snap back to the right dock.
Preserve the empty string through SetDockState() so the pref-restore path
runs; still reject any non-empty invalid value to keep the JS-injection
guard from #50646 intact.
* chore: iwyu in shell/browser/api/electron_api_web_contents.h
* chore: iwyu in shell/browser/browser.h
* chore: iwyu in shell/browser/javascript_environment.h
* chore: iwyu in shell/common/gin_hhelper/function_template.h
* chore: do not include node_includes.h if we are not using it
* chore: fix transitive include
chore: remove unused FileSystemAccessPermissionContext::Access enum class
chore: remove unused FileSystemAccessPermissionContext::RequestType enum class
declared in 344aba08 but never used
Adds the ability to temporarily suspend and resume global shortcut
handling via `globalShortcut.setSuspended()` and query the current
state via `globalShortcut.isSuspended()`. When suspended, registered
shortcuts stop listening and new registrations are rejected. When
resumed, previously registered shortcuts are automatically restored.
* chore: do not expose menu.isItemCheckedAt() to JS
Not used, documented, or typed. Added in dae98fa43f.
* chore: do not expose menu.isEnabledAt() to JS
Nto used, documented, or typed. Added in dae98fa43f.
* chore: do not expose menu.isVisibleAt() to JS
Not used, documented, or typed. Added in dae98fa43f.
* chore: remove unused undocumented API `getOjectHash`
Not used, documented, or typed. Added in ddad3e4846.
Appears to never have been used.
* chore: bump chromium in DEPS to 148.0.7765.0
* chore: bump chromium in DEPS to 148.0.7766.0
* fix(patch-conflict): update packed_resources dep name after upstream rename
Upstream renamed //chrome:packed_resources_integrity_header to
//chrome:packed_resources. Updated the patch to guard the new dependency
name with !is_electron_build while preserving the same intent.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7714543
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(patch-conflict): update code_cache_host_impl.cc for upstream includes and TODO
Upstream added #include <stdint.h> and a TODO comment in
code_cache_host_impl.cc which conflicted with the Electron code cache
custom schemes patch. Resolved by keeping both upstream additions and
the Electron ProcessLockURLIsCodeCacheScheme function.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7615151
Co-Authored-By: Claude <noreply@anthropic.com>
* chore: update patch hunk headers
Co-Authored-By: Claude <noreply@anthropic.com>
* 7700837: update RecordContentToVisibleTimeRequest from mojom to native struct
Upstream typemapped RecordContentToVisibleTimeRequest from a Mojo
struct to a native C++ struct. Updated OSR virtual method signatures
from blink::mojom::RecordContentToVisibleTimeRequestPtr to
std::optional<blink::RecordContentToVisibleTimeRequest> and
blink::RecordContentToVisibleTimeRequest to match.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7700837
Co-Authored-By: Claude <noreply@anthropic.com>
* 7714579: update WebString::FromASCII to FromUTF8
Upstream renamed blink::WebString::FromASCII to FromAscii. Updated
Electron's usage to FromUTF8 which is equivalent for ASCII scheme
strings and avoids a dependency on the renamed method. Also fixed
blink::String::FromUTF8 to use the String constructor directly.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7714579
Co-Authored-By: Claude <noreply@anthropic.com>
* 7696480: add stream_info dep after StreamInfo extraction
Upstream extracted extensions::StreamInfo from PdfViewerStreamManager
to a standalone class in extensions/browser/mime_handler/stream_info.h.
Added the new target as a dependency since Electron's streams_private
and pdf_viewer_private APIs use PdfViewerStreamManager which now
depends on the separate StreamInfo target.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7696480
Co-Authored-By: Claude <noreply@anthropic.com>
* chore: bump chromium in DEPS to 148.0.7768.0
* fix(patch-conflict): update PiP patch for new toggle_mute_button in overlay window
Upstream added a toggle_mute_button to the live caption dialog controls
in VideoOverlayWindowViews::SetLiveCaptionDialogVisibility. Extended the
existing #if 0 guard to include the new button handling since Electron
disables live caption dialog functionality.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7682308
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(patch-conflict): update packed_resource_integrity patch after upstream dep removal
Upstream removed the deps += [ "//chrome:packed_resources" ] line from
the if (!is_win) block in chrome/browser/BUILD.gn. The Electron patch
no longer needs to guard this dep with !is_electron_build in this
location since the dep was already relocated by an earlier upstream CL.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7714543
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(patch-conflict): update WebSocket throttling revert for DisconnectWebSocketOnBFCache guard
Upstream added a DisconnectWebSocketOnBFCacheEnabled() runtime feature
check that wraps the WebSocket BFCache feature registration. Updated the
Electron revert patch to place the kAllowAggressiveThrottlingWithWebSocket
ternary inside the new conditional guard.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7698838
Co-Authored-By: Claude <noreply@anthropic.com>
* fix(patch-conflict): update SCContentSharingPicker patch for upstream native picker refactor
Upstream added is_native_picker and filter_ based native picker session
validation to ScreenCaptureKitDeviceMac. Electron's patch uses its own
native picker approach (active_streams_ counter + direct SCContentSharingPicker
API), so marked the new upstream parameters as [[maybe_unused]] and kept
Electron's implementation.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7713560
Co-Authored-By: Claude <noreply@anthropic.com>
* chore: update patch hunk headers
Co-Authored-By: Claude <noreply@anthropic.com>
* 7708800: update StartDragging signature to use RenderFrameHost
Upstream refactored StartDragging to take a RenderFrameHost& instead of
separate source_origin and source_rwh parameters. Updated
OffScreenWebContentsView to match the new signature and derive the
RenderWidgetHostImpl from the RenderFrameHost internally.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7708800
Co-Authored-By: Claude <noreply@anthropic.com>
* 7682308: add toggle_mute_button to chromium_src build sources
Upstream added a ToggleMuteButton to the PiP overlay window controls.
Added the new toggle_mute_button.cc/h source files to Electron's
chromium_src/BUILD.gn to resolve linker errors.
Ref: https://chromium-review.googlesource.com/c/chromium/src/+/7682308
Co-Authored-By: Claude <noreply@anthropic.com>
* chore: update patches after main rebase
* fixup! 7708800: update StartDragging signature to use RenderFrameHost
fix linting
* 7705541: [trap-handler] Track individual Wasm memories | https://chromium-review.googlesource.com/c/v8/v8/+/7705541
Moved the SetUpWebAssemblyTrapHandler() call to before the V8 isolate is created
* fixup! fix utility process tests
---------
Co-authored-by: electron-roller[bot] <84116207+electron-roller[bot]@users.noreply.github.com>
Co-authored-by: Keeley Hammond <khammond@slack-corp.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Keeley Hammond <vertedinde@electronjs.org>
Resolve the Squirrel.Mac target bundle URL to a canonical path once at the
top of -[SQRLInstaller installRequest:] and use it for every step of the
install chain, rejecting requests whose path is not already canonical. When
running with elevated privileges, additionally require the target to be the
application bundle that contains the installer. SQRLUpdater now writes the
resolved bundle URL so the serialized request is canonical by construction.
* ci: use hermetic mac SDK for the release ffmpeg build
gn gen out/ffmpeg runs as a raw gn invocation, so it never receives the
mac_sdk_path arg that e build injects for out/Default. On macOS runners
that means out/Default builds against the hermetic build-tools SDK while
out/ffmpeg falls through to the runner's system Xcode SDK. Reuse the
value e build already wrote so both builds share the same sysroot.
* ci: copy hermetic SDK symlink into out/ffmpeg and rewrite path
mac_sdk_path must live under root_build_dir, so pointing out/ffmpeg at
//out/Default/... doesn't work. Copy the xcode_links symlink tree into
out/ffmpeg and rewrite the path. Gate on Darwin so Windows/Linux don't
run the sed/cp at all.
ci: make src-cache upload atomic and sweep orphaned temp files
The checkout action's cp of the ~6GB zstd archive directly to the final
path on the cache share is non-atomic; an interrupted copy or a
concurrent reader produces zstd "Read error (39): premature end" on
restore, and the truncated file then satisfies the existence check so
no later run repairs it.
Upload to a run-unique *.tar.upload-<run_id>-<attempt> temp name on the
share and mv to the final path, discarding our temp if a concurrent run
got there first. A new clean-orphaned-cache-uploads workflow removes
temp files older than 4h every 4 hours.
* build: derive patches upstream-head ref from script path
gclient-new-workdir.py symlinks each repo's .git/refs back to the source
checkout, so the fixed refs/patches/upstream-head was shared across all
worktrees. Parallel `e sync` runs in different worktrees clobbered each
other's upstream-head, breaking `e patches` and check-patch-diff.
Suffix the ref with an md5 of the script directory so each worktree writes
a distinct ref into the shared refs dir. Fall back to the legacy ref name
in guess_base_commit so existing checkouts keep working until next sync.
* fixup: also write legacy upstream-head ref and note it in docs
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.
fix-sync re-downloads llvm-build on macOS/Windows with the base clang
and objdump packages, but not clang-tidy. A local gclient sync pulls
clang-tidy (checkout_clang_tidy=True in DEPS), so CI's llvm-build tree
diverges from a local one. siso hashes the toolchain as action input,
so cache-only local runs against the CI-populated RBE cache miss.
* ci: shrink src cache and fix Windows tar cleanup
- Exclude platform-specific toolchains (llvm-build, rust-toolchain) from
the src cache; all platforms now fetch them via fix-sync post-restore
- Exclude unused test data and benchmarks: blink/web_tests, jetstream,
speedometer, catapult/tracing/test_data, swiftshader/tests/regres
- Fix Windows restore leaving the tarball on disk after extraction
($src_cache was scoped to the previous PowerShell step)
- Bump src-cache key v1 -> v2
* ci: fetch llvm/rust toolchains in gn-check and clang-tidy
These workflows restore the src cache but don't run fix-sync. Now that
llvm-build and rust-toolchain are excluded from the cache, they need to
download them directly — gn gen read_file()s both, and clang-tidy runs
the binary from llvm-build.
* ci: fetch clang-tidy package explicitly
update.py's default 'clang' package doesn't include the clang-tidy
binary; it ships as a separate package.
* ci: preserve blink/web_tests/BUILD.gn when stripping test data
//BUILD.gn references //third_party/blink/web_tests:wpt_tests as a
target label, so the BUILD.gn must exist for gn gen. The data = [...]
entries it declares are runtime-only and not existence-checked at gen
time, so the actual test directories can still be removed.
* ci: compress src cache with zstd and drop gclient sync -vv
The src cache was an uncompressed tar (~16GB after exclusions). Switch
to zstd -T0 --long=30 for ~4x smaller transfer and multi-threaded
compression. Decompress on restore:
- Linux/macOS: zstd -d -c | tar -xf -
- Windows: zstd -d to an intermediate .tar, then the existing 7z
-snld20 extraction (preserves symlink handling)
All filename references updated .tar -> .tar.zst. -f added to the two
-o invocations so re-runs overwrite instead of failing.
Also drop -vv from gclient sync; default verbosity is sufficient.
* ci: keep .tar extension for src cache (zstd content inside)
The sas-sidecar that issues Azure SAS tokens validates filenames against
/^v[0-9]+-[a-z\-]+-[a-f0-9]+\.(tar|tgz)$/ and is not easily redeployed,
so keep the .tar extension and decode zstd on restore. Windows
decompresses to a distinct intermediate (src_cache.tar) so input and
output don't collide.
* ci: log NTFS 8.3/lastaccess/Defender state before Windows cache extract
Temporary diagnostics to see whether 8.3 short-name generation is the
cause of the ~20 min tar extraction.
* ci: revert src-cache exclusion additions
The new exclusions (web_tests contents, jetstream, speedometer,
catapult test_data, regres, llvm-build, rust-toolchain) caused siso/RBE
cache misses — even data-only deps are part of action input hashes.
Revert to the original exclusion list and drop the corresponding
toolchain-fetch plumbing. zstd compression, the Windows tar cleanup,
and the -vv removal remain.
* ci: drop win_toolchain from src cache; remove NTFS diagnostics
The Windows src cache includes 14.6GB of depot_tools/win_toolchain —
7.3GB of MSVC/SDK doubled because tar captures both the vs_files.ciopfs
backing store and the live ciopfs mount at vs_files/. Every Windows
cache consumer already re-fetches this via vs_toolchain.py update
--force (fix-sync for build/publish, inline for gn-check/clang-tidy),
so the cached copy is never used.
Diagnostics removed — CI confirmed 8dot3, last-access, and Defender are
all already off on the AKS Windows nodes.
* ci: unmount ciopfs vs_files before removing win_toolchain
vs_files is a live ciopfs mount during the win-targeted checkout; rm -rf
fails with EBUSY until it's unmounted.
* ci: skip win_toolchain download during checkout instead of removing after
fusermount isn't on the checkout container, so the ciopfs mount can't be
torn down before rm. Setting DEPOT_TOOLS_WIN_TOOLCHAIN=0 makes the
win_toolchain hook a no-op (vs_toolchain.py:525-527), so there's no
download and no mount. All Windows consumers re-fetch it post-restore
anyway. The rm -rf stays as a safety net.
* ci: also set ELECTRON_DEPOT_TOOLS_WIN_TOOLCHAIN=0 for checkout sync
build.yml sets ELECTRON_DEPOT_TOOLS_WIN_TOOLCHAIN=1 at the job level for
the Windows checkout, which makes e d inject DEPOT_TOOLS_WIN_TOOLCHAIN=1
and override the inline =0. Need both: the ELECTRON_ var stops e d from
overriding, the plain one stops vs_toolchain.py from defaulting to 1.
* ci: extract Windows src cache with piped tar instead of 7z
7z takes ~20 min to extract the ~1.1M-entry tar regardless of size —
~1ms per entry of header parsing and path handling, single-threaded,
well under the 75k IOPS / 1000 MBps the ephemeral disk can do. Switch
to the same zstd -d | tar -xf - pipe used on Linux/macOS (via Git Bash
tar). No intermediate src_cache.tar, download deleted after extract.
The -snld20 flag was working around 7z's own "dangerous symlink"
refusal; GNU tar extracts symlinks as-is so it shouldn't be needed.
* ci: keep depot_tools/win_toolchain scripts in src cache
The rm -rf removed get_toolchain_if_necessary.py (a depot_tools source
file), breaking vs_toolchain.py update --force on restore.
DEPOT_TOOLS_WIN_TOOLCHAIN=0 on the sync already prevents the vs_files
download, so the rm was only removing scripts.
* ci: split src cache into 4 parallel-extractable shards
Windows tar extraction is ~1ms/entry for ~1.2M entries (~20 min)
regardless of tool, well under the 75k IOPS / 1000 MBps the D16lds_v5
ephemeral disk can do. Tar is a sequential stream so the only way to
parallelize is to split at creation time.
Shards (balanced by entry count, ~220-360k each):
a: src/third_party/blink
b: src/third_party/{dawn,electron_node,tflite,devtools-frontend}
c: src/third_party (rest)
d: src (excluding third_party)
DEPSHASH is now the raw hash; shard files are
v2-src-cache-shard-{a..d}-${DEPSHASH}.tar (all pass the sas-sidecar
filename regex). sas-token is now a JSON keyed by shard letter. All
restore paths extract the four shards in parallel with per-PID wait so
a failed shard aborts the step.
* Revert "ci: split src cache into 4 parallel-extractable shards"
This reverts commit 970574998b.
This removes two `raw_ptr<context::StoragePartition>` instances.
These pointers were used to build a ServiceWorkerMain* lookup key.
The key was built from [version_id, raw_ptr<StoragePartition>].
Unfortunately these keys could be dangling on shutdown.
This PR now uses stable, immutable fields for building the key:
[version_id, BrowserContext::UniqueId(), context::StoragePartitionConfig].
context::StoragePartitionConfig is a unique lookup key for StoragePartition
within a BrowserContext.
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.
WebContentsPermissionHelper::CheckPermission was hardcoding
GetPrimaryMainFrame() and deriving the requesting origin from
web_contents_->GetLastCommittedURL(), so the setPermissionCheckHandler
callback always received the top frame's origin and
details.isMainFrame/details.requestingUrl always reflected the main
frame, even when a cross-origin subframe with allow="serial" or
allow="camera; microphone" triggered the check.
Thread the requesting RenderFrameHost through CheckPermission,
CheckSerialAccessPermission, and CheckMediaAccessPermission so the
permission manager receives the real requesting frame. Update the
serial delegate and WebContents::CheckMediaAccessPermission callers to
pass the frame they already have.
Adds a regression test that loads a cross-origin iframe with
allow="camera; microphone", calls enumerateDevices() from within the
iframe, and asserts the permission check handler receives the iframe
origin for requestingOrigin, isMainFrame, and requestingUrl.
* ci: add Datadog metrics to clean-src-cache job
Report free space (before/after cleanup), space freed, and total space
for both cross-instance-cache and win-cache volumes to Datadog, matching
the pattern used in the macOS disk cleanup workflow.
https://claude.ai/code/session_013bpDsZLrFDpWMiARNFH4z9
* ci: use awk instead of bc, add workflow_dispatch trigger
- Replace bc with awk for KB-to-GB conversion since bc may not be
available in the container image
- Add workflow_dispatch trigger for manual testing
https://claude.ai/code/session_013bpDsZLrFDpWMiARNFH4z9
* ci: remove workflow_dispatch, handled in another PR
https://claude.ai/code/session_013bpDsZLrFDpWMiARNFH4z9
* ci: move DD_API_KEY to job-level env for if-condition
The step-level env is not available when GitHub evaluates the step's
if expression, so env.DD_API_KEY was always empty. Move it to
job-level env so the conditional works correctly.
https://claude.ai/code/session_013bpDsZLrFDpWMiARNFH4z9
---------
Co-authored-by: Claude <noreply@anthropic.com>
* refactor: replace deprecated API base::GetProcId() in web_frame_main
* refactor: replace deprecated API base::GetProcId() in web_contents
* refactor: replace deprecated API base::GetProcId() in a11y ui
* refactor: frame.osProcessId now returns 0 instead of -1 for invalid processes.
This is consistent with WebContents.getOSProcessId
* chore: do not expose v8Util.getObjectHash() to JS
Not used, documented, or typed. Added in ddad3e4846.
* chore: do not expose DownloadItem.isDone() to JS
Not used, documented, or typed. Added in dcad25c98c.
* chore: do not expose BrowserWindow.isWebViewFocused() to JS
Not used, documented, or typed. Added in a949e9542d.
Previously, concurrent calls to FileSystemAccessPermissionContext::ConfirmSensitiveEntryAccess
for the same file path would silently discard the subsequent callbacks because
the internal callback map used a single callback per file path and std::map::try_emplace
would drop the callback if the key already existed. This caused Promises in JS
(e.g., dirHandle.getFileHandle()) to stall indefinitely.
This commit updates the callback map to hold a vector of callbacks, so all
concurrent requesters for the same filepath are grouped together and resolved
once the asynchronous blocklist check completes.
Notes: Fixed an issue where concurrent `getFileHandle` requests on the same path could stall indefinitely.
* feat: forward activation token from libnotify notification clicks
When a notification action is clicked on Linux, retrieve the activation
token from libnotify (if available) via dlsym and set it using
`base::nix::SetActivationToken()`. This enables proper window focus
handling under Wayland, where the compositor requires a valid activation
token to grant focus to the application.
The `notify_notification_get_activation_token` symbol is resolved at
runtime to maintain compatibility with older libnotify versions that
do not expose this API.
* refactor: simplify libnotify soname loading and activation token lookup
Replace the chained Load() calls with a loop over a constexpr array of
sonames, and inline the lazy EnsureActivationTokenFunc() into
Initialize() since it is only called once and the library handle is
already known at that point.
fix: validate dock_state_ against allowlist before JS execution
The dock_state_ member was concatenated directly into a JavaScript
string and executed via ExecuteJavaScript() in the DevTools context.
We should validate against the four known dock states and fall back
to "right" for any unrecognized value for safety
* chore: remove unused undocumented API `menu.worksWhenHiddenAt()`.
Not used, documented, or typed. Added by 544d8a423c.
* chore: remove unused undocumented API `menu.getCommandIdAt()
Not used, documented, or typed. Added by dae98fa43f.
* chore: do not expose `menu.getIndexOfCommandId()` to JS
Added by dae98fa43f but not documented, typed, or used by JS code.
The C++ method is used by other shell code, but not in JS.
* chore: remove unused undocumented API `menu.getLabelAt()`
Not used, documented, or typed. Added by dae98fa43f.
* chore: remove unused undocumented API `menu.getToolTipAt()`
Not used, documented, or typed. Added by 06d48514c6.
* chore: remove unused undocumented API `menu.getSubLabelAt()`
Not used, documented, or typed. Added by dae98fa43f.
When silent printing with non-default margins (custom, no margins, or
printable area margins), the kFitToPrintableArea scaling option causes
double-marginalization: the custom margins define the content area, then
the scaling additionally fits content to the printer's printable area.
Only apply kFitToPrintableArea when using default margins in silent mode.
For non-default margins, use the same scaling as non-silent prints.
Chromium enabled out-of-process (OOP) printing by default on macOS in
https://chromium-review.googlesource.com/c/chromium/src/+/6032774. This
broke webContents.print() option prefilling (e.g. copies, collate,
duplex) in two ways:
1. ScriptedPrint() silently aborted because RegisterSystemPrintClient()
was only called from GetDefaultPrintSettings(), but Electron's flow
calls UpdatePrintSettings() instead when options are provided.
2. PrinterQueryOop::UpdatePrintSettings() sends settings to the remote
PrintBackend service, but on macOS the native dialog runs in-browser
using the local PrintingContextMac::print_info_, which was never
updated with the user's requested settings.
Fix by registering the system print client in UpdatePrintSettings() and
applying cached settings to the local printing context before showing
the in-browser system print dialog.
refactor: remove unused internal method contents.canGoToIndex()
refactor: make WebContents::CanGoToIndex() private
The JS binding has been unused since 2021-04-27 #288390a1b26b1
Native addons that hold persistent references to callbacks, emitters,
and threadsafe functions prevent Electron from quitting cleanly since
Electron 40.5.0 due to changes in Node.js shutdown behavior. This adds
a `destroy()` method to all four native code tutorials (Swift macOS,
Obj-C macOS, C++ Linux, C++ Win32) that releases these resources and
must be called before app quit.
The destroy method resets callback and emitter references and aborts the
threadsafe function, allowing the addon's destructor to run properly.
An [!IMPORTANT] note is added to each tutorial's JavaScript wrapper
section explaining when and why to call destroy().
Fixes#50457
Signed-off-by: Asish Kumar <officialasishkumar@gmail.com>
Fixes#45414
Storing files directly in the userData root can cause naming conflicts
with Chromium's own subdirectories (Cache, GPUCache, Local Storage, etc.).
Added a recommendation to use a subdirectory such as
path.join(app.getPath('userData'), 'my-app-data') instead.
Notes: no-notes
* build: replace npx with lockfile-pinned binaries
- nan-spec-runner: reorder yarn install first, invoke nan node-gyp bin directly
- publish-to-npm: use host npm with E404 try/catch (closes existing TODO)
- upload-symbols: add @sentry/cli devDep, invoke from node_modules/.bin
- remove script/lib/npx.py (dead since #48243)
* build: bump @sentry/cli to 1.70.0 for arm support
* build: bump @sentry/cli to 1.72.0, skip CDN download on test jobs
@sentry/cli fetches its platform binary from Sentry CDN at postinstall.
Only upload-symbols.py (release pipeline) needs the binary; set
SENTRYCLI_SKIP_DOWNLOAD=1 in the two test-segment workflows that
call install-dependencies. The 64k variant uses pre-built artifacts
and does not install deps.
ShowInvalidPrinterSettingsError() called TerminatePrintJob(true),
but when no print_job_ had been created yet (e.g. settings validation
failed before a job could start), TerminatePrintJob bails out
immediately without reaching ReleasePrintJob() where the callback
is invoked. This left the CompletionCallback stuck in callback_
until WebContents destruction, causing webContents.print() to only
fire its callback when the application closed.
The `OnTraceBufferUsageAvailable` callback creates V8 handles via
`Dictionary::CreateEmpty()` before `promise.Resolve()` enters its
`SettleScope` (which provides a `HandleScope`). When the callback
fires asynchronously from a Mojo response (i.e. when a trace session
is active), there is no `HandleScope` on the stack, causing a fatal
V8 error: "Cannot create a handle without a HandleScope".
Add an explicit `v8::HandleScope` at the top of the callback, matching
the pattern used by the other contentTracing APIs which resolve their
promises through `SettleScope` or the static `ResolvePromise` helper.
Made-with: Cursor
* fix: re-enable MacWebContentsOcclusion with embedder window fix
Replace the full revert of Chromium's MacWebContentsOcclusion cleanup
with a targeted patch that handles embedder windows shown after
WebContentsViewCocoa attachment. This lets us drop the feature flag
disable in feature_list.cc and re-enable upstream occlusion tracking.
Adds tests for show/hide event counts on macOS and visibility tracking
across multiple child WebContentsViews.
* test: drop show/hide event count assertion
The assertion that 'show' fires exactly once per w.show() call is not
an API guarantee - macOS can send multiple occlusion state
notifications during a single show() when other windows are on screen
(common on CI after hundreds of prior tests). The
visibilitychange-count test in api-web-contents-view-spec.ts covers
the actual invariant we care about.
* fix: ignore WebContentsOcclusionCheckerMac synthetic notifications in window delegate
On macOS 13.3-25.x, Chromium's occlusion checker enables manual
frame-intersection detection and posts synthetic
NSWindowDidChangeOcclusionStateNotification tagged with its class name
in userInfo. These fire when the checker's NSContainsRect heuristic
decides a window is covered by another window's frame, but the real
-[NSWindow occlusionState] hasn't changed.
Our delegate was treating these the same as real macOS notifications
and emitting show/hide events based on occlusionState, which was
unchanged - resulting in spurious duplicate show events when e.g.
Quick Look opened and its frame intersected the BrowserWindow.
Removes unreferenced code found via codebase sweep. Each category below may
indicate a missing feature rather than truly-unused code — see PR description.
Dead class (1):
ElectronNavigationUIData — never instantiated; ElectronBrowserClient uses
upstream ExtensionNavigationUIData directly
Unused methods (7):
CertificateManagerModel: ImportUserCert, ImportCACerts, ImportServerCert,
Delete, is_user_db_available (only PKCS12 path is used)
AutofillDriverFactory::AddDriverForFrame + CreationCallback type
ZoomLevelDelegate::SetDefaultZoomLevelPref
gtk_util: GetOpenLabel, GetSaveLabel
Unused members (2):
AutofillPopup::selected_index_
InspectableWebContents::synced_setting_names_
Declaration fixes (6):
menu_util.h: BuildMenuItemWithImage signature corrected (GtkWidget* → gfx::Image&)
win_frame_view.h: GetReadableFeatureColor (impl removed, decl left behind)
frameless_view.h: friend class NativeWindowsViews (typo, class does not exist)
Forward decls: WebDialogHelper, ChromeContentRendererClient,
ElectronNativeWindowObserver, ValueStoreFactory
* Document known issue for dock.hide() method
Added a note about a known issue with dock.hide() method.
* Adjust workaround time for dock.hide() method
Updated workaround time for dock.hide() known issue.
* Fix known issue timing for dock.hide() workaround
Updated the workaround time in the known issue section for dock.hide() to 1000ms.
* Adjust workaround delay for dock.hide() method
Updated workaround time for dock.hide() known issue.
* fix: harden GitHub Actions against script injection vulnerabilities
Replace direct ${{ }} expression interpolation in run: blocks with
environment variables to prevent script injection attacks. Changes:
- archaeologist-dig.yml: move clone_url, head.sha, base.ref to env vars
- non-maintainer-dependency-change.yml: move user.login to env var
- issue-unlabeled.yml: move toJSON(labels) to env var
- issue-labeled.yml: move issue.number to env var
- pipeline-electron-lint.yml: validate chromium_revision format
- cipd-install/action.yml: move all inputs to env vars and quote them
- set-chromium-cookie/action.yml: reference secrets via $ENV_VAR
- Add security comments to all 5 pull_request_target workflows
https://claude.ai/code/session_01UUWmLxn5hyyxrhK8rGxU2s
* fix: allow version strings in chromium_revision validation
The previous regex `^[a-f0-9]+$` only matched git SHAs but
chromium_revision is a version string like `148.0.7741.0`.
Broaden to `^[a-zA-Z0-9._-]+$` which still blocks shell
metacharacters.
https://claude.ai/code/session_01UUWmLxn5hyyxrhK8rGxU2s
---------
Co-authored-by: Claude <noreply@anthropic.com>
* fix: fire AXMenuOpened event when a visible ARIA menu instance is added to the DOM
* fix: remove redundent FireMenuPopupEndForDeletedMenus
MENU_POPUP_END for deleted menus is already handled by
AXTreeManager::OnNodeWillBeDeleted, which
fires the event directly on the menu node before destruction.
* chore: add feature flag (kDynamicMenuPopupEvents)
* chore: update patches
* remove comment based label removal
* ci: add functionality for programmatic add/remove needs-signed-commits label
* add new line to pull-request-opened-synchronized
The weak persistent tracking the OffscreenReleaseHolderMonitor was tied
to the texture object, but the release() closure holds a raw pointer to
the monitor via its v8::External data. If JS retained texture.release
while dropping the texture itself, the monitor would be freed on GC and
a later release() call would crash.
Track the release function instead of the texture object. Since the
texture holds release as a property, this keeps the monitor alive as
long as either is reachable.
The frameNamesToWindow map was a holdover from the BrowserWindowProxy
IPC shim. Since nativeWindowOpen became the only code path, Blink's
FrameTree::FindOrCreateFrameForNavigation resolves named window targets
directly in the renderer, scoped to the opener's browsing context
group. When a matching named window exists, Blink navigates it without
ever sending a CreateNewWindow IPC to the browser, so this map was
never consulted in the legitimate same-opener case.
The only time the map found a match was when two unrelated renderers
happened to use the same target name, in which case openGuestWindow
would short-circuit before consuming the guest WebContents that
Chromium had already created for the new window, leaking it.
Adds a test verifying Blink handles same-opener named-target reuse
end-to-end without any browser-side tracking.
gfx::PNGCodec::Decode() returns a null SkBitmap when it fails to decode
the clipboard contents as a PNG. Passing that null bitmap to
gfx::Image::CreateFrom1xBitmap() triggers a crash.
Return an empty gfx::Image instead, matching the existing null-check
pattern in skia_util.cc.
GetDefaultPrinterDPI() creates a blank GtkPrintSettings and reads
its resolution, which returns 0 for uninitialized settings. With
DPI=0, SetPrintableAreaIfValid() computes a zero scale factor,
producing empty page dimensions that fail PrintMsgPrintParamsIsValid().
Fall back to kDefaultPdfDpi (72) when GTK returns 0, matching the
existing Windows fallback pattern when CreateDC fails.
fix: register PrintDialogLinuxFactory on Linux
Chromium 145 refactored Linux print dialog creation to use a factory
pattern instead of directly calling LinuxUi::CreatePrintDialog().
Chrome registers this factory in
ChromeBrowserMainExtraPartsViewsLinux::ToolkitInitialized(), but
Electron did not, causing PrintingContextLinux::EnsurePrintDialog()
to leave print_dialog_ null on every call.
Without a dialog, UseDefaultSettings() and UpdatePrinterSettings()
return success but with empty/unprocessed settings, causing
PrintMsgPrintParamsIsValid() to fail. This broke both window.print()
(no dialog appears) and webContents.print() (callback stuck until
app close with "Invalid printer settings").
Use platform_util::GetXdgAppId() with fallback to argv0 as PA_PROP_APPLICATION_ICON_NAME.
Use electron::GetPossiblyOverriddenApplicationName()
to set environment variable "ELECTRON_PA_APP_NAME" in audio_service.cc,
to use it in pulse_util.cc for setting input/output pa_context name.
This replaces hard-codded kBrowserDisplayName that was used for PA_PROP_APPLICATION_ICON_NAME,
and PRODUCT_STRING that was used for pa_context names.
This is done to make audio streams recognizable in tools like qpwgrapth and general audio managers,
instead of having 20 "Chromium" outputs and "Chromium input" inputs, that are actually coming from
completely different applications.
* fix: hex-encode Windows notification icon temp filenames
NotificationPresenterWin was using SHA1HashString(origin.spec()) directly
as the basename for the temporary PNG written for toast icons.
SHA1HashString returns raw digest bytes, so the generated filename could
contain invalid path characters on Windows. That caused WriteFile to fail
when saving notification icons, which left toast XML without the expected
icon path.
Hex-encode the digest before appending .png so the temporary filename is
filesystem-safe while keeping deterministic naming for a given origin.
* Update shell/browser/notifications/win/notification_presenter_win.cc
Co-authored-by: Robo <hop2deep@gmail.com>
---------
Co-authored-by: Robo <hop2deep@gmail.com>
- export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch:
gin::V8Platform::GetPageAllocator() is now exported upstream via the
public v8::Platform interface, so we no longer need to patch gin to
expose a custom accessor. Update javascript_environment.cc to use the
upstream API instead.
- fix_getcursorscreenpoint_wrongly_returns_0_0.patch: this fix has
landed upstream in Chromium and is no longer needed as a local patch.
* refactor: SafeV8Function to be backed by cppgc
* spec: focus renderer before attempting paste
* spec: remove listeners to prevent leak on failed tests
docs: handle cold-start deep links on Windows/Linux
add a check for `process.argv` in the `app.whenReady()` callback to handle deep links when the application is cold-started on Windows and Linux.
* fix: remove ELECTRON_SKIP_BINARY_DOWNLOAD
it is redundant as of electron v42
its purpose was to skip the binary download for post install script
but as of electron v42, post install script is gone
and replaced with a lazy download
it was also slated for removal in [this comment](https://github.com/electron/rfcs/pull/22#issuecomment-3387307743)
* docs: remove ELECTRON_SKIP_BINARY_DOWNLOAD section
the env is redundant as of electron v42
so docs don't have to mention it anymore
* docs: add ELECTRON_SKIP_BINARY_DOWNLOAD to breaking changes
* ci: upload object change stats to Datadog
Assisted-by: Claude Opus 4.6
* ci: bump actions/upload-artifact version
* chore: only output new object count if non-zero
* chore: skip object change tracking on ASan builds
* chore: handle pull requests as well
* chore: always set chromium-version-changed
* chore: remove npx usage
* fix: lazily initialize safeStorage async encryptor
The SafeStorage constructor previously registered a browser observer that
called os_crypt_async()->GetInstance() on app-ready. Because ESM named
imports (import { x } from 'electron') eagerly evaluate all electron
module getters, simply importing electron in an ESM entrypoint would
construct SafeStorage and touch the OS keychain on app-ready, even when
safeStorage was never used.
This showed up as a macOS CI hang: the esm-spec import-meta fixture
triggers a keychain access prompt that blocks the test runner until
timeout.
Now the async encryptor is requested lazily on the first call to
encryptStringAsync, decryptStringAsync, or isAsyncEncryptionAvailable.
isAsyncEncryptionAvailable now returns a Promise that resolves once
initialization completes, matching what the docs already stated.
* chore: lint
* fix: add HandleScope in OnOsCryptReady for pending operations
OnOsCryptReady fires asynchronously from a posted task without an active
V8 HandleScope. Previously this was harmless because eager init meant the
pending queues were always empty when it fired. With lazy init, operations
queue up first, then the callback processes them and needs to create V8
handles (Buffer::Copy, Dictionary::CreateEmpty, Promise::Resolve).
* build: enable V8 builtins PGO
Removes the gn arg that disabled V8 builtins profile-guided optimization
and adds a V8 patch to warn instead of abort when the builtin PGO profile
data does not match. Also strips the PGO-related flags from the generated
mksnapshot_args so they are not passed through to downstream mksnapshot
invocations.
* docs: clarify Node.js async_hooks as reason for promise_hooks flag
Addresses review feedback: the v8_enable_javascript_promise_hooks flag
is set to support Node.js async_hooks, not used directly by Electron.
git am rewrites the index 2-3x per patch. In Chromium (~500K files,
70MB index) this dominated wall time: ~67 of 73 seconds were spent
rehashing and rewriting the index ~300 times for 150 patches.
- Add index.skipHash=true to skip recomputing the trailing SHA over
the full index on every write
- Force index v4 before am so path-prefix compression roughly halves
the on-disk index size (70MB -> 40MB)
- Disable core.fsync and gc.auto during am since a crashed apply is
just re-run from a clean reset
- Apply patch targets in parallel (capped at ncpu-2); Chromium still
dominates but this hides node/nan/etc behind it. Falls back to
sequential on roller/ branches where conflict output needs to be
readable.
- Prefix each output line with the target name so parallel output is
attributable
Measured on a 13-target config with 238 total patches: 73s -> 28s.
feat: add nativeTheme.shouldDifferentiateWithoutColor on macOS
Adds nativeTheme.shouldDifferentiateWithoutColor on macOS that maps to
NSWorkspace.accessibilityDisplayShouldDifferentiateWithoutColor. If true,
the user has indicated that they prefer UI that differentiates items with
something other than color alone. This is useful for users with color
vision deficiency.
* feat: add copyVideoFrameAt and saveVideoFrameAs Method on Webcontent
chore: change the description of savevideoframe api
chore: add the description of the restrictive elements for using the APIs.
move to webframemain
fixed mediaPlayerAction to kSaveVideoFrameAs
Update spec/api-web-frame-main-spec.ts
Co-authored-by: John Kleinschmidt <kleinschmidtorama@gmail.com>
Update spec/api-web-frame-main-spec.ts
Co-authored-by: John Kleinschmidt <kleinschmidtorama@gmail.com>
fixed clipboard tests for video frame copying
fixed test for copying video frame to clipboard. check video loaded before copy video frame in test.
chore: try non-proprietary video format
Revert "chore: try non-proprietary video format"
This reverts commit ef085f88a1af53b6408a7af695cc60b8681398cf.
fix: format video as file url
* test: skip webFrameMain.copyVideoFrameAt on win32 CI due Chromium DCHECK
build(deps): bump flatted in the npm_and_yarn group across 1 directory
Bumps the npm_and_yarn group with 1 update in the / directory: [flatted](https://github.com/WebReflection/flatted).
Updates `flatted` from 3.2.7 to 3.4.1
- [Commits](https://github.com/WebReflection/flatted/compare/v3.2.7...v3.4.1)
---
updated-dependencies:
- dependency-name: flatted
dependency-version: 3.4.1
dependency-type: indirect
dependency-group: npm_and_yarn
...
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* fix: correct utility process exit code on Windows
On Windows, process exit codes are 32-bit unsigned integers (DWORD).
When passed from Chromium to Electron as a signed int and then
implicitly converted to uint64_t, values with the high bit set
(e.g., NTSTATUS codes) undergo sign extension, producing incorrect
values.
Cast the exit code to uint32_t before widening to uint64_t to
prevent sign extension and preserve the original Windows exit code.
Fixes#49455
* fix: narrow HandleTermination and Shutdown to uint32_t, add tests
* feat: support notification priority on Windows
Add Windows notifications support urgency/priority levels.
This maps the existing `urgency` option (previously Linux-only) to
Windows toast notification priorities:
- 'critical' maps to ToastNotificationPriority_High, which sorts the
notification above default-priority items in Action Center.
- 'normal' and 'low' both map to ToastNotificationPriority_Default.
Note that on Windows, 'critical' priority does not prevent the toast
from being auto-dismissed. Users should additionally set `timeoutType`
to 'never' for that behavior.
* chore: make linter happy
---------
Co-authored-by: Charles Kerr <charles@charleskerr.com>
build: remove macos hittest workaround patch
CL:6574464 changed BridgedContentView::hitTest: to use GetHitTestResult(), which
returns kRootView for any non-null, non-NativeViewHost view — causing
BridgedContentView to absorb all web content mouse events. In BrowserWindow,
content_view_ sits in front of the sibling WebContentsView and covers the full
client area, so it was always found first, breaking all loadURL page interaction.
Fix this by installing a ContentViewTargeterDelegate on content_view_ in
NativeWindowMac::SetContentView that returns nullptr (instead of the view itself)
when no children cover the target point. This makes GetHitTestResult return kOther,
allowing hitTest: to fall through to [super hitTest:] and find
RenderWidgetHostViewCocoa. This also removes the now-unnecessary chromium
partial-revert patch that worked around the same issue.
* docs: fix markdown formatting in fuses.md
* Use bulleted list (was being run together on one line)
* Wrap ASCII diagram in code block
* docs: apply suggestions from code review
Co-authored-by: John Kleinschmidt <kleinschmidtorama@gmail.com>
Co-authored-by: Erick Zhao <erick@hotmail.ca>
* docs: fix misapplied suggestion
---------
Co-authored-by: John Kleinschmidt <kleinschmidtorama@gmail.com>
Co-authored-by: Erick Zhao <erick@hotmail.ca>
refactor: replace CHILD_PLUGIN with CHILD_EMBEDDER_FIRST on macOS
Chromium removed upstream support for child plugin processes without
library validation in https://crbug.com/461717105, which we patched
back via feat_restore_macos_child_plugin_process.patch.
Chromium's CHILD_EMBEDDER_FIRST mechanism already provides the right
extensibility point for this: values > CHILD_EMBEDDER_FIRST are reserved
for embedders and resolved via ContentBrowserClient::GetChildProcessSuffix().
Chrome itself uses this pattern for its Alerts helper process.
This commit replaces the Chromium patch with an Electron-native
implementation.
description: Guide for performing Node.js version upgrades in the Electron project. Use when working on the roller/node/main branch to fix patch conflicts during `e sync --3`. Covers the patch application workflow, conflict resolution, analyzing upstream Node.js changes, and proper commit formatting for patch fixes.
---
# Electron Node.js Upgrade: Phase One
## Summary
Run `e sync --3` repeatedly, fixing patch conflicts as they arise, until it succeeds. Then export patches and commit changes atomically.
## Success Criteria
Phase One is complete when:
-`e sync --3` exits with code 0 (no patch failures)
- All changes are committed per the commit guidelines
Do not stop until these criteria are met.
**CRITICAL** Do not delete or skip patches unless 100% certain the patch is no longer needed. For major version upgrades, patches that shim deprecated V8 APIs or backport upstream changes are often deletable because the new Node.js version already incorporates them — but verify before removing. Complicated conflicts or hard to resolve issues should be presented to the user after you have exhausted all other options. Do not delete the patch just because you can't solve it.
**CRITICAL** Never use `git am --skip` and then manually recreate a patch by making a new commit. This destroys the original patch's authorship, commit message, and position in the series. If `git am --continue` reports "No changes", investigate why — the changes were likely absorbed by a prior conflict resolution's 3-way merge. Present this situation to the user rather than skipping and recreating.
## Context
The `roller/node/main` branch is created by automation to update Electron's Node.js dependency version in `DEPS`. No work has been done to handle breaking changes between the old and new versions.
There are two types of Node.js version updates:
- **Bumps** (patch/minor): Automated by `electron-roller[bot]` with commit title `chore: bump node to v{version}`. Trivial patch index updates are handled automatically by `patchup[bot]`. These often land cleanly, but may require manual patch fixes.
- **Major upgrades** (e.g., v22 → v24): Manual, large PRs with commit title `chore: upgrade Node.js to v{X}.{Y}.{Z}`. These typically involve deleting obsolete patches, adapting many others, and updating `@types/node` in `package.json`.
**Key directories:**
- Current directory: Electron repo (always run `e` commands here)
-`docs/development/patches.md`: Patch system documentation
## Pre-flight Checks
Run these once at the start of each upgrade session:
1.**Clear rerere cache** (if enabled): `git rerere clear` in both the electron and `../third_party/electron_node` repos. Stale recorded resolutions from a prior attempt can silently apply wrong merges.
2.**Ensure pre-commit hooks are installed**: Check that `.git/hooks/pre-commit` exists. If not, run `yarn husky` to install it. The hook runs `lint-staged` which handles clang-format for C++ files.
## Workflow
1. Run `e sync --3` (the `--3` flag enables 3-way merge, always required)
2. If succeeds → skip to step 5
3. If patch fails:
- Identify target repo and patch from error output
- Analyze failure (see references/patch-analysis.md)
- Fix conflict in `../third_party/electron_node` working directory
- Run `git am --continue` in `../third_party/electron_node`
- Repeat until all patches for that repo apply
- IMPORTANT: Once `git am --continue` succeeds you MUST run `e patches node` to export fixes
- Return to step 1
4. When `e sync --3` succeeds, run `e patches all`
5.**Read `references/phase-one-commit-guidelines.md` NOW**, then commit changes following those instructions exactly.
## Commands Reference
| Command | Purpose |
|---------|---------|
| `e sync --3` | Clone deps and apply patches with 3-way merge |
| `git am --continue` | Continue after resolving conflict (run in node repo) |
| `e patches node` | Export commits from node repo to patch files |
| `e patches all` | Export all patches from all targets |
| Creating new patch (rare, avoid) | Commit in node repo, then `e patches node` |
Fix existing patches 99% of the time rather than creating new ones.
## Patch Fixing Rules
1.**Preserve authorship**: Keep original author in TODO comments (from patch `From:` field)
2.**Never change TODO assignees**: `TODO(name)` must retain original name
3.**Update descriptions**: If upstream changed APIs or macros, update patch commit message to reflect current state
4.**Never skip-and-recreate a patch**: If `git am --continue` says "No changes — did you forget to use 'git add'?", do NOT run `git am --skip` and create a replacement commit. The patch's changes were already absorbed by a prior 3-way merge resolution. This means an earlier conflict resolution pulled in too many changes. Present the situation to the user for guidance — the correct fix may require re-doing an earlier resolution more carefully to keep each patch's changes separate.
# Electron Node.js Upgrade: Phase Two
## Summary
Run `e build -k 999 -- --quiet` repeatedly, fixing build issues as they arise, until it succeeds. Then run `e start --version` to validate Electron launches and commit changes atomically.
Run Phase Two immediately after Phase One is complete.
## Success Criteria
Phase Two is complete when:
-`e build -k 999 -- --quiet` exits with code 0 (no build failures)
-`e start --version` has been run to check Electron launches
- All changes are committed per the commit guidelines
Do not stop until these criteria are met. Do not delete code or features, never comment out code in order to take short cut. Make all existing code, logic and intention work.
## Context
The `roller/node/main` branch is created by automation to update Electron's Node.js dependency version in `DEPS`. No work has been done to handle breaking changes between the old and new versions. Node.js APIs (especially internal V8 integration, OpenSSL/BoringSSL compatibility, and build system files) frequently change between versions. In every case the code in Electron must be updated to account for the change in Node.js, strongly avoid making changes to the code in Node.js to fix Electron's build.
**Key directories:**
- Current directory: Electron repo (always run `e` commands here)
-`../third_party/electron_node`: Node.js repo (do not touch this code to fix build issues, just read it to obtain context)
## Workflow
1. Run `e build -k 999 -- --quiet` (the `--quiet` flag suppresses per-target status lines, showing only errors and the final result)
2. If succeeds → skip to step 6
3. If build fails:
- Identify underlying file in "electron" from the compilation error message
- Analyze failure
- Fix build issue by adapting Electron's code for the change in Node.js
- Run `e build -t {target_that_failed}.o` to build just the failed target we were specifically fixing
- You can identify the target_that_failed from the failure line in the build log. E.g. `FAILED: 2e506007-8d5d-4f38-bdd1-b5cd77999a77 "./obj/electron/shell/browser/api/electron_api_utility_process.o" CXX obj/electron/shell/browser/api/electron_api_utility_process.o` the target name is `obj/electron/shell/browser/api/electron_api_utility_process.o`
- **Read `references/phase-two-commit-guidelines.md` NOW**, then commit changes following those instructions exactly.
- Return to step 1
4.**CRITICAL**: After ANY commit (especially patch commits), immediately run `git status` in the electron repo
- Look for other modified `.patch` files that only have index/hunk header changes
- These are dependent patches affected by your fix
6. When `e build` succeeds, run `e start --version`
7. Check if you have any pending changes in the Node.js repo by running `git status` in `../third_party/electron_node`
- If you have changes follow the instructions below in "A. Patch Fixes" to correctly commit those modifications into the appropriate patch file
## Commands Reference
| Command | Purpose |
|---------|---------|
| `e build -k 999 -- --quiet` | Build Electron, continue on errors, suppress status lines |
| `e build -t {target}.o` | Build just one specific target to verify a fix |
| `e start --version` | Validate Electron launches after successful build |
## Two Types of Build Fixes
### A. Patch Fixes (for files in patched Node.js files)
When the error is in a file that Electron patches (check with `grep -l "filename" patches/node/*.patch`):
1. Edit the file in the Node.js source tree (`../third_party/electron_node/...`)
2. Create a fixup commit targeting the original patch commit:
```bash
cd ../third_party/electron_node
git add <modified-file>
git commit --fixup=<original-patch-commit-hash>
GIT_SEQUENCE_EDITOR=: git rebase --autosquash --autostash -i <commit>^
```
3. Export the updated patch: `e patches node`
4. Commit the updated patch file following `references/phase-one-commit-guidelines.md`.
To find the original patch commit to fixup: `git log --oneline | grep -i "keyword from patch name"`
The base commit for rebase is the Node.js commit before patches were applied. Find it by checking the `refs/patches/upstream-head` ref.
### B. Electron Code Fixes (for files in shell/, electron/, etc.)
When the error is in Electron's own source code:
1. Edit files directly in the electron repo
2. Commit directly (no patch export needed)
# Critical: Read Before Committing
- Before ANY Phase One commits: Read `references/phase-one-commit-guidelines.md`
- Before ANY Phase Two commits: Read `references/phase-two-commit-guidelines.md`
# High-Churn Patches
These patches consistently require the most work during Node.js upgrades:
- **`fix_handle_boringssl_and_openssl_incompatibilities.patch`** — Electron uses BoringSSL (via Chromium) while Node.js expects OpenSSL. This patch is large and complex, and upstream OpenSSL API changes frequently break it.
- **`fix_crypto_tests_to_run_with_bssl.patch`** — Companion to the above; adapts Node.js crypto tests for BoringSSL. Can grow significantly during major upgrades.
- **`support_v8_sandboxed_pointers.patch`** — V8 sandbox pointer support requires careful adaptation when V8 APIs change.
- **`build_add_gn_build_files.patch`** — The GN build file patch is large and touches many build targets. Upstream build system changes frequently conflict.
# Major Version Upgrades
Major Node.js version transitions (e.g., v22 → v24) are significantly more involved than patch bumps:
1. **Expect patch deletions.** Electron uses Chromium's V8, which is often ahead of the V8 version bundled in Node.js. Many patches exist to bridge this gap — shimming newer V8 APIs that Chromium's V8 has but Node.js' older V8 doesn't. When Node.js bumps to a newer major version, its V8 catches up to Chromium's, and those bridge patches can be deleted. In the v22 → v24 upgrade, 17 patches were deleted for this reason.
2. **Update `@types/node`** in `package.json` to match the new major version.
3. **Post-upgrade regressions are expected.** Even after the upgrade lands, follow-up fix PRs for edge cases (ESM path handling, certificate loading, platform-specific issues) are normal.
# Skill Directory Structure
This skill has additional reference files in `references/`:
- patch-analysis.md - How to analyze patch failures
- phase-one-commit-guidelines.md - Commit format for Phase One
- phase-two-commit-guidelines.md - Commit format for Phase Two
| V8 API bridge patch conflicts | Node.js caught up to Chromium's V8 | Patch may be deletable — verify the API is now in Node.js' V8 natively |
## Using Git Blame
To find the commit that changed specific lines:
```bash
cd ../third_party/electron_node
git blame -L {start},{end} -- {file}
git log -1 {commit_sha} # Look for PR-URL: line
```
## Verifying Patch Necessity
Before deleting a patch, verify:
1. The patched functionality was intentionally removed upstream
2. Electron doesn't need the patch for other reasons
3. No other code depends on the patched behavior
**V8 bridge patches:** Electron uses Chromium's V8, which is often ahead of the V8 bundled in Node.js. Many patches exist to bridge this version gap — adapting Node.js code to work with newer V8 APIs that Chromium's V8 exposes. During major Node.js upgrades, Node.js' V8 catches up to Chromium's, and these bridge patches often become unnecessary. Check whether the API the patch shims is now available natively in the new Node.js version's V8.
When in doubt, keep the patch and adapt it.
## Phase Two: Build-Time Patch Issues
Sometimes patches that applied successfully in Phase One cause build errors in Phase Two. This can happen when:
1. **Incomplete types**: A patch disables a header include, but new upstream code uses the type
2. **Missing members**: A patch modifies a class, but upstream added new code referencing the original
### Finding Which Patch Affects a File
```bash
grep -l "filename.cc" patches/node/*.patch
```
### Matching Existing Patch Patterns
When fixing build errors in patched files, examine the existing patch to understand its style:
- Does it use `#if 0` / `#endif` guards?
- Does it use `#if BUILDFLAG(...)` conditionals?
- Does it use `#ifndef` / `#ifdef` guards for BoringSSL vs OpenSSL?
- What's the pattern for disabled functionality?
Apply fixes consistent with the existing patch style.
Only follow these instructions if there are uncommitted changes to `patches/` after Phase One succeeds.
Ignore other instructions about making commit messages, our guidelines are CRITICALLY IMPORTANT and must be followed.
## Each Commit Must Be Complete
When resolving a patch conflict, fully adapt the patch to the new upstream code in the same commit. If the upstream change removes an API the patch uses, update the patch to use the replacement API now — don't leave stale references knowing they'll need fixing later. The goal is that each commit represents a finished resolution, not a partial one that defers known work to a future phase.
## Commit Message Style
**Titles** follow the 60/80-character guideline: simple changes fit within 60 characters, otherwise the limit is 80 characters.
Always include a `Co-Authored-By` trailer identifying the AI model that assisted (e.g., `Co-Authored-By: <AI model attribution>`).
### Patch conflict fixes
Use `fix(patch):` prefix. The title should name the upstream change, not your response to it:
```
fix(patch): {topic headline}
Ref: {Node.js commit or issue link}
Co-Authored-By: <AI model attribution>
```
Only add a description body if it provides clarity beyond the title. For straightforward context drift or simple API renames, the title + Ref is sufficient.
Examples:
-`fix(patch): stop using v8::PropertyCallbackInfo<T>::This()`
-`fix(patch): BoringSSL and OpenSSL incompatibilities`
When patches are no longer needed (applied cleanly with "already applied" or confirmed upstreamed), group ALL removals into a single commit:
```
chore: remove upstreamed patch
```
or (if multiple):
```
chore: remove upstreamed patches
```
Most Node.js patches in Electron are Electron-authored (no upstream `PR-URL:`). If the patch originated from an upstream Node.js PR, no extra `Ref:` is needed. Otherwise, add a `Ref:` pointing to the relevant Node.js issue or commit if one exists.
### Trivial patch updates
After all fix commits, stage remaining trivial changes (index, line numbers, context only):
**Conflict resolution can produce trivial results.** A `git am` conflict doesn't always mean the patch content changed — context drift alone can cause a conflict. After resolving and exporting, inspect the patch diff: if only index hashes, line numbers, and context lines changed (not the patch's own `+`/`-` lines), it's trivial and belongs here, not in a `fix(patch):` commit.
## Atomic Commits
Each patch conflict fix gets its own commit with its own Ref.
IMPORTANT: Try really hard to find the PR or commit reference per the instructions below. Each change you made should in theory have been in response to a change made in Node.js that you identified or can identify. Try for a while to identify and include the ref in the commit message. Do not give up easily.
## Finding Commit/Issue References
Use `git log` or `git blame` on Node.js source files in `../third_party/electron_node`. Look for:
```
PR-URL: https://github.com/nodejs/node/pull/XXXXX
```
or issue references in the patch itself:
```
Refs: https://github.com/nodejs/node/issues/XXXXX
```
Note: Most Node.js patches in Electron are Electron-authored and won't have upstream references. In that case, check `git log` in the Node.js repo to find which upstream commit caused the conflict.
If no reference found after searching: `Ref: Unable to locate reference`
## Example Commits
### Patch conflict fix (simple — title is sufficient)
```
fix(patch): stop using v8::PropertyCallbackInfo<T>::This()
Only follow these instructions if there are uncommitted changes in the Electron repo after any fixes are made during Phase Two that result a target that was failing, successfully building.
Ignore other instructions about making commit messages, our guidelines are CRITICALLY IMPORTANT and must be followed.
## Commit Message Style
**Titles** follow the 60/80-character guideline: simple changes fit within 60 characters, otherwise the limit is 80 characters. Exception: upstream Node.js PR titles are used verbatim even if longer.
Always include a `Co-Authored-By` trailer identifying the AI model that assisted (e.g., `Co-Authored-By: <AI model attribution>`).
## Two Commit Types
### For Electron Source Changes (shell/, electron/, etc.)
When the upstream Node.js commit has a `PR-URL:`:
```
node#{PR-Number}: {upstream PR's original title}
Ref: {Node.js PR link}
Co-Authored-By: <AI model attribution>
```
When there is no `PR-URL:` but there is an issue reference or commit:
```
fix: {description of the adaptation}
Ref: {Node.js issue or commit link}
Co-Authored-By: <AI model attribution>
```
Use the **upstream commit's original title** when available — do not paraphrase or rewrite it. To find it: check the commit message in `../third_party/electron_node` for `PR-URL:` or `Refs:` lines.
Only add a description body if it provides clarity beyond what the title already says (e.g., when Electron's adaptation is non-obvious). For simple renames, method additions, or straightforward API updates, the title + Ref link is sufficient.
Each change should have its own commit and its own Ref. Logically group into commits that make sense rather than one giant commit. You may include multiple "Ref" links if required.
IMPORTANT: Try really hard to find a reference. Each change you made should in theory have been in response to a change in Node.js. Check `git log` and `git blame` in the Node.js repo. Do not give up easily.
### For Patch Updates (patches/node/*.patch)
Use the same fixup workflow as Phase One and follow `references/phase-one-commit-guidelines.md` for the commit message format (`fix(patch):` prefix, topic style).
## Dependent Patch Header Updates
After any patch modification, check for other affected patches:
```bash
git status
# If other .patch files show as modified with only index, line number, and context changes:
Use `git log` or `git blame` on Node.js source files in `../third_party/electron_node`. Look for:
```
PR-URL: https://github.com/nodejs/node/pull/XXXXX
Refs: https://github.com/nodejs/node/issues/XXXXX
```
Note: Many Node.js patches in Electron are Electron-authored and won't have upstream `PR-URL:` lines. Check the patch's own commit message for `Refs:` lines, or use `git log` in the Node.js repo to find which upstream commit caused the build break.
If no reference found after searching: `Ref: Unable to locate reference`
## Example Commits
### Electron Source Fix (with upstream PR)
```
node#61898: src: stop using v8::PropertyCallbackInfo<T>::This()
Ref: https://github.com/nodejs/node/pull/61898
Co-Authored-By: <AI model attribution>
```
### Electron Source Fix (with issue reference, no PR)
```
fix: adapt to v8::PropertyCallbackInfo<T>::This() removal
Updated NodeBindings to use HolderV2() after upstream Node.js
Using a coding agent / AI? Read the policy: https://github.com/electron/governance/blob/main/policy/ai.md
NOTE: PRs submitted that do not follow this template will be automatically closed.
-->
#### Checklist
<!-- Remove items that do not apply. For completed items, change [ ] to [x]. -->
- [ ]PR description included
- [ ] I have built and tested this PR
- [ ]I have built and tested this change
- [ ] I have filled out the PR description
- [ ] [I have reviewed and verified the changes](https://github.com/electron/governance/blob/main/policy/ai.md)
- [ ]`npm test` passes
- [ ] tests are [changed or added](https://github.com/electron/electron/blob/main/docs/development/testing.md)
- [ ] relevant API documentation, tutorials, and examples are updated and follow the [documentation style guide](https://github.com/electron/electron/blob/main/docs/development/style-guide.md)
ELECTRON_USE_THREE_WAY_MERGE_FOR_PATCHES=1 e d gclient sync --with_branch_heads --with_tags -vv
ELECTRON_DEPOT_TOOLS_WIN_TOOLCHAIN=0 DEPOT_TOOLS_WIN_TOOLCHAIN=0 ELECTRON_USE_THREE_WAY_MERGE_FOR_PATCHES=1 e d gclient sync --with_branch_heads --with_tags
if [[ "${{ inputs.is-release }}" != "true" ]]; then
# Re-export all the patches to check if there were changes.
printf "<!-- disallowed-non-maintainer-change -->\n\nHello @${{ github.event.pull_request.user.login }}! It looks like this pull request touches one of our dependency or CI files, and per [our contribution policy](https://github.com/electron/electron/blob/main/CONTRIBUTING.md#dependencies-upgrades-policy) we do not accept these types of changes in PRs." | gh pr review $PR_URL -r --body-file=-
Hello @%AUTHOR%! It looks like this pull request touches one of our dependency or CI files, and per [our contribution policy](https://github.com/electron/electron/blob/main/CONTRIBUTING.md#dependencies-upgrades-policy) we do not accept these types of changes in PRs.
To move this PR forward, please:
1. Revert the dependency/CI file changes from your branch. (e.g. `yarn.lock`, `.yarn/`, `.yarnrc.yml`, `.github/workflows/`, `.github/actions/`)
2. Ensure your branch [allows maintainer commits](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/allowing-changes-to-a-pull-request-branch-created-from-a-fork) so a maintainer can push the necessary dependency changes on your behalf.
3. Leave a comment letting reviewers know the dependency change is still needed.
<details>
<summary>For maintainers</summary>
To land this PR, push a verified commit to the contributor's branch with the required dependency/CI changes, then dismiss this review.
body: `This PR was automatically closed because the PR template was not properly filled out. The following required sections are missing:\n\n${list}\n\nPlease update your PR description to include all required sections and reopen the PR.`,
Hello @${{ github.event.pull_request.user.login }}. Due to the high amount of AI spam PRs we receive, if a PR is detected to be majority AI-generated without disclosure and untested, we will automatically close the PR.
We welcome the use of AI tools, as long as the PR meets our quality standards and has clearly been built and tested. If you believe your PR was closed in error, we welcome you to resubmit. However, please read our [CONTRIBUTING.md](http://contributing.md/) carefully before reopening. Thanks for your contribution.
We welcome the use of AI tools, as long as the PR meets our quality standards and has clearly been built and tested. If you believe your PR was closed in error, we welcome you to resubmit. However, please read our [CONTRIBUTING.md](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) and [AI Tool Policy](https://github.com/electron/governance/blob/main/policy/ai.md) carefully before reopening. Thanks for your contribution.
⚠️ This PR contains unsigned commits. This repository enforces [commit signatures](https://docs.github.com/en/authentication/managing-commit-signature-verification)
for all incoming PRs. To get your PR merged, please sign those commits
(`git rebase --exec 'git commit -S --amend --no-edit -n' @{upstream}`) and force push them to this branch
(`git push --force-with-lease`)
For more information on signing commits, see GitHub's documentation on [Telling Git about your signing key](https://docs.github.com/en/authentication/managing-commit-signature-verification/telling-git-about-your-signing-key).
**Never use `npx`.** It is considered dangerous because it can silently fetch and execute arbitrary packages from the registry. Always run binaries through one of these safer mechanisms instead:
1.**Preferred** — spawn the executable directly from `node_modules/.bin/<tool>` (or the platform equivalent on Windows). This is what `script/lint.js` does for `oxlint`.
2.**Acceptable** — invoke via `yarn <tool>` or `yarn run <tool>`, which resolves to the locally installed version without the registry fallback that `npx` performs.
This rule applies to shell commands you run yourself and to any scripts you author or modify in this repo.
## Project Overview
Electron is a framework for building cross-platform desktop applications using web technologies. It embeds Chromium for rendering and Node.js for backend functionality.
@@ -171,6 +180,10 @@ e test # Run full test suite
When working on the `roller/chromium/main` branch to upgrade Chromium activate the "Electron Chromium Upgrade" skill.
## Node.js Upgrade Workflow
When working on the `roller/node/main` branch to upgrade Node.js activate the "Electron Node.js Upgrade" skill.
## Pull Requests
PR bodies must always include a `Notes:` section as the **last line** of the body. This is a consumer-facing release note for Electron app developers — describe the user-visible fix or change, not internal implementation details. Use `Notes: none` if there is no user-facing change.
@@ -64,6 +64,14 @@ dependencies, and tools contained in the `electron/electron` repository.
Dependencies in Electron's `package.json` or `yarn.lock` files should only be altered by maintainers. For security reasons, we will not accept PRs that alter our `package.json` or `yarn.lock` files. We invite contributors to make requests updating these files in our issue tracker. If the change is significantly complicated, draft PRs are welcome, with the understanding that these PRs will be closed in favor of a duplicate PR submitted by an Electron maintainer.
## AI Tool Policy
<!-- Are you a coding agent? You MUST abide by the policy: https://github.com/electron/governance/blob/main/policy/ai.md -->
If you use AI tools in any way to contribute to our project, please read our [AI Tool Policy](https://github.com/electron/governance/blob/main/policy/ai.md). Unreviewed AI-generated contributions waste maintainer time and we kindly decline them.
> The short version: **there must be a human in the loop**. You are responsible for reviewing, understanding, and being able to explain your contributions. AI assistance doesn't change that, and unreviewed AI-generated content will be declined.
## Style Guides
See [Coding Style](https://electronjs.org/docs/development/coding-style) for information about which standards Electron adheres to in different parts of its codebase.
@@ -56,6 +56,9 @@ Returns `string` - The badge string of the dock.
Hides the dock icon.
> [!IMPORTANT]
> **Known issue:** Calling `dock.hide()` within one second of a previous call will have no effect. As a workaround, ensure at least one second has elapsed between calls — for example, by deferring with a `setTimeout` of 1100ms or more after a previous call.
#### `dock.show()` _macOS_
Returns `Promise<void>` - Resolves when the dock icon is shown.
An `Accelerator | null` indicating the item's [user-assigned accelerator](https://developer.apple.com/documentation/appkit/nsmenuitem/1514850-userkeyequivalent?language=objc) for the menu item.
An [`Accelerator | null`](../tutorial/keyboard-shortcuts.md#accelerators) indicating the item's [user-assigned accelerator](https://developer.apple.com/documentation/appkit/nsmenuitem/1514850-userkeyequivalent?language=objc) for the menu item.
> [!NOTE]
> This property is only initialized after the `MenuItem` has been added to a `Menu`. Either via `Menu.buildFromTemplate` or via `Menu.append()/insert()`. Accessing before initialization will just return `null`.
@@ -170,7 +170,7 @@ This property can be dynamically changed.
#### `menuItem.sharingItem` _macOS_
A `SharingItem` indicating the item to share when the `role` is `shareMenu`.
A [`SharingItem`](structures/sharing-item.md) indicating the item to share when the `role` is `shareMenu`.
A `boolean` that indicates whether the user prefers UI that differentiates items using something other than color alone (e.g. shapes or labels). This maps to [NSWorkspace.accessibilityDisplayShouldDifferentiateWithoutColor](https://developer.apple.com/documentation/appkit/nsworkspace/accessibilitydisplayshoulddifferentiatewithoutcolor).
*`id` string (optional) _macOS_ - A unique identifier for the notification, mapping to `UNNotificationRequest`'s [`identifier`](https://developer.apple.com/documentation/usernotifications/unnotificationrequest/identifier) property. Defaults to a random UUID if not provided or if an empty string is passed. This can be used to remove or update previously delivered notifications.
*`groupId` string (optional) _macOS_ - A string identifier used to visually group notifications together in Notification Center. Maps to `UNNotificationContent`'s [`threadIdentifier`](https://developer.apple.com/documentation/usernotifications/unnotificationcontent/threadidentifier) property.
*`id` string (optional) _macOS__Windows_ - A unique identifier for the notification. On macOS, maps to `UNNotificationRequest`'s [`identifier`](https://developer.apple.com/documentation/usernotifications/unnotificationrequest/identifier) property. On Windows, maps to the toast notification's [`Tag`](https://learn.microsoft.com/en-us/uwp/api/windows.ui.notifications.toastnotification.tag) property. Defaults to a random UUID if not provided or if an empty string is passed. This can be used to remove or update previously delivered notifications.
*`groupId` string (optional) _macOS__Windows_ - A string identifier used to visually group notifications together in Notification Center / Action Center. On macOS, maps to `UNNotificationContent`'s [`threadIdentifier`](https://developer.apple.com/documentation/usernotifications/unnotificationcontent/threadidentifier) property. On Windows, maps to the toast notification's [`Group`](https://learn.microsoft.com/en-us/uwp/api/windows.ui.notifications.toastnotification.group) property.
*`groupTitle` string (optional) _Windows_ - A title for the notification group header. When both `groupId` and `groupTitle` are specified, Windows will display a header above the notification that groups related notifications together. Maps to the toast notification's [`header`](https://learn.microsoft.com/en-us/windows/apps/design/shell/tiles-and-notifications/toast-headers) element.
*`title` string (optional) - A title for the notification, which will be displayed at the top of the notification window when it is shown.
*`subtitle` string (optional) _macOS_ - A subtitle for the notification, which will be displayed below the title.
*`body` string (optional) - The body text of the notification, which will be displayed below the title or subtitle.
*`silent` boolean (optional) - Whether or not to suppress the OS notification noise when showing the notification.
*`icon` (string | [NativeImage](native-image.md)) (optional) - An icon to use in the notification. If a string is passed, it must be a valid path to a local icon file.
*`hasReply` boolean (optional) _macOS_ - Whether or not to add an inline reply option to the notification.
*`hasReply` boolean (optional) _macOS__Windows_ - Whether or not to add an inline reply option to the notification.
*`timeoutType` string (optional) _Linux__Windows_ - The timeout duration of the notification. Can be 'default' or 'never'.
*`replyPlaceholder` string (optional) _macOS_ - The placeholder to write in the inline reply input field.
*`replyPlaceholder` string (optional) _macOS__Windows_ - The placeholder to write in the inline reply input field.
*`sound` string (optional) _macOS_ - The name of the sound file to play when the notification is shown.
*`urgency` string (optional) _Linux_ - The urgency level of the notification. Can be 'normal', 'critical', or 'low'.
*`actions` [NotificationAction[]](structures/notification-action.md) (optional) _macOS_ - Actions to add to the notification. Please read the available actions and limitations in the `NotificationAction` documentation.
*`urgency` string (optional) _Linux__Windows_ - The urgency level of the notification. Can be 'normal', 'critical', or 'low'.
*`actions` [NotificationAction[]](structures/notification-action.md) (optional) _macOS__Windows_ - Actions to add to the notification. Please read the available actions and limitations in the `NotificationAction` documentation.
*`closeButtonText` string (optional) _macOS_ - A custom title for the close button of an alert. An empty string will cause the default localized text to be used.
*`toastXml` string (optional) _Windows_ - A custom description of the Notification on Windows superseding all properties above. Provides full customization of design and behavior of the notification.
> [!NOTE]
> On Windows, `urgency` type 'critical' sorts the notification higher in Action Center (above default priority notifications), but does not prevent auto-dismissal. To prevent auto-dismissal, you should also set
> `timeoutType` to 'never'.
### Instance Events
Objects created with `new Notification` emit the following events:
A `string` property representing the unique identifier of the notification. This is set at construction time — either from the `id` option or as a generated UUID if none was provided.
A `string` property representing the group identifier of the notification. Notifications with the same `groupId` will be visually grouped together in Notification Center.
A `string` property representing the group identifier of the notification. Notifications with the same `groupId` will be visually grouped together in Notification Center (macOS) or Action Center (Windows).
The actual output pixel format and color space of the texture should refer to [`OffscreenSharedTexture`](../structures/offscreen-shared-texture.md) object in the `paint` event.
*`argb` - The requested output texture format is 8-bit unorm RGBA, with SRGB SDR color space.
*`rgbaf16` - The requested output texture format is 16-bit float RGBA, with scRGB HDR color space.
*`nv12` - The requested output texture format is 12bpp with Y plane followed by a 2x2 interleaved UV plane, with REC709 color space.
*`deviceScaleFactor` number (optional) _Experimental_ - The device scale factor of the offscreen rendering output. If not set, will use `1` as default.
*`contextIsolation` boolean (optional) - Whether to run Electron APIs and
the specified `preload` script in a separate JavaScript context. Defaults
* JavaScript will always be disabled in the opened `window` if it is disabled on
the parent window.
*Non-standard features (that are not handled by Chromium or Electron) given in
`features` will be passed to any registered `webContents`'s
`did-create-window` event handler in the `options` argument.
*Features that are not handled by Chromium and not in Electron's allowlist of
presentational `BrowserWindowConstructorOptions` are ignored. The raw
`features` string is still available to the main process via
`setWindowOpenHandler`.
*`frameName` follows the specification of `target` located in the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters).
* When opening `about:blank`, the child window's [`WebPreferences`](structures/web-preferences.md) will be copied
from the parent window, and there is no way to override it because Chromium
@@ -12,6 +12,34 @@ This document uses the following convention to categorize breaking changes:
* **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release.
* **Removed:** An API or feature was removed, and is no longer supported by Electron.
## Planned Breaking API Changes (43.0)
### Behavior Changed: Dialog methods default to Downloads directory
The `defaultPath` option for the following methods now defaults to the user's Downloads folder (or their home directory if Downloads doesn't exist) when not explicitly provided:
*`dialog.showOpenDialog`
*`dialog.showOpenDialogSync`
*`dialog.showSaveDialog`
*`dialog.showSaveDialogSync`
Previously, when no `defaultPath` was provided, the underlying OS file dialog would determine the initial directory — typically remembering the last directory the user navigated to, or falling back to an OS-specific default. Now, Electron explicitly sets the initial directory to Downloads, which also means the OS will no longer track and restore the last-used directory between dialog invocations.
To preserve the old behavior, you can track the last-used directory yourself and pass it as `defaultPath`:
```js
constpath=require('node:path')
letlastUsedPath
constresult=awaitdialog.showOpenDialog({
defaultPath:lastUsedPath
})
if(!result.canceled&&result.filePaths.length>0){
lastUsedPath=path.dirname(result.filePaths[0])
}
```
## Planned Breaking API Changes (42.0)
### Behavior Changed: macOS notifications now use `UNNotification` API
@@ -70,6 +98,9 @@ npm install electron --save-dev
ELECTRON_INSTALL_PLATFORM=mas npx electron . --no
```
This also means the `ELECTRON_SKIP_BINARY_DOWNLOAD` environment variable is no
longer supported, as its primary purpose was to prevent the `postinstall` script from running.
### Removed: `quotas` object from `Session.clearStorageData(options)`
When calling `Session.clearStorageData(options)`, the `options.quotas` object is no longer supported because it has been
Note that `git-import-patches` will mark the commit that was `HEAD` when it was run as `refs/patches/upstream-head`. This lets you keep track of which commits are from Electron patches (those that come after `refs/patches/upstream-head`) and which commits are in upstream (those before `refs/patches/upstream-head`).
Note that `git-import-patches` will mark the commit that was `HEAD` when it was run as `refs/patches/upstream-head` (and a checkout-specific `refs/patches/upstream-head-<hash>` so that gclient worktrees sharing a `.git/refs` directory don't clobber each other). This lets you keep track of which commits are from Electron patches (those that come after `refs/patches/upstream-head`) and which commits are in upstream (those before `refs/patches/upstream-head`).
@@ -1547,6 +1564,10 @@ class CppLinuxAddon extends EventEmitter {
return this.addon.helloGui()
}
destroy() {
this.addon.destroy()
}
// Parse JSON and convert date to JavaScript Date object
parse(payload) {
const parsed = JSON.parse(payload)
@@ -1569,8 +1590,12 @@ This wrapper:
* Only loads on Linux platforms
* Forwards events from C++ to JavaScript
* Provides clean methods to call into C++
* Provides a `destroy()` method to release native resources
* Converts JSON data into proper JavaScript objects
> [!IMPORTANT]
> You must call `destroy()` before the app quits (e.g. in the `will-quit` or `before-quit` event handler). Without this, persistent references to callbacks and the threadsafe function will prevent the native addon's destructor from running, causing Electron to hang on quit.
This allows JavaScript to register callbacks for specific event types.
This allows JavaScript to register callbacks for specific event types. The `Destroy` method releases all persistent references and aborts the threadsafe function, which must be called before the app quits to prevent the process from hanging.
@@ -1309,6 +1334,10 @@ class CppWin32Addon extends EventEmitter {
this.addon.helloGui()
}
destroy() {
this.addon.destroy()
}
#parse(payload) {
const parsed = JSON.parse(payload)
@@ -1323,6 +1352,9 @@ if (process.platform === 'win32') {
}
```
> [!IMPORTANT]
> You must call `destroy()` before the app quits (e.g. in the `will-quit` or `before-quit` event handler). Without this, persistent references to callbacks and the threadsafe function will prevent the native addon's destructor from running, causing Electron to hang on quit.
Let's take a look at what we've added in this step:
@@ -922,10 +935,11 @@ Let's take a look at what we've added in this step:
* `HelloWorld()`: Takes a string input, calls our Objective-C function, and returns the result
* `HelloGui()`: A simple wrapper around the Objective-C `hello_gui` function
* `On`: Allows JavaScript to register event listeners that will be called when native events occur
* `Destroy`: Releases all persistent references (callbacks and emitter) and aborts the threadsafe function, allowing the addon to be properly cleaned up on quit
The `On` method is particularly important as it creates the event system that our JavaScript code will use to receive notifications from the native UI.
Together, these three components form a complete bridge between our Objective-C code and the JavaScript world, allowing bidirectional communication. Here's what the finished file should look like:
Together, these four components form a complete bridge between our Objective-C code and the JavaScript world, allowing bidirectional communication. Here's what the finished file should look like:
@@ -1101,6 +1128,10 @@ class ObjcMacosAddon extends EventEmitter {
this.addon.helloGui()
}
destroy () {
this.addon.destroy()
}
parse (payload) {
const parsed = JSON.parse(payload)
@@ -1122,7 +1153,11 @@ This wrapper:
3. Loads the native addon
4. Sets up event listeners and forwards them
5. Provides a clean API for our functions
6. Parses JSON payloads and converts timestamps to JavaScript Date objects
6. Provides a `destroy()` method to release native resources
7. Parses JSON payloads and converts timestamps to JavaScript Date objects
> [!IMPORTANT]
> You must call `destroy()` before the app quits (e.g. in the `will-quit` or `before-quit` event handler). Without this, persistent references to callbacks and the threadsafe function will prevent the native addon's destructor from running, causing Electron to hang on quit.
@@ -934,7 +947,8 @@ This final part does multiple things:
2. The HelloWorld method implementation takes a string input from JavaScript, passes it to the Swift code, and returns the processed result back to the JavaScript environment.
3. The `HelloGui` method implementation provides a simple wrapper that calls the Swift UI creation function to display the native macOS window.
4. The `On` method implementation allows JavaScript code to register callback functions that will be invoked when specific events occur in the native Swift code.
5. The code sets up the module initialization process that registers the addon with Node.js and makes its functionality available to JavaScript.
5. The `Destroy` method releases all persistent references (callbacks and emitter) and aborts the threadsafe function. This must be called before the app quits to allow the destructor to run and prevent the process from hanging.
6. The code sets up the module initialization process that registers the addon with Node.js and makes its functionality available to JavaScript.
The final and full `src/swift_addon.mm` should look like:
@@ -1122,6 +1149,10 @@ class SwiftAddon extends EventEmitter {
this.addon.helloGui()
}
destroy () {
this.addon.destroy()
}
parse (payload) {
const parsed = JSON.parse(payload)
@@ -1143,7 +1174,11 @@ This wrapper:
3. Loads the native addon
4. Sets up event listeners and forwards them
5. Provides a clean API for our functions
6. Parses JSON payloads and converts timestamps to JavaScript Date objects
6. Provides a `destroy()` method to release native resources
7. Parses JSON payloads and converts timestamps to JavaScript Date objects
> [!IMPORTANT]
> You must call `destroy()` before the app quits (e.g. in the `will-quit` or `before-quit` event handler). Without this, persistent references to callbacks and the threadsafe function will prevent the native addon's destructor from running, causing Electron to hang on quit.
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.