Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
8af69ab
perf(renderer): keep the dictation pill off the ipc.ts parser graph (…
sambitcreate Oct 3, 2026
6488157
perf(renderer): lazy-load highlight.js grammars and drop auto-detecti…
sambitcreate Oct 3, 2026
eeec4f4
perf(renderer): load KaTeX only for messages that contain math (UI-3)
sambitcreate Oct 3, 2026
e60eedb
perf(renderer): split non-chat routes and rare panels out of the entr…
sambitcreate Oct 3, 2026
12f486d
perf(renderer): issue startup reads before the app chunk evaluates (U…
sambitcreate Oct 3, 2026
0d2bcdd
perf(renderer): give the query client deliberate defaults (UI-16)
sambitcreate Oct 3, 2026
856ae66
perf(git): memoize the git executable per PATH (MAIN-22)
sambitcreate Oct 3, 2026
3a0fcbb
perf(git): push repository changes from a .git metadata watcher (MAIN…
sambitcreate Oct 3, 2026
877fc2c
perf(renderer): refresh Git panels from events and poll only as a saf…
sambitcreate Oct 3, 2026
ac143f4
perf(renderer): poll Remote status only while it is on screen (UI-19,…
sambitcreate Oct 3, 2026
5ab2fed
perf(renderer): derive the model picker lists only while it is open (…
sambitcreate Oct 3, 2026
57ad10c
docs(memory): record the renderer bundle and polling work
sambitcreate Oct 3, 2026
353ad2d
Merge remote-tracking branch 'origin/main' into perf/renderer-bundle-…
sambitcreate Oct 4, 2026
a665fb2
fix(e2e): stub the startup catalog refresh with the palette's providers
sambitcreate Oct 4, 2026
3b98c5f
Merge origin/main into perf/renderer-bundle-polling
sambitcreate Oct 4, 2026
e156c2c
Merge origin/main into perf/renderer-bundle-polling
sambitcreate Oct 4, 2026
c12d45b
Merge origin/main into perf/renderer-bundle-polling
sambitcreate Oct 4, 2026
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
2 changes: 1 addition & 1 deletion .memory/git-display-read-performance.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Git display reads and bounded review statistics — 2026-09-28

Scope X01/X02 from the performance supplement; baseline `a9baa4aa3027893e5455043083465c34b4c8b4ac`. Read-only shared Git queries now coalesce independent subscribers (info, branches, review, push capability and comparison). One subscriber's abort detaches only that subscriber; the last abort cancels the underlying work and blocks late cache publication. Branch reads reuse a concurrent info read with the original caller path (important for macOS `/var` versus `/private/var` aliases).
Scope X01/X02 from the performance supplement (later polling and executable changes: `renderer-bundle-polling.md`); baseline `a9baa4aa3027893e5455043083465c34b4c8b4ac`. Read-only shared Git queries now coalesce independent subscribers (info, branches, review, push capability and comparison). One subscriber's abort detaches only that subscriber; the last abort cancels the underlying work and blocks late cache publication. Branch reads reuse a concurrent info read with the original caller path (important for macOS `/var` versus `/private/var` aliases).

Repository-root reads reuse discovery only within the existing display TTL, validating root, `.git`, linked administrative/common-directory identity and pointer/config metadata before admission and after completion. Nested/unusual layouts remain uncached. Discovery deliberately expires at the existing one-second default: indirect/global Git configuration can change without touching local config. No polling interval or stale-time was increased; expired/no-op polling still performs fresh Git commands. Mutation admission still calls the original uncached discovery, and common-dir mutation epochs remain authoritative. Display reuse never authorizes writes.

Expand Down
27 changes: 27 additions & 0 deletions .memory/renderer-bundle-polling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Renderer bundle and display polling — 2026-10-03

Branch `perf/renderer-bundle-polling`. Audit IDs UI-1–5, UI-14–19, MAIN-22/23 (from the 2026-10 whole-app audit). No persisted-format or Remote protocol change; `git:changed` is desktop-only and never forwarded to iOS/Android.

## Bundle (main-window startup closure, vite build)
- Baseline 3,328 KB JS (1,019 KB gzip) → 1,640 KB (509 KB gzip); dictation pill 475 → 234 KB.
- UI-1 `renderer/lib/syntax-highlight.ts`: hljs core plus per-language dynamic imports; aliases map to grammar modules. `highlightAuto` was dropped, so unlabeled fences render plain (owner decision).
- UI-3 `renderer/lib/markdown-math.ts`: remark-math/rehype-katex and the KaTeX CSS load only when a message contains math delimiters.
- UI-2 `router.tsx` `lazyRouteComponent` for non-chat routes; BrowserPanel and DevicesPanel are lazy.
- UI-4 `renderer/lib/ipc-bridge.ts` / `ipc-voice.ts`: the pill no longer pulls the `ipc.ts` parser graph.
- UI-5 `renderer/main/index.tsx` is a thin entry that issues startup reads, then imports `./app` (`startApp(startup)`). Source-grep startup tests now target `app.tsx`.

## Queries and polling
- UI-16 `createAppQueryClient` (`renderer/lib/query-client.ts`): staleTime 30 s, refetchOnWindowFocus off, retry 1; live surfaces opt back in.
- MAIN-22 `resolveGitExecutableMemoized` (`main/services/git-executable.ts`): keyed on binary/PATH/DEVELOPER_DIR, revalidated, 5 min TTL, failures uncached. Removes one `xcode-select` per Git command under a GUI PATH.
- MAIN-22 `main/services/git-repo-watcher.ts`: `fs.watch` on gitDir admin files, commonDir packed-refs and recursive refs (fallback refs/heads); debounced 250 ms, monotonic generation, evicted after 10 min unread. Started by `workspaces:gitInfo`, `git:review`, `git:pushCapability`; broadcasts `git:changed {workspaceId, generation}`.
- UI-17 `renderer/lib/git-query-sync.ts` (mounted in `root-view.tsx`): `git:changed` invalidates repository reads, `chats:settled` and throttled (5 s trailing) tool results invalidate working-tree reads, window activation restarts intervals and refetches stale reads. Git panels poll at 60 s only while the window is visible and focused (`gitSafetyPoll`).
- UI-18 PR status polls every 5 min; a repository change refreshes it only once it is ≥1 min old.
- UI-19/MAIN-23 `aidenRemoteSettingsQueryOptions(live)`: the always-mounted badge polls at 60 s while active, none while inactive; the open popover and Remote settings keep 10 s. No main-side Tailscale cache (deferred).
- UI-15 ModelPicker memoizes catalog entries on per-provider data references and derives list order/detail positions only while open. `useProvidersModelInfo` itself is untouched (owned by the MCP/network workstream).

## Deferred / skipped
- Repository discovery cache: kept at the 1 s TTL for the reasons in `git-display-read-performance.md`; the watcher removes the need for faster polling instead.
- UI-14 header `backdrop-filter`: kept. Without blur, 6% of sharp transcript text ghosts through the 94% surface; an opaque fill would stop matching the translucent window.

## Measurements
Git spawn counts per read (GUI PATH): info 12 → 6, review 28 → 14, pushCapability 46 → 23. Idle minute with the environment panel open: ~1,116 processes → ~43 focused, 0 blurred.
33 changes: 24 additions & 9 deletions main/handlers/workspaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
type GitPushInput,
} from "../services/git.js";
import { githubCurrentPullRequest } from "../services/github-pull-request.js";
import { GitRepoWatcher } from "../services/git-repo-watcher.js";
import { workspaceApplicationService } from "../services/workspace-application-service-main.js";
import {
listWorkspaceFiles,
Expand Down Expand Up @@ -138,6 +139,17 @@ async function withOptionalWorkspaceOperation<T>(
);
}

// Repository changes (commit, checkout, stage, fetch, push) are pushed to the
// renderer so its Git queries can poll slowly as a safety net only.
const gitRepoWatcher = new GitRepoWatcher({
notify: (workspaceId, generation) => ipcMain.broadcast("git:changed", { workspaceId, generation }),

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] Invalidate the main Git caches before notifying the renderer

An external checkout shortly after a display read triggers this notification while GitService's one-second info/branch caches are still valid, so the renderer's immediate refetch can install the old branch as fresh data. A real repository reproduction returned main instead of the newly checked-out topic at 260 ms; with the new minute safety poll, the branch display can remain wrong long after that cache expires.

Technical details
# Ensure repository-change reads bypass pre-change cached state

## Affected sites
- https://github.com/sambitcreate/aiden-agent/blob/57ad10c1938c99d3ef22d4f6b400fe47fdb4486a/main/handlers/workspaces.ts#L145 — broadcasts without invalidating main-process read caches.
- https://github.com/sambitcreate/aiden-agent/blob/57ad10c1938c99d3ef22d4f6b400fe47fdb4486a/main/services/git.ts#L1554 — repositoryInfo can return the cached pre-change status.
- https://github.com/sambitcreate/aiden-agent/blob/57ad10c1938c99d3ef22d4f6b400fe47fdb4486a/main/services/git.ts#L1585 — branch reads can return a cached pre-change branch list.
- https://github.com/sambitcreate/aiden-agent/blob/57ad10c1938c99d3ef22d4f6b400fe47fdb4486a/renderer/lib/git-query-sync.ts#L68 — renderer invalidation immediately re-reads those caches.

## Required outcome
- A read triggered by git:changed must observe the changed repository state rather than cached data from before the event.
- Verify an external checkout immediately after an info/branches read, followed by the default 250 ms watcher notification, returns the new branch.

## Suggested approach
Invalidate the affected main-process display caches before broadcasting, including shared/common-directory consumers. Their existing routing signatures track directory/config identity, not HEAD/index/ref changes; renderer invalidation alone cannot make those cache entries current.

});

function observeGitRepository(resolved: WorkspaceEnvironmentDirectory | undefined): void {
if (!resolved) return;
void gitRepoWatcher.observe(resolved.workspace.id, resolved.folderPath);
}

export function registerWorkspaceHandlers(): void {
ipcMain.handle("workspaces:list", async () => workspaceApplicationService.list());

Expand Down Expand Up @@ -173,9 +185,10 @@ export function registerWorkspaceHandlers(): void {
);

ipcMain.handle("workspaces:gitInfo", async (event, workspaceId: unknown) =>
withOptionalWorkspaceOperation(event, workspaceId, async (resolved, signal) =>
resolved ? gitInfo(resolved.folderPath, signal) : { isRepo: false },
),
withOptionalWorkspaceOperation(event, workspaceId, async (resolved, signal) => {
observeGitRepository(resolved);
return resolved ? gitInfo(resolved.folderPath, signal) : { isRepo: false };
}),
);

ipcMain.handle("git:pullRequestStatus", async (event, workspaceId: unknown) =>
Expand Down Expand Up @@ -233,9 +246,10 @@ export function registerWorkspaceHandlers(): void {
);

ipcMain.handle("git:review", async (event, workspaceId: unknown) =>
withWorkspaceOperation(event, workspaceId, (resolved, signal) =>
gitReview(resolved.folderPath, signal),
),
withWorkspaceOperation(event, workspaceId, (resolved, signal) => {
observeGitRepository(resolved);
return gitReview(resolved.folderPath, signal);
}),
);

ipcMain.handle("git:diff", async (event, workspaceId: unknown, input: unknown) =>
Expand All @@ -251,9 +265,10 @@ export function registerWorkspaceHandlers(): void {
);

ipcMain.handle("git:pushCapability", async (event, workspaceId: unknown) =>
withWorkspaceOperation(event, workspaceId, (resolved, signal) =>
gitPushCapability(resolved.folderPath, signal),
),
withWorkspaceOperation(event, workspaceId, (resolved, signal) => {
observeGitRepository(resolved);
return gitPushCapability(resolved.folderPath, signal);
}),
);

ipcMain.handle("git:push", async (event, workspaceId: unknown, input: unknown) =>
Expand Down
97 changes: 96 additions & 1 deletion main/services/git-executable.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import { resolveGitExecutable } from "./git-executable.js";
import { createGitExecutableResolver, resolveGitExecutable } from "./git-executable.js";

function fixture(paths: Record<string, string>, developerDir?: string) {
let probes = 0;
Expand Down Expand Up @@ -109,3 +109,98 @@ test("cancellation during default CLT fallback remains cancellation", async () =
};
await assert.rejects(resolveGitExecutable("git", "/workspace", { PATH: "/usr/bin" }, controller.signal, f.deps), { name: "AbortError" });
});

function memoFixture(paths: Record<string, string>, developerDir?: string) {
const f = fixture(paths, developerDir);
const inspected: string[] = [];
const executablePath = f.deps.executablePath;
f.deps.executablePath = async (candidate: string) => {
inspected.push(candidate);
return executablePath(candidate);
};
return Object.assign(f, { inspected });
}

const CLT_GIT = "/Library/Developer/CommandLineTools/usr/bin/git";

test("memoized resolution probes developer tools once and revalidates hits with one file check", async () => {
const f = memoFixture({ "/usr/bin/git": "/usr/bin/git", [CLT_GIT]: CLT_GIT }, "/Library/Developer/CommandLineTools");
const resolve = createGitExecutableResolver(f.deps);
const env = { PATH: "/usr/bin:/bin" };
for (let i = 0; i < 5; i++) assert.equal(await resolve("git", "/workspace", env), CLT_GIT);
assert.equal(f.probes, 1);
// The first resolution inspects the shim and CLT Git; each hit re-checks only the result.
assert.deepEqual(f.inspected.slice(2), Array(4).fill(CLT_GIT));
});

test("a changed PATH or DEVELOPER_DIR resolves again", async () => {
const f = memoFixture({
"/usr/bin/git": "/usr/bin/git",
[CLT_GIT]: CLT_GIT,
"/opt/homebrew/bin/git": "/opt/homebrew/Cellar/git/bin/git",
}, "/Library/Developer/CommandLineTools");
const resolve = createGitExecutableResolver(f.deps);
assert.equal(await resolve("git", "/w", { PATH: "/usr/bin" }), CLT_GIT);
assert.equal(await resolve("git", "/w", { PATH: "/opt/homebrew/bin:/usr/bin" }), "/opt/homebrew/Cellar/git/bin/git");
assert.equal(await resolve("git", "/w", { PATH: "/usr/bin", DEVELOPER_DIR: "/Library/Developer/CommandLineTools" }), CLT_GIT);
assert.equal(f.probes, 2);
});

test("a removed Git is noticed on the next command instead of being reused", async () => {
const paths: Record<string, string> = {
"/usr/bin/git": "/usr/bin/git",
"/opt/homebrew/bin/git": "/opt/homebrew/bin/git",
[CLT_GIT]: CLT_GIT,
};
const f = memoFixture(paths, "/Library/Developer/CommandLineTools");
const resolve = createGitExecutableResolver(f.deps);
const env = { PATH: "/opt/homebrew/bin:/usr/bin" };
assert.equal(await resolve("git", "/w", env), "/opt/homebrew/bin/git");
delete paths["/opt/homebrew/bin/git"];
assert.equal(await resolve("git", "/w", env), CLT_GIT);
});

test("resolution is repeated after the trust window", async () => {
let clock = 0;
const f = memoFixture({ "/usr/bin/git": "/usr/bin/git", [CLT_GIT]: CLT_GIT }, "/Library/Developer/CommandLineTools");
const resolve = createGitExecutableResolver(f.deps, { ttlMs: 1_000, now: () => clock });
await resolve("git", "/w", { PATH: "/usr/bin" });
clock = 999;
await resolve("git", "/w", { PATH: "/usr/bin" });
assert.equal(f.probes, 1);
clock = 1_000;
await resolve("git", "/w", { PATH: "/usr/bin" });
assert.equal(f.probes, 2);
});

test("failures are not cached, so installing Git later works without restarting", async () => {
const paths: Record<string, string> = { "/usr/bin/git": "/usr/bin/git" };
const f = memoFixture(paths);
const resolve = createGitExecutableResolver(f.deps);
await assert.rejects(resolve("git", "/w", { PATH: "/usr/bin" }), /Git is not installed/);
paths[CLT_GIT] = CLT_GIT;
assert.equal(await resolve("git", "/w", { PATH: "/usr/bin" }), CLT_GIT);
});

test("concurrent commands share one resolution and one caller's cancellation does not fail the rest", async () => {
let release!: (dir: string) => void;
const f = memoFixture({ "/usr/bin/git": "/usr/bin/git", [CLT_GIT]: CLT_GIT });
f.deps.developerDirectory = () => new Promise<string>((resolve) => { release = resolve; });
const resolve = createGitExecutableResolver(f.deps);
const controller = new AbortController();
const cancelled = resolve("git", "/w", { PATH: "/usr/bin" }, controller.signal);
const others = [resolve("git", "/w", { PATH: "/usr/bin" }), resolve("git", "/w", { PATH: "/usr/bin" })];
await new Promise((r) => setImmediate(r));
controller.abort();
await assert.rejects(cancelled, { name: "AbortError" });
release("/Library/Developer/CommandLineTools");
assert.deepEqual(await Promise.all(others), [CLT_GIT, CLT_GIT]);
assert.equal(f.inspected.filter((p) => p === "/usr/bin/git").length, 1);
});

test("memoized resolver leaves non-macOS binaries untouched", async () => {
const f = memoFixture({});
const resolve = createGitExecutableResolver({ ...f.deps, platform: "linux" });
assert.equal(await resolve("git", "/w", {}), "git");
assert.deepEqual(f.inspected, []);
});
77 changes: 77 additions & 0 deletions main/services/git-executable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,80 @@ export async function resolveGitExecutable(
}
throw new Error("Git is not installed or unavailable. Install Git to use repository features; ordinary chat does not require it.");
}

export type GitExecutableResolver = (
binary: string,
cwd: string,
env: NodeJS.ProcessEnv,
signal?: AbortSignal,
) => Promise<string>;

interface GitExecutableResolverOptions {
/** How long a resolution is trusted before the full search (and its xcode-select probe) reruns. */
ttlMs?: number;
now?: () => number;
}

const DEFAULT_RESOLUTION_TTL_MS = 5 * 60_000;

function abortable<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
if (!signal) return promise;
signal.throwIfAborted();
return new Promise<T>((resolve, reject) => {
const onAbort = () => reject(signal.reason);
signal.addEventListener("abort", onAbort, { once: true });
promise.then(
(value) => { signal.removeEventListener("abort", onAbort); resolve(value); },
(error) => { signal.removeEventListener("abort", onAbort); reject(error); },
);
});
}

/**
* Memoizes {@link resolveGitExecutable} per binary/PATH/DEVELOPER_DIR. Every Git command
* otherwise repeats the PATH walk and, when Apple's shim leads PATH, spawns xcode-select.
* A hit is revalidated with one filesystem probe of the resolved file, so an uninstalled
* or replaced Git is noticed on the next command; failures are never cached.
*/
export function createGitExecutableResolver(
deps: GitExecutableDependencies = defaults,
options: GitExecutableResolverOptions = {},
): GitExecutableResolver {
const ttlMs = options.ttlMs ?? DEFAULT_RESOLUTION_TTL_MS;
const now = options.now ?? Date.now;
const resolved = new Map<string, { executable: string; at: number }>();
const pending = new Map<string, Promise<string>>();

return async (binary, cwd, env, signal) => {
signal?.throwIfAborted();
if (deps.platform !== "darwin") return binary;
const key = JSON.stringify([
binary.includes("/") ? path.resolve(cwd, binary) : binary,
env.PATH ?? null,
env.DEVELOPER_DIR ?? null,
]);
const cached = resolved.get(key);
if (cached && now() - cached.at < ttlMs) {
const current = await abortable(deps.executablePath(cached.executable), signal);
if (current === cached.executable) return cached.executable;
}
if (resolved.get(key) === cached) resolved.delete(key);
let resolution = pending.get(key);
if (!resolution) {
// Shared by concurrent callers, so it must not inherit any one caller's signal.
resolution = resolveGitExecutable(binary, cwd, env, undefined, deps).then(
(executable) => {
resolved.set(key, { executable, at: now() });
return executable;
},
).finally(() => pending.delete(key));
// A caller may abort before attaching; the failure still surfaces to the others.
resolution.catch(() => undefined);
pending.set(key, resolution);
}
return abortable(resolution, signal);
};
}

/** Process-wide memoized resolver used by the Git service. */
export const resolveGitExecutableMemoized: GitExecutableResolver = createGitExecutableResolver();
Loading
Loading