Skip to content

perf(renderer): halve startup JavaScript and replace idle git polling - #326

Merged
sambitcreate merged 17 commits into
mainfrom
perf/renderer-bundle-polling
Oct 4, 2026
Merged

sambitcreate merged 17 commits into
mainfrom
perf/renderer-bundle-polling

Conversation

@sambitcreate

@sambitcreate sambitcreate commented Oct 4, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Startup JS 3,328 → 1,642 KB:
    • Non-chat routes and rare panels are split out (UI-2).
    • highlight.js grammars load lazily, without auto-detection (UI-1).
    • KaTeX loads only for messages with math (UI-3).
    • The dictation pill is kept off the ipc.ts graph (UI-4).
    • Startup reads are issued before the app chunk evaluates (UI-5).
  • Fewer git processes, ~1,116 → ~43 per idle minute:
    • A .git metadata watcher pushes repository changes (MAIN-22).
    • The git executable is memoized per PATH.
    • Git panels refresh from events and poll only as a safety net (UI-17/18).
  • Remote status (UI-19, MAIN-23, partial): polled only while on screen.
  • Query client (UI-16): deliberate defaults.
  • Model picker (UI-15): lists are derived only while it's open.

Test plan

  • Renderer unit suites, type-check and lint.
  • The relevant Playwright specs after a build.

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.

🤖 Generated with Claude Code

Flake recorded

🤖 Generated with Claude Code

sambitcreate and others added 12 commits October 3, 2026 06:44
…UI-4)

Move the bridge primitives and the settings/voice/dictation wrappers into
parser-free modules that ipc.ts re-exports, and point the pill window and
its voice helpers at them directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…on (UI-1)

Code blocks now load highlight.js/lib/core plus an allowlisted grammar on
demand, keyed by the fence label. Unlabeled or unknown fences render as
plain text instead of running every grammar through highlightAuto.

Main-window initial JS: 3328 KB -> 2438 KB (gzip 1019 KB -> 723 KB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
rehype-katex and the KaTeX stylesheet now load the first time a message
contains a $ delimiter. Until then the TeX source renders as typed, then
the message re-renders as KaTeX.

Main-window initial JS: 2438 KB -> 2174 KB; initial CSS 189 KB -> 161 KB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…y (UI-2)

Settings, Profile, Scheduled, Bots and bot chat now load through
lazyRouteComponent. The router awaits each chunk before committing the
navigation, so the previous view stays up rather than flashing a
placeholder. The Browser and Simulator panels load with the environment
panel. Onboarding stays eager because it gates the first-run workbench.

Main-window initial JS: 2174 KB -> 1636 KB (gzip 645 KB -> 506 KB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…I-5)

The main-window entry is now a small loader. It applies the cached theme,
starts app:getInfo and providers:list concurrently, then dynamically
imports the app. The main process answers both while the renderer parses
the app chunk, so first render no longer waits on two serial round trips
after module evaluation. Capabilities and the provider alias migration
still resolve before the router renders, so onboarding and
capability-gated navigation see the same state as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Queries now default to a 30 s staleTime, no refetch on window focus and a
single retry. Focusing the window no longer resends every active query,
including whole chats, over IPC. Chats, workspaces, bots, schedules and
config are invalidated by push events. Skills, the skill catalog, MCP
servers, the local voice engine status and usage opt back into focus
refetch, because they can change with no push event. A chat still
re-reads when it is revisited.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every Git command re-walked PATH and, when Apple's shim leads a GUI PATH,
spawned xcode-select before Git itself. Resolutions are now memoized per
binary/PATH/DEVELOPER_DIR, revalidated with one file check per hit,
re-resolved after five minutes, shared between concurrent callers, and
never cached on failure. On a synthetic repo this removes one
xcode-select spawn per git spawn (info 12 -> 6, review 28 -> 14,
pushCapability 46 -> 23 processes per read).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-22)

Display reads (gitInfo, review, pushCapability) now start a lazy,
worktree-aware fs.watch on the workspace's Git directories: HEAD, index
and packed-refs in the administrative dir, packed-refs in the common dir,
and refs recursively. Bursts are debounced into one git:changed
{workspaceId, generation} broadcast. Only Git metadata is watched, never
the working tree, and workspaces not read for ten minutes are released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ety net (UI-17, UI-18)

Git display queries are invalidated by git:changed, settled chats and
(throttled to one refresh per 5 s) agent tool results, and stale reads are
refetched when the window is re-activated. Their intervals drop from
4-5 s to a 60 s safety net that stops while the window is hidden or
blurred. Pull-request status (gh pr view) polls every five minutes and
repository changes refresh it only once it is a minute old.

