Repository navigation
perf(main): show the window sooner and load cold modules on first use #327
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
bcd5ce7
92260a2
7a80cf0
e33fdad
9747c7e
1ff4a0a
6d47046
6e7517d
3b9bdce
36cea95
113573c
3576713
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| # Main-process startup path (branch perf/startup-path, 2026-10-03) | ||
|
|
||
| Fixes from the optimization audit, findings MAIN-1/2/3. | ||
|
|
||
| ## MAIN-1: window created during reconciliation | ||
| - Before: `whenReady` ran ~20 sequential reconcile awaits (terminal history, | ||
| live/pi runtime stores, bots, migrations, worktree reconcile, dock, shortcuts, | ||
| Remote — ~380 ms on an empty profile) and only then `createMainWindow()`. | ||
| - Now: after the first settings read (to set `nativeTheme.themeSource`, so no | ||
| theme flash) `whenReady` starts `createMainWindow({ startupAdmissionHeld: true })` | ||
| and keeps reconciling. The renderer bundle loads in parallel. | ||
| - Invariant kept: no renderer invoke runs before reconciliation finishes. | ||
| `main/services/startup-ipc-admission.ts` wraps `ipcMain.handle` (installed in | ||
| `main/bootstrap.ts` before `import("./index.js")`, so before any handler | ||
| registration) and holds every invoke in arrival order until | ||
| `openProcessStartupIpcAdmission()` runs after `initializeAidenRemoteService`. | ||
| The app has only `ipcMain.handle` (no `ipcMain.on`/`sendSync`). | ||
| - The renderer awaits `app:getInfo` before its first React render, so while | ||
| invokes are held the user sees only the themed empty window, never stale UI. | ||
| - `createMainWindow` skips awaiting `shortcutInitializationPromise` when | ||
| admission is held (shortcuts initialize later in the same chain). | ||
| - If startup fails before admission opens, the startup window is destroyed | ||
| (its held invokes could never answer the close handshake), then quit. | ||
| - `toolOutputStore.pruneExpired()` is now fire-and-forget (logged on failure). | ||
| - New diagnostic milestone `startup-reconciled` (allowlisted in | ||
| `diagnostics-contract.ts`). | ||
|
|
||
| ## MAIN-2: lazy externals (esbuild `packages: "external"` hoists static imports) | ||
| - electron-updater: `createRequire` on first use in `app-updater.ts` (CJS, keeps | ||
| the protected install handoff synchronous). `start()` runs after the window. | ||
| Test harness mocks `node:module`; a test asserts the SDK is not loaded until a check. | ||
| - remark/unified: `ensureSpeechTextParser()` awaited in the TTS service before | ||
| `reservation.assertCurrent()`; `prepareSpeechText` stays sync and throws if | ||
| the parser was not loaded. | ||
| - bonjour-service: dynamic import inside the Linux publisher's `start()`. | ||
| - parse5/acorn/postcss/postcss-value-parser: `browserAssetReferences` is async. | ||
| - Deferred: `@google/genai` (6 files, enum values + sync TTS client factory, | ||
| ~19 ms), MCP SDK + ajv (~72 ms; owned by perf/mcp-network-background — ajv | ||
| savings in peer-response only materialize once MCP is lazy too), pi-ai/ | ||
| pi-agent-core (core runtime), yaml (~16 ms, skills discovery), and lazy | ||
| handler-module stubs (broad refactor). | ||
|
|
||
| ## MAIN-3: large blobs | ||
| - Remote OpenAPI JSON (289 KB) + Ajv 2020 now load on first peer response; | ||
| `validatePeerResponse`/`peerOperationResult` are async. | ||
| - Playwright injected source (326 KB) left alone: it is a string literal and | ||
| measured ~1 ms to evaluate. | ||
|
|
||
| ## Measuring | ||
| - `measure-startup` launches Electron with `HOME`, `AIDEN_CONFIG_DIR` and | ||
| `--user-data-dir` in a temp dir and reads `user-data/logs/aiden-dev.log`. | ||
| - Run it from the repo root: native helpers resolve from `process.cwd()/build/native` | ||
| in unpacked builds, and a different cwd fails startup with | ||
| `SubagentRunStoreStorageError: io_failed`. | ||
| - Medians, 6 interleaved runs, empty profile, busy shared machine, ms after | ||
| `session-started`: origin/main window 1064 / shown 1342; MAIN-1 only 779 / | ||
| 1192; MAIN-1+2+3 653 / 925. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -61,6 +61,7 @@ import type { | |
| } from "../renderer/shared/app-update.js"; | ||
| import { devLogPath } from "./services/dev-log.js"; | ||
| import { flushDiagnosticJournal, writeDiagnosticEvent } from "./services/diagnostic-journal.js"; | ||
| import { openProcessStartupIpcAdmission } from "./services/startup-ipc-admission.js"; | ||
| import { projectDiagnosticError } from "./services/diagnostics-contract.js"; | ||
| import { flushDiagnosticHealth } from "./services/diagnostic-health.js"; | ||
| import { pruneExpiredDiagnosticCrashDumps } from "./services/diagnostic-support.js"; | ||
|
|
@@ -1027,12 +1028,16 @@ function refreshFoundationModelsStatus(force = false): void { | |
| void foundationModelsConnection.status(force ? { force: true } : undefined); | ||
| } | ||
|
|
||
| async function createMainWindow(): Promise<void> { | ||
| 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; | ||
|
Comment on lines
+1031
to
+1040
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P1 · logic] Startup window signature change and deferred invocation break native-menu-command-contract.test.ts 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.
Comment on lines
+1031
to
+1040
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P1 · logic] Native menu command contract test fails on unadapted createMainWindow signature and startup ordering anchor 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(). |
||
| if (mainWindow && !mainWindow.isDestroyed()) { | ||
| const existingWindow = mainWindow; | ||
| await mainWindowLoads.wait(); | ||
|
|
@@ -1665,6 +1670,8 @@ if (!ownsSingleInstanceLock) { | |
| ), | ||
| ); | ||
|
|
||
| let initialMainWindow: Promise<void> = Promise.resolve(); | ||
| let startupIpcAdmitted = false; | ||
| app | ||
| .whenReady() | ||
| .then(async () => { | ||
|
|
@@ -1709,6 +1716,16 @@ if (!ownsSingleInstanceLock) { | |
| crashDumpsPath: runtimeProfile.crashDumpsPath, | ||
| }); | ||
| } | ||
| // Start the main window now so the renderer bundle loads in parallel | ||
| // with the reconcile chain below. The startup IPC admission (installed in | ||
| // bootstrap.ts) holds every renderer invoke until that chain finishes, | ||
| // so no renderer reads or writes state before reconciliation. | ||
| nativeTheme.themeSource = normalizeAppearanceConfig( | ||
| (await configStore.getSettings()).appearance, | ||
| ).mode; | ||
| initialMainWindow = createMainWindow({ startupAdmissionHeld: true }); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Coordinate accepted quit with pending startup An accepted Quit on the newly visible window can enter 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. |
||
| // Observed below after reconciliation; never an unhandled rejection. | ||
| initialMainWindow.catch(() => undefined); | ||
| try { | ||
| terminalService.installHistoryStore( | ||
| await TerminalHistoryStore.create(), | ||
|
|
@@ -1759,7 +1776,9 @@ if (!ownsSingleInstanceLock) { | |
| ); | ||
| } | ||
| await subagentRunStore.initialize(); | ||
| await toolOutputStore.pruneExpired().catch(() => { | ||
| // Expiry cleanup is not part of reconciliation; let it run alongside | ||
| // the rest of startup instead of delaying the first window. | ||
| void toolOutputStore.pruneExpired().catch(() => { | ||
| logger.warn("pi", "Expired tool output cleanup could not complete."); | ||
| }); | ||
| const toolOutputCleanup = setInterval(() => { | ||
|
|
@@ -2019,7 +2038,15 @@ if (!ownsSingleInstanceLock) { | |
| ); | ||
| } | ||
|
|
||
| await createMainWindow(); | ||
| openProcessStartupIpcAdmission(); | ||
| startupIpcAdmitted = true; | ||
| writeDiagnosticEvent({ | ||
| level: "info", | ||
| area: "app", | ||
| event: "startup-reconciled", | ||
| outcome: "completed", | ||
| }); | ||
| await initialMainWindow; | ||
|
Comment on lines
+2046
to
+2049
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2 · logic] Replacing startup createMainWindow call breaks subagents and command-system contract tests 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()'. |
||
| if (packagedSubagentSoak) { | ||
| await runPackagedSubagentSoak(packagedSubagentSoak); | ||
| return; | ||
|
|
@@ -2049,6 +2076,10 @@ if (!ownsSingleInstanceLock) { | |
| }) | ||
| .catch((error: unknown) => { | ||
| logger.error("main", "Failed to start Aiden Agent", error); | ||
| // A startup window whose renderer was never admitted holds no user | ||
| // state, and its held invokes could never answer a close handshake. | ||
| if (!startupIpcAdmitted && mainWindow && !mainWindow.isDestroyed()) | ||
| mainWindow.destroy(); | ||
| void shutdownAndQuit(); | ||
| }); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[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.