Skip to content

fix(javascript): resolve module-level Electron options in functions - #8495

Closed
ShuaixinHuang wants to merge 6 commits into
morluto:mainfrom
ShuaixinHuang:codex/fix-electron-module-options
Closed

ShuaixinHuang wants to merge 6 commits into
morluto:mainfrom
ShuaixinHuang:codex/fix-electron-module-options

Conversation

@ShuaixinHuang

@ShuaixinHuang ShuaixinHuang commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Superseded by #8634 at the author's request: #8634 . The replacement reuses the same published branch and HEAD. This closed PR preserves the original discussion and historical validation.

Supersedes #8250 at the author's explicit request to resubmit the existing PRs. This replacement reuses the identical published head cc2bb1242a5611527bfb99935bc7dbcf85e902f7 and full three-file patch. Prior discussion and historical verification remain at #8250 (earlier #8087). No code changes or new local test runs were made for this resubmission. This new PR requires its own hosted CI. The owner has specifically confirmed review of this replacement PR's final diff, evidence, limitations and unresolved P1, accepted full responsibility, and approved it for initial maintainer review. The P1 remains a before-merge blocker.

Outstanding review follow-up — addressed in the current published revision

The known P1 review finding was addressed in the current head. In a classic script, an early globalThis.createWindow() followed by a later bare call can make module-constant initialization appear definite even though the early activation encounters the temporal dead zone. The previously reported 115-test verification below does not establish that this additional case is fixed.

A separate local draft follow-up has 67 focused tests and three build tasks passing, plus check:fast; expanded verification and commit/push are not complete. That draft is not part of this PR's published commit or diff, and those draft results are not claimed as a fix in this revision. The prior finding is covered by the current-head regression; hosted CI and maintainer review still apply; the original review is preserved rather than marked resolved.

Supersedes #8087 at the author's request. This replacement reuses verified head cc2bb12 and preserves the original discussion and validation record at #8087. Historical revision-specific validation below remains at its stated execution points. This new PR must pass its own hosted CI.

Problem and resulting behavior

Fixes #7227. Electron static analysis loses module-level immutable webPreferences read inside a later activation. Retain those settings when initialization precedes the function's module-level uses, while preserving uncertainty when a hoisted function can run earlier.

For example, this source must remain dynamic rather than report a proven nodeIntegration: true:

const { BrowserWindow } = require("electron");
createWindow();
const webPreferences = { nodeIntegration: true };
function createWindow() {
  return new BrowserWindow({ webPreferences });
}

Moving the call after the const initializer yields object-literal with the literal setting, including when the function declaration appears before the initializer.

Owning change and scope

Initialization coverage stays in javascriptSemanticMutationInitializers.ts; Electron consumers use that fact without reinterpreting declaration order. A hoisted declaration's position does not prove activation timing. The owner indexes module-level function references once per immutable module body and treats earlier aliases, indirect activations, live exports and unproven timing conservatively. This is a bounded reference-order check, not a general call graph or runtime execution proof.

The existing ancestry cache also retains the enclosing function, avoiding repeated walks from deep reads. Initialization coverage remains separate from cross-function capture ordering: the latter stays unresolved so named child-process argv shapes retain their existing uncertainty. No public schema, provider, execution authority, deadline, resource ceiling or assertion was weakened.

Validation at the current follow-up

Windows, Node 24.22.1 / npm 11.16.0:

  • Exact preceding head fb2532ad61ceb4cce7d233131fc1edd4305925ff, with the new source regressions: 4 failed / 47 passed. Three cases expose early direct, aliased and forwarding calls; the fourth exposes a late-call positive control.
  • Inert Node VM controls reproduce a temporal-dead-zone ReferenceError for the three early calls. They substitute a stub BrowserWindow and do not run Electron.
  • Final committed follow-up 9bafc838629358fb8ebc0ce86abefa5c82c8a0ab: 112/112 passed across six complete files: Electron options 51, existing scope-depth/resource controls 14, binding initializers 13, argument shapes 30, existing child-process compiled CLI/stdio MCP 2, and new Electron initialization compiled CLI/stdio MCP 2. Three build prerequisite tasks passed.
  • Both public adapters report dynamic/empty preferences for the early-call source and object-literal/literal true for the late-call source. Source ranges distinguish the two files. Fixtures remain inert.
  • Test discovery passed: all 2,866 test files discovered exactly once. Normal precommit passed; typecheck/lint passed 2/2. Normal prepush typecheck/lint passed 2/2, 26.986 seconds; the normal fast-forward push to this PR's existing fork branch completed.