Registers the watcher and sync suites, and replaces the source-grep of
the old 30 s pull-request interval with behavioral coverage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… MAIN-23)

The always-mounted Remote badge read Tailscale status every 10 s, about two
CLI runs per snapshot. It now polls once a minute while the window is
active and not at all while blurred or hidden. The open popover and the
Remote settings page keep the 10 s live cadence, and remote:changed still
invalidates immediately.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…UI-15)

The composer re-renders on every streamed token, and the closed picker rebuilt
its catalog lookup, entries, list order and both pad layouts each time. The
catalog entries are now memoized on their inputs (the per-provider cached
answers are compared by reference), and list order and detail positions are
derived only while the popover is open. The provider-scoped catalog lookup is
shared with createChatModelProviders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@pullfrog pullfrog Bot left a comment

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.

Important

Three refresh bugs need addressing: Remote polling does not resume after desktop focus, repository notifications can publish cached pre-change Git state, and newly initialized repositories can remain unwatched.

Reviewed changes — Reviewed all 44 changed files across the startup, rendering, IPC, and query refresh paths.

  • Startup loading: Concurrent startup IPC reads, deferred non-chat routes and panel modules, and a separate app bootstrap.
  • Transcript rendering: On-demand syntax grammars and KaTeX, with plain text while dependencies load.
  • IPC split: Shared settings, voice, and dictation wrappers moved into parser-free modules for the pill.
  • Git refresh: Memoized executable resolution, metadata watchers, event-driven query invalidation, and slower safety polling.
  • Query behavior: New cache/retry defaults, visibility-dependent Remote polling, and memoized model-picker derivation.

Validation: 184 focused tests, TypeScript, targeted ESLint, and the renderer build passed. Separate behavioral reproductions confirmed all three inline findings. Electron E2E was not run on this Linux runner.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

Comment thread renderer/lib/queries.ts
refetchOnWindowFocus: true,
refetchInterval: 10_000,
staleTime: live ? 0 : AIDEN_REMOTE_IDLE_POLL_MS,
refetchInterval: live ? AIDEN_REMOTE_LIVE_POLL_MS : pollWhileWindowActive(AIDEN_REMOTE_IDLE_POLL_MS),

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] Resume Remote badge polling on window activation

Once a scheduled poll runs while the window is blurred, this callback returns false and clears its timer, but ordinary desktop focus never restarts it. The closed Remote badge can then stay stale indefinitely until another render or notification: a reproduction using the real observer and Git sync recorded no further reads across five active minutes.

Technical details
# Restart the Remote observer after activation

## Affected sites
- https://github.com/sambitcreate/aiden-agent/blob/57ad10c1938c99d3ef22d4f6b400fe47fdb4486a/renderer/lib/queries.ts#L683 — the idle Remote interval can disable itself.
- https://github.com/sambitcreate/aiden-agent/blob/57ad10c1938c99d3ef22d4f6b400fe47fdb4486a/renderer/lib/git-query-sync.ts#L87 — activation restarts only Git observers.
- https://github.com/sambitcreate/aiden-agent/blob/57ad10c1938c99d3ef22d4f6b400fe47fdb4486a/renderer/components/remote-connection-popover.tsx#L98 — the closed badge stays mounted with live=false.

## Required outcome
- After blur/focus, the idle Remote badge must resume its minute cadence, even if its last snapshot is still fresh.
- Add behavioral coverage that mounts the idle observer, blurs through a scheduled tick, focuses, and advances several active minutes.

## Suggested approach
Reuse the window-activation subscription to re-evaluate Remote observer options, as the Git path already does. refetchOnWindowFocus alone is insufficient: TanStack v5 listens to visibilitychange rather than desktop focus, and a visibility event also does not fetch fresh data. See https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#window-focus-refetching-no-longer-listens-to-the-focus-event .

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

this.entries.set(workspaceId, entry);
this.ensureSweep();
const targets = await this.resolveTargets(folderPath).catch(() => undefined);
if (entry.closed || !targets) return;

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] Allow later reads to retry unsuccessful watcher discovery

When a workspace is first read before git init, this return leaves an entry with no watchers, and every later observe call for the same folder exits at the existing-entry check. Initializing Git afterward therefore never enables repository notifications while the workspace remains active, because each safety read renews lastRead and prevents idle eviction.

Technical details
# Recover observation when a folder becomes a repository

