Skip to content

fix(electron): fail startup loudly on port errors and validate tray config - #4299

Merged
kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:claude/electron-port-tray-validation
Sep 26, 2026
Merged

kovtcharov-amd merged 4 commits into
amd:mainfrom
kovtcharov:claude/electron-port-tray-validation

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Before: if the desktop app couldn't reserve a free port, it quietly started the backend on 4200. If another process already held 4200, the backend failed to bind and the window talked to whatever was listening there. After: startup stops and shows the existing fatal error dialog, which says what failed and where the log is. Separately, the tray settings handler used to crash on a null payload, write any key the renderer sent into ~/.gaia/tray-config.json, and pass non-booleans to the OS "start at login" API. It now accepts only the three real settings and rejects anything that isn't a boolean.

Unknown keys are dropped rather than rejected. The renderer sends back whatever tray:get-config returned, so junk keys already on disk from the old behaviour get cleaned up on the next save instead of breaking it. No overlap with #4186, which touches a different function in main.cjs.

Test plan

  • New tests fail on origin/main (10 failed / 25 passed): cd tests/electron && npx jest main-startup-order.test.cjs tray-manager.test.cjs
  • Same command after the fix: 35/35 pass
  • Full Electron Jest suite: cd tests/electron && npm test: 25 suites, 710 tests pass
  • CI node:test step: node --test tests/electron/test_port_manager.mjs tests/electron/test_loadapp_query.mjs: 25 pass
  • Manual: launch the packaged app and change tray settings (start on login, minimize to tray); they still persist

Fixes #4234

…onfig

If the desktop app couldn't reserve a free port it quietly started the backend on 4200, where another GAIA or any other process may already be listening, so the window could talk to the wrong server. It now stops with the startup error dialog instead. The tray settings handler crashed on a null payload, wrote any key the renderer sent into ~/.gaia/tray-config.json, and handed non-booleans to the OS login-item API; it now accepts only the three known settings and requires booleans.

Fixes amd#4234
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Two real fail-loudly gaps get closed here: the desktop app no longer quietly starts the backend on 4200 when it can't reserve a port (it now stops with the branded error dialog), and the tray settings handler no longer crashes on a null payload, writes arbitrary renderer keys to disk, or hands non-booleans to the OS "start at login" API. The change is well-tested and the error message tells the user what to check and where the log is.

One thing worth fixing before merge: the new tray validation also rejects values it finds already on disk. If a config file written by the old, unvalidated handler holds a wrong-typed setting, every future save fails with an error the user can't act on — tray settings become permanently unsavable. The PR description says stale junk from the old behaviour gets cleaned up on the next save; that holds for unknown keys, not for wrong-typed known ones. Sanitizing when the file is read fixes it in a few lines.

Smaller: a comment elsewhere in the app still documents the port fallback this PR just deleted, and the neighbouring "GAIA backend not found" branch in the same function still degrades quietly rather than failing loudly — out of scope for the title, but worth a follow-up.

Real-world evidence

No evidence-bundle.md in this checkout — N/A for the automated lane, since the Electron main process can't be launched on a no-inference CI runner. I ran the PR's own Jest target here to confirm the claim in the test plan:

$ npx jest main-startup-order.test.cjs tray-manager.test.cjs
Test Suites: 2 passed, 2 total
Tests:       35 passed, 35 total

I also reproduced the stale-config failure above with a scratch Jest case (non-boolean startOnLogin on disk → a valid minimizeToTray save rejects and nothing is written). The remaining surfaces — the fatal dialog on a port failure, and the unchecked test-plan item for tray settings persisting in the packaged app — rest on static review only; both need the packaged desktop app, so the manual check is the one gap left.

🔍 Technical details

🟡 Important

Stale non-boolean in tray-config.json blocks every later save (src/gaia/apps/webui/services/tray-manager.cjs:281-286)

