Skip to content

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

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

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

Conversation

@ShuaixinHuang

@ShuaixinHuang ShuaixinHuang commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Superseded by #8666 at the author's request: #8666 . Same published branch/HEAD; original discussion and historical validation are preserved below.

Current review correction

Current HEAD: 4cd804cbcc17dc76f02c27f327f577d2fc7b3665.

Reproduced the global-object-alias early-call case and the unrelated same-named parameter case (3 new cases failed on the prior head). The shared initializer timing owner now consumes existing lexical binding state: identifier reads match the actual function binding, and classic-script global receivers follow binding-owned initializer aliases with a cycle guard. All production callers now pass their existing analysis state rather than only its parent map; low-level parent-map-only tests retain their API. No target source is executed by analysis. Validation: 112 passed across initializer, call-resolution, Electron options and compiled CLI/stdio MCP files, plus 277 sibling binding/loader/fingerprint cases; check:fast 2/2 passed (43.349s). The VM controls confirm the early alias call reaches the temporal dead zone while the late control succeeds. These are synthetic source/VM and actual compiled CLI/MCP checks, not a real Electron application run.

The new HEAD requires its own hosted CI; earlier green runs below belong to earlier commits. Existing human declarations remain in force. The original replacement description and its execution points follow as historical context.

Supersedes #8495 at the author's explicit request to resubmit all current PRs. Same published branch and HEAD 9611e5cbe8d0d3639f87df529d2989e69a63d1f2. Original discussion and historical validation remain at #8495. This new PR requires its own hosted CI and a new human declaration for this PR ID; prior review declarations are historical.

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 2, 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-02T11:24:31.077781Z 4cd804c New commits
ℹ️ 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.

@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".

Comment on lines +900 to +902
name = semanticStaticPropertyKey(node.property, node.computed);
}
if (name === null) return;

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 Keep unresolved global accesses in the activation check

For a classic script containing const key = 'createWindow'; globalThis[key](); before the preferences declaration and a later bare createWindow(), the early access is dropped: semanticStaticPropertyKey cannot resolve the identifier key, so name stays null. The late call then makes hasDefiniteInitializer true although the early activation reaches the captured const in its temporal dead zone, enabling incorrect literal-option resolution through optionObjectCandidate. Resolve the computed key through the semantic owner or invalidate the timing proof for unresolved global accesses; an unresolved function identity is not evidence that no early access occurred.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

Comment on lines +1037 to +1041
let owner = parents.get(enclosingFunction);
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 creation-position lookup at enclosing callable boundaries

With createWindow(); const webPreferences = {nodeIntegration: true}; function createWindow(make = () => new BrowserWindow({webPreferences})) { make(); } after the Electron import, this walk reaches the outer FunctionDeclaration and treats its later source position as the arrow's creation time, even though the hoisted function was already activated. The early call throws on webPreferences, but the new branch returns hasDefiniteInitializer: true, enabling literal-option resolution. Stop at intervening callable boundaries, or prove the outer activation's timing, rather than using its declaration order.

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 3/5 Tier: plus

[Medium impact] The change reaches shared JavaScript static-analysis results across several analysis paths.

The PR needs corrections before merging because early calls can be missed and long alias chains can break file analysis.

Findings

  1. P1 Early calls are skipped ▶
  2. P1 Long aliases break file analysis ▶
  3. P2 CommonJS calls hide settings ▶
Fix with agent prompt
### Issue 1
src/domain/javascript/javascriptSemanticMutationInitializers.ts:909-915
`resolveSemanticBindingState` drops uncertain bindings, so the scan ignores `with ({}) { createWindow(); }` before the `webPreferences` initializer. A later bare `createWindow()` then looks like the first use. The early call can reach the hoisted function before initialization, yet Electron analysis reports literal preferences.

Keep possible matches unknown instead of dropping them. The repository requires unresolved identity to remain unknown.

### Issue 2
src/domain/javascript/javascriptSemanticMutationInitializers.ts:886-890
`globalReceiver` adds one nested call per alias with no depth bound. A valid flat script with thousands of aliases and a member access through the last alias can exhaust the call stack when a captured module constant starts this scan. The `seen` set stops cycles, not long chains. The worker reports a resource failure before retaining the file's static results.

Use an iterative, bounded walk and reuse its results across member accesses. Repository rules require bounded resource use and shared work.

### Issue 3
src/domain/javascript/javascriptSemanticMutationInitializers.ts:871-872
A plain `.cjs` file has `program.sourceType === "script"`, but its top-level functions belong to Node's wrapper. For example, `exports.createWindow = () => {}; this.createWindow();` before the preferences initializer calls an exported function, not the separate local `createWindow`. This scan counts it as an early local call, so valid preferences used by a later bare call stay unknown.

Use the parser-owned `javaScriptRuntimeContext` to exclude CommonJS. The repository requires consumers to use the owner's parsed facts; that requirement must be satisfied before merging.

---

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

Summary