## Affected sites
- https://github.com/sambitcreate/aiden-agent/blob/57ad10c1938c99d3ef22d4f6b400fe47fdb4486a/main/services/git-repo-watcher.ts#L94 — entry is inserted before discovery succeeds.
- https://github.com/sambitcreate/aiden-agent/blob/57ad10c1938c99d3ef22d4f6b400fe47fdb4486a/main/services/git-repo-watcher.ts#L97 — unsuccessful discovery leaves that entry installed.
- https://github.com/sambitcreate/aiden-agent/blob/57ad10c1938c99d3ef22d4f6b400fe47fdb4486a/main/services/git-repo-watcher.ts#L88 — later reads renew the empty entry without retrying discovery.

## Required outcome
- A later display read must establish watchers if a previously plain folder has become a repository.
- Extend watcher coverage with observe(empty folder), git init, observe(same workspace/folder), and a metadata change that must notify.

## Suggested approach
Do not retain an unsuccessful discovery as an established observation. Release the empty entry so a subsequent read retries; likewise ensure an entry with no successfully installed watchers can recover. A real temporary-directory reproduction installed zero watchers after Git initialization and the second observe call.

sambitcreate and others added 2 commits October 4, 2026 03:54
Two command-palette specs replace `providers:list` and reload. Startup
reads that list and then `providers:refreshIfStale`, and the renderer
keeps whichever answers last. Before, a stale-on-mount refetch of
`providers:list` happened to overwrite the refresh result; with the new
30 s query staleTime the renderer reuses that startup data, so the
real catalog from the unstubbed refresh replaced the stubbed providers.
Stub both reads with the same inventory so the mocked main process
answers consistently.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@pullfrog pullfrog Bot left a comment

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.

ℹ️ No new issues found in this delta. Approval remains withheld because the existing refresh findings are still unresolved.

Reviewed changes
Reviewed the changes since 57ad10c1, including the merge from main and the command-palette fixture fix.

  • Stabilized startup fixtures: Stubbed providers:refreshIfStale with the same inventory as providers:list in the duplicate-provider and delayed-settings E2E cases, preserving their selection and readiness assertions.
  • Preserved test registration: Integrated the parallel CI runner from main while retaining the new renderer and Git tests in the serial test chain and CI registry.

Validation: E2E TypeScript checking passed, Playwright collected all 20 specs in chat-shell-interactions.spec.ts, and all 110 focused unit and CI-policy tests passed. Electron E2E execution was not available on this Linux runner; exact-head CI is still pending.

Pullfrog  | Fix it ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

Main's IPC error normalization now lives in ipc-bridge.ts, where this
branch moved invoke(), so ipc.ts re-exports the normalized version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@pullfrog pullfrog Bot left a comment

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.

ℹ️ No new issues found in this delta. Approval remains withheld because the three existing refresh findings are still unresolved.

Reviewed changes
Reviewed the merge from main since the prior review at a665fb2a, focusing on its integration with the shared IPC boundary.

  • Preserved IPC error normalization: Moved main's rejection normalization into ipc-bridge.ts, retaining the public ipc.ts re-export and extending the same user-facing error handling to settings, voice, and dictation callers without restoring the heavy parser dependency graph.

Validation: All 64 focused IPC, voice, appearance, and refresh tests and all 55 CI-policy tests passed. TypeScript and targeted ESLint passed; a separate behavioral check verified normalized failures across the shared APIs and preservation of successful values and unrelated rejection values. Electron E2E was not run on Linux; exact-head hosted CI remains pending.

Pullfrog  | Fix it ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

@very-hermes-bot

very-hermes-bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Hermes Review Bot

Confidence: 5

Engine: agy/gemini-3.8-flash-high
Review mode: full
Head: c12d45bb8b718b8da45dcedbf6ada0711663747d
Generated: 2026-10-04T12:16:01+00:00
Reviews: 1

Summary

This optimization pass significantly reduces initial renderer bundle size (from 3.3 MB to ~1.6 MB) and replaces aggressive Git polling (~1,116 spawns/min down to ~43 focused, 0 blurred) with an event-driven synchronization architecture. Main-window startup dispatches early IPC reads (app:getInfo and providers:list) before asynchronously evaluating the application chunk, while non-chat routes, KaTeX, and highlight.js grammars are loaded on demand. Repository state is tracked by a debounced fs.watch observer on .git administrative files and refs, allowing TanStack Query to transition to a 60-second safety poll that automatically suspends when the window is hidden or blurred. Maintainers should double-check that multi-worktree setups and nested directory symlinks on unusual host filesystems reliably trigger the .git watcher without exceeding platform file-descriptor limits.

Confidence Score: 5/5

All 45 changed files were inspected, asynchronous lifecycles and concurrency paths in git watching and executable resolution were traced end-to-end, and test coverage/contract alignments were verified across the codebase.

