Skip to content

fix(webui): fix fresh-install crash on first launch (#934) - #935

Merged
itomek merged 14 commits into
mainfrom
934-bug-running-gaia-fails-after-a-fresh-install-of-gaia-0174
May 1, 2026
Merged

itomek merged 14 commits into
mainfrom
934-bug-running-gaia-fails-after-a-fresh-install-of-gaia-0174

Conversation

@itomek

@itomek itomek commented May 1, 2026

Copy link
Copy Markdown
Collaborator

Fixes #934 — GAIA fails to start after a clean install of 0.17.4.

What was the bug

Three layered failures, each masking the next:

1. ERR_STREAM_WRITE_AFTER_END → bare Electron crash dialog. The log-tee stream (electron-main.log) was created early in startup. On app exit, process.on('exit') called stream.end(). If anything then called console.log(), the stream emitted an async 'error' event. Because no 'error' listener was attached, Node promoted it to uncaughtException, which Electron surfaced as a raw JS error dialog with no GAIA branding.

2. ERR_FAILED (-2) loading index.html. Even after adding an 'error' listener to absorb the stream error, the app still crashed with a navigation failure. The URL format was wrong: Node's url.format() (used internally by Electron's loadFile()) produces file:///C:\path with backslashes on Windows. Chromium 130+ (Electron 40) rejects backslash file URLs → ERR_FAILED (-2).

3. ERR_FAILED (-2) on a clean install even with correct URL. After switching to pathToFileURL() (which produces forward-slash URLs), the crash still happened on a truly fresh install where ~/.gaia didn't exist. The root cause: after the backend installer's progress dialog is destroyed on install completion, Electron fires window-all-closed. At that point trayManager hadn't been created yet, so the handler called app.quit(). The async cleanup finished instantly (nothing to tear down), fired a second app.quit() that will-quit didn't prevent, and Electron began tearing down Chromium — right as the startup sequence called createWindow() then loadURL(). The renderer process was invalidated mid-navigation → ERR_FAILED (-2).

What we changed

  • main-safety-net.cjs (new) — extracted installSafetyNet and installLogTee from main.cjs. installSafetyNet registers uncaughtException/unhandledRejection handlers that write a FATAL entry to the log and show a GAIA-branded error dialog. installLogTee attaches a 'error' listener to the log-tee stream, absorbing write-after-end errors before they reach the global handler.
  • main.cjs — switched loadFile() → loadURL(pathToFileURL(...)) for correct forward-slash file URLs on Windows. Added isBootstrapping flag (true until createWindow() runs) that makes window-all-closed a no-op during the install phase, preventing the premature quit race.
  • electron-builder.yml — added main-safety-net.cjs to the ASAR files list.
  • tests/electron/test_main_error_handling.js — 12 Jest tests covering installSafetyNet and installLogTee (re-entry guard, pre/post-ready dialog branch, crash counter, stream error absorption, etc.).

How we tested

Manual fresh-install test on Windows 11 (uninstall → delete ~/.gaia → reinstall from the built NSIS .exe):

  • Before: "GAIA crashed" dialog appeared immediately after the backend installer completed; ~/.gaia/electron-main.log showed FATAL ERR_FAILED (-2) loading file:///C:/...index.html.
  • After: app launched normally, backend connected, chat UI loaded.

@itomek
itomek requested a review from kovtcharov-amd as a code owner May 1, 2026 18:19
@itomek itomek linked an issue May 1, 2026 that may be closed by this pull request
2 of 3 tasks
@github-actions github-actions Bot added the tests Test changes label May 1, 2026
@itomek itomek self-assigned this May 1, 2026
@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Tight, well-documented fix for the layered fresh-install crash in #934. Each of the three failure modes is addressed at its root: a stream-error listener for ERR_STREAM_WRITE_AFTER_END, pathToFileURL() for Windows file URLs on Chromium 130+, and an isBootstrapping guard for the window-all-closed race. The extraction into main-safety-net.cjs with dependency injection is the right call and makes the code testable without dragging in main.cjs side effects. No blocking issues — a few minor cleanups below would tighten this up.

Issues Found

🟡 Important

1. CR-3 symlink protection is a TOCTOU and doesn't deliver on its claim (main-safety-net.cjs:41-47)

The pattern lstatSync → unlinkSync → mkdirSync → writeFileSync has two TOCTOU windows. Between lstatSync and unlinkSync an attacker can swap; between unlinkSync and writeFileSync they can re-create the symlink. The comment "prevents symlink-planting attack" overpromises. Real prevention requires fs.openSync(p, 'wx') (with O_CREAT|O_EXCL, O_NOFOLLOW is platform-dependent in Node).

Given the file lives in ~/.gaia (already user-owned), the threat model is weak — a local attacker who can plant symlinks there can do worse things. Either drop the CR-3 block (and its comment) entirely, or replace it with openSync('wx') and a fallback unlink-and-retry. As written, the code reads as security theater.

2. Log-path duplication invites drift (main.cjs:29 and main.cjs:72)

Two independent computations of ~/.gaia/electron-main.log now exist:

// line 29
const _SAFETY_NET_LOG = path.join(os.homedir(), ".gaia", "electron-main.log");
// line 72 (inside installMainLogTee IIFE)
const logPath = path.join(gaiaDir, "electron-main.log");

Both must stay in sync; nothing enforces it. Consider extracting one constant and reusing it:

const GAIA_DIR = path.join(os.homedir(), ".gaia");
const MAIN_LOG_PATH = path.join(GAIA_DIR, "electron-main.log");

// ── Safety net (issue #934) ───────────────────────────────────────────────────
// Install top-level error handlers BEFORE any service module is required so
// that synchronous throws at module-load time are caught and shown as a
// GAIA-branded error box instead of Electron's bare JS-error dialog.
// Extracted into main-safety-net.cjs (CR-6) so tests can require it
// without triggering main.cjs side effects.
const { installSafetyNet } = require("./main-safety-net.cjs");
const { fatal: _fatalHandler } = installSafetyNet({
  logPath: MAIN_LOG_PATH,
  dialogModule: dialog,
  appModule: app,
});

…and reuse GAIA_DIR / MAIN_LOG_PATH inside installMainLogTee().

🟢 Minor

3. STREAM_ERROR line writes "undefined" when error has no message (main-safety-net.cjs:150)

function installLogTee({ stream, logPath }) {
  stream.on("error", (err) => {
    const detail = (err && err.message) || (err && err.stack) || String(err);
    appendLog(logPath, `[${new Date().toISOString()}] STREAM_ERROR ${detail}`);
  });
}

Matches the pattern fatal() already uses on line 83.

4. CR-1 comment says "module-scoped" but the guard is closure-scoped (main-safety-net.cjs:73)

The distinction matters — test 6 (crash-loop counter increments) relies on closure scoping (each fresh installSafetyNet call gets its own guard, which is why the test can fire crash 2 after jest.resetModules()). Update for accuracy:

  // Per-handler re-entry guard (closure-scoped — each installSafetyNet
  // call gets its own, intentionally; see test_main_error_handling.js).
  let _inFatalHandler = false;

5. Test 11 silently passes if installLogTee is removed from exports (tests/electron/test_main_error_handling.js:608-613)

const { installLogTee } = require(SAFETY_NET_PATH);
if (!installLogTee) {
  // If installLogTee is not exported, skip — implementation detail may vary.
  return;
}

This is a green test that would silently regress if the export were dropped. Since installLogTee is the root-cause fix, it should be a hard requirement:

    const { installLogTee } = require(SAFETY_NET_PATH);
    expect(typeof installLogTee).toBe("function");
    const mockStream = new EventEmitter();
    mockStream.write = jest.fn();
    mockStream.end = jest.fn();

6. Test 11 doesn't actually exercise the absorption behavior, only the listener-count (tests/electron/test_main_error_handling.js:608-623)

Stronger coverage of the literal #934 root cause would emit an 'error' on the mock stream and assert that process.emit('uncaughtException') was NOT triggered (or that the log line landed). As-is, the test passes if the listener is a no-op — but the safety-net's whole job is what the listener does. Worth a follow-up.

7. Test 6 relies on cross-install listener ordering (tests/electron/test_main_error_handling.js:472-506)

After jest.resetModules() + installSafetyNet2, both the first and second process.on("uncaughtException") listeners fire on process.emit(...). The test passes only because the first listener's _inFatalHandler is still true from crash 1 and bails through the re-entry guard. Cleaner alternatives: process.removeAllListeners('uncaughtException') between the two crashes, or seed the counter file directly to count=1 and only test the increment-from-1-to-2 case once. Current approach works but is fragile to future refactoring of the guard semantics.

8. Crash counter is write-only (main-safety-net.cjs:91, :121)

writeCount(readCount(homedir) + 1, homedir) is incremented on each fatal and reset on browser-window-focus, but no code reads the count to gate behavior (no safe-mode threshold, no "skip log-tee on Nth consecutive crash"). If this is intentional diagnostics-only, consider noting it in the file header so a future reader doesn't think a threshold check is missing.