The earlier head's independent hosted CI passed, but it did not cover this hoisted-declaration review case. The new head requires its own hosted CI; an earlier green run does not validate it. Local checks use synthetic JavaScript through production static analysis and real local compiled CLI/stdio MCP. No real Electron application or Linux/macOS execution is claimed.

Loop ownership review follow-up

Commit cc2bb1242a5611527bfb99935bc7dbcf85e902f7 keeps enclosing-function identity in its own immutable ancestry cache. Loop ordering remains uncertain; entering a loop no longer erases which function owns the read. This retains initialized module-level Electron settings inside for-of, for and while loops while keeping early calls dynamic. No downstream reinterpretation or call graph expansion was added.

On exact preceding head 9bafc838, the three new loop source cases fail while the existing 51 pass. With the correction, six complete files pass 115/115 (Electron 54, scope-depth 14, initializers 13, shapes 30, existing child-process CLI/MCP 2, Electron initialization CLI/MCP 2). The public adapter cases include both early and late calls inside loops and outside loops, with source provenance. All three committed files match the tested bytes exactly after normal precommit hooks. Three build tasks passed; normal prepush typecheck/lint passed 2/2, 46.166 seconds. No assertions or resource controls were relaxed.

The earlier 9bafc838 own hosted workflow 41009833080 completed successfully; the new cc2bb124 head requires independent hosted validation. Validation uses synthetic inert JavaScript and real local compiled CLI/stdio MCP on Windows, Node 24.22.1 / npm 11.16.0; no real Electron application or Linux/macOS run is claimed.

Author readiness

Human owner: @ShuaixinHuang

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths. The known early-global-call P1 below still needs its published regression/fix.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

Current-head P1 correction

Commit 9611e5cbe8d0d3639f87df529d2989e69a63d1f2 covers the classic-script global activation case. Focused domain and CLI/stdio MCP validation passed 67/67 tests; check:fast passed 2/2. The local regression covers early and late globalThis/window/self/this activations without expanding call-graph or authority semantics.

This replacement preserves the prior PR discussion and validation history at #8331. It reuses the verified published head and requires its own hosted CI.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-01T11:28:19.237262Z 9611e5c PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change reaches REA's shared JavaScript static-analysis workflow.

Fix the missed early calls through global-object aliases before merging.

Findings

  1. P1 Early aliased calls look initialized ▶
  2. P2 Unrelated helpers hide preferences ▶
Fix with agent prompt
### Issue 1
src/domain/javascript/javascriptSemanticMutationInitializers.ts:893-900
This check misses early calls through an alias of the global object. In a classic script, `const root = globalThis; root.createWindow(); const webPreferences = { nodeIntegration: true }; function createWindow() { return new BrowserWindow({ webPreferences }); } createWindow();` reads `webPreferences` before initialization.

The index ignores `root.createWindow()` and uses the later bare call to return `hasDefiniteInitializer: true`. Electron analysis then reports literal preferences instead of keeping them unknown. Track global-object aliases at the shared owner, or keep initialization uncertain when those accesses cannot be ruled out.

### Issue 2
src/domain/javascript/javascriptSemanticMutationInitializers.ts:903-912
`functions.get(name)` confuses shadowed local names with the module function. For example, add `function helper() { function createWindow() {} createWindow(); }` beside a module-level `createWindow` that reads initialized preferences. The unrelated local call sets the module function's read to `null`, even if `helper` is never called.

A later real `createWindow()` cannot restore it, so adding an unrelated helper makes known preferences disappear from analysis results. Match references by binding identity rather than spelling, and add a shadowing regression.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR lets Electron analysis recover immutable module-level preferences inside functions while keeping early activations unknown.

  • Electron findings include captured webPreferences when initialization comes before activation.

The supplied history says this replaces earlier PRs. Live supersession status could not be checked because GitHub authentication was unavailable. No tests were run during this review.

ShuaixinHuang explicitly preserved the earlier direct-global-call finding and its history while stating that the current head addresses it. That exact case is covered by the new regression; the alias case above is distinct.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Read module constant inside function] --> B[Find enclosing function]
  B --> C[Index module function references]
  C --> D{Initialization precedes references?}
  D -->|Yes| E[Mark initializer definite]
  D -->|No or unknown| F[Keep preferences unknown]
  E --> G[Electron checks object mutations]
  G --> H[Report constant preferences]
Loading

