electron-node-upgrade

electron/electron

Руководство по обновлению версии Node.js в проекте Electron: разрешение конфликтов патчей в ветке roller/node/main при `e sync --3`.

Звёзды123 962
Авторelectron
Установок60

Установка

SKILL.md

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)
  • ../third_party/electron_node: Node.js repo (where patches apply)
  • patches/node/: Patch files for Node.js
  • 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

CommandPurpose
e sync --3Clone deps and apply patches with 3-way merge
git am --continueContinue after resolving conflict (run in node repo)
e patches nodeExport commits from node repo to patch files
e patches allExport all patches from all targets
e patches node --commit-updatesExport patches and auto-commit trivial changes
e patches --list-targetsList targets and config paths

Patch System Mental Model

patches/node/*.patch  →  [e sync --3]  →  ../third_party/electron_node commits
                      ←  [e patches]   ←

When to Edit Patches

SituationAction
During active git am conflictFix in node repo, then git am --continue
Modifying patch outside conflictEdit .patch file directly
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
    • Commit them immediately with: git commit -am "chore: update patches (trivial only)"
  5. Return to step 1
  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

CommandPurpose
e build -k 999 -- --quietBuild Electron, continue on errors, suppress status lines
e build -t {target}.oBuild just one specific target to verify a fix
e start --versionValidate 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:<!-- -->
    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)

Electron Node.js Upgrade: Phase Three

Summary

Run the Node.js test suite via script/node-spec-runner.js, fix failing tests, and commit fixes until all tests pass. Certain tests are permanently disabled (listed in script/node-disabled-tests.json) and should not be run.

Run Phase Three immediately after Phase Two is complete.

Success Criteria

Phase Three is complete when:

  • node script/node-spec-runner.js --default exits with zero failures
  • All changes are committed per the commit guidelines

Do not stop until these criteria are met.

Context

Electron runs a subset of Node.js's upstream test suite using a custom runner (script/node-spec-runner.js). Tests are executed with the built Electron binary via ELECTRON_RUN_AS_NODE=true. Many tests need adaptation because Electron uses BoringSSL (not OpenSSL) and Chromium's V8 (which may differ from Node.js's bundled V8).

Key files:

  • script/node-spec-runner.js — Test runner script
  • script/node-disabled-tests.json — Permanently disabled tests (do not try to fix these)
  • ../third_party/electron_node/test/ — Node.js test files (where patches apply)
  • patches/node/fix_crypto_tests_to_run_with_bssl.patch — BoringSSL crypto test adaptations
  • patches/node/test_formally_mark_some_tests_as_flaky.patch — Flaky test list

Workflow

  1. Run node script/node-spec-runner.js --default from the electron repo
  2. If all tests pass → Phase Three is complete
  3. If tests fail:<!-- -->
    • Identify the failing test file(s) from the output
    • Analyze each failure (see "Common Failure Patterns" below)
    • Fix the test in ../third_party/electron_node/test/...
    • Re-run the specific failing test to verify: node script/node-spec-runner.js {test-path}
      • The test path is relative to the node test/ directory, e.g. test/parallel/test-crypto-key-objects-raw.js
      • Do NOT use --default when running specific tests — it adds the full suite flags
      • Do NOT run tests directly with ELECTRON_RUN_AS_NODE — the runner handles environment setup (e.g. temporarily switching package.json from ESM to CommonJS)
    • Commit the fix using the fixup workflow and commit guidelines
    • Return to step 1

Commands Reference

CommandPurpose
node script/node-spec-runner.js --defaultRun full Node.js test suite
node script/node-spec-runner.js test/parallel/test-foo.jsRun a single test
NODE_REGENERATE_SNAPSHOTS=1 node script/node-spec-runner.js test/test-runner/test-foo.mjsRegenerate snapshot for a snapshot-based test

Common Failure Patterns

BoringSSL incompatibilities

Electron builds Node.js against Chromium's BoringSSL instead of Node.js's bundled OpenSSL. As of the v24.18.0 roll this is wired up through a GN arg rather than large source patches:

# build/args/all.gn
# Build Node.js against Chromium's BoringSSL instead of node's bundled OpenSSL.
node_openssl_path = "//third_party/boringssl"

Upstream Node.js now supports building against BoringSSL natively (see nodejs/node commits 677ca7e76c9 and 61b20f60a39), so most of Electron's historical BoringSSL workarounds have been eliminated. During the v24.18.0 roll:

  • fix_crypto_tests_to_run_with_bssl.patch shrank from ~1100 lines to skipping just two test files.
  • fix_handle_boringssl_and_openssl_incompatibilities.patch dropped ~176 lines. What remains is C++-level shimming in deps/ncrypto/ncrypto.cc, src/crypto/crypto_{common,context,hash}.cc, src/env.h, src/node_metadata.h, and src/node_options.h.

Expect to delete these workarounds over time rather than grow them. Only add a guard when a feature is genuinely still missing from BoringSSL; upstream tests increasingly self-skip when process.features.openssl_is_boringssl is set, so no Electron change is needed.

Preferred guard for a still-unsupported feature — skip the whole test file at the top, and add it to fix_crypto_tests_to_run_with_bssl.patch:

if (process.features.openssl_is_boringssl) {
  common.skip('Skipping unsupported ML-DSA key tests');
}

For tests that can't be cleanly guarded inline, add the whole file to script/node-disabled-tests.json instead.

Still unsupported in Chromium's BoringSSL (as of v24.18.0):

FeatureCurrent handling
RSA-PSS keygen (deprecation path)file-level common.skip in test-crypto-keygen-deprecation
ML-DSA keysfile-level common.skip in test-crypto-pqc-key-objects-ml-dsa
ML-KEM keysdisabled in node-disabled-tests.json (test-crypto-pqc-key-objects-ml-kem)
FIPS modedisabled (test-crypto-fips)
Secure heapdisabled (test-crypto-secure-heap)
Stateless DHdisabled (test-crypto-dh-stateless)
Assorted keygen / WebCrypto keygendisabled (test-crypto-keygen, test-webcrypto-keygen, wpt/test-webcrypto)

Behavioral differences (assertion updates, not skips) — some errors just changed shape:

  • Creating a private key from an unsupported OKP (Ed448) JWK now throws Invalid JWK OKP key (previously Invalid JWK data); see nodejs/node#62499. Electron's spec/node-spec.ts assertion was loosened to /Invalid JWK/.

When you do need to guard a test, prefer a precise capability check (e.g. ciphers.includes('aes-128-ccm')) over a blanket process.features.openssl_is_boringssl check where the feature can be probed directly.

Snapshot test mismatches

Some tests compare output against committed .snapshot files using assert.strictEqual — these are NOT wildcard comparisons. When Chromium's V8 produces different output (e.g. different stack traces due to V8 enhancements), the snapshot must be regenerated:

NODE_REGENERATE_SNAPSHOTS=1 node script/node-spec-runner.js test/test-runner/test-foo.mjs

Then inspect the diff to verify the changes are expected, and commit the updated snapshot into the appropriate patch.

V8 behavioral differences

Chromium's V8 may be ahead of Node.js's bundled V8. This can cause:

  • Различные форматы трассировки стека (например, кадры асинхронного стека thenable)
  • Различные сообщения об ошибках
  • Функции, доступные в Chromium V8, которых нет в стандартном Node.js V8 (или наоборот)

Два типа исправлений тестов

A. Патч-исправления (наиболее частые при сбоях тестов)

Большинство исправлений тестов вносятся в существующие патчи в patches/node/. Используйте рабочий процесс fixup:

  1. Отредактируйте файл теста в ../third_party/electron_node/test/...
  2. Найдите соответствующий коммит патча: git log --oneline | grep -i "keyword"
    • Тесты Crypto/BoringSSL → fix crypto tests to run with bssl
    • Тесты снимков (snapshot) → конкретный патч снимка (например, test: accomodate V8 thenable)
    • Нестабильные тесты → test: formally mark some tests as flaky
  3. Создайте fixup-коммит:
    cd ../third_party/electron_node
    git add test/path/to/test.js
    git commit --fixup=<patch-commit-hash>
    GIT_SEQUENCE_EDITOR=: git rebase --autosquash --autostash -i <commit>^
    
  4. Экспорт: e patches node
  5. Прочитайте references/phase-three-commit-guidelines.md СЕЙЧАС, затем закоммитьте обновлённый файл патча.

B. Новые патчи (редко)

Создавайте новый патч только тогда, когда исправление не относится ни к одному существующему патчу. Коммит нового патча в ../third_party/electron_node должен содержать описание, объясняющее, почему патч существует и когда его можно удалить — это проверяется линтером.

Добавление в отключённые тесты

Добавляйте тест в script/node-disabled-tests.json as a крайняя мера — когда тест принципиально несовместим с архитектурой Electron (а не просто отличие BoringSSL, которое можно обойти проверкой). Тесты, отключённые здесь, полностью пропускаются и никогда не запускаются.

Важно: прочитайте перед коммитом

  • Перед ЛЮБЫМИ коммитами Фазы один: прочитайте references/phase-one-commit-guidelines.md
  • Перед ЛЮБЫМИ коммитами Фазы два: прочитайте references/phase-two-commit-guidelines.md
  • Перед ЛЮБЫМИ коммитами Фазы три: прочитайте references/phase-three-commit-guidelines.md

Патчи с высокой частотой изменений

Эти патчи стабильно требуют больше всего работы при обновлениях Node.js:

  • fix_handle_boringssl_and_openssl_incompatibilities.patch — Electron использует BoringSSL (через Chromium), тогда как Node.js ожидает OpenSSL. Исторически большой и сложный, этот патч был значительно сокращён после того как Node.js получил нативную поддержку BoringSSL (включается через node_openssl_path = "//third_party/boringssl" in build/args/all.gn). Он всё ещё обходит некоторые различия на уровне C++, и изменения API OpenSSL/ncrypto в upstream могут его сломать.
  • fix_crypto_tests_to_run_with_bssl.patch — Дополнение к предыдущему; адаптирует тесты crypto Node.js для BoringSSL. Также значительно сокращён теперь, когда тесты upstream сами пропускаются под BoringSSL — в основном он пропускает несколько всё ещё неподдерживаемых тестовых файлов. См. раздел «Несовместимости с BoringSSL» выше.
  • support_v8_sandboxed_pointers.patch — Поддержка указателей песочницы V8 требует тщательной адаптации при изменении API V8.
  • build_add_gn_build_files.patch — Патч файла сборки GN большой и затрагивает множество целей сборки. Изменения системы сборки в upstream часто конфликтуют.

Обновления мажорных версий

Переходы между мажорными версиями Node.js (например, v22 → v24) значительно сложнее, чем обновления патчей:

  1. Ожидайте удаления патчей. Electron использует V8 из Chromium, который часто опережает версию V8, поставляемую с Node.js. Многие патчи существуют для преодоления этого разрыва — обхода новых API V8, которые есть в V8 из Chromium, но отсутствуют в более старой V8 из Node.js. Когда Node.js переходит на более новую мажорную версию, его V8 догоняет Chromium, и эти связующие патчи можно удалить. При обновлении v22 → v24 по этой причине было удалено 17 патчей.
  2. Обновите @types/node in package.json в соответствии с новой мажорной версией.
  3. Регрессии после обновления ожидаемы. Даже после того как обновление влито, последующие PR с исправлениями для крайних случаев (обработка путей ESM, загрузка сертификатов, платформенно-специфичные проблемы) — это нормально.

Структура каталога навыка

У этого навыка есть дополнительные справочные файлы в references/:

  • patch-analysis.md - Как анализировать сбои патчей
  • phase-one-commit-guidelines.md - Формат коммитов для Фазы один
  • phase-two-commit-guidelines.md - Формат коммитов для Фазы два
  • phase-three-commit-guidelines.md - Формат коммитов для Фазы три

Читайте их, когда на них ссылаются в шагах рабочего процесса.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: electron-node-upgrade](https://darkplay.ru/ai/skills/electron-electron-electron-node-upgrade)

Описание

Руководство по обновлению версии Node.js в проекте Electron. Используется при работе в ветке roller/node/main для исправления конфликтов патчей во время `e sync --3`. Охватывает процесс применения патчей, разрешение конфликтов, анализ изменений в upstream Node.js, сборку, запуск набора тестов Node.js и правильное форматирование коммитов для исправлений патчей.

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Typescript Revieweraffaan-m · Ревьюер TypeScript/JavaScript: типы, async, безопасность Node/web.
225 587 ★
aws-transformanthropics · Миграция, модернизация и обновление кодовых баз на AWS: .NET Framework в .NET 8/10, COBOL…
100 комп.
expoanthropics · Официальные навыки Expo для создания, развёртывания, обновления и отладки приложений…
100 комп.
qdrant-skillsanthropics · Навыки для векторного поиска Qdrant: масштабирование, оптимизация производительности…
100 комп.
javascript-typescriptwshobson · Разработка на JavaScript и TypeScript с ES6+, Node.js, React и современными…
495 комп.
copilotkitcopilotkit · Навыки AI-агентов для CopilotKit — настройка, разработка, интеграция, отладка, обновление…
11 комп.
qdrant-skillsanthropics · Навыки агентов для векторного поиска Qdrant: масштабирование, оптимизация…
233 комп.
.NET Upgradegithub · Выполняет задачи по поддержке кода C#/.NET, включая очистку, модернизацию и устранение…
36 140 ★
Electron Code Review Mode Instructionsgithub · Режим код-ревью для приложения Electron с бэкендом на Node.js (main), фронтендом на…
36 140 ★
Legacy Analystanthropics · Глубоко изучает легаси-код: структура, зависимости, мёртвый код.
31 495 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8