Strengths

  • Three-layer root-cause analysis is excellent. The PR description nails the chain (stream-error → URL backslashes → window-all-closed race) and each layer gets its own fix rather than papering over symptoms with a top-level try/catch.
  • Dependency injection (dialogModule, appModule, homedirFn) makes the suite hermetic. No real Electron runtime or filesystem clobber — tests run in a mkdtempSync directory and clean up in afterEach. This is the right pattern for Electron-main testing.
  • installSafetyNet correctly handles both 'render-process-gone' and 'child-process-gone' (CR-5), which uncaughtException doesn't catch — a class of bugs that frequently sneaks past JS-only safety nets.
  • pathToFileURL() switch is the canonical stdlib fix for the Windows backslash issue — far better than string manipulation, and it composes cleanly with URLSearchParams for the ?api= query.
  • isBootstrapping flag is a minimal, well-commented guard for the window-all-closed race; doesn't introduce new global state beyond what's needed.

Verdict

Approve with suggestions. Core fix is correct, well-justified, and the test coverage hits the right surfaces. The 🟡 items (CR-3 TOCTOU comment + log-path duplication) are worth addressing before merge but aren't blocking. The 🟢 items can be follow-ups.

@itomek

itomek commented May 1, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review. Addressed in 4f9a038:

🟡 Fixed before merge:

  • CR-3 TOCTOU — dropped the symlink check entirely. The threat model in ~/.gaia (user-owned) doesn't justify the TOCTOU windows it introduced; writeFileSync is sufficient.
  • Log-path duplication — extracted _GAIA_DIR / _MAIN_LOG_PATH constants in main.cjs; both installSafetyNet and installMainLogTee now reference the same binding.

🟢 Fixed in the same commit:

  • STREAM_ERROR message — (err && err.message) || (err && err.stack) || String(err) to match the pattern fatal() already uses.
  • CR-1 comment — updated to "closure-scoped" with a note pointing at the test file.
  • Test 11 silent pass — replaced the early-return with expect(typeof installLogTee).toBe("function").

Deferred as follow-ups:

  • Items 6/7/8 (test 11 absorption behavior, test 6 listener ordering fragility, crash counter read-path annotation) are noted and will be tracked against the open hardening plan.

On the CI failures: both Test Electron Framework (.input-cursor CSS assertion) and AppImage userns-restricted are pre-existing regressions on main unrelated to this PR. The .input-cursor class was removed by 37e35eb1 without updating the test; the AppImage job requires a release-tagged Python wheel artifact that doesn't exist for PR builds.

@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

This is a high-quality fix for a real, painful bug. The PR layers three independent fixes — each addressing a distinct failure mode that masked the next — and pairs them with a clean, hermetic Jest test suite (12 tests, all dependency-injected). The architecture is sound: installSafetyNet is the defense-in-depth layer, installLogTee is the root-cause fix, and the isBootstrapping flag plus pathToFileURL switch close the remaining race conditions. The single most important thing: the fix is well-scoped, the test design (no main.cjs side effects, all Electron objects injected) is exactly the right pattern for testable Electron main-process code.

Issues Found

🟢 Minor

1. Empty catch { } blocks conflict with the "fail-loudly" rule (main-safety-net.cjs:43, 52, 75, 103, 105)

CLAUDE.md ("No Silent Fallbacks — Fail Loudly") prohibits empty catch blocks for new code. The fatal/crash path is a reasonable exception — we are the fail mode — but a stderr fallback for the log/dialog catches is cheap insurance and aligns with project convention:

function appendLog(logPath, msg) {
  try {
    fs.mkdirSync(path.dirname(logPath), { recursive: true });
    fs.appendFileSync(logPath, msg + "\n", { encoding: "utf8" });
  } catch (err) {
    try { process.stderr.write(`[safety-net] log append failed: ${err.message}\n`); } catch { /* truly unrecoverable */ }
  }
}

Same pattern applies to writeCount (line 43) — at minimum, write a stderr breadcrumb. The process.exit catches at lines 75 and 105 are fine as-is (process.exit only throws when stubbed in tests).

2. require("./main-safety-net.cjs") is duplicated in main.cjs (lines 35, 106)

Module is cached, so functionally equivalent — but a single destructure at the top is cleaner:

const { installSafetyNet, installLogTee } = require("./main-safety-net.cjs");
const { fatal: _fatalHandler } = installSafetyNet({
  logPath: _MAIN_LOG_PATH,
  dialogModule: dialog,
  appModule: app,
});

