Repository navigation
fix(webui): fix fresh-install crash on first launch (#934) - #935
Conversation
SummaryTight, 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 Issues Found🟡 Important1. CR-3 symlink protection is a TOCTOU and doesn't deliver on its claim ( The pattern Given the file lives in 2. Log-path duplication invites drift ( Two independent computations of // 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: …and reuse 🟢 Minor3. Matches the pattern 4. CR-1 comment says "module-scoped" but the guard is closure-scoped ( The distinction matters — test 6 ( 5. Test 11 silently passes if 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 6. Test 11 doesn't actually exercise the absorption behavior, only the listener-count ( Stronger coverage of the literal #934 root cause would emit an 7. Test 6 relies on cross-install listener ordering ( After 8. Crash counter is write-only (
Strengths
VerdictApprove 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. |
|
Thanks for the thorough review. Addressed in 4f9a038: 🟡 Fixed before merge:
🟢 Fixed in the same commit:
Deferred as follow-ups:
On the CI failures: both |
SummaryThis 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: Issues Found🟢 Minor1. Empty
Same pattern applies to 2. Module is cached, so functionally equivalent — but a single destructure at the top is cleaner: Then drop line 106 entirely (it'll already be in scope inside 3. Not a bug — 4. 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
VerdictApprove with suggestions. No blocking issues. The four 🟢 items above are stylistic / convention nits — none block merge. Recommend folding suggestion 1 (stderr fallback in |
|
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 ( This PR touches only |
SummaryTight, 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 → Issues Found🟢 MinorCrash-loop counter is write-only — no consumer drives safe-mode ( Mock The safety net calls
No unit test for the
Strengths
VerdictApprove with suggestions. No 🔴 or 🟡 blockers. The minor items above (counter consumer, dead |
SummaryThis PR cleanly fixes the three-layered fresh-install crash documented in #934 (stream-error promotion → backslash file URL → premature Issues Found🟡 Important
If 🟢 Minor
This is layer 3 of the fix — the most subtle of the three (timing-dependent race against 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 (
Test 3 name is slightly misleading ( The dialog throw is swallowed by the Fragile regex for
Crash counter writes are non-atomic (
Strengths
VerdictApprove with suggestions. No blocking issues. The 🟡 |
SummarySolid, well-scoped fix for a three-layer fresh-install crash on Windows. Each layer of the bug ( Issues Found🟢 Minor —
|
SummaryHigh-quality, layered fix for a fresh-install crash that was masking three independent failures (stream Issues Found🟢 Minor1. Test 3 ( The test makes To genuinely cover the guard, the test needs a path that re-invokes 2.
3. The JSDoc warns "Must be called at most once per stream instance" but there's no enforcement. Currently safe (only called once from Strengths
VerdictApprove 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. |
SummarySolid, well-diagnosed three-layer fix for the fresh-install crash (#934). The root-cause work — attaching a stream Issues Found🟢 Minor1. Coverage globs don't include The 2. Inline fallback The catch block defines a fallback 3. Test 6's cross-instance interaction is fragile ( The test depends on instance 1's 4. Operator-precedence readability (
5. No regression test that
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. Setting 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
VerdictApprove 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 |
SummaryTargeted, well-scoped fix for the fresh-install crash on Windows (#934). The PR addresses three layered root causes — async stream Issues Found🟢 Minor — dead-code branch in the safety-net loader fallback (
|
SummarySolid, layered fix for a real fresh-install crash on Windows (#934). The PR diagnoses three stacked failures (async stream Issues Found🟢 Minor
Electron emits (Similar consideration for Bare The safety-net layer uses
In production
Strengths
VerdictApprove with suggestions. The minor issues above are non-blocking — |
SummarySolid, surgical fix for a nasty three-layer bootstrap crash on fresh installs. Each layer is correctly diagnosed (stream Issues Found🟢 Minor1. Counter-reset comment overstates "first" interaction ( The comment says "Reset counter on the first successful user interaction" but the listener fires on every 2. Electron's (If you'd rather keep the stricter filter and surface 3. If the 4. Spying on
Strengths
VerdictApprove 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 |
SummaryTargeted three-layer fix for the v0.17.4 fresh-install crash (#934): a process-wide safety net for async stream errors / unhandled rejections, a Issues Found🟢 Minor1.
2. Underscore-prefixed module-level constants ( JS convention reserves 3. Bootstrap-failure path leaves When 4. Test 6's listener-removal dance is brittle ( The test installs two safety nets back-to-back on the same 5. Greedy regex in const loadAppMatch = src.match(/async function loadApp\(\)\s*{([\s\S]*?)\n}/);The 6. If something unrelated re-runs the IIFE (e.g. test harness loading Strengths
VerdictApprove with suggestions. No 🔴 or 🟡 blockers; the fix is correct, well-tested, and well-explained. The minor items above are optional polish — none gate merge. |
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
- 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``.
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]>
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')calledstream.end(). If anything then calledconsole.log(), the stream emitted an async'error'event. Because no'error'listener was attached, Node promoted it touncaughtException, which Electron surfaced as a raw JS error dialog with no GAIA branding.2.
ERR_FAILED (-2)loadingindex.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'surl.format()(used internally by Electron'sloadFile()) producesfile:///C:\pathwith 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 topathToFileURL()(which produces forward-slash URLs), the crash still happened on a truly fresh install where~/.gaiadidn't exist. The root cause: after the backend installer's progress dialog is destroyed on install completion, Electron fireswindow-all-closed. At that pointtrayManagerhadn't been created yet, so the handler calledapp.quit(). The async cleanup finished instantly (nothing to tear down), fired a secondapp.quit()thatwill-quitdidn't prevent, and Electron began tearing down Chromium — right as the startup sequence calledcreateWindow()thenloadURL(). The renderer process was invalidated mid-navigation →ERR_FAILED (-2).What we changed
main-safety-net.cjs(new) — extractedinstallSafetyNetandinstallLogTeefrommain.cjs.installSafetyNetregistersuncaughtException/unhandledRejectionhandlers that write a FATAL entry to the log and show a GAIA-branded error dialog.installLogTeeattaches a'error'listener to the log-tee stream, absorbing write-after-end errors before they reach the global handler.main.cjs— switchedloadFile()→loadURL(pathToFileURL(...))for correct forward-slash file URLs on Windows. AddedisBootstrappingflag (true untilcreateWindow()runs) that makeswindow-all-closeda no-op during the install phase, preventing the premature quit race.electron-builder.yml— addedmain-safety-net.cjsto the ASAR files list.tests/electron/test_main_error_handling.js— 12 Jest tests coveringinstallSafetyNetandinstallLogTee(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):~/.gaia/electron-main.logshowedFATAL ERR_FAILED (-2) loading file:///C:/...index.html.