The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): bound complete signing probes without patching fs
ethernet21ddd6a943ef
diff --git a/apps/desktop/scripts/fs-open-limit.cjs b/apps/desktop/scripts/fs-open-limit.cjsdeleted file mode 100644index 346a1eeac6f..00000000000--- a/apps/desktop/scripts/fs-open-limit.cjs+++ /dev/null@@ -1,153 +0,0 @@-// Bound how many fs.open calls are in flight at once, process-wide.-//-// WHY THIS EXISTS-//-// @electron/osx-sign decides what to sign by walking the whole .app-// (dist/util.js::walk). The walk recurses with-// `Promise.all(children.map(...))` and no concurrency bound, and every-// regular file it reaches is probed by isbinaryfile, which opens a-// descriptor. Peak descriptors therefore track the size of the tree, not-// any fixed budget.-//-// The bundled payload makes that fatal. site-packages/lark_oapi alone is-// 11,112 files, so signing died with:-//-// EMFILE: too many open files, open-// '.../agent-payload/site-packages/lark_oapi/api/im/v1/model/reaction.py'-//-// Raising `ulimit -n` also clears it, but only moves the ceiling: the-// walk still asks for as many descriptors as there are files, so the-// next payload growth hits the new limit. This caps the demand instead.-//-// WHAT IT PATCHES-//-// `fs.open` (callback form) and `fs.promises.open`. That covers the-// paths that actually consume descriptors here:-// - isbinaryfile captures `promisify(fs.open)` at module load, so the-// patch must be installed BEFORE it is required — hence --require.-// - fs.createReadStream routes through the public fs.open (verified).-//-// Deliberately NOT patched: openSync. A synchronous open cannot be-// queued without blocking the loop that would drain the queue, and it is-// self-limiting anyway — one at a time, by definition.-//-// WHY IT CANNOT DEADLOCK-//-// The slot is released when the open() call SETTLES, not when the-// descriptor is closed. A task holding ten descriptors occupies zero-// slots while it works, so "hold one, open another" always makes-// progress. Gating the descriptor's lifetime instead does deadlock —-// measured: 4 tasks each holding 1 fd and awaiting a second, under-// cap=2, never completes.-//-// Failures propagate unchanged: a rejected open releases its slot in-// `finally` and the original error reaches the caller. This changes-// timing only, never behavior.-//-// HERMES_FS_OPEN_LIMIT overrides the computed cap; 0 disables the patch.--'use strict'--const fs = require('fs')--// The cap must sit well BELOW the process's fd limit, not near it. The-// slot ends before read+close, so live descriptors can exceed LIMIT.-// The supplier test measures the actual walk, including isbinaryfile's-// late close callback; this is not a descriptor-lifetime bound. Leave room-// for Node's stdio, module loader, sockets and spawned children.-// Measured against the real walk: cap 100 fails at-// a 64 limit and passes at 256; cap 16 passes at 64.-//-// So: a quarter of the soft limit, clamped to a sane band. On the macOS-// default of 256 that is 64; on a raised limit it grows, keeping the-// walk fast; on a tiny limit it shrinks instead of guaranteeing EMFILE.-function defaultLimit() {- const override = Number(process.env.HERMES_FS_OPEN_LIMIT)- if (Number.isFinite(override) && override >= 0) return override- let soft = 0- try {- soft = process.report.getReport().userLimits.open_files.soft- } catch {- soft = 0- }- // `unlimited` reports as -1 (or a huge number); either way the clamp holds.- if (!Number.isFinite(soft) || soft <= 0) soft = 256- return Math.max(8, Math.min(512, Math.floor(soft / 4)))-}--const LIMIT = defaultLimit()--// A guard against double-install (nested spawns inheriting NODE_OPTIONS).-if (!globalThis.__hermesFsOpenLimited && LIMIT > 0) {- globalThis.__hermesFsOpenLimited = true-- let active = 0- /** @type {Array<() => void>} */- const queue = []-- const pump = () => {- while (active < LIMIT && queue.length > 0) {- active += 1- try {- queue.shift()()- } catch (err) {- // Invalid arguments never install a completion callback.- active -= 1- queueMicrotask(pump)- throw err- }- }- }-- const release = () => {- active -= 1- // A queued validation error must not suppress the completed callback.- queueMicrotask(pump)- }-- // ── fs.open (callback form) ───────────────────────────────────────- const realOpen = fs.open- fs.open = function open(...args) {- const cb = args[args.length - 1]- if (typeof cb !== 'function') {- // No callback: not the async form we can queue (and node throws on- // it anyway). Hand it straight to the real implementation.- return realOpen.apply(this, args)- }- const rest = args.slice(0, -1)- queue.push(() => {- realOpen.call(fs, ...rest, function (...cbArgs) {- // Release BEFORE the callback runs: the descriptor is open, this- // call is done, and the caller may synchronously open another.- release()- cb.apply(this, cbArgs)- })- })- pump()- return undefined- }- // promisify(fs.open) reads these off the function it is handed.- Object.defineProperty(fs.open, 'name', { value: 'open' })- if (realOpen[Symbol.for('nodejs.util.promisify.custom')]) {- fs.open[Symbol.for('nodejs.util.promisify.custom')] =- realOpen[Symbol.for('nodejs.util.promisify.custom')]- }-- // ── fs.promises.open ──────────────────────────────────────────────- const realPromisesOpen = fs.promises.open- fs.promises.open = function open(...args) {- return new Promise((resolve, reject) => {- queue.push(() => {- realPromisesOpen- .apply(fs.promises, args)- .then(resolve, reject)- .finally(release)- })- pump()- })- }-- if (process.env.HERMES_FS_OPEN_LIMIT_DEBUG) {- console.log(`[fs-open-limit] fs.open concurrency capped at ${LIMIT}`)- }-}diff --git a/apps/desktop/scripts/fs-open-limit.test.mjs b/apps/desktop/scripts/fs-open-limit.test.mjsdeleted file mode 100644index 8a7ed363387..00000000000--- a/apps/desktop/scripts/fs-open-limit.test.mjs+++ /dev/null@@ -1,253 +0,0 @@-import assert from 'node:assert/strict'-import { spawnSync } from 'node:child_process'-import fs from 'node:fs'-import { createRequire } from 'node:module'-import os from 'node:os'-import path from 'node:path'-import { pathToFileURL } from 'node:url'-import { test } from 'vitest'--// ─── fs-open-limit.cjs ─────────────────────────────────────────────-//-// The preload caps concurrent fs.open calls so @electron/osx-sign's-// unbounded walk cannot exhaust the descriptor table (EMFILE during mac-// signing). These tests run REAL node processes against REAL trees with a-// REAL low `ulimit -n`, because the whole contract is "does this survive-// a descriptor limit" — a mocked fs would prove nothing.--const PRELOAD = path.join(import.meta.dirname, 'fs-open-limit.cjs')-const POSIX = process.platform !== 'win32'-const require = createRequire(import.meta.url)-const supplierWalk = pathToFileURL(path.join(path.dirname(require.resolve('@electron/osx-sign')), 'util.js')).href--/** Run `body` in a child node process, optionally with the preload + a soft fd limit. */-function runNode(body, { preload = false, ulimit = null, env = {} } = {}) {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fsopen-test-'))- const script = path.join(dir, 'body.mjs')- fs.writeFileSync(script, body)- const childEnv = { ...process.env, NODE_OPTIONS: '', ...env }- delete childEnv.HERMES_FS_OPEN_LIMIT_DEBUG- if (!Object.hasOwn(env, 'HERMES_FS_OPEN_LIMIT')) delete childEnv.HERMES_FS_OPEN_LIMIT- const nodeArgs = preload ? ['--require', PRELOAD, script] : [script]- // ulimit needs a shell; keep the arg vector explicit either way.- const cmd = ulimit- ? `ulimit -n ${ulimit} || exit; exec "$0" ${nodeArgs.map((a) => `'${a}'`).join(' ')}`- : null- const res = cmd- ? spawnSync('/bin/sh', ['-c', cmd, process.execPath], { encoding: 'utf8', env: childEnv, timeout: 15000 })- : spawnSync(process.execPath, nodeArgs, { encoding: 'utf8', env: childEnv, timeout: 15000 })- fs.rmSync(dir, { recursive: true, force: true })- return res-}--/** Build a tree big enough to exhaust a low fd limit, like the payload does. */-function mkTree(fileCount) {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fsopen-tree-'))- for (let i = 0; i < fileCount; i++) {- const d = path.join(root, `pkg${i % 40}`, `mod${i % 15}`)- fs.mkdirSync(d, { recursive: true })- fs.writeFileSync(path.join(d, `f${i}.py`), '# python\n')- }- return root-}--// Import the installed supplier: a lookalike walk cannot prove that its-// isbinaryfile dependency's actual descriptor lifetime is protected.-const WALK_BODY = (root) => `-import fs from 'node:fs'-import path from 'node:path'-const root = ${JSON.stringify(root)}-const framework = path.join(root, 'Child.app/Contents/Demo.framework')-fs.mkdirSync(framework, { recursive: true })-fs.writeFileSync(path.join(framework, 'Demo'), Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0]))-fs.writeFileSync(path.join(root, 'old.cstemp'), 'temporary signature')-const link = path.join(root, 'framework-link')-if (!fs.existsSync(link)) fs.symlinkSync(framework, link)--let live = 0, peak = 0, opens = 0-const open = fs.open, close = fs.close-fs.open = function (...args) {- const callback = args.pop()- return open.call(fs, ...args, (error, fd) => {- if (!error) { live++; opens++; peak = Math.max(peak, live) }- callback(error, fd)- })-}-fs.close = function (fd, callback) {- return close.call(fs, fd, error => {- if (!error) live--- callback(error)- })-}-const { walk } = await import(${JSON.stringify(supplierWalk)})-const selected = await walk(root)-// isbinaryfile resolves before its close callback; drain without a timed sleep.-while (live) await new Promise(resolve => setImmediate(resolve))-console.log(JSON.stringify({ selected: selected.map(p => path.relative(root, p)), opens, peak, live,- tempRemoved: !fs.existsSync(path.join(root, 'old.cstemp')) }))-`--test.skipIf(!POSIX)('the real supplier walk survives a low fd limit without changing signing candidates', () => {- const tree = mkTree(3000)- try {- const unbounded = runNode(WALK_BODY(tree), { ulimit: 64 })- assert.notEqual(unbounded.status, 0)- assert.match(unbounded.stderr, /EMFILE/)- const reference = runNode(WALK_BODY(tree), { ulimit: 4096 })- const limited = runNode(WALK_BODY(tree), { preload: true, ulimit: 64 })- assert.equal(reference.status, 0, reference.error?.message || reference.stderr)- assert.equal(limited.status, 0, limited.error?.message || limited.stderr)- const before = JSON.parse(reference.stdout)- const after = JSON.parse(limited.stdout)- assert.deepEqual(after.selected, before.selected)- assert.deepEqual(after.selected, [- 'Child.app/Contents/Demo.framework/Demo', 'Child.app/Contents/Demo.framework', 'Child.app',- ])- assert.equal(after.opens, 3001)- assert.equal(after.live, 0)- assert.equal(after.tempRemoved, true)- assert.ok(after.peak < 64, JSON.stringify(after))- assert.ok(before.peak > after.peak, JSON.stringify({ before, after }))- } finally {- fs.rmSync(tree, { recursive: true, force: true })- }-})--test.skipIf(!POSIX)('both fs.open forms are queued, so a huge fan-out survives', () => {- // isbinaryfile uses promisify(fs.open); other packaging callers may use- // fs.promises.open. Both public interfaces remain covered by the preload.- //- // Each iteration opens AND CLOSES before the next needs a descriptor,- // which is the shape the cap can actually satisfy. (Holding 400- // descriptors live at once is impossible under a 64 fd limit no matter- // how the opens are scheduled — an earlier version of this test asked- // for exactly that and failed for its own reasons, not the patch's.)- const body = `-import fs from 'node:fs'-import os from 'node:os'-import path from 'node:path'-const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'peak-'))-for (let i = 0; i < 400; i++) fs.writeFileSync(path.join(dir, 'f' + i), 'x')--// promise form: 400 concurrent open+close cycles.-await Promise.all(Array.from({length: 400}, async (_, i) => {- const fh = await fs.promises.open(path.join(dir, 'f' + i), 'r')- await fh.close()-}))--// callback form: same fan-out, through promisify like isbinaryfile does.-import { promisify } from 'node:util'-const openAsync = promisify(fs.open)-const closeAsync = promisify(fs.close)-await Promise.all(Array.from({length: 400}, async (_, i) => {- const fd = await openAsync(path.join(dir, 'f' + i), 'r')- await closeAsync(fd)-}))--fs.rmSync(dir, { recursive: true, force: true })-console.log('BOTH_FORMS_OK')-`- const res = runNode(body, { preload: true, ulimit: 64 })- assert.equal(res.status, 0, `failed: ${res.stderr.slice(0, 400)}`)- assert.match(res.stdout, /BOTH_FORMS_OK/)-})--test.skipIf(!POSIX)('the callback fan-out DOES fail without the preload', () => {- // Guards the test above: if 400 open+close cycles were survivable- // unpatched, it would prove nothing about the queue.- const body = `-import fs from 'node:fs'-import os from 'node:os'-import path from 'node:path'-import { promisify } from 'node:util'-const openAsync = promisify(fs.open)-const closeAsync = promisify(fs.close)-const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'peak-raw-'))-for (let i = 0; i < 400; i++) fs.writeFileSync(path.join(dir, 'f' + i), 'x')-await Promise.all(Array.from({length: 400}, async (_, i) => {- const fd = await openAsync(path.join(dir, 'f' + i), 'r')- await closeAsync(fd)-}))-console.log('UNEXPECTEDLY_OK')-`- const res = runNode(body, { ulimit: 64 })- assert.notEqual(res.status, 0, 'unpatched fan-out should exhaust the fd table')- assert.match(res.stderr, /EMFILE/)-})--test('open errors still reach the caller unchanged', () => {- const body = `-import fs from 'node:fs'-let promiseErr = null, cbErr = null-try { await fs.promises.open('/definitely/not/here', 'r') } catch (e) { promiseErr = e }-await new Promise((res) => fs.open('/definitely/not/here', 'r', (e) => { cbErr = e; res() }))-if (promiseErr?.code !== 'ENOENT') throw new Error('promise form lost the error: ' + promiseErr?.code)-if (cbErr?.code !== 'ENOENT') throw new Error('callback form lost the error: ' + cbErr?.code)-console.log('ERRORS_PROPAGATE')-`- const res = runNode(body, { preload: true })- assert.equal(res.status, 0, res.stderr.slice(0, 400))- assert.match(res.stdout, /ERRORS_PROPAGATE/)-})--test('a rejected open releases its slot instead of wedging the queue', () => {- // If the failure path forgot to release, the queue drains to zero- // permanently and this hangs rather than failing.- const body = `-import fs from 'node:fs'-import os from 'node:os'-import path from 'node:path'-const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rej-'))-fs.writeFileSync(path.join(dir, 'real'), 'x')-// 300 failures (more than the cap of 100) then a real open.-await Promise.all(Array.from({length: 300}, () =>- fs.promises.open(path.join(dir, 'missing'), 'r').catch(() => null)))-const fh = await fs.promises.open(path.join(dir, 'real'), 'r')-await fh.close()-fs.rmSync(dir, { recursive: true, force: true })-console.log('QUEUE_STILL_LIVE')-`- const res = runNode(body, { preload: true })- assert.equal(res.status, 0, res.stderr.slice(0, 400))- assert.match(res.stdout, /QUEUE_STILL_LIVE/)-})--test.skipIf(!POSIX)('holding descriptors while opening more cannot deadlock', () => {- // The slot is released when open() SETTLES, not when the fd closes, so a- // task holding many descriptors occupies no slots. Gating the fd lifetime- // instead deadlocks — that is the design this asserts against.- const body = `-import fs from 'node:fs'-import os from 'node:os'-import path from 'node:path'-const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hold-'))-for (let i = 0; i < 600; i++) fs.writeFileSync(path.join(dir, 'f' + i), 'x')-// 200 tasks (> the cap of 100) each holding one fd, then asking for two more.-const held = []-await Promise.all(Array.from({length: 200}, (_, i) => (async () => {- const a = await fs.promises.open(path.join(dir, 'f' + i), 'r')- const b = await fs.promises.open(path.join(dir, 'f' + (i + 200)), 'r')- const c = await fs.promises.open(path.join(dir, 'f' + (i + 400)), 'r')- held.push(a, b, c)-})()))-for (const h of held) await h.close()-fs.rmSync(dir, { recursive: true, force: true })-console.log('NO_DEADLOCK')-`- const res = runNode(body, { preload: true, ulimit: 1024 })- assert.equal(res.status, 0, res.stderr.slice(0, 400))- assert.match(res.stdout, /NO_DEADLOCK/)-})--test('HERMES_FS_OPEN_LIMIT=0 disables the patch', () => {- // An escape hatch that must genuinely leave fs.open alone.- const body = `-import fs from 'node:fs'-if (fs.open.name !== 'open') throw new Error('unexpected name')-if (globalThis.__hermesFsOpenLimited) throw new Error('patch installed despite limit 0')-console.log('DISABLED_OK')-`- const res = runNode(body, { preload: true, env: { HERMES_FS_OPEN_LIMIT: '0' } })- assert.equal(res.status, 0, res.stderr.slice(0, 400))- assert.match(res.stdout, /DISABLED_OK/)-})diff --git a/apps/desktop/scripts/fs-open-sync-throw.test.mjs b/apps/desktop/scripts/fs-open-sync-throw.test.mjsdeleted file mode 100644index c594b127d99..00000000000--- a/apps/desktop/scripts/fs-open-sync-throw.test.mjs+++ /dev/null@@ -1,72 +0,0 @@-import assert from 'node:assert/strict'-import { spawnSync } from 'node:child_process'-import fs from 'node:fs'-import os from 'node:os'-import path from 'node:path'-import { test } from 'vitest'--const PRELOAD = path.join(import.meta.dirname, 'fs-open-limit.cjs')--function runNode(body) {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fsopen-sync-'))- const script = path.join(dir, 'body.mjs')- try {- fs.writeFileSync(script, body)- return spawnSync(process.execPath, ['--require', PRELOAD, script], {- cwd: dir,- encoding: 'utf8',- timeout: 15000,- env: { ...process.env, NODE_OPTIONS: '', HERMES_FS_OPEN_LIMIT: '1' },- })- } finally {- fs.rmSync(dir, { recursive: true, force: true })- }-}--test('immediate validation errors preserve throws and rejections without consuming slots', () => {- const result = runNode(`-import assert from 'node:assert/strict'-import fs from 'node:fs'-for (let i = 0; i < 3; i++) {- assert.throws(() => fs.open(1, 'r', () => {}), { code: 'ERR_INVALID_ARG_TYPE' })-}-await assert.rejects(fs.promises.open(1, 'r'), { code: 'ERR_INVALID_ARG_TYPE' })-const file = await fs.promises.open(new URL(import.meta.url), 'r')-await file.close()-console.log('SLOTS_RELEASED')-`)- assert.equal(result.status, 0, result.error?.message || result.stderr)- assert.match(result.stdout, /SLOTS_RELEASED/)-})--test('a deferred validation throw cannot suppress a settled callback or strand queued work', () => {- const result = runNode(`-import assert from 'node:assert/strict'-import fs from 'node:fs'-const errors = []-const completed = []-process.on('uncaughtException', error => { errors.push(error) })-function open(name) {- return new Promise((resolve, reject) => {- fs.open(new URL(import.meta.url), 'r', (error, fd) => {- if (error) { reject(error); return }- fs.close(fd, closeError => {- if (closeError) { reject(closeError); return }- completed.push(name)- resolve()- })- })- })-}-const first = open('first')-fs.open(1, 'r', () => { throw new Error('validation must throw, not call back') })-const last = open('last')-await Promise.all([first, last])-assert.equal(errors.length, 1)-assert.equal(errors[0].code, 'ERR_INVALID_ARG_TYPE')-assert.deepEqual(completed.sort(), ['first', 'last'])-console.log('QUEUE_DRAINED')-`)- assert.equal(result.status, 0, result.error?.message || result.stderr)- assert.match(result.stdout, /QUEUE_DRAINED/)-})diff --git a/apps/desktop/scripts/patch-electron-builder-mac-binary.mjs b/apps/desktop/scripts/patch-electron-builder-mac-binary.mjsindex 6cfa41f32ec..a81fe15d481 100644--- a/apps/desktop/scripts/patch-electron-builder-mac-binary.mjs+++ b/apps/desktop/scripts/patch-electron-builder-mac-binary.mjs@@ -1,64 +1,62 @@+// Loaded in the builder child before osx-sign. Keep its walk and classifier,+// but own each probe through close: isbinaryfile's path API resolves too early.+// The prebuilder lifecycle also imports this file to validate the supplier pins.import fs from 'node:fs'import path from 'node:path'+import { createRequire, registerHooks } from 'node:module'+import { pathToFileURL } from 'node:url'-if (process.platform !== 'darwin') {- process.exit(0)+const require = createRequire(import.meta.url)+const signerEntry = require.resolve('@electron/osx-sign')+const signerRequire = createRequire(signerEntry)+const binaryEntry = signerRequire.resolve('isbinaryfile')+const signerVersion = JSON.parse(fs.readFileSync(path.resolve(path.dirname(signerEntry), '../package.json'), 'utf8')).version+const binaryVersion = JSON.parse(fs.readFileSync(path.resolve(path.dirname(binaryEntry), '../package.json'), 'utf8')).version+if (signerVersion !== '2.4.0' || binaryVersion !== '5.0.7') {+ throw new Error('Revalidate signing probe ownership for the installed osx-sign/isbinaryfile versions')}-const desktopRoot = path.resolve(import.meta.dirname, '..')-const repoRoot = path.resolve(desktopRoot, '..', '..')-const electronMacPath = path.join(repoRoot, 'node_modules', 'app-builder-lib', 'out', 'electron', 'electronMac.js')--const marker = 'hermes-macos-electron-binary-fallback'-const needle = ` await Promise.all([- doRename(path.join(contentsPath, "MacOS"), electronBranding.productName, appPlist.CFBundleExecutable),- (0, builder_util_1.unlinkIfExists)(path.join(appOutDir, "LICENSE")),- (0, builder_util_1.unlinkIfExists)(path.join(appOutDir, "LICENSES.chromium.html")),- ]);`-const replacement = ` // ${marker}: electron-builder 26.8.x can sometimes copy- // Electron.app without its main MacOS/Electron binary before this rename.- // Restore it from the installed Electron runtime so local desktop installs- // do not fail with ENOENT during macOS arm64 packaging.- const macosDir = path.join(contentsPath, "MacOS");- const bundledElectronBinary = path.join(macosDir, electronBranding.productName);- if (!fs.existsSync(bundledElectronBinary)) {- const candidates = [- path.join(packager.info.framework.distMacOsAppName, "Contents", "MacOS", electronBranding.productName),- // npm may nest the workspace-only electron devDep under- // apps/desktop/node_modules (process.cwd() during pack), or hoist- // it to the repo root. Try the workspace-local install first, then- // the root hoist, so the fallback works under either layout.- path.join(process.cwd(), "node_modules", "electron", "dist", "Electron.app", "Contents", "MacOS", electronBranding.productName),- path.join(process.cwd(), "..", "..", "node_modules", "electron", "dist", "Electron.app", "Contents", "MacOS", electronBranding.productName),- ];- const sourceBinary = candidates.find(candidate => fs.existsSync(candidate));- if (sourceBinary == null) {- throw new Error("Electron binary missing from packaged app and Electron runtime: " + bundledElectronBinary);+const utilUrl = pathToFileURL(path.join(path.dirname(signerEntry), 'util.js')).href+const needle = `async function getFilePathIfBinary(filePath) {+ if (await isBinaryFile(filePath)) {+ return filePath;+ }+ return null;+}`+const replacement = `// Shared by concurrent walks in this builder child, never by unrelated fs users.+const probeWaiters = [];+let activeProbes = 0;+async function getFilePathIfBinary(filePath) {+ // Sixteen complete probes leave room for Node and codesign at a 64-fd limit.+ if (activeProbes >= 16) await new Promise(resolve => probeWaiters.push(resolve));+ else activeProbes++;+ try {+ const stat = await fs.promises.stat(filePath);+ if (!stat.isFile()) throw new Error('Path provided was not a file!');+ const file = await fs.promises.open(filePath, 'r');+ try {+ // Match isbinaryfile 5.0.7's sample, including its UTF-8 boundary reserve.+ const buffer = Buffer.alloc(515);+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);+ return await isBinaryFile(buffer, bytesRead) ? filePath : null;+ } finally {+ await file.close();}- await (0, promises_1.copyFile)(sourceBinary, bundledElectronBinary);- await (0, promises_1.chmod)(bundledElectronBinary, 0o755);+ } finally {+ const next = probeWaiters.shift();+ if (next) next();+ else activeProbes--;}- await Promise.all([- doRename(macosDir, electronBranding.productName, appPlist.CFBundleExecutable),- (0, builder_util_1.unlinkIfExists)(path.join(appOutDir, "LICENSE")),- (0, builder_util_1.unlinkIfExists)(path.join(appOutDir, "LICENSES.chromium.html")),- ]);`--if (!fs.existsSync(electronMacPath)) {- console.warn(`[patch-electron-builder] skipped: ${electronMacPath} not found`)- process.exit(0)-}--const source = fs.readFileSync(electronMacPath, 'utf8')-if (source.includes(marker)) {- console.log('[patch-electron-builder] macOS Electron binary fallback already applied')- process.exit(0)-}--if (!source.includes(needle)) {- console.warn('[patch-electron-builder] skipped: expected electronMac.js shape not found')- process.exit(0)-}+}`-fs.writeFileSync(electronMacPath, source.replace(needle, replacement))-console.log('[patch-electron-builder] applied macOS Electron binary fallback')+// Transform just the private supplier helper in memory; never mutate node_modules+// or fs.open. An upstream shape change must fail instead of silently losing the cap.+registerHooks({+ load(url, context, nextLoad) {+ const loaded = nextLoad(url, context)+ if (url !== utilUrl) return loaded+ const source = loaded.source.toString()+ if (!source.includes(needle)) throw new Error('osx-sign binary probe shape changed; revalidate the signing adapter')+ return { ...loaded, source: source.replace(needle, replacement) }+ }+})\ No newline at end of filediff --git a/apps/desktop/scripts/run-electron-builder.mjs b/apps/desktop/scripts/run-electron-builder.mjsindex 9e585af00cb..7f9ea8a40fd 100644--- a/apps/desktop/scripts/run-electron-builder.mjs+++ b/apps/desktop/scripts/run-electron-builder.mjs@@ -86,14 +86,10 @@ if (args.includes('--win') && process.env.AZURE_SIGN_ENDPOINT && process.env.AZU)}-// Cap concurrent fs.open calls in the electron-builder process.-// @electron/osx-sign walks the whole .app with Promise.all and no-// concurrency bound. The payload (lark_oapi alone is thousands of files)-// exhausts the macOS table: EMFILE on a random .py. Raising ulimit only-// moves the ceiling. --require, not an import: isbinaryfile captures-// promisify(fs.open) at its own load.-const preloads = ['--require', path.join(import.meta.dirname, 'fs-open-limit.cjs')]+const preloads = []if (process.platform === 'darwin') {+ // Install the supplier-only probe owner before electron-builder imports osx-sign.+ preloads.push('--import', path.join(import.meta.dirname, 'patch-electron-builder-mac-binary.mjs'))preloads.push('--require', path.join(import.meta.dirname, 'dmgbuild-diagnostics.cjs'))}diff --git a/apps/desktop/scripts/signing-resources.test.mjs b/apps/desktop/scripts/signing-resources.test.mjsnew file mode 100644index 00000000000..6890d44b8f6--- /dev/null+++ b/apps/desktop/scripts/signing-resources.test.mjs@@ -0,0 +1,179 @@+import assert from 'node:assert/strict'+import { execFileSync, spawnSync } from 'node:child_process'+import fs from 'node:fs'+import { createRequire } from 'node:module'+import os from 'node:os'+import path from 'node:path'+import { pathToFileURL } from 'node:url'+import { test } from 'vitest'++const require = createRequire(import.meta.url)+const adapter = path.join(import.meta.dirname, 'patch-electron-builder-mac-binary.mjs')+const supplier = path.dirname(require.resolve('@electron/osx-sign'))+const walkUrl = pathToFileURL(path.join(supplier, 'util.js')).href+const signUrl = pathToFileURL(path.join(supplier, 'index.js')).href++function run(root, body, { patched = true, limit = 64 } = {}) {+ const script = path.join(root, 'probe.mjs')+ fs.writeFileSync(script, body)+ const args = [...(patched ? ['--import', adapter] : []), script]+ const result = spawnSync('/bin/sh', ['-c',+ `ulimit -S -n ${limit} && ulimit -H -n ${limit} && exec "$@"`, 'signing-probe', process.execPath, ...args], {+ encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '', DEBUG: '' }, timeout: 30000+ })+ assert.ifError(result.error)+ return result+}++function fixture(root) {+ const app = path.join(root, 'Probe.app')+ const child = path.join(app, 'Contents/Frameworks/Child.app')+ const framework = path.join(child, 'Contents/Frameworks/Demo.framework')+ const binaries = [path.join(app, 'Contents/MacOS/Probe'), path.join(child, 'Contents/MacOS/Child'),+ path.join(framework, 'Versions/A/Demo')]+ for (const binary of binaries) {+ fs.mkdirSync(path.dirname(binary), { recursive: true })+ fs.writeFileSync(binary, Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0]))+ }+ fs.symlinkSync('A', path.join(framework, 'Versions/Current'))+ fs.symlinkSync('Versions/Current/Demo', path.join(framework, 'Demo'))+ fs.symlinkSync('Frameworks/Child.app', path.join(app, 'Contents/child-link'))+ fs.symlinkSync('missing', path.join(app, 'Contents/broken-link'))+ for (let i = 0; i < 3000; i++) {+ const dir = path.join(app, 'Contents/Resources', `pkg${i % 40}`, `mod${i % 15}`)+ fs.mkdirSync(dir, { recursive: true })+ fs.writeFileSync(path.join(dir, `f${i}.py`), '# text resource\n')+ }+ // Exercise the exact supplier classifier, including its 3-byte UTF-8 reserve.+ const resources = path.join(app, 'Contents/Resources')+ fs.writeFileSync(path.join(resources, 'utf8.txt'), 'a'.repeat(511) + '😀')+ fs.writeFileSync(path.join(resources, 'empty'), '')+ fs.writeFileSync(path.join(resources, 'pdf'), '%PDF-1.0\n')+ if (process.platform === 'darwin') {+ const plist = require('plist')+ fs.writeFileSync(path.join(root, 'main.c'), 'int main(void) { return 0; }\n')+ for (const binary of binaries) execFileSync('/usr/bin/clang', [path.join(root, 'main.c'),+ ...(binary === binaries[2] ? ['-dynamiclib'] : []), '-o', binary])+ for (const [dir, name, type] of [[app, 'Probe', 'APPL'], [child, 'Child', 'APPL'], [framework, 'Demo', 'FMWK']]) {+ const info = type === 'APPL' ? path.join(dir, 'Contents/Info.plist') : path.join(dir, 'Versions/A/Resources/Info.plist')+ fs.mkdirSync(path.dirname(info), { recursive: true })+ fs.writeFileSync(info, plist.build({ CFBundleExecutable: name, CFBundleIdentifier: `org.hermes.fixture.${name}`,+ CFBundleVersion: '1', CFBundlePackageType: type }))+ }+ fs.symlinkSync('Versions/Current/Resources', path.join(framework, 'Resources'))+ }+ return app+}++const tracking = `+import assert from 'node:assert/strict'+import fs from 'node:fs'+import path from 'node:path'+let live = 0, peak = 0+const opened = () => { live++; peak = Math.max(peak, live) }+const open = fs.open, close = fs.close, promisesOpen = fs.promises.open+fs.open = function (...args) {+ const cb = args.pop()+ return open.call(fs, ...args, (error, fd) => { if (!error) opened(); cb(error, fd) })+}+fs.close = function (fd, cb) {+ return close.call(fs, fd, error => { if (!error) live--; cb(error) })+}+fs.promises.open = async function (...args) {+ const handle = await promisesOpen.apply(fs.promises, args)+ opened()+ const closeHandle = handle.close.bind(handle)+ handle.close = async () => { await closeHandle(); live-- }+ return handle+}+const { walk } = await import(${JSON.stringify(walkUrl)})+`++test.skipIf(process.platform === 'win32')('bounded probes preserve real supplier candidates and native nested signatures at a low fd limit', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'signing-resources-'))+ try {+ const app = fixture(root)+ const body = `${tracking}+const app = ${JSON.stringify(app)}, contents = path.join(app, 'Contents')+fs.writeFileSync(path.join(contents, 'old.cstemp'), 'stale signature')+const selected = await walk(contents)+while (live) await new Promise(resolve => setImmediate(resolve))+assert.ok(!fs.existsSync(path.join(contents, 'old.cstemp')))+const signed = []+if (process.platform === 'darwin') {+ // The walk excludes dangling links; strict codesign correctly rejects them.+ fs.rmSync(path.join(contents, 'broken-link'), { force: true })+ const { sign } = await import(${JSON.stringify(signUrl)})+ await sign({ app, platform: 'darwin', identity: '-', identityValidation: false,+ preAutoEntitlements: false, preEmbedProvisioningProfile: false, strictVerify: true,+ batchCodesignCalls: false, ignore: file => file.endsWith('/pdf'),+ optionsForFile(file) { signed.push(file); return { timestamp: 'none', hardenedRuntime: true } } })+}+console.log(JSON.stringify({ selected, signed, peak, live }))+`+ const raw = run(root, body, { patched: false })+ assert.notEqual(raw.status, 0)+ assert.match(raw.stderr, /EMFILE/)+ const reference = run(root, body, { patched: false, limit: 4096 })+ assert.equal(reference.status, 0, reference.stderr)+ // Remove signatures from the native reference before the identical second run.+ fs.rmSync(app, { recursive: true })+ fixture(root)+ const limited = run(root, body)+ assert.equal(limited.status, 0, limited.stderr)+ const before = JSON.parse(reference.stdout), after = JSON.parse(limited.stdout)+ assert.deepEqual(after.selected, before.selected)+ assert.deepEqual(after.signed, before.signed)+ assert.ok(after.selected.some(file => file.endsWith('/Demo.framework')))+ assert.ok(after.selected.some(file => file.endsWith('/Child.app')))+ assert.ok(after.selected.every(file => !file.includes('link') && !file.includes('utf8.txt')))+ assert.ok(after.peak <= 16, JSON.stringify(after))+ assert.ok(before.peak > after.peak)+ assert.equal(after.live, 0)+ if (process.platform === 'darwin') execFileSync('/usr/bin/codesign', ['--verify', '--deep', '--strict', app])+ } finally { fs.rmSync(root, { recursive: true, force: true }) }+}, 60000)++test.skipIf(process.platform === 'win32')('probe errors release complete operations and concurrent walks share the bound without patching fs', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'signing-errors-'))+ try {+ const tree = path.join(root, 'tree')+ fs.mkdirSync(tree)+ for (let i = 0; i < 100; i++) fs.writeFileSync(path.join(tree, `f${i}`), 'text')+ const result = run(root, `+import assert from 'node:assert/strict'+import fs from 'node:fs'+const originalOpen = fs.open, originalPromisesOpen = fs.promises.open+await import(${JSON.stringify(pathToFileURL(adapter).href)})+assert.equal(fs.open, originalOpen)+assert.equal(fs.promises.open, originalPromisesOpen)+${tracking.replaceAll("import assert from 'node:assert/strict'", '').replaceAll("import fs from 'node:fs'", '')}+const tree = ${JSON.stringify(tree)}+await assert.rejects(walk(tree + '/missing'), { code: 'ENOENT' })+const measuredOpen = fs.promises.open+let failed = false+fs.promises.open = async (...args) => {+ if (!failed) { failed = true; throw Object.assign(new Error('open failure'), { code: 'EACCES' }) }+ return measuredOpen(...args)+}+await assert.rejects(walk(tree), { code: 'EACCES' })+// Drain the rest of Promise.all by completing a second walk through the same queue.+assert.deepEqual(await walk(tree), [])+failed = false+fs.promises.open = async (...args) => {+ const handle = await measuredOpen(...args)+ if (!failed) { failed = true; handle.read = async () => { throw Object.assign(new Error('read failure'), { code: 'EIO' }) } }+ const closeHandle = handle.close.bind(handle)+ handle.close = async () => { await new Promise(resolve => setTimeout(resolve, 2)); await closeHandle() }+ return handle+}+await assert.rejects(walk(tree), { code: 'EIO' })+assert.deepEqual(await Promise.all([walk(tree), walk(tree), walk(tree)]), [[], [], []])+assert.equal(live, 0)+assert.ok(peak <= 16, String(peak))+console.log('errors released, late closes bounded, fs unchanged')+`, { patched: false })+ assert.equal(result.status, 0, result.stderr)+ assert.match(result.stdout, /late closes bounded/)+ } finally { fs.rmSync(root, { recursive: true, force: true }) }+}, 60000)