📁 Important Files Changed
  • main/services/git-repo-watcher.ts: Watches repository metadata (HEAD, index, packed-refs, and refs) using debounced fs.watch with idle eviction, pushing git:changed notifications to renderer display queries.
  • main/handlers/workspaces.ts: Instantiates the repository watcher and attaches observers during workspace queries (gitInfo, gitReview, gitPushCapability).
  • main/services/git-executable.ts & main/services/git.ts: Introduces a process-wide memoized resolver for the git executable with revalidation and caller-isolated cancellation, eliminating repetitive PATH walks and macOS xcode-select subprocess checks.
  • renderer/lib/git-query-sync.ts: Synchronizes TanStack Query cache with git:changed push events, agent tool execution boundaries, chat completions, and window activation, replacing rapid polling with event-driven invalidation.
  • renderer/lib/queries.ts & renderer/lib/query-client.ts: Configures app query defaults (30 s staleTime, refetchOnWindowFocus: false, retry count 1) and converts git and remote status polling into safety nets that sleep when the window is inactive.
  • renderer/main/index.tsx & renderer/main/app.tsx: Splits the entry point into a minimal bootstrap that dispatches early IPC reads (app:getInfo, providers:list) before importing and evaluating the main application bundle.
  • renderer/lib/syntax-highlight.ts & renderer/components/code-block.tsx: Replaces the full highlight.js library with lazy on-demand grammar loading and language aliasing, dropping synchronous bundle weight and unneeded auto-detection.
  • renderer/lib/markdown-math.ts & renderer/components/markdown.tsx: Defers loading KaTeX and its stylesheet until a rendered message contains mathematical delimiters.
  • renderer/main/router.tsx: Applies route-level code splitting via lazyRouteComponent for non-chat routes (Settings, Profile, Bots, Scheduled Tasks).
  • renderer/lib/ipc-bridge.ts & renderer/lib/ipc-voice.ts: Decouples low-level IPC primitives and voice APIs from the large ipc.ts dependency graph so the dictation pill window avoids loading main-window parsers.

Findings

No findings.

Sequence Diagram

sequenceDiagram
  autonumber
  participant Git as Local Git / Subprocess
  participant Watcher as GitRepoWatcher (Main)
  participant Renderer as GitQuerySync (Renderer)
  participant Cache as QueryClient Cache
  participant UI as Active Git Panels

  Git->>Watcher: Metadata file change (.git/HEAD, index, refs)
  Watcher->>Watcher: Debounce 250ms & increment generation
  Watcher->>Renderer: Broadcast "git:changed" { workspaceId, generation }
  Renderer->>Cache: Invalidate REPOSITORY_ROOTS queries
  Cache->>Git: Refetch active queries (gitInfo, gitReview, pushCapability)
  Cache-->>UI: Deliver updated state to subscribers
Loading
[]

Last reviewed commit: c12d45bb8b71
Reviews (1) · Comment /hermes review to trigger a new review · /hermes review full for full re-review

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@pullfrog pullfrog Bot left a comment

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.

ℹ️ No new issues found in this delta. Approval remains withheld because the three existing refresh findings are still unresolved.

Reviewed changes
Reviewed the merge from main since the prior review at 3b98c5fe, focusing on the test-chain integration.

  • Integrated shared-helper tests: Added test:main-shared to the serial chain while preserving every prior test and its ordering, including this PR's Git watcher and renderer test registrations.

Validation: All 85 focused shared-helper, CI-policy, and refresh tests passed. The three existing review threads were checked against the current implementations and left open. Electron E2E was not run on Linux; exact-head hosted CI is still pending.

Pullfrog  | Fix it ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@pullfrog pullfrog Bot left a comment

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.

ℹ️ No new issues found in this delta. Approval remains withheld because the three existing refresh findings are still unresolved.

Reviewed changes
Reviewed the merge from main since the prior review at e156c2c0, focusing on the serial test-chain integration.

  • Integrated renderer-helper tests: Added the dialog Enter-key, chat pull-request chip, and workspace file-open error suites to test:serial, preserving all previous test entries and their ordering, including this PR's renderer and Git suites.

Validation: All 75 focused renderer-helper, refresh, and CI-policy tests passed. An exact comparison confirmed that the three added test paths are the only test-chain changes. Electron E2E was not run on Linux; exact-head hosted CI is still pending.

Pullfrog  | Fix it ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

@sambitcreate
sambitcreate merged commit 081e7e0 into main Oct 4, 2026
25 checks passed
@sambitcreate
sambitcreate deleted the perf/renderer-bundle-polling branch October 4, 2026 13:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants