Repository navigation
perf(main): show the window sooner and load cold modules on first use - #327
Conversation
…N-1) The main window used to be created only after ~20 sequential reconcile awaits. Create it as soon as the theme is known so the renderer bundle loads in parallel, and hold every renderer invoke behind a startup admission gate (installed before any ipcMain.handle registration) until reconciliation finishes, preserving the "no renderer reads before reconcile" invariant. Tool-output pruning no longer blocks startup. Adds a startup-reconciled diagnostic milestone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
electron-updater (~37 ms of module evaluation) was imported eagerly on the startup path, though it is only reachable from start() after the main window or a user update action. Load it through createRequire on first use so the protected install handoff stays synchronous. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The unified/remark stack (~44 ms) was evaluated at startup only to back read-aloud. Load it on the first read-aloud request, before the reservation check so the synchronous preparation section is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…IN-2) bonjour-service (~20 ms) was evaluated at every startup although only the Linux local-discovery publisher uses it (macOS uses dns-sd). Import it when that publisher starts, keeping the existing stopped-before-ready contract. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…IN-3) The 289 KB Aiden Remote OpenAPI document and the Ajv 2020 validator were imported at startup only to validate peer-host responses. Load both on the first validation; peer response validation becomes async and the handler awaits it, with identical accept/reject behavior. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
parse5, acorn, postcss and postcss-value-parser (~16 ms) were evaluated at startup only for browser-preview asset discovery. Load them on the first discovery; reference extraction becomes async with unchanged output. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Important
The earlier window introduces a startup-versus-quit race: reconciliation can resume and start services after shutdown has stopped them. This lifecycle interleaving needs to be addressed before merging.
Reviewed changes Reviewed the complete startup-ordering and lazy-loading changes across all seven commits.
- Earlier window: Window loading overlaps persisted-state reconciliation, with process-wide IPC admission holding renderer invokes until reconciliation completes.
- Startup diagnostics and cleanup: Adds the
startup-reconciledmilestone, defers expired tool-output cleanup, and destroys an unadmitted window on startup failure. - Lazy updater: Loads
electron-updateron service start or update use while preserving the guarded Linux AppImage installation path. - Lazy feature dependencies: Defers the read-aloud Markdown stack, Node Bonjour publisher, and preview asset parsers until use, updating async callers and tests.
- Lazy peer validation: Defers the OpenAPI contract and Ajv until the first peer response while retaining existing response validation.
TypeScript checking and the focused startup, updater, TTS, peer, Remote, diagnostics, and browser suites passed. The browser suite initially lacked its Chromium executable and passed after installation; full Electron E2E was not run locally.
gpt-6.1-sol | 𝕏
| nativeTheme.themeSource = normalizeAppearanceConfig( | ||
| (await configStore.getSettings()).appearance, | ||
| ).mode; | ||
| initialMainWindow = createMainWindow({ startupAdmissionHeld: true }); |
There was a problem hiding this comment.
[P2] Coordinate accepted quit with pending startup
An accepted Quit on the newly visible window can enter shutdownAndQuit() while this startup callback is still suspended in reconciliation. The callback resumes without a shutdown fence, allowing reconciliation to race store teardown and Remote, schedules, and Telegram to start after shutdown has already stopped them.
Technical details
# Startup resumes after service shutdown
## Affected sites
- [main/index.ts:1726](https://github.com/sambitcreate/aiden-agent/blob/6d47046a6e9929a33a5059869b2d71832f02bcd3/main/index.ts#L1726) exposes a native window before the reconciliation chain settles.
- [main/index.ts:588-625](https://github.com/sambitcreate/aiden-agent/blob/6d47046a6e9929a33a5059869b2d71832f02bcd3/main/index.ts#L588-L625) accepts Quit, closes the renderer, and enters shutdown independently of startup.
- [main/index.ts:407-426](https://github.com/sambitcreate/aiden-agent/blob/6d47046a6e9929a33a5059869b2d71832f02bcd3/main/index.ts#L407-L426) stops Remote and background services and closes persistence while startup may still be pending.
- [main/index.ts:2031-2075](https://github.com/sambitcreate/aiden-agent/blob/6d47046a6e9929a33a5059869b2d71832f02bcd3/main/index.ts#L2031-L2075) initializes Remote, opens IPC admission, and starts background services without checking whether Quit was accepted.
- [main/services/aiden-remote-service-main.ts:917-928](https://github.com/sambitcreate/aiden-agent/blob/6d47046a6e9929a33a5059869b2d71832f02bcd3/main/services/aiden-remote-service-main.ts#L917-L928) allows initialization after a stop with no existing runtime; [main/services/schedule-service-core.ts:296-300](https://github.com/sambitcreate/aiden-agent/blob/6d47046a6e9929a33a5059869b2d71832f02bcd3/main/services/schedule-service-core.ts#L296-L300) allows start after stop.
## Reproduction
Executed the actual AST-extracted `whenReady` callback, `shutdownAndQuit`, and `cleanupApplication` with deferred service dependencies. Hold `migrateLegacyEmptyWorkspaceChats`, enter shutdown, pause browser teardown after Remote has stopped, then release reconciliation. The observed ordering was:
`window shown -> remote stopped -> remote initialized -> admission opened -> schedule started -> telegram started -> updater started -> app quit`
This is an ordering reproduction with service stubs, not a full Electron E2E test.
## Required outcome
- Coordinate accepted Quit with pending startup so reconciliation settles or is cancelled before its stores/services are torn down.
- Do not open admission or initialize/start background services after Quit has committed to shutdown.
- Add behavioral coverage for accepting Quit while reconciliation and `app:getInfo` admission remain pending; assert that services cannot restart after their shutdown.
## Suggested approach
Make accepted shutdown terminal for startup and coordinate the outstanding startup task with teardown. A check only at the final service-start block would not prevent earlier reconciliation from racing store closure.
very-hermes-bot
left a comment
There was a problem hiding this comment.
Inline review — 2 finding(s) anchored to the diff. See the pinned summary comment for the overview.
| event: "startup-reconciled", | ||
| outcome: "completed", | ||
| }); | ||
| await initialMainWindow; |
There was a problem hiding this comment.
[P2 · logic] Replacing startup createMainWindow call breaks subagents and command-system contract tests
Confidence: 0.95
Line 2049 replaces 'await createMainWindow();' with 'await initialMainWindow;', causing main.indexOf('await createMainWindow()', finalizeOrphanedJournals) in main/services/subagents/subagent-phase3-contract.test.ts:421 to return -1 and main.lastIndexOf('await createMainWindow()') in main/services/native-menu-command-contract.test.ts:55 to resolve before resolveIndex.
Repair: Update both contract tests to match 'await initialMainWindow' instead of 'await createMainWindow()'.
| async function createMainWindow( | ||
| options: { startupAdmissionHeld?: boolean } = {}, | ||
| ): Promise<void> { | ||
| let rendererCrashTimes: number[] = []; | ||
| // macOS activate, a second-instance event, or a newly registered global | ||
| // shortcut can all arrive while whenReady is still initializing. Never let | ||
| // those alternate paths expose a renderer to a partial shortcut snapshot. | ||
| await shortcutInitializationPromise; | ||
| // The startup window may skip the wait: the startup IPC admission holds its | ||
| // renderer's invokes until shortcuts and reconciliation have finished. | ||
| if (!options.startupAdmissionHeld) await shortcutInitializationPromise; |
There was a problem hiding this comment.
[P2 · logic] Parameterizing createMainWindow breaks shortcut barrier contract test
Confidence: 0.95
Adding options to createMainWindow changes its signature from 'async function createMainWindow(): Promise' to 'async function createMainWindow(', causing main.indexOf('async function createMainWindow()') in main/services/native-menu-command-contract.test.ts:48 to return -1 and fail createFunctionIndex >= 0.
Repair: Update main/services/native-menu-command-contract.test.ts:48 to search for 'async function createMainWindow(' and align the test with the startupAdmissionHeld bypass.
Hermes Review BotConfidence: 5 Engine: SummaryAccelerates the application startup path by creating and loading the main browser window concurrently with persisted-state reconciliation, rather than waiting for ~20 sequential initialization awaits before window creation. Renderer IPC calls are queued in arrival order behind a new startup admission gate installed before handler registration in Confidence Score: 5/5Fully traced startup sequencing, concurrency gates, lazy module initialization, error paths, and all contract test suites reading 📁 Important Files Changed
Findings
📊 Sequence DiagramsequenceDiagram
participant Renderer
participant Preload
participant IPCAdmission as Startup IPC Admission
participant MainReconcile as Main Startup & Reconcile
participant Stores as Core Stores & Services
MainReconcile->>MainReconcile: createMainWindow({ startupAdmissionHeld: true })
MainReconcile->>Stores: Run reconciliation concurrently
Renderer->>Preload: appApi.getInfo()
Preload->>IPCAdmission: ipcRenderer.invoke("app:getInfo")
Note over IPCAdmission: Hold invoke (opened == false)
Stores-->>MainReconcile: Reconciliation complete
MainReconcile->>IPCAdmission: openProcessStartupIpcAdmission()
Note over IPCAdmission: Flush held invokes in arrival order
IPCAdmission-->>Preload: Resolve app:getInfo
Preload-->>Renderer: App capabilities & info
Renderer->>Renderer: First React render
Machine-Readable Findings[
{
"file": "main/index.ts",
"start_line": 1031,
"end_line": 1040,
"severity": "P1",
"comment_type": "logic",
"confidence": 0.95,
"title": "Native menu command contract test fails on unadapted createMainWindow signature and startup ordering anchor",
"mechanism": "Changing createMainWindow's signature and moving its startup await breaks main/services/native-menu-command-contract.test.ts because createFunctionIndex evaluates to -1 and resolveIndex < createIndex fails.",
"repair": "Update main/services/native-menu-command-contract.test.ts to match createMainWindow without parameter parentheses and anchor the startup completion assertion to openProcessStartupIpcAdmission().",
"id": "3537661f51d5bc5f"
}
]
|
…creation The startup window is now created while reconciliation runs, and the startup IPC admission holds every renderer invoke until reconciliation finishes. The ordering contract still requires private-run and worktree deletion reconciliation to finish before the renderer is admitted and before schedules start, so anchor it on openProcessStartupIpcAdmission(). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Important
No new issues found in this delta. The previously reported startup-versus-quit race remains unresolved, so approval is still withheld.
Reviewed changes Reviewed the changes since 6d47046a, with the complete current PR diff as context.
- Updated startup-ordering coverage to use
openProcessStartupIpcAdmission()as the renderer-readiness boundary instead of window creation, matching the renderer's blocked bootstrap. - Merged current
maininto the branch and retained startup-admission test registration alongside its parallel test runner andtest:serialinventory.
The revised ordering, startup-admission, and bootstrap suites passed all 36 tests; test-inventory validation passed all 10 tests. Full Electron E2E was not run locally, and hosted CI on this head was still in progress when checked.
gpt-6.1-sol | 𝕏
very-hermes-bot
left a comment
There was a problem hiding this comment.
Inline review — 1 finding(s) anchored to the diff. See the pinned summary comment for the overview.
| async function createMainWindow( | ||
| options: { startupAdmissionHeld?: boolean } = {}, | ||
| ): Promise<void> { | ||
| let rendererCrashTimes: number[] = []; | ||
| // macOS activate, a second-instance event, or a newly registered global | ||
| // shortcut can all arrive while whenReady is still initializing. Never let | ||
| // those alternate paths expose a renderer to a partial shortcut snapshot. | ||
| await shortcutInitializationPromise; | ||
| // The startup window may skip the wait: the startup IPC admission holds its | ||
| // renderer's invokes until shortcuts and reconciliation have finished. | ||
| if (!options.startupAdmissionHeld) await shortcutInitializationPromise; |
There was a problem hiding this comment.
[P1 · logic] Startup window signature change and deferred invocation break native-menu-command-contract.test.ts
Confidence: 0.95
Changing the createMainWindow signature to accept options and replacing the post-reconciliation createMainWindow call with await initialMainWindow breaks native-menu-command-contract.test.ts (createFunctionIndex evaluates to -1 and resolveIndex < createIndex fails), causing npm run test:command-system to fail.
Repair: Update native-menu-command-contract.test.ts to match createMainWindow's updated signature and verify that resolveShortcutInitialization precedes openProcessStartupIpcAdmission.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Important
No new issues found in this delta. The previously reported startup-versus-quit race remains unresolved, so approval is still withheld.
Reviewed changes Reviewed the changes since 3b9bdce7, using the complete current PR diff as context.
- Updated updater test dependencies to accommodate the merged shared path-containment helper while retaining isolated filesystem mocks and the existing lazy-loading and disposal assertions.
- Added shared-main test coverage to
test:serial, preserving the complete test inventory after mergingmain.
The focused updater and startup-related suites passed all 62 tests; test:main-shared passed all 17 tests; CI test-inventory validation passed all 10 tests. Full Electron/macOS E2E was not run locally.
gpt-6.1-sol | 𝕏
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The spec pressed Enter twice right after filling, without the Queue-enabled check every other queue spec uses, so an Enter could land before the composer accepted queueing and the queue showed one item instead of two. It failed this way on #327 and #328. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 57b4896)
The spec pressed Enter twice right after filling, without the Queue-enabled check every other queue spec uses, so an Enter could land before the composer accepted queueing and the queue showed one item instead of two. It failed this way on #327 and #328. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 57b4896)
There was a problem hiding this comment.
Important
No new issues found in this delta. The previously reported startup-versus-quit race remains unresolved, so approval is still withheld.
Reviewed changes Reviewed the changes since 36cea956, using the complete current PR diff as context.
- Updated queued-message Steer coverage to wait for the Queue action to become enabled before each queued Enter and verify the first queue row before submitting the second, retaining the existing delivery and uniqueness assertions.
- Merged current
mainand preserved its added renderer test registrations alongside startup-admission coverage; the complete serial test inventory still validates.
E2E TypeScript checking passed, and Playwright collected all 19 tests in the changed spec. The focused queue and startup-admission suites passed all 29 tests; CI test-inventory validation passed all 10 tests. Electron E2E was not run because this Linux checkout lacks the required macOS-only native helpers, so the recorded flake's resolution is not independently confirmed. Hosted CI on this exact head was still in progress when inspected.
gpt-6.1-sol | 𝕏
very-hermes-bot
left a comment
There was a problem hiding this comment.
Inline review — 1 finding(s) anchored to the diff. See the pinned summary comment for the overview.
| async function createMainWindow( | ||
| options: { startupAdmissionHeld?: boolean } = {}, | ||
| ): Promise<void> { | ||
| let rendererCrashTimes: number[] = []; | ||
| // macOS activate, a second-instance event, or a newly registered global | ||
| // shortcut can all arrive while whenReady is still initializing. Never let | ||
| // those alternate paths expose a renderer to a partial shortcut snapshot. | ||
| await shortcutInitializationPromise; | ||
| // The startup window may skip the wait: the startup IPC admission holds its | ||
| // renderer's invokes until shortcuts and reconciliation have finished. | ||
| if (!options.startupAdmissionHeld) await shortcutInitializationPromise; |
There was a problem hiding this comment.
[P1 · logic] Native menu command contract test fails on unadapted createMainWindow signature and startup ordering anchor
Confidence: 0.95
Changing createMainWindow's signature and moving its startup await breaks main/services/native-menu-command-contract.test.ts because createFunctionIndex evaluates to -1 and resolveIndex < createIndex fails.
Repair: Update main/services/native-menu-command-contract.test.ts to match createMainWindow without parameter parentheses and anchor the startup completion assertion to openProcessStartupIpcAdmission().
* perf(main): cache MCP tool lists, discover servers in parallel under deadlines (MAIN-20, MAIN-21) - Cache tools/list per connected client; notifications/tools/list_changed and reconnects invalidate it, so a warm generation issues no tools/list. - Discover enabled servers concurrently with Promise.allSettled. Connect (initialize) is bounded at 10 s, tools/list at 5 s, and each server's whole step at 17 s; a server that misses its deadline loses its tools for the turn and is reported as a timed-out mcp-degraded diagnostic. - Tool calls pass an explicit 60 s timeout and maxTotalTimeout alongside the caller's signal (unchanged from the SDK default bound). - closeAll disconnects servers in parallel and shutdown awaits it within a 2 s budget. Connections idle for 10 minutes are closed without superseding their generation, so an older turn's tools reconnect on use. - Removing a server prunes its generation bookkeeping. Generations now come from one monotonic sequence so pruning cannot revive a stale caller. - The merge step moved into a pure core with behavioral tests, replacing the mcp.ts source-grep assertion. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(main): bound Telegram requests and coalesce thinking edits (MAIN-26) Every Bot API fetch now carries a deadline combined with the caller's signal: long polls get the poll window plus 10 s, file downloads and uploads get size-scaled deadlines, and stopping the poller aborts the in-flight getUpdates socket instead of only abandoning it. Streamed reasoning edits are coalesced to one per 900 ms with the latest text, and unchanged renders are skipped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(main): bound cloud voice transcription requests OpenAI and Gemini transcription now run under a size-scaled deadline (2 min base, 5 min cap) that covers upload, response and body read, even for callers without a signal such as Telegram voice notes. A deadline abort is reported as a timeout; user cancellation passes through. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(main): read subagent process identity without blocking the event loop (MAIN-24) The PID-reuse fence now reads ps asynchronously. Launch keeps its ten 25 ms identity attempts, concurrent reads share one ps, and hard-kill and exit proofs are awaited by the owner, re-checking the exit flag after the read. Owner semantics are unchanged: indeterminate proof still fails closed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(main): bound and stagger scheduled catch-up (MAIN-25) Startup catch-up of missed runs now goes through a queue that runs at most two at a time, 3 s apart, holds while the screen is locked, and re-evaluates on resume and unlock. Stopping the service drops queued entries so a restart starts clean. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(main): throttle portable-config refresh on window focus (MAIN-28) Focus storms now cost one re-read per 2 s plus one trailing pass. An mtime gate was not used: DataStore.reload deliberately avoids stat gating because coarse mtimes can drop a second edit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(main): stop forking the speech worker for every voice status read (MAIN-28) Whether the native engine loads is fixed for the app's lifetime, so the first engine answer is reused; transient launch failures are not cached. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(main): pause hidden browser PiP and skip unchanged frames (MAIN-28) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(e2e): wait for Queue before each queued Enter in the Steer spec The spec pressed Enter twice right after filling, without the Queue-enabled check every other queue spec uses, so an Enter could land before the composer accepted queueing and the queue showed one item instead of two. It failed this way on #327 and #328. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 57b4896) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
#327 now loads electron-updater lazily through createRequire, so the bundle no longer lists it as an external. Record it in RUNTIME_LOADED so the production-dependency check keeps it in dependencies (and app.asar). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Summary
startup-ipc-admission.tsgate holds renderer IPC until main is ready. Window shown 1342 → 925 ms.electron-updater, the read-aloud Markdown parser,bonjour-service(Linux Remote only) and the preview asset parsers load on first use.Test plan
Part of the October optimization pass. Finding IDs refer to
docs/performance/optimization-audit-2026-10-03.md(#320). The branch's.memory/note has per-finding rationale.Flake recorded
tests/e2e/chat-message-queue.spec.ts:340, "Steer on a queued message adds it to the running response once".--fail-on-flaky-teststurned the retry into a failure.subagent-phase3-contract, the startup-ordering anchor moved fromcreateMainWindow()toopenProcessStartupIpcAdmission(). The window is now created early, but the renderer stays blocked until reconciliation finishes.🤖 Generated with Claude Code