Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions .memory/perf-startup-path.md
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.
6 changes: 5 additions & 1 deletion main/bootstrap.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import path from "node:path";
import { app } from "electron";
import { app, ipcMain } from "electron";

import { initDiagnosticJournal, writeDiagnosticEventSync } from "./services/diagnostic-journal.js";
import { initDiagnosticHealth } from "./services/diagnostic-health.js";
import { projectDiagnosticError } from "./services/diagnostics-contract.js";
import { pruneExpiredDiagnosticCrashDumps } from "./services/diagnostic-support.js";
import { installProcessDiagnostics } from "./services/process-diagnostics.js";
import { installProcessStartupIpcAdmission } from "./services/startup-ipc-admission.js";
import { applyLinuxGraphicsFlags } from "./linux-graphics-flags.js";
import { configureRuntimeProfile } from "./runtime-profile.js";
import { parseCaptureAcceptanceLaunch } from "./services/gemini-live/display-capture-acceptance-core.js";
Expand Down Expand Up @@ -51,6 +52,9 @@ try {
);
app.exit(await runDisplayCaptureAcceptance(runtimeProfile));
} else {
// Hold renderer invokes until index.ts finishes startup reconciliation;
// install before any module in the app graph registers a handler.
installProcessStartupIpcAdmission(ipcMain);
await import("./index.js");
}
} catch (error) {
Expand Down
2 changes: 1 addition & 1 deletion main/handlers/peer-hosts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export function registerPeerHostHandlers(): void {
});
if (owner.isDestroyed())
throw new Error("The application document changed.");
return peerOperationResult(operation, result);
return await peerOperationResult(operation, result);
} finally {
detach();
}
Expand Down
39 changes: 35 additions & 4 deletions main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Collaborator

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.

Comment on lines +1031 to +1040

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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
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.

Comment on lines +1031 to +1040

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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
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().

if (mainWindow && !mainWindow.isDestroyed()) {
const existingWindow = mainWindow;
await mainWindowLoads.wait();
Expand Down Expand Up @@ -1665,6 +1670,8 @@ if (!ownsSingleInstanceLock) {
),
);

let initialMainWindow: Promise<void> = Promise.resolve();
let startupIpcAdmitted = false;
app
.whenReady()
.then(async () => {
Expand Down Expand Up @@ -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 });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 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.

// Observed below after reconciliation; never an unhandled rejection.
initialMainWindow.catch(() => undefined);
try {
terminalService.installHistoryStore(
await TerminalHistoryStore.create(),
Expand Down Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The 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
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()'.

if (packagedSubagentSoak) {
await runPackagedSubagentSoak(packagedSubagentSoak);
return;
Expand Down Expand Up @@ -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();
});
}
10 changes: 8 additions & 2 deletions main/services/aiden-remote-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AidenRemoteTtsService } from "./aiden-remote-tts.js";
import { spawn, type ChildProcess } from "node:child_process";
import Bonjour from "bonjour-service";
import type Bonjour from "bonjour-service";
import { createHash, X509Certificate } from "node:crypto";
import { createServer as createHttpServer, type Server as HttpServer } from "node:http";
import { createServer as createHttpsServer, type Server as HttpsServer } from "node:https";
Expand Down Expand Up @@ -400,6 +400,12 @@ export class NodeAidenRemoteBonjourPublisher implements AidenRemoteBonjourPublis
): Promise<void> {
this.stop();
const generation = ++this.generation;
// bonjour-service is only needed once Remote publishes on Linux, so it
// loads here rather than on the main-process startup path.
const { default: BonjourService } = await import("bonjour-service");
if (this.generation !== generation) {
throw new Error("Local discovery was stopped before it became ready.");
}
let ready = false;
let failed = false;
let rejectStartup: (error: Error) => void = () => undefined;
Expand All @@ -418,7 +424,7 @@ export class NodeAidenRemoteBonjourPublisher implements AidenRemoteBonjourPublis
if (!ready) rejectStartup(error);
else onUnexpectedFailure(error);
};
const bonjour = new Bonjour(undefined, fail);
const bonjour = new BonjourService(undefined, fail);
this.bonjour = bonjour;
const service = bonjour.publish({
name: aidenRemoteBonjourServiceName(input.displayName, input.instanceId),
Expand Down
25 changes: 24 additions & 1 deletion main/services/app-updater-core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,6 @@ test("production updater awaits downloads and exposes a sender-scoped retry entr
const handler = main.slice(handlerStart, handlerEnd);

assert.doesNotMatch(service, /checkForUpdatesAndNotify/u);
assert.match(service, /await autoUpdater\.downloadUpdate\(cancellation\)/u);
assert.match(service, /DOWNLOAD_STALL_TIMEOUT_MS/u);
assert.match(service, /appUpdateRetryDelay\(this\.retryAttempt\)/u);
assert.match(handler, /event\.sender\.id !== mainWindow\.webContents\.id/u);
Expand Down Expand Up @@ -394,6 +393,7 @@ async function simulatedService() {
let downloads = 0;
let cancellations = 0;
let installs = 0;
const loaded: string[] = [];
const dialogs: unknown[] = [];
const updater = Object.assign(new EventEmitter(), {
checkForUpdates: () => check.promise,
Expand Down Expand Up @@ -434,6 +434,14 @@ async function simulatedService() {
"node:fs/promises": {},
"node:path": nodePath,
};
// The service loads electron-updater lazily through createRequire.
mocks["node:module"] = {
createRequire: () => (name: string) => {
assert.ok(name in mocks, `unexpected dependency: ${name}`);
loaded.push(name);
return mocks[name];
},
};
const bundle = await build({
entryPoints: [new URL("./app-updater.ts", import.meta.url).pathname],
bundle: true,
Expand All @@ -447,6 +455,7 @@ async function simulatedService() {
run(
(name: string) => {
assert.ok(name in mocks, `unexpected dependency: ${name}`);
loaded.push(name);
return mocks[name];
},
module,
Expand All @@ -459,6 +468,7 @@ async function simulatedService() {
download,
updater,
dialogs,
loaded,
downloads: () => downloads,
cancellations: () => cancellations,
installs: () => installs,
Expand All @@ -469,6 +479,19 @@ async function flushUpdater() {
for (let step = 0; step < 12; step += 1) await Promise.resolve();
}

test("service defers loading the updater SDK until an update check needs it", async () => {
const fixture = await simulatedService();
try {
assert.ok(!fixture.loaded.includes("electron-updater"), "startup must not load electron-updater");
const operation = fixture.service.checkNow(false);
fixture.check.resolve({ isUpdateAvailable: false, updateInfo: { version: "0.28.31" } });
assert.deepEqual(await operation, { outcome: "up-to-date" });
assert.equal(fixture.loaded.filter((name) => name === "electron-updater").length, 1);
} finally {
fixture.service.dispose();
}
});

test("service disposal prevents late feed downloads, manual dialogs, and restarts", async () => {
const fixture = await simulatedService();
try {
Expand Down
Loading
Loading