_loadConfig() (line 238) still blind-merges the file into this.config, so the new handler's per-key loop reads an unvalidated stored value for any key the payload omits and throws on it. The renderer round-trips tray:get-config → tray:set-config, so the full-payload path fails too — and _saveConfig() never runs, so the bad value can't be overwritten. Verified with a scratch test: disk {"tray":{"startOnLogin":"true",…}}, payload {tray:{minimizeToTray:false}} → rejects with tray.startOnLogin must be a boolean, writeFileSync not called.

Validate where the untrusted bytes enter — keep the IPC handler strict about caller input, and repair the file at load with a warning:

        const storedTray = isPlainObject(loaded.tray) ? loaded.tray : {};
        const tray = { ...DEFAULT_CONFIG.tray };
        for (const key of Object.keys(DEFAULT_CONFIG.tray)) {
          if (typeof storedTray[key] === "boolean") {
            tray[key] = storedTray[key];
          } else if (key in storedTray) {
            console.warn(
              `[tray] Ignoring non-boolean ${key} in ${CONFIG_PATH}; using default`
            );
          }
        }
        return { ...DEFAULT_CONFIG, ...loaded, tray };

(replaces the return { ...DEFAULT_CONFIG, ...loaded, tray: {...} } block at lines 238-242). Worth a test alongside the new ones, and narrowing the "junk keys … get cleaned up on the next save" sentence in the description to unknown keys.

🟢 Minor

Stale JSDoc still documents the removed fallback (src/gaia/apps/webui/services/index-query.cjs:29-31) — the only other place describing this behaviour:

 * @param {number} port - Integer in (0, 65535]. Chosen by
 *   PortManager.findFreePort(); a failure there is fatal in main.cjs and
 *   never reaches this function.

Adjacent quiet-degradation branch left in place (src/gaia/apps/webui/main.cjs:303-308) — a missing gaia binary still console.errors and returns null, after which whenReady skips waitForBackend and the user gets a generic "cannot connect" banner instead of the dialog this PR just wired up. Outside the stated scope, but it's the same function and the same class of bug; a follow-up issue would be reasonable.

Strengths

  • The error text meets the project's actionable-error bar — what failed, what to check, where the log is — and { cause: err } keeps the original stack for the safety net, which routes it through _fatalHandler and exits rather than hanging with no window.
  • Allow-list-by-DEFAULT_CONFIG.tray-keys is the right shape for an IPC boundary: unknown keys can't reach disk, and _applyLoginItemSetting only ever sees a boolean.
  • Tests actually fail on main before the fix (10 failed / 25 passed per the description) and cover the payload matrix — null/undefined/string/array, unknown-key dropping, non-boolean rejection, and that a rejected path touches neither disk nor the login item.

pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Sep 25, 2026
… registration (amd#4338)

Several Electron IPC tests passed without ever calling the handler with
bad input. They only checked that a channel was registered, or they
mocked out the method under test. A broken check would still pass: the
updater could accept a path-traversal release tag, or the agent manager
could spawn a process for an unknown id, with no test failing. These
tests now call each handler the way the renderer does, pass malformed
input, and assert that the call is rejected and nothing else happens.
The install progress window had no tests at all and now has coverage.
This PR changes tests only. Temporarily loosening the updater's tag
regex fails 7 of the new tests, and removing the agent-id and
URL-encoding guards fails 11.

Tray-manager `tray:set-config` validation is left to amd#4299 and amd#4330,
which already add those tests.

## Test plan
- [x] `cd tests/electron && npm ci && npx jest` (26 suites, 770 tests
pass on Node 20)
- [x] Weaken `TAG_RE` in `auto-updater.cjs` to `/^v\d+\.\d+\.\d+/`: 7
new tag tests fail
- [x] Remove the agent-id guard and `encodeURIComponent` in
`agent-process-manager.cjs`: 11 new IPC tests fail

Part of amd#4258

Co-authored-by: Kalin Ovtcharov <[email protected]>
A tray-config.json written by the old unvalidated handler could hold a
non-boolean setting. _loadConfig blind-merged it, and the new set-config
validation re-reads stored values for keys the payload omits — so every
later save threw and tray settings became permanently unsavable. The
renderer's get-config -> set-config round-trip hit it too, because
get-config handed the bad value straight back.

_loadConfig now keeps only boolean values for known keys, falls back to
the default for anything else with a warning, and ignores a config file
that isn't an object at all. Validation stays strict for caller input.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Fixed the bricking case: a tray setting already stored with the wrong type no longer blocks every future save.

The new validation was right for what the renderer sends, but the config file is a second, untrusted input. _loadConfig merged whatever was on disk straight into memory, and the save path re-reads stored values for any key the payload leaves out — so one bad value made tray settings permanently unsavable, with an error the user can't act on. The renderer's own round-trip hit it too, since tray:get-config handed the bad value right back.

Loading now repairs instead of trusting: a known key keeps its value only if it's a boolean, anything else falls back to the default with a warning, and a config file that isn't an object at all is ignored. Validation stays strict for caller input — nothing about the IPC boundary was loosened.

Also merged current main (the branch was 60 behind); it came through clean.

🔍 Technical details

_loadConfig (src/gaia/apps/webui/services/tray-manager.cjs) now filters loaded.tray per key against DEFAULT_CONFIG.tray and guards that loaded is a plain object before spreading it (JSON.parse("null").tray would otherwise throw into the catch, and a JSON array spread index keys into the config).

Five tests added to tests/electron/tray-manager.test.cjs under tray config already on disk from the unvalidated handler — 4 of the 5 fail without the fix:

FAIL  a non-boolean on disk is replaced by the default at load
FAIL  a non-boolean on disk does not block saving an unrelated setting
FAIL  the renderer's get-config → set-config round-trip still saves
FAIL  a non-object tray section on disk falls back to defaults

After the fix:

$ npx jest tray-manager.test.cjs main-startup-order.test.cjs
Tests: 40 passed, 40 total

$ npx jest            # full Electron suite
Test Suites: 26 passed, 26 total
Tests: 1 skipped, 786 passed, 787 total

$ node --test tests/electron/test_port_manager.mjs tests/electron/test_loadapp_query.mjs
pass 24, fail 1

The one node --test failure is killBackend escalates to SIGKILL when SIGTERM is trapped/ignored, which fails identically on origin/main on Windows (SIGTERM can't be trapped there) — pre-existing, unrelated.

The two 🟢 nits from the review (the stale JSDoc in index-query.cjs and the adjacent quiet-degradation branch in main.cjs) are untouched — both are outside this PR's title and worth a follow-up.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit c1f6751 Sep 26, 2026
47 of 48 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/electron-port-tray-validation branch September 26, 2026 03:44
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
)

**Stacked on amd#4299 — merge that first.** This branch includes amd#4299's
commit, so the diff will shrink to one commit once it lands.

Before: agent settings saved in the desktop app's config dialog looked
saved but were gone after a restart. The settings handler dropped them,
nothing loaded them back at startup, and a failed disk write still
reported success. After: the settings file validates and stores
per-agent settings, the agent store loads them on startup, and the
dialog closes only once the save has landed. If the save fails, the
dialog stays open and shows the error.

Note: the agent manager panel that hosts this dialog isn't mounted in
the app yet, so there's no clickable golden path today. The fix is
verified at the IPC, store, and component level.

## Test plan
- [x] `cd tests/electron && npx jest` — 25 suites / 721 tests pass. The
new `agent config persistence` cases (save → new TrayManager reads the
file → same config, merge by id, validation, write failure) fail 10/10
without the fix.
- [x] `cd src/gaia/apps/webui && npx vitest run` — 52 files / 403 tests
pass. The new `agentStore.config.test.ts` fails 3/3 without the fix.
- [x] `npx tsc --noEmit` and `npx vite build` pass

Fixes amd#4300

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
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

tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(electron): startup silently falls back to port 4200 and tray config isn't validated

2 participants