Reviews (1) · Last reviewed commit: "fix(javascript): account for classic glo..." · Reviewed by Greptile

Comment on lines +893 to +900
if (
t.isThisExpression(receiver) ||
(t.isIdentifier(receiver) &&
(receiver.name === "globalThis" ||
receiver.name === "window" ||
receiver.name === "self"))
)
name = semanticStaticPropertyKey(node.property, node.computed);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Early aliased calls look initialized

This check misses early calls through an alias of the global object. In a classic script, const root = globalThis; root.createWindow(); const webPreferences = { nodeIntegration: true }; function createWindow() { return new BrowserWindow({ webPreferences }); } createWindow(); reads webPreferences before initialization.

The index ignores root.createWindow() and uses the later bare call to return hasDefiniteInitializer: true. Electron analysis then reports literal preferences instead of keeping them unknown. Track global-object aliases at the shared owner, or keep initialization uncertain when those accesses cannot be ruled out.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptSemanticMutationInitializers.ts
Line: 893-900

Comment:
**Early aliased calls look initialized**

This check misses early calls through an alias of the global object. In a classic script, `const root = globalThis; root.createWindow(); const webPreferences = { nodeIntegration: true }; function createWindow() { return new BrowserWindow({ webPreferences }); } createWindow();` reads `webPreferences` before initialization.

The index ignores `root.createWindow()` and uses the later bare call to return `hasDefiniteInitializer: true`. Electron analysis then reports literal preferences instead of keeping them unknown. Track global-object aliases at the shared owner, or keep initialization uncertain when those accesses cannot be ruled out.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +903 to +912
const fn = functions.get(name);
if (fn == null || active.has(fn)) return;
const current = indexedReads.get(fn);
if (current === null || current === undefined) return;
// Indirect activations and live exports have no proven module timing.
indexedReads.set(
fn,
active.size > 0 || t.isExportSpecifier(parent)
? null
: Math.min(current, index),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Unrelated helpers hide preferences

functions.get(name) confuses shadowed local names with the module function. For example, add function helper() { function createWindow() {} createWindow(); } beside a module-level createWindow that reads initialized preferences. The unrelated local call sets the module function's read to null, even if helper is never called.

A later real createWindow() cannot restore it, so adding an unrelated helper makes known preferences disappear from analysis results. Match references by binding identity rather than spelling, and add a shadowing regression.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/domain/javascript/javascriptSemanticMutationInitializers.ts
Line: 903-912

Comment:
**Unrelated helpers hide preferences**

`functions.get(name)` confuses shadowed local names with the module function. For example, add `function helper() { function createWindow() {} createWindow(); }` beside a module-level `createWindow` that reads initialized preferences. The unrelated local call sets the module function's read to `null`, even if `helper` is never called.

A later real `createWindow()` cannot restore it, so adding an unrelated helper makes known preferences disappear from analysis results. Match references by binding identity rather than spelling, and add a shadowing regression.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9611e5cbe8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

owner !== undefined;
owner = parents.get(owner)
)
if (t.isStatement(owner)) return statementPosition(owner, parents);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Stop parameter callbacks at the enclosing activation boundary

For a function expression in a hoisted function's parameter default, this walk reaches the outer FunctionDeclaration and treats its textual position as the callback's creation point. After the Electron import, start(); const webPreferences = { nodeIntegration: true }; function start(make = () => new BrowserWindow({ webPreferences })) { return make(); } therefore produces hasDefiniteInitializer: true, even though the early call creates and invokes the callback before initialization. optionObjectCandidate trusts this flag, allowing literal preferences to be reported instead of dynamic. Stop at the enclosing function boundary unless its activation timing is also proven.

Useful? React with 👍 / 👎.

Comment on lines +895 to +898
(t.isIdentifier(receiver) &&
(receiver.name === "globalThis" ||
receiver.name === "window" ||
receiver.name === "self"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Track early calls through global-object aliases

In a classic script, const root = globalThis; root.createWindow(); before the options initializer activates the hoisted declaration, but this spelling-only matcher skips it. If a later bare createWindow() remains, that late call becomes the indexed first read, so semanticBindingAtRead marks the captured preferences definitely initialized even though the early call hits the temporal dead zone. The existing ambient-path owner already follows stable aliases; share those canonical receiver facts, or retain unknown timing, rather than letting a trivial global-object alias turn uncertain options into literal settings.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

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

Labels

area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior bug Something isn't working provider: electron Analysis provider / engine: electron

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Module-level webPreferences constants are reported as dynamic when the window is created inside a function

2 participants