Then drop line 106 entirely (it'll already be in scope inside installMainLogTee()).

3. pathToFileURL is required inside loadApp() (main.cjs:463) instead of at file top

Not a bug — url is a Node built-in so the require is cheap — but inconsistent with the other module-level requires (fs, os, etc.) in this file. Hoisting it next to the other Node requires (around line 17) is more consistent and removes one micro-cost from the navigation hot path:

const { spawn } = require("child_process");
const { pathToFileURL } = require("url");

4. appendLog's mkdirSync runs on every fatal call (main-safety-net.cjs:50)

Each fatal write re-creates the parent directory recursively. Negligible cost in practice (we're already crashing), but worth flagging if this gets reused outside the fatal path. Not blocking — leave as-is.

Strengths

  • Dependency-injected design (CR-6). installSafetyNet({ logPath, dialogModule, appModule, homedirFn }) is exactly how Electron main-process code should be factored for testability — the test file requires the module without triggering any app.commandLine / spawn / log-tee side effects from main.cjs. Good model for the rest of src/gaia/apps/webui/.
  • Single source of truth for the log path. _GAIA_DIR and _MAIN_LOG_PATH at the top of main.cjs (lines 26–27) replace the previous duplicate path computations between the safety-net and installMainLogTee. The comment explaining why (paths could drift apart) is exactly the kind of why-comment CLAUDE.md asks for.
  • The PR description carries its weight. Three failure modes documented in causal order, each with the actual error string (ERR_STREAM_WRITE_AFTER_END, ERR_FAILED (-2)), reproduction steps for the manual fresh-install test, and the precise root cause (Chromium 130+ rejecting backslash file URLs). This is the gold standard for a debugging PR.
  • CR-2/CR-4/CR-5 are visibly addressed. Pre-app.ready uses showErrorBox; post-ready uses showMessageBoxSync. Counter resets on browser-window-focus, not loadApp(). render-process-gone and child-process-gone are wired alongside uncaughtException. The corresponding tests (4, 5, 7, 8, 9) lock these decisions in.
  • Test 10's pre-dialog log invariant (writes FATAL line to logPath before calling dialog) is the right thing to assert — if showErrorBox itself crashes on a broken Windows install, the log entry must already be on disk.

Verdict

Approve with suggestions. No blocking issues. The four 🟢 items above are stylistic / convention nits — none block merge. Recommend folding suggestion 1 (stderr fallback in appendLog/writeCount) and suggestion 2 (single destructured require) into this PR before merge; suggestions 3 and 4 can be deferred. Solid fix, well tested, well written up.

@itomek

itomek commented May 1, 2026

Copy link
Copy Markdown
Collaborator Author

Build complete / AppImage userns-restricted — same pre-existing infra failure as run 25226840084, unrelated to this PR.

Root cause: the userns job installs from a release-tagged PyPI wheel (gaia==0.17.x) that doesn't exist for PR branches. build, appimage-structural-smoke, and appimage-distro-matrix all passed.

This PR touches only main-safety-net.cjs and main.cjs (Electron ASAR content); nothing in the AppImage Python packaging path changed.

@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Tight, well-scoped fix for a nasty three-layered Windows fresh-install regression (#934). The PR description does an excellent job of separating the layered failures (stream-error → backslash file URL → window-all-closed race), and each fix is matched to the specific cause: extracting installSafetyNet/installLogTee for testability, switching loadFile() → loadURL(pathToFileURL(...)), and gating window-all-closed behind an isBootstrapping flag. 12 hermetic Jest tests cover the new module with dependency injection — the right shape for this kind of process-level handler. Most important takeaway: the crash-loop counter is incremented but nothing reads it, so its only value today is forensic (post-mortem grep of ~/.gaia/electron-startup-failures.json).

Issues Found

🟢 Minor

Crash-loop counter is write-only — no consumer drives safe-mode (main-safety-net.cjs:30-43,92)
readCount() is only used internally to compute the next written value. Nothing reads the counter to trigger safe-mode, suppress auto-restart, or surface a "GAIA has crashed N times" UI. As written, this is forensic data only. That's fine if intentional, but the comment at main.cjs:182-185 and the CR-4 test reasoning ("user may crash before first interaction") imply the counter is supposed to drive behavior eventually. Either wire up a consumer (e.g. on the next launch, if count >= 3, skip log-tee init and show a "reset state?" dialog) or drop the file's pretense of crash-loop protection and label it what it is — a startup-failure breadcrumb. A short // TODO(#XYZ): wire this counter into safe-mode launch is enough for now.

Mock app.exit is never exercised (tests/electron/test_main_error_handling.js:43)

  const emitter = new EventEmitter();
  emitter.isReady = jest.fn(() => isReady);
  return emitter;

The safety net calls process.exit, never app.exit. The emitter.exit = jest.fn() line is dead weight that suggests a contract that doesn't exist.

require("url") belongs at top-level (main.cjs:462)
The dynamic const { pathToFileURL } = require("url"); inside loadApp() runs every navigation. Hoisting it to the top-level imports block (alongside path/fs/os) matches the rest of main.cjs and avoids the per-call lookup.

No unit test for the pathToFileURL fix (tests/electron/test_loadapp_query.mjs)
Layer 2 of the bug ("backslash file URLs on Windows → ERR_FAILED -2") was a real regression but has no unit-test guard. A small node:test case in test_loadapp_query.mjs that asserts pathToFileURL("C:\\foo\\dist\\index.html").href starts with file:///C:/ and contains no backslashes would pin the contract on every CI run, not just the manual Windows pass. Layer 1 (stream error) and Layer 3 (isBootstrapping) are likewise untested at the integration level — only the extracted handlers get coverage. Manual Windows testing is great but easily forgotten on follow-up edits.

installLogTee allows duplicate listeners on repeated calls (main-safety-net.cjs:167-172)
Not a bug today (only called once from installMainLogTee), but if a future caller calls it twice on the same stream they'll get N error log entries per stream error. Consider stream.removeAllListeners('error') first, or document "must be called at most once per stream" in the JSDoc.

require("./main-safety-net.cjs") runs before any safety net is installed (main.cjs:35)
A throw during the require itself (e.g. corrupt ASAR, bad path) bypasses installSafetyNet entirely — the very class of crash this PR is trying to surface as a GAIA-branded dialog. The recent commit 877ed7e4 ("add stderr fallbacks and consolidate safety-net require") suggests this is already on the author's radar; flagging in case there's a leftover edge. Wrapping the require in a try/catch that falls back to process.stderr.write + dialog.showErrorBox (electron is already in scope) closes the last mile.

Strengths

  • Dependency injection is the right call here. The extraction of installSafetyNet from main.cjs so tests can require it without main-process side effects (CR-6 in the PR's own annotation) is exactly how Electron main-process handler modules should be written. Other Electron service modules in this repo (tray-manager, agent-process-manager) follow the same pattern and benefit from the same testability.
  • The isBootstrapping guard reads correctly. It's a one-flag, one-flip change with a clear comment explaining the race (main.cjs:182-185, 711, 783-788). No global state machine, no event-driven lifecycle gymnastics — just a flag set false at the exact moment createWindow() finishes. Matches the principle "a bug fix doesn't need surrounding cleanup."
  • Hermetic tests with mkdtempSync + homedirFn injection (test_main_error_handling.js:35,503,547). No ~/.gaia pollution on the test runner, no flakiness from leftover state. The jest.resetModules() calls in test 6 to bypass the closure-scoped re-entry guard show the author understood the module's stateful nature.
  • Single-source-of-truth log path (main.cjs:26-27). _GAIA_DIR and _MAIN_LOG_PATH constants prevent the safety-net and the log-tee from drifting apart — a real failure mode if both ends had independent path.join(os.homedir(), ".gaia", ...) calls.
  • Comments earn their place. The // Root-cause fix for #934 and // CR-2/4/5/6 annotations point to the specific failure each line addresses, exactly the "non-obvious WHY" CLAUDE.md asks for.

Verdict

Approve with suggestions. No 🔴 or 🟡 blockers. The minor items above (counter consumer, dead emitter.exit, hoisted require, missing unit tests for layers 1/2/3 at the main.cjs integration level) are improvements rather than blockers — the fix itself is sound, scoped, and well-tested for the extracted module. Approved by @kovtcharov-amd already; merging unblocks the v0.17.5 release.

@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR cleanly fixes the three-layered fresh-install crash documented in #934 (stream-error promotion → backslash file URL → premature app.quit() race). The extraction of installSafetyNet/installLogTee into main-safety-net.cjs with full dependency injection is exactly the right shape for testability, and the 12 Jest tests cover the meaningful branches (pre-/post-ready dialog, re-entry guard, crash counter, renderer/GPU process events, non-Error rejections). The code is well-narrated — every non-obvious decision has a CR-N/#934 cross-reference. The single biggest thing the author should know: the third layer of the fix (isBootstrapping guard) has no direct test, and the safety-net loader has a small TypeError window if its own require fails.

Issues Found

🟡 Important

_fatalHandler may be undefined if safety-net require fails (src/gaia/apps/webui/main.cjs:39-51, :785-789)

If require("./main-safety-net.cjs") throws (corrupt ASAR, missing file in the package), the catch block calls dialog.showErrorBox and app.exit(1). But app.exit() is documented to schedule an exit — execution can continue. The app.whenReady().then(...).catch((err) => _fatalHandler(err)) registration at line 785-789 still runs, and if app.whenReady() later rejects, calling _fatalHandler (still undefined) throws TypeError: _fatalHandler is not a function — replacing the GAIA-branded dialog with the bare Electron one we were trying to avoid.

let installSafetyNet, installLogTee, _fatalHandler;
try {
  ({ installSafetyNet, installLogTee } = require("./main-safety-net.cjs"));
  ({ fatal: _fatalHandler } = installSafetyNet({
    logPath: _MAIN_LOG_PATH,
    dialogModule: dialog,
    appModule: app,
  }));
} catch (err) {
  try { process.stderr.write(`[main] safety-net load failed: ${err.message}\n`); } catch { }
  try { dialog.showErrorBox("GAIA failed to start", String(err && err.stack || err)); } catch { }
  // Inline fallback so any later .catch(_fatalHandler) still has something callable
  // if app.exit(1) hasn't taken effect yet.
  _fatalHandler = (e) => {
    try { dialog.showErrorBox("GAIA crashed", String(e && e.stack || e)); } catch { }
    try { process.exit(1); } catch { }
  };
  app.exit(1);
}

🟢 Minor

isBootstrapping guard has no regression test (src/gaia/apps/webui/main.cjs:196, :793-799)

This is layer 3 of the fix — the most subtle of the three (timing-dependent race against loadURL()). If someone later removes the guard or moves isBootstrapping = false earlier, the bug silently returns. Consider a small static-source test similar to the pathToFileURL regression guard in tests/electron/test_loadapp_query.mjs:353-369:

test("window-all-closed handler short-circuits during bootstrap", () => {
  const src = fs.readFileSync(mainCjsPath, "utf8");
  // The guard must appear inside the window-all-closed handler.
  const handler = src.match(/app\.on\("window-all-closed",\s*\(\)\s*=>\s*{([\s\S]*?)\n}\);/);
  assert.ok(handler, "window-all-closed handler must exist");
  assert.match(
    handler[1],
    /isBootstrapping/,
    "window-all-closed must check isBootstrapping (issue #934)"
  );
});

Dead variables in test fixture (tests/electron/test_main_error_handling.js:59-60)

origUncaughtException and origUnhandledRejection are declared but never assigned or read. Drop them.

  let tmpDir;
  let logPath;
  let addedListeners;

Test 3 name is slightly misleading (tests/electron/test_main_error_handling.js:118)

The dialog throw is swallowed by the try { ... } catch { } at main-safety-net.cjs:100-111, so the fatal handler never re-enters — the test verifies "dialog throw is contained and exit still happens", not actual re-entry. Either rename to match what's asserted, or trigger re-entry by calling process.emit("uncaughtException", ...) from inside the mocked dialog (so the second emission would re-enter fatal). Not blocking — current test is still useful.

Fragile regex for loadApp body match (tests/electron/test_loadapp_query.mjs:363)

/async function loadApp\(\)\s*{([\s\S]*?)\n}/ relies on the function's closing } being at column 0 with no whitespace. Holds today (verified against main.cjs:455-492), but a stylistic refactor that indents loadApp could break the regex silently. Consider anchoring on a sentinel comment or matching balanced braces. Cosmetic — fine to defer.

Crash counter writes are non-atomic (src/gaia/apps/webui/main-safety-net.cjs:42-50)

writeFileSync is not atomic; if two GAIA processes crash simultaneously, one increment can be lost. Per the inline comment the counter is "forensic only" with a follow-up TODO, so this is acceptable for v0.17.5 — flagging for the #934-follow-up work where the counter becomes load-bearing for safe-mode entry.

Strengths

  • Layered debug narrative. Every CR-N comment ties back to a specific reviewer concern from the design doc, and each of the three "what we changed" layers in the PR description has an in-code comment that explains why (e.g., main.cjs:471-475 on pathToFileURL, main.cjs:793-798 on the bootstrap quit race). Future readers will not need git archaeology.
  • Hermetic, DI-shaped tests. installSafetyNet({ logPath, dialogModule, appModule, homedirFn }) is the right separation — no electron import in the test, no os.homedir() pollution, tmpdir per test, listener cleanup in afterEach. This is a model worth copying for other Electron-side modules.
  • Single source of truth for _MAIN_LOG_PATH (main.cjs:27-28). Removes the drift risk between installSafetyNet and installMainLogTee that the comment calls out.
  • installLogTee is a real root-cause fix, not a bandage — adding the missing 'error' listener on the write stream is what actually prevents promotion to uncaughtException. The safety-net handlers are correctly framed as defense-in-depth on top of that.

Verdict

Approve with suggestions. No blocking issues. The 🟡 _fatalHandler undefined window is worth fixing in this PR (one-line fallback). The minor items can be folded in or deferred to the #934-follow-up ticket.

@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Solid, well-scoped fix for a three-layer fresh-install crash on Windows. Each layer of the bug (ERR_STREAM_WRITE_AFTER_END → ERR_FAILED (-2) from backslash file URLs → ERR_FAILED (-2) from a premature app.quit() race) gets a root-cause fix plus a regression test pinning it. Extracting the safety net into main-safety-net.cjs with dependency injection is the right call — tests can now exercise the handlers without dragging in main.cjs side effects, which is a meaningful long-term win for this file. The single most important takeaway: this PR raises the bar for how main.cjs is tested going forward; future changes to startup logic should follow the same DI pattern.

Issues Found

🟢 Minor — installLogTee name doesn't match what the function does (main-safety-net.cjs:155)

The function only attaches an 'error' listener to a stream. The actual log-tee'ing (rotation, console.log wrapping, write stream creation) all happens in the installMainLogTee IIFE in main.cjs. A name like guardStreamErrors or attachStreamErrorHandler would more accurately describe the contract documented in the JSDoc. Not blocking — just a future readability nit.

🟢 Minor — Brief unprotected window if safety-net require() itself throws (main.cjs:47-57)

If require("./main-safety-net.cjs") fails (corrupt ASAR, unlikely but possible), the catch block calls app.exit(1), which is scheduled, not synchronous. Execution continues into require("./services/tray-manager.cjs") etc. on lines 60-67. If any of those throws synchronously during that window, no uncaughtException handler is installed yet → bare Electron dialog returns. Consider also calling process.exit(1) synchronously in the catch (after the dialog) so we don't continue loading service modules:

} catch (err) {
  try { process.stderr.write(`[main] safety-net load failed: ${err.message}\n`); } catch { }
  try { dialog.showErrorBox("GAIA failed to start", String(err && err.stack || err)); } catch { }
  // Inline fallback so any later .catch(_fatalHandler) still has something callable
  // if app.exit(1) hasn't taken effect yet (app.exit schedules, not instant).
  _fatalHandler = (e) => {
    try { dialog.showErrorBox("GAIA crashed", String(e && e.stack || e)); } catch { }
    try { process.exit(1); } catch { }
  };
  app.exit(1);
  // Stop loading the rest of main.cjs synchronously so a service-module throw
  // can't fall through to the bare Electron dialog before app.exit() takes effect.
  process.exit(1);
}

🟢 Minor — Unnecessary jest.resetModules() in test 6 (tests/electron/test_main_error_handling.js:178-212)

The _inFatalHandler flag is closure-scoped inside installSafetyNet(), not module-scoped. Each call to installSafetyNet creates a fresh closure regardless of module cache state, so the jest.resetModules() calls and the installSafetyNet2 re-require aren't needed for correctness — calling installSafetyNet twice would suffice. Harmless, but the comment "Reset re-entry guard so we can fire a second fatal" is misleading about why this works (it works because each call has its own closure, not because of module reset).

🟢 Minor — Crash-loop counter currently has no consumer (main-safety-net.cjs:24-50)

The TODO at line 27-28 acknowledges this — count is written but never read for safe-mode entry. Acceptable as forensic-only telemetry, but worth filing the follow-up issue now (rather than letting #934-follow-up languish as a free-floating reference) since the data path is already paid for.

Strengths

  • Three-layer fix mirrors the three-layer bug, with regression tests pinning each layer. test_loadapp_query.mjs now guards against loadFile() regressing back into loadApp() (layer 2) and against the isBootstrapping guard being removed (layer 3); test_main_error_handling.js covers layer 1. Forensic test design at its best.
  • Dependency injection (dialogModule, appModule, homedirFn) makes the safety net hermetic. Tests run without Electron, without touching the real ~/.gaia, and without leaking process.on listeners between tests (afterEach cleanup is thorough).
  • Both root-cause and defense-in-depth fixes layered correctly. The stream.on('error') listener is the primary fix; the uncaughtException handler is the safety net beneath it. This is the right way to harden a crash-prone path — fix the root cause AND catch the next surprise.
  • _GAIA_DIR / _MAIN_LOG_PATH consolidation removes the drift risk between installSafetyNet and installMainLogTee writing to subtly different paths.

Verdict

Approve with suggestions. No blocking issues; the minor items above are polish that can be picked up as follow-ups. Already approved by @kovtcharov-amd — safe to merge.

@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

High-quality, layered fix for a fresh-install crash that was masking three independent failures (stream error event, Windows backslash file URL, premature app.quit() race). The author has clearly iterated through several review rounds — extraction of main-safety-net.cjs (CR-6) for testability, dependency injection for dialog/app, and 12 hermetic Jest tests are all the right calls. The single most important takeaway: this is one of those rare Electron fixes where every layer is also its own root cause, and the PR addresses each one rather than papering over with a single broad handler.

Issues Found

🟢 Minor

1. Test 3 (re-entry guard prevents recursive dialog on second call) doesn't actually exercise the re-entry guard (tests/electron/test_main_error_handling.js:536-557)

The test makes dialog.showErrorBox throw on the first call, then emits a single uncaughtException. But fatal() wraps both showErrorBox and showMessageBoxSync in try { } catch { } (main-safety-net.cjs:118-129), so the throw is swallowed and fatal() is never re-entered. The expect(showErrorBox).toHaveBeenCalledTimes(1) assertion holds whether or not the _inFatalHandler guard exists.

To genuinely cover the guard, the test needs a path that re-invokes fatal() synchronously — e.g. spy on appendLog/writeCount and have the spy call fatal() again, then assert showErrorBox/showMessageBoxSync are still only called once on the outer call. Worth fixing because the rest of the suite is genuinely strong, and a misleading test invites future drift.

2. package.json files array missing main-safety-net.cjs (src/gaia/apps/webui/package.json:34-44)

electron-builder.yml was correctly updated, so the production build is fine. But the npm files array still only lists main.cjs. If anyone runs npm pack / npm publish on this directory (the package isn't marked "private": true and has a bin entry), the tarball will ship without main-safety-net.cjs and main.cjs will throw MODULE_NOT_FOUND at startup.

  "files": [
    "bin/",
    "dist/",
    "main.cjs",
    "main-safety-net.cjs",
    "preload.cjs",
    "services/",
    "assets/",
    "app.config.json",
    "README.md",
    "LICENSE"
  ],

3. installLogTee has no defensive single-call guard (src/gaia/apps/webui/main-safety-net.cjs:173-178)

The JSDoc warns "Must be called at most once per stream instance" but there's no enforcement. Currently safe (only called once from installMainLogTee()), but a future refactor that, say, recreates the stream after a rotation would silently double-log every error. A 3-line guard (if (stream._gaiaLogTeeBound) return; stream._gaiaLogTeeBound = true;) would make the contract self-enforcing without any behavioral change today.

Strengths

  • Root-cause analysis is genuinely thorough. The PR description walks through the three layered failures in order, and each fix targets the real cause rather than the symptom — installLogTee's 'error' listener is the textbook stream fix, pathToFileURL is the correct Chromium-130+ replacement for loadFile(), and isBootstrapping is the right guard for the window-all-closed race.
  • The extraction for testability (CR-6) is well done. Keeping installSafetyNet/installLogTee pure-with-injected-dependencies means the Jest suite can validate behavior without booting Electron at all, and test_loadapp_query.mjs adds source-level regression guards that pin the call sites — so e.g. swapping back to loadFile() will fail a test rather than silently re-introducing the Windows bug.
  • Defensive layering around the safety-net loader itself (main.cjs:39-61) is the right paranoia for a feature whose entire job is to be the last line of defense — wrapping the require("./main-safety-net.cjs") in its own try/catch with an inline _fatalHandler fallback is exactly what you want when corrupt-ASAR is on the threat model.

Verdict

Approve with suggestions — issues 2 and 3 are quick wins worth applying before merge; issue 1 is a follow-up if you'd like the test to actually match its name. None block.

@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Solid, well-diagnosed three-layer fix for the fresh-install crash (#934). The root-cause work — attaching a stream 'error' listener via installLogTee — is the correct one; the other two layers (pathToFileURL + isBootstrapping guard) are independent bugs that were masking each other. Extracting main-safety-net.cjs for hermetic testability (CR-6) is the right call, and the pin-tests in test_loadapp_query.mjs will keep all three layers from silently regressing. The single most important thing the author should know: the collectCoverageFrom patterns in tests/electron/package.json do not include the new safety-net module, so its 12 tests don't count toward the enforced 50% threshold (see Minor #1 below).

Issues Found

🟢 Minor

1. Coverage globs don't include main-safety-net.cjs (tests/electron/package.json:14-22)

The collectCoverageFrom patterns enumerate src/gaia/electron/** and src/gaia/apps/**/webui/src/** but not src/gaia/apps/webui/*.cjs. The new module — and its 12 hermetic tests — are excluded from the coverage report and the 50 % threshold. Suggested addition:

    "collectCoverageFrom": [
      "../../src/gaia/electron/**/*.js",
      "../../src/gaia/apps/webui/*.cjs",
      "../../src/gaia/apps/webui/services/*.cjs",
      "../../src/gaia/apps/**/webui/src/**/*.js",
      "!../../src/gaia/apps/**/webui/src/renderer/**/*.js",
      "!**/node_modules/**",
      "!**/dist/**",
      "!**/out/**"
    ],

2. Inline fallback _fatalHandler is effectively unreachable (src/gaia/apps/webui/main.cjs:50-60)

The catch block defines a fallback _fatalHandler (lines 52-55) and then unconditionally calls process.exit(1) (line 60), which terminates synchronously. The .catch(_fatalHandler) on line 798 can only be reached if process.exit(1) itself throws — so the inline definition is, in practice, dead code. The comment frames it as defense-in-depth, but it's worth either dropping the inline definition (process.exit(1) is the safety) or moving the process.exit(1) to the very end of the catch block so the inline _fatalHandler definition isn't redundant. Not a correctness bug — just code that misleads future readers about whether the fallback path is exercised.

3. Test 6's cross-instance interaction is fragile (tests/electron/test_main_error_handling.js:180-217)

The test depends on instance 1's _inFatalHandler staying true (because process.exit is mocked) so that instance 2's listener is the one that increments. The comment on lines 199-202 documents this, but the cleaner pattern is to remove instance 1's listeners before installing instance 2 — the addedListeners array tracked in beforeEach already gives you what you need:

    process.emit("uncaughtException", new Error("crash 1"));
    const after1 = JSON.parse(fs.readFileSync(counterPath, "utf8"));
    expect(after1.count).toBe(1);

    // Remove instance 1's listeners so instance 2's fatal() runs cleanly
    // (rather than relying on instance 1's _inFatalHandler being stuck true
    // because process.exit is mocked).
    addedListeners.forEach(({ event, handler }) => {
      process.removeListener(event, handler);
    });
    addedListeners.length = 0;

    jest.resetModules();
    const { installSafetyNet: installSafetyNet2 } = require(SAFETY_NET_PATH);
    installSafetyNet2({

4. Operator-precedence readability (src/gaia/apps/webui/main.cjs:49, 53)

String(err && err.stack || err) parses correctly (&& binds tighter than ||) but the intent reads more clearly with explicit parens, matching the style used elsewhere in the file:

  try { dialog.showErrorBox("GAIA failed to start", String((err && err.stack) || err)); } catch { }

5. No regression test that installSafetyNet returns { fatal } (tests/electron/test_main_error_handling.js)

main.cjs:42 destructures { fatal: _fatalHandler } from the return value and routes the app.whenReady().then(...).catch() rejection through it (line 798). If a future refactor stops returning fatal, _fatalHandler becomes undefined and the catch handler silently no-ops on rejection. Worth a one-line assertion:

test("returns { fatal } so main.cjs can route .catch() through it", () => {
  const { installSafetyNet } = require(SAFETY_NET_PATH);
  const result = installSafetyNet({
    logPath, dialogModule: mockDialog(), appModule: mockApp(false),
  });
  expect(typeof result.fatal).toBe("function");
});

6. installLogTee re-bind sentinel is non-enumerable-friendly but documented (src/gaia/apps/webui/main-safety-net.cjs:155-157)

Setting stream._gaiaLogTeeBound = true mutates the user-supplied stream. The JSDoc note on line 152-153 already calls out single-call safety, so this is fine — but you could harden it by using WeakSet:

const _teedStreams = new WeakSet();
function installLogTee({ stream, logPath }) {
  if (_teedStreams.has(stream)) return;
  _teedStreams.add(stream);
  stream.on("error", (err) => { /* ... */ });
}

Optional cleanup, not a blocker.

Strengths

  • Three-layer diagnosis is exemplary — the PR description traces each masking failure clearly, and the comments at the call sites (main.cjs:124-126, main.cjs:203-206, main.cjs:480-482) tie each line of code back to its layer of [Bug]: Running GAIA fails after a fresh install of GAIA 0.17.4 #934 with the right level of "why this can't be removed."
  • Dependency-injection seam is the right design — main-safety-net.cjs accepts dialogModule / appModule / homedirFn, which makes the 12 Jest tests genuinely hermetic (no Electron runtime, no real ~/.gaia writes). This is the pattern other webui services should follow.
  • Pin tests in test_loadapp_query.mjs:242-308 lock all three layers (isBootstrapping, pathToFileURL, no-loadFile) at the call-site level — these will catch a partial revert that the unit tests in main-safety-net.cjs would miss.
  • Root-cause fix vs. defense-in-depth is correctly labelled — installLogTee is the actual fix; the uncaughtException / unhandledRejection handlers and crash-loop counter are explicitly framed as the safety net for the next time something like this slips through.

Verdict

Approve with suggestions. No blocking issues — the fix is correct, tested, and well-explained. The minor items above are optional polish; #1 (coverage globs) and #5 (assert { fatal } in the return) are the two worth applying before merge.

@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Targeted, well-scoped fix for the fresh-install crash on Windows (#934). The PR addresses three layered root causes — async stream 'error' from the log-tee, backslash file URLs rejected by Chromium 130+, and a window-all-closed race during the bootstrap-progress phase — and pulls the safety-net into main-safety-net.cjs so it can be unit-tested without main.cjs's side effects. Code is clean, tests are thorough (12 new Jest tests + 5 regression guards), and the approach is conservative (DI for Electron modules, single source of truth for the log path).

Issues Found

🟢 Minor — dead-code branch in the safety-net loader fallback (src/gaia/apps/webui/main.cjs:47-60)

The catch block defines an inline _fatalHandler (lines 53-56) and then immediately calls process.exit(1) on line 59. Because process.exit is synchronous, the app.whenReady().catch(_fatalHandler) microtask scheduled later in the file never runs — so the inline _fatalHandler definition is effectively dead. Either drop the fallback assignment, or drop the synchronous process.exit and rely on _fatalHandler to surface the failure. Picking one removes the contradiction the comment hints at ("narrow window before process.exit() below terminates").

} catch (err) {
  try { process.stderr.write(`[main] safety-net load failed: ${err.message}\n`); } catch { }
  try { dialog.showErrorBox("GAIA failed to start", String((err && err.stack) || err)); } catch { }
  // Synchronous exit — service module requires below have no
  // uncaughtException handler installed, so we cannot continue.
  process.exit(1);
}

🟢 Minor — internal review-round markers leak into source comments

Several comments reference internal review-round labels: CR-2 (main-safety-net.cjs:98, main.cjs:34), CR-4 (main-safety-net.cjs:123), CR-5 (main-safety-net.cjs:128), CR-6 (main-safety-net.cjs:24, main.cjs:34), and a couple in tests (e.g. test_main_error_handling.js:589, 668, 702, 722). These are meaningful right now but rot fast — a future reader has no way to look up "CR-4". Replace each with a one-line description of the constraint (e.g. CR-2: → // Pre-ready: showErrorBox is the only dialog that works on Windows...).

🟢 Minor — installLogTee WeakSet is module-level (main-safety-net.cjs:155)

_teedStreams is a module-level WeakSet, so its idempotency is process-global rather than per-installer. That's fine for the single-streamed real app, but the test in test_main_error_handling.js:768-781 works only because each jest.resetModules() re-requires the module and gets a fresh WeakSet. If a future test shares a module instance across cases and re-tees the same EventEmitter, the second call silently no-ops. Worth a one-line note in the JSDoc that the guard is module-scoped (not per-call).

🟢 Minor — installLogTee.logPath parameter is currently unused

installLogTee accepts logPath (main-safety-net.cjs:156) and appendLog writes to it on stream error (line 161). That's correct and documented, but worth confirming with a test — test_main_error_handling.js:767-779 only asserts that an 'error' listener is attached. A one-line follow-up expect(fs.readFileSync(logPath, "utf8")).toMatch(/STREAM_ERROR/) after emitting stream.emit('error', new Error('boom')) would lock in the actual root-cause fix, not just its prerequisite.

Strengths

  • Layered diagnosis matched by layered fix. Each of the three failure modes documented in the PR description has a corresponding code path: the stream 'error' listener (root-cause absorber), pathToFileURL (correct URL contract), and the isBootstrapping guard (race fix). Regression tests are pinned to all three layers in tests/electron/test_loadapp_query.mjs:374-441.
  • Clean extraction for testability. main-safety-net.cjs takes dialogModule / appModule / homedirFn via DI, so the 12 Jest tests cover real branches (pre-/post-ready dialog, re-entry guard, counter increment & reset, render-/child-process-gone, non-Error rejection coercion) without any Electron mock-globals trickery.
  • Single source of truth for the log path. Hoisting _GAIA_DIR / _MAIN_LOG_PATH to module scope (main.cjs:27-28) eliminates the two-callers-with-independent-path-computations footgun.

Verdict

Approve with suggestions. Already approved by @kovtcharov-amd; the items above are tidy-ups, not blockers. Worth folding in before merge if a quick fixup is convenient, otherwise track as a follow-up.

@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Solid, layered fix for a real fresh-install crash on Windows (#934). The PR diagnoses three stacked failures (async stream 'error' → uncaughtException → bare Electron dialog; loadFile() backslash URL rejected by Chromium 130+; premature app.quit() from window-all-closed while only the install-progress dialog existed) and addresses each at its root rather than masking the symptom. Code is well-commented, the dependency-injected main-safety-net.cjs factor-out makes the previously-untestable error path hermetically testable, and the regression suite (12 Jest tests for behavior + 4 grep-based contract pins in test_loadapp_query.mjs) is unusually thoughtful — every test ties back to a specific failure mode. The most important thing: the fix is bulletproof against the exact race in #934 and locks the contract with regression tests, so this won't silently come back.

Issues Found

🟢 Minor

child-process-gone may fire fatal on normal shutdown (main-safety-net.cjs:133-137)

Electron emits child-process-gone for any utility/GPU subprocess termination. During normal app.quit(), the GPU helper can disappear with reason: "killed" and would trigger the GAIA crash dialog. Worth filtering on details.reason (e.g., ignore "clean-exit" / "killed" while isQuitting):

  appModule.on("child-process-gone", (_event, details) => {
    const reason = details && details.reason;
    // Ignore expected terminations during shutdown so the crash dialog
    // doesn't flash on a clean quit.
    if (reason === "clean-exit" || reason === "killed") return;
    fatal(new Error(
      `child-process-gone: type=${details && details.type} reason=${reason}`
    ));
  });

(Similar consideration for render-process-gone, but the renderer's clean-exit path already covers shutdown.)

Bare catch { } blocks vs. CLAUDE.md "no silent fallbacks" (main-safety-net.cjs:48, 59, 83, 111, 113)

The safety-net layer uses try { ... } catch { } to swallow stderr/dialog/exit errors. This is the textbook exception to the rule — we're already in the fatal-exit path with no upstream caller to report to — but the guideline says to catch specific exceptions. A short comment on the bare catches reaffirming "intentional swallow: fatal path" would help future reviewers and bring this in line with the CLAUDE.md spirit. No code change required if you'd rather leave it as-is.

installSafetyNet registers appModule.on(...) handlers without a teardown hook (main-safety-net.cjs:125, 129, 133)

In production installSafetyNet is called once, so no leak. But the API doesn't expose an uninstall() and tests only clean up process.on listeners (the appModule is a fresh EventEmitter per test, so it's incidentally safe). If anyone ever calls this twice on the same app (e.g., a future "safe-mode reload"), browser-window-focus will reset the counter twice and the dialog will fire twice. Worth a one-line comment on the function or returning an uninstall callback for symmetry with { fatal }.

URLSearchParams ordering / encoding parity (main.cjs:475-477)

pathToFileURL().href + ?api=... is correct, but buildIndexQuery previously fed Electron's loadFile({ query }), which uses Node's querystring. URLSearchParams differs in encoding rules (e.g., it percent-encodes +, *, etc. differently). If apiBase.ts parses the query strictly against an allowlist (the comment at loadApp:466-468 references TRUSTED_API_RE), confirm an http://localhost URL still round-trips identically. Worth a quick manual smoke run against the regex to make sure you didn't shift any encoding.

Strengths

  • Three-layer bug → three-layer fix, each at the root. The PR description traces the chain (ERR_STREAM_WRITE_AFTER_END → ERR_FAILED -2 from backslash URLs → ERR_FAILED -2 from premature app.quit() race) and addresses each layer rather than papering over the symptom. The installLogTee 'error' listener in particular is a genuine root-cause fix, not a workaround.
  • Hermetic tests via dependency injection. installSafetyNet({ logPath, dialogModule, appModule, homedirFn }) makes the error path fully testable without launching Electron — every fs write goes to a tmp dir, every electron call is a Jest mock. The 12-test suite covers the re-entry guard, pre/post-app.ready dialog branch, crash counter increment + reset, stream error absorption, non-Error rejection coercion, and contract ({ fatal } return shape). Contract pins via grep in test_loadapp_query.mjs add a second layer of regression protection.
  • WHY-comments at every non-obvious decision. _GAIA_DIR/_MAIN_LOG_PATH shared-constant rationale, isBootstrapping reset placement after createWindow(), showErrorBox vs. showMessageBoxSync based on app.isReady(), the explicit TODO(feat(electron): wire crash-loop counter into safe-mode launch #938) for crash-loop safe-mode entry — all the load-bearing decisions carry their reason inline. This makes future maintenance much cheaper.

Verdict

Approve with suggestions. The minor issues above are non-blocking — child-process-gone filtering is the most consequential and is worth a follow-up either here or in a dedicated commit. Everything else is a nit. The core fix is correct, well-tested, and the right shape architecturally.

@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Solid, surgical fix for a nasty three-layer bootstrap crash on fresh installs. Each layer is correctly diagnosed (stream 'error' not caught by sync try/catch → backslash file:// URLs rejected by Chromium 130+ → premature app.quit() racing loadURL()), each layer gets a targeted fix, and the regression guards in test_loadapp_query.mjs are well-chosen pins so future refactors can't silently re-introduce any of the three. The extracted main-safety-net.cjs is hermetic, dependency-injected, and well-covered by 12 Jest tests. Most important thing for the author: layer-3's isBootstrapping flag is set true at module load and only flipped after createWindow() — keep that invariant in mind for any future refactor of app.whenReady(), because the early-return path (bootstrapOk === false at main.cjs:712) leaves isBootstrapping = true forever, which is benign today but would matter if a future caller depended on the flag.

Issues Found

🟢 Minor

1. Counter-reset comment overstates "first" interaction (main-safety-net.cjs:144)

The comment says "Reset counter on the first successful user interaction" but the listener fires on every browser-window-focus, so the counter is rewritten on every refocus. The behavior is fine (it's idempotent and cheap), but the comment is misleading.

  // Reset counter on user interaction. Resetting at loadApp() is too early —
  // the user may crash before their first focus. browser-window-focus fires
  // on every focus (idempotent rewrite of count=0 is fine).
  appModule.on("browser-window-focus", () => writeCount(0, homedir));

2. child-process-gone filter only excludes two reasons (main-safety-net.cjs:153-161)

Electron's details.reason can be clean-exit, abnormal-exit, killed, crashed, oom, launch-failed, or integrity-failure. Filtering only clean-exit and killed means a backend SIGTERM during shutdown that races with Chromium teardown could surface as abnormal-exit and trigger the FATAL dialog on quit. Worth either documenting why only those two are filtered, or expanding the filter:

  appModule.on("child-process-gone", (_event, details) => {
    const reason = details && details.reason;
    // Ignore expected terminations during shutdown so the crash dialog
    // doesn't flash on a clean quit. abnormal-exit covers SIGTERM races
    // between the backend and Chromium teardown.
    if (reason === "clean-exit" || reason === "killed" || reason === "abnormal-exit") return;
    fatal(new Error(
      `child-process-gone: type=${details && details.type} reason=${reason}`
    ));
  });

(If you'd rather keep the stricter filter and surface abnormal-exit as fatal, leave it — but please add a one-line comment about why.)

3. _fatalHandler is referenced before being guaranteed-defined (main.cjs:790)

If the require("./main-safety-net.cjs") block at line 40 throws, _fatalHandler is undefined — but that path also calls process.exit(1) synchronously, so app.whenReady() never resolves and the .catch() handler never fires. The code is correct as-written, but a future refactor could turn process.exit(1) into something async and silently break the catch path. A defensive null check would future-proof:

}).catch((err) => {
  // Route explicit rejection through the safety-net so the user gets a
  // GAIA-branded dialog and a stack trace in the log (issue #934).
  if (_fatalHandler) {
    _fatalHandler(err);
  } else {
    try { process.stderr.write(`[main] whenReady rejected with no fatal handler: ${err && err.stack || err}\n`); } catch { }
    process.exit(1);
  }
});

4. Spying on process.on is broad (tests/electron/test_main_error_handling.js:531-536)

jest.spyOn(process, "on").mockImplementation(...) captures every process.on call during the test, not just installSafetyNet's. If anything else (Jest internals, lazy requires) registers a process listener mid-test, it lands in addedListeners and gets removed in afterEach. Hasn't bitten today, but it's a flakiness vector. Cheap fix — filter to known events:

    addedListeners = [];
    const origOn = process.on.bind(process);
    jest.spyOn(process, "on").mockImplementation((event, handler) => {
      if (event === "uncaughtException" || event === "unhandledRejection") {
        addedListeners.push({ event, handler });
      }
      origOn(event, handler);
    });

Strengths

  • Three-layer root-cause analysis is exemplary. PR description names the symptom, the masking, and the fix at each layer. The split into "absorb stream errors" ([Bug]: Running GAIA fails after a fresh install of GAIA 0.17.4 #934 layer 1, the proximate cause) and "fix the URL format / quit-race" (layers 2-3, the actually-fatal causes) is the right way to think about masked failures.
  • Hermetic, DI-friendly extraction (main-safety-net.cjs). Pulling the safety-net into its own module so tests can require it without dragging in Electron's dialog/app is the right call. The homedirFn injection on top of that lets the crash-counter test point at a tmp dir cleanly.
  • Regression guards pin the invariants, not the implementation. The new tests in test_loadapp_query.mjs (forward-slash URL, no loadFile(), isBootstrapping set after createWindow()) are exactly the right shape: they pin the contract layer-by-layer, so a future refactor that re-introduces any of the three bugs fails at PR time instead of on a customer's fresh install.
  • pathToFileURL is the textbook fix. Going through URL + URLSearchParams for the query string also avoids a class of escaping bugs that ad-hoc string concatenation hits.

Verdict

Approve with suggestions — the four minor items are polish, not blockers. Already approved by @kovtcharov-amd; safe to merge as-is or after applying any of the suggestions above (the child-process-gone filter is the most worth picking up before shipping, since it's user-visible if it triggers on a clean backend SIGTERM during quit).

@github-actions github-actions Bot added the devops DevOps/infrastructure changes label May 1, 2026
@github-actions

github-actions Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Targeted three-layer fix for the v0.17.4 fresh-install crash (#934): a process-wide safety net for async stream errors / unhandled rejections, a loadFile() → loadURL(pathToFileURL(...)) switch for Windows backslash compatibility, and an isBootstrapping guard that prevents the progress-dialog teardown from racing app.quit() against createWindow(). The extraction of main-safety-net.cjs as a dependency-injected module makes the otherwise untestable Electron main-process logic hermetically unit-testable, and the 12 new Jest tests + 4 new regex regression tests pin every layer of the fix against silent regressions. The most important thing the author should know: the fix is well-scoped and well-documented — only minor polish items below.

Issues Found

🟢 Minor

1. URLSearchParams constructor expects iterable/object, not the result of buildIndexQuery() if it returns nested values (src/gaia/apps/webui/main.cjs:476)

new URLSearchParams(indexQuery).toString() only round-trips correctly if every value in indexQuery is a primitive (string / number / boolean). Looking at services/index-query.cjs would confirm, but worth a one-line guard or a comment pinning the contract since the previous loadFile({ query }) was more permissive about types. Not blocking — flagging because the encoding contract is now subtly different from before.

2. Underscore-prefixed module-level constants (src/gaia/apps/webui/main.cjs:27-28)

const GAIA_DIR = path.join(os.homedir(), ".gaia");
const MAIN_LOG_PATH = path.join(GAIA_DIR, "electron-main.log");

JS convention reserves _ prefix for "private" object/class members; module-scoped constants typically use SCREAMING_SNAKE without the underscore. Same applies to _fatalHandler, _inFatalHandler, _teedStreams — the underscore reads like "deprecated/internal" in JS rather than "module-private", but the rest of these are scoped tightly enough that I'd leave them alone. Stylistic only.

3. Bootstrap-failure path leaves isBootstrapping = true (src/gaia/apps/webui/main.cjs:712-715)

When bootstrapBackend() returns false, the code calls app.quit() directly. Because isBootstrapping is still true, the window-all-closed handler (line 800) early-returns and does not call app.quit() again — which is actually the desired behavior (avoid double-quit), but it's worth either a one-line comment at line 714 acknowledging the interaction, or explicitly setting isBootstrapping = false before app.quit() so the flag's lifecycle is monotonic. Right now reading this in isolation looks like a bug.

4. Test 6's listener-removal dance is brittle (tests/electron/test_main_error_handling.js:660-698)

The test installs two safety nets back-to-back on the same process and manually removes instance 1's listeners between the two emits. This works because _inFatalHandler is closure-scoped (per-instance), and the comment correctly explains why — but jest.isolateModules(() => { ... }) would express the same intent without manual listener bookkeeping and would survive future refactors that change which listeners are installed. Not blocking; current test is correct.

5. Greedy regex in loadApp() regression test (tests/electron/test_loadapp_query.mjs:467)

const loadAppMatch = src.match(/async function loadApp\(\)\s*{([\s\S]*?)\n}/);

The \n} terminator only matches a closing brace at column 0. That happens to be true for loadApp() today, so the test passes, but a future Prettier-style indent change would silently truncate the captured body. Consider matching a balanced-brace span or anchoring on the next async function declaration. Minor — would only fail loudly anyway, so not blocking.

6. installMainLogTee() IIFE registers process.on("exit", ...) unconditionally (src/gaia/apps/webui/main.cjs:127)

If something unrelated re-runs the IIFE (e.g. test harness loading main.cjs), exit listeners would accumulate. Currently main.cjs isn't imported by tests (good — that's the whole point of the extraction), but worth noting that _teedStreams.has(stream) makes installLogTee itself idempotent while the surrounding IIFE is not. Acceptable as-is.

Strengths

  • Root-cause fix at the right layer. Adding stream.on('error') directly absorbs ERR_STREAM_WRITE_AFTER_END before it escalates, rather than relying solely on the uncaughtException net to mask it. Both layers are present, and the comment at main.cjs:116-118 explains exactly why both are needed.
  • Hermetic, dependency-injected test surface. installSafetyNet({ dialogModule, appModule, homedirFn }) is a textbook seam — Electron objects mocked, os.homedir() overridable per test, tmp-dir-isolated I/O. The 12 Jest tests + 4 regex pinning tests cover every documented invariant (re-entry guard, pre/post-app.ready dialog branch, counter reset trigger, render/child-process-gone handlers, non-Error rejection coercion, return contract).
  • Single source of truth for the log path. Moving _GAIA_DIR / _MAIN_LOG_PATH to module scope eliminates the previous duplicate-path drift between installSafetyNet and installMainLogTee.
  • Each fix carries a stack-trace-grade comment. The why is documented at every site ([Bug]: Running GAIA fails after a fresh install of GAIA 0.17.4 #934 layer 1/2/3, why pathToFileURL, why move isBootstrapping = false after createWindow(), why browser-window-focus instead of loadApp() for the counter reset).
  • CI smoke timeout bump (90s → 300s) is justified in-line — the comment explains that fresh-install runs include a ~3GB model download and references the matching structural / distro-matrix jobs.

Verdict

Approve with suggestions. No 🔴 or 🟡 blockers; the fix is correct, well-tested, and well-explained. The minor items above are optional polish — none gate merge.

@itomek
itomek added this pull request to the merge queue May 1, 2026
Merged via the queue into main with commit ce9c808 May 1, 2026
46 checks passed
@itomek
itomek deleted the 934-bug-running-gaia-fails-after-a-fresh-install-of-gaia-0174 branch May 1, 2026 19:33
itomek added 5 commits May 1, 2026 16:33
Without a top-level uncaughtException/unhandledRejection handler, a
synchronous throw at service-module-load time (missing native dep,
malformed JSON in agent-seeder, missing VC++ runtime, etc.) escapes to
Electron's default handler. On a packaged Windows build that either
dies silently (no console attached) or shows the bare "A JavaScript
error occurred in the main process" dialog with no GAIA branding and
no actionable info — the v0.17.4 fresh-install crash class.

This is the T0 minimal patch: just enough to (a) write the full stack
to ~/.gaia/electron-main.log so we have post-mortem evidence on real
fresh-install failures, and (b) show a native error box that survives
the pre-app-ready window. Uses dialog.showErrorBox because
showMessageBoxSync silently no-ops on Windows pre-app.ready.

Also fixes the missing .catch() on app.whenReady().then(...) — without
it, an async throw in the whenReady chain becomes an unhandledRejection
that Node logs and may exit on silently.

Per-stage labelling, crash-loop guard, and diagnostics-bundle button
land in T2-T11 once T0 has captured a real stack trace from a fresh
Win11 repro.
#934)

Three root-cause fixes confirmed on Win11 fresh install:

1. Extract installSafetyNet/installLogTee into main-safety-net.cjs so the
   safety net is testable without main.cjs side effects. Replaces the T0
   inline block with a proper module (12 Jest tests, all passing).

2. Add stream.on('error') listener via installLogTee to absorb the async
   ERR_STREAM_WRITE_AFTER_END that fires when console.log writes to an
   already-ended log-tee stream. The try/catch in wrap() only catches
   synchronous throws; Node.js emits stream errors asynchronously so they
   escaped to uncaughtException in v0.17.4.

3. Replace mainWindow.loadFile() with loadURL(pathToFileURL()) to produce
   forward-slash file:// URLs on Windows. Node's url.format() (used by
   loadFile internally) emits file:///C:\path with backslashes; Chromium
   130+ (Electron 40) rejects these, causing ERR_FAILED (-2) on the initial
   page load.

Closes #934
When the backend installer's progress dialog is destroyed after a
successful first-run install, Electron fires window-all-closed. At that
point trayManager is null (not yet created), so app.quit() fired
immediately. The async cleanup completed instantly (nothing to tear
down), fired a second app.quit() that wasn't prevented by will-quit,
and Electron began tearing down Chromium right as the startup sequence
called createWindow() then loadURL() — causing the renderer to fail
navigation with ERR_FAILED (-2).

Fix: add an isBootstrapping flag (true until createWindow() runs) that
makes window-all-closed a no-op during the install phase. The premature
quit chain never starts; startup continues normally after the progress
dialog closes.

Verified on a fresh install (uninstall + delete ~/.gaia + reinstall) on
Windows 11 — app now loads correctly after backend install completes.
- Drop CR-3 symlink check from writeCount() — the TOCTOU windows it
  introduced were worse than the threat it guarded against in ~/.gaia
  (user-owned directory); plain writeFileSync is sufficient.
- Extract _GAIA_DIR/_MAIN_LOG_PATH constants in main.cjs so
  installSafetyNet and installMainLogTee share a single log-path
  computation rather than two independent strings that could drift.
- Fix STREAM_ERROR log line to prefer err.message, fall back to
  err.stack, then String(err) — avoids logging "undefined" on errors
  with no message property.
- Correct the re-entry guard comment from "module-scoped" to
  "closure-scoped" (each installSafetyNet call gets its own guard).
- Harden test 11: replace the silent early-return on missing
  installLogTee export with expect(typeof installLogTee).toBe("function")
  so a missing export fails loudly.
- appendLog and writeCount now write to stderr on failure instead of
  silently swallowing errors, so log/counter failures are visible in
  packaged builds that don't have a terminal
- Consolidate two separate require('./main-safety-net.cjs') calls in
  main.cjs into a single destructured require at the top of the file;
  installLogTee was already in scope and did not need re-requiring
  inside the installMainLogTee IIFE
itomek and others added 9 commits May 1, 2026 18:37
- Hoist pathToFileURL require to top-level imports (was re-required on
  every loadApp() call); remove the inline require inside loadApp()
- Wrap safety-net require in try/catch so a corrupt ASAR or bad path
  still surfaces via stderr + dialog.showErrorBox instead of Electron's
  bare JS-error dialog
- Add TODO comment on crash-loop counter noting it is forensic-only until
  a safe-mode consumer is wired up
- Add JSDoc note to installLogTee that it must be called at most once per
  stream instance to avoid duplicate listeners
- Remove dead emitter.exit mock from mockApp() helper in tests -- the
  safety net calls process.exit, never app.exit
- Add three pathToFileURL tests to test_loadapp_query.mjs pinning the
  forward-slash contract that fixes issue #934 layer 2 (backslash file
  URLs on Windows -> ERR_FAILED -2)
- Add inline _fatalHandler fallback in the safety-net catch block so
  any later .catch(_fatalHandler) does not TypeError if app.exit(1) has
  not yet terminated the process
- Remove dead origUncaughtException/origUnhandledRejection variables from
  test_main_error_handling.js beforeEach (never assigned or read)
- Add two isBootstrapping regression tests to test_loadapp_query.mjs that
  pin the layer-3 fix: window-all-closed must check isBootstrapping, and
  isBootstrapping must be set false only after createWindow() returns
- Add synchronous process.exit(1) after app.exit(1) in the safety-net
  catch block so service module requires cannot execute in the window
  between app.exit() being scheduled and taking effect
- Correct misleading comment in test 6 -- the re-entry guard is
  closure-scoped per installSafetyNet() call, not module-scoped; the
  resetModules()+re-require creates a second independent instance
- Update crash-loop counter TODO to reference issue #938 (filed)
- Add main-safety-net.cjs to package.json files array so npm pack/publish
  does not ship a tarball that throws MODULE_NOT_FOUND at startup
- Add _gaiaLogTeeBound idempotency guard to installLogTee so calling it
  twice on the same stream does not register duplicate error listeners
- Rewrite test 3 to genuinely exercise the re-entry guard: the first
  showErrorBox call now emits a second uncaughtException synchronously
  while _inFatalHandler is true, asserting the re-entrant call bails
  with process.exit(2) before reaching the dialog again
- Add main-safety-net.cjs and services/*.cjs to Jest collectCoverageFrom
  so the 13 hermetic tests count toward the 50% coverage threshold
- Move process.exit(1) to end of safety-net catch block so _fatalHandler
  fallback is reachable before the process terminates; fix operator
  precedence to String((err && err.stack) || err) in both dialog calls
- Clean up instance 1 listeners before installing instance 2 in test 6
  (counter increment) so the test does not rely on _inFatalHandler being
  stuck true due to mocked process.exit
- Add test 13 asserting installSafetyNet returns { fatal } -- guards
  against a refactor that drops the return value silently no-oping the
  app.whenReady().catch(_fatalHandler) call in main.cjs
- Replace _gaiaLogTeeBound stream mutation with a WeakSet so installLogTee
  idempotency does not mutate the caller-supplied stream object
- Drop dead _fatalHandler fallback from safety-net catch block -- process.exit(1)
  is synchronous so the fallback was unreachable; keep only the synchronous exit
- Replace all CR-N comment markers with descriptive text so future readers
  do not need review-round archaeology to understand the constraint
- Add module-scoped WeakSet note to installLogTee JSDoc clarifying that the
  idempotency guard is process-global, not per-call
- Extend test 11 to assert that installLogTee actually writes STREAM_ERROR
  to logPath on stream error emission -- pins the root-cause fix, not just
  the listener registration prerequisite
…ursor test

Safety-net changes:
- Filter child-process-gone for clean-exit/killed reasons so normal Electron
  shutdown does not trigger the crash dialog
- Add intentional-swallow comment on bare catch blocks in the fatal path
  per CLAUDE.md spirit (we are already in fatal-exit, no upstream to report)

Test cleanup:
- Remove stale input-cursor test from test_electron_chat_app.js -- the
  .input-cursor span was intentionally removed by 37e35eb (Chat Lite
  feature, April 29) without updating the test, causing this CI failure
  on every run since that commit merged
…catches

- Filter child-process-gone for reason=clean-exit or reason=killed so the
  crash dialog does not flash during a normal app.quit() sequence when the
  GPU helper terminates as expected
- Add "intentional: fatal path" annotation on bare catch blocks in fatal()
  per CLAUDE.md spirit -- we are in the fatal-exit path with no upstream
  caller to surface errors to
The userns-restricted AppImage smoke test polled ``state: ready`` for
90 seconds, but ``gaia init --profile minimal`` downloads the Gemma-4-E4B
GGUF model (~3 GB) on first run and that exceeds 90s on the public
runner.  The structural and distro-matrix smoke jobs already use 300s
for the same reason; align this one too.

Failure mode it fixed: ``state: installing (gaia-init)`` … ``Step 3/4:
Downloading models for 'minimal' profile`` → timer elapses →
``::error::userns-restricted launch did not reach state: ready``.
theonlychant pushed a commit to theonlychant/gaia that referenced this pull request May 5, 2026
Fixes amd#934 — GAIA fails to start after a clean install of 0.17.4.

## What was the bug

Three layered failures, each masking the next:

**1. `ERR_STREAM_WRITE_AFTER_END` → bare Electron crash dialog.** The
log-tee stream (`electron-main.log`) was created early in startup. On
app exit, `process.on('exit')` called `stream.end()`. If anything then
called `console.log()`, the stream emitted an async `'error'` event.
Because no `'error'` listener was attached, Node promoted it to
`uncaughtException`, which Electron surfaced as a raw JS error dialog
with no GAIA branding.

**2. `ERR_FAILED (-2)` loading `index.html`.** Even after adding an
`'error'` listener to absorb the stream error, the app still crashed
with a navigation failure. The URL format was wrong: Node's
`url.format()` (used internally by Electron's `loadFile()`) produces
`file:///C:\path` with backslashes on Windows. Chromium 130+ (Electron
40) rejects backslash file URLs → `ERR_FAILED (-2)`.

**3. `ERR_FAILED (-2)` on a clean install even with correct URL.** After
switching to `pathToFileURL()` (which produces forward-slash URLs), the
crash still happened on a *truly* fresh install where `~/.gaia` didn't
exist. The root cause: after the backend installer's progress dialog is
destroyed on install completion, Electron fires `window-all-closed`. At
that point `trayManager` hadn't been created yet, so the handler called
`app.quit()`. The async cleanup finished instantly (nothing to tear
down), fired a second `app.quit()` that `will-quit` didn't prevent, and
Electron began tearing down Chromium — right as the startup sequence
called `createWindow()` then `loadURL()`. The renderer process was
invalidated mid-navigation → `ERR_FAILED (-2)`.

## What we changed

- **`main-safety-net.cjs`** (new) — extracted `installSafetyNet` and
`installLogTee` from `main.cjs`. `installSafetyNet` registers
`uncaughtException`/`unhandledRejection` handlers that write a FATAL
entry to the log and show a GAIA-branded error dialog. `installLogTee`
attaches a `'error'` listener to the log-tee stream, absorbing
write-after-end errors before they reach the global handler.
- **`main.cjs`** — switched `loadFile()` → `loadURL(pathToFileURL(...))`
for correct forward-slash file URLs on Windows. Added `isBootstrapping`
flag (true until `createWindow()` runs) that makes `window-all-closed` a
no-op during the install phase, preventing the premature quit race.
- **`electron-builder.yml`** — added `main-safety-net.cjs` to the ASAR
files list.
- **`tests/electron/test_main_error_handling.js`** — 12 Jest tests
covering `installSafetyNet` and `installLogTee` (re-entry guard,
pre/post-ready dialog branch, crash counter, stream error absorption,
etc.).

## How we tested

Manual fresh-install test on Windows 11 (uninstall → delete `~/.gaia` →
reinstall from the built NSIS `.exe`):
- Before: "GAIA crashed" dialog appeared immediately after the backend
installer completed; `~/.gaia/electron-main.log` showed `FATAL
ERR_FAILED (-2) loading file:///C:/...index.html`.
- After: app launched normally, backend connected, chat UI loaded.

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

devops DevOps/infrastructure changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Running GAIA fails after a fresh install of GAIA 0.17.4

3 participants