This PR recovers module-level Electron options inside functions while keeping early calls uncertain.

  • The analyzer resolves module constants inside functions only when initialization comes first.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A["Captured module constant"] --> B["Find enclosing function"]
  B --> C{"Initializer precedes first possible use?"}
  C -->|"No or unknown"| D["Keep options dynamic"]
  C -->|"Yes"| E["Mark initialized; keep capture order unknown"]
  E --> F{"Relevant writes or escapes?"}
  F -->|"Yes"| D
  F -->|"No"| G["Report literal Electron options"]
Loading

Reviews (2) · Last reviewed commit: "fix(javascript): bind first activations ..." · Reviewed by Greptile

Comment on lines +909 to +915
: resolveSemanticBindingState(state, node, node.name);
if (
state === undefined ||
(candidate != null &&
binding?.initializers.some(
({ node: value }) => value === candidate,
))

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 calls are skipped

resolveSemanticBindingState drops uncertain bindings, so the scan ignores with ({}) { createWindow(); } before the webPreferences initializer. A later bare createWindow() then looks like the first use. The early call can reach the hoisted function before initialization, yet Electron analysis reports literal preferences.

Keep possible matches unknown instead of dropping them. The repository requires unresolved identity to remain unknown.

Context Used: AGENTS.md (source)

Knowledge Base Used: Artifact and application analysis

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

Comment:
**Early calls are skipped**

`resolveSemanticBindingState` drops uncertain bindings, so the scan ignores `with ({}) { createWindow(); }` before the `webPreferences` initializer. A later bare `createWindow()` then looks like the first use. The early call can reach the hoisted function before initialization, yet Electron analysis reports literal preferences.

Keep possible matches unknown instead of dropping them. The repository requires unresolved identity to remain unknown.

**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))

**Knowledge Base Used:** [Artifact and application analysis](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fartifact-and-application-analysis.md)

---

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

Comment on lines +886 to +890
if (seen.has(binding.bindingId)) return false;
seen.add(binding.bindingId);
return binding.initializers.some(({ node: value }) =>
globalReceiver(value, seen),
);

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 Long aliases break file analysis

globalReceiver adds one nested call per alias with no depth bound. A valid flat script with thousands of aliases and a member access through the last alias can exhaust the call stack when a captured module constant starts this scan. The seen set stops cycles, not long chains. The worker reports a resource failure before retaining the file's static results.

Use an iterative, bounded walk and reuse its results across member accesses. Repository rules require bounded resource use and shared work.

Context Used: AGENTS.md (source)

Knowledge Base Used: Artifact and application analysis

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

Comment:
**Long aliases break file analysis**

`globalReceiver` adds one nested call per alias with no depth bound. A valid flat script with thousands of aliases and a member access through the last alias can exhaust the call stack when a captured module constant starts this scan. The `seen` set stops cycles, not long chains. The worker reports a resource failure before retaining the file's static results.

Use an iterative, bounded walk and reuse its results across member accesses. Repository rules require bounded resource use and shared work.

**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))

**Knowledge Base Used:** [Artifact and application analysis](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fartifact-and-application-analysis.md)

---

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

Comment on lines +871 to +872
const classicScript =
t.isProgram(program) && program.sourceType === "script";

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 CommonJS calls hide settings

A plain .cjs file has program.sourceType === "script", but its top-level functions belong to Node's wrapper. For example, exports.createWindow = () => {}; this.createWindow(); before the preferences initializer calls an exported function, not the separate local createWindow. This scan counts it as an early local call, so valid preferences used by a later bare call stay unknown.

Use the parser-owned javaScriptRuntimeContext to exclude CommonJS. The repository requires consumers to use the owner's parsed facts; that requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Knowledge Base Used: Artifact and application analysis

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

Comment:
**CommonJS calls hide settings**

A plain `.cjs` file has `program.sourceType === "script"`, but its top-level functions belong to Node's wrapper. For example, `exports.createWindow = () => {}; this.createWindow();` before the preferences initializer calls an exported function, not the separate local `createWindow`. This scan counts it as an early local call, so valid preferences used by a later bare call stay unknown.

Use the parser-owned `javaScriptRuntimeContext` to exclude CommonJS. The repository requires consumers to use the owner's parsed facts; that requirement must be satisfied before merging.

**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))

**Knowledge Base Used:** [Artifact and application analysis](https://app.greptile.com/-/switch-tenant?tenant=pre&next=%2Fcustom-context%2Fknowledge-base%2Fmorluto%2Frea%2F-%2Fdocs%2Fartifact-and-application-analysis.md)

---

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: 4cd804cbcc

ℹ️ 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".

Comment on lines +912 to +915
(candidate != null &&
binding?.initializers.some(
({ node: value }) => value === candidate,
))

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 Preserve possible function reads through with scopes

When a classic-script createWindow captures webPreferences, an early with ({}) { createWindow(); } followed by the preferences declaration and a later bare call is incorrectly considered safe. semanticBindingLookupAt returns uncertain-binding for the early call, but resolveSemanticBindingState reduces it to undefined, so this condition drops the possible reference and moduleFunctionFirstRead retains only the late call. The new branch consequently sets hasDefiniteInitializer: true even though the early call accesses the captured const in its temporal dead zone, enabling incorrect literal preferences through optionObjectCandidate. Use the tagged lookup to retain the possible outer binding and invalidate its timing proof.

AGENTS.md reference: AGENTS.md:L21-L21

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