Performance architecture
The App slowed down after every few weeks of work, was refactored, and slowed down again. Each cost found was a small habit repeated across components, and nothing failed when one was added. This page sets the rules a fast path follows and the gates that fail a change that breaks them.
- Watchlong frames, event-loop lag, slow replies in both installed Apps
- Gatesdeterministic counts fail a change; times are reported
- StackReact 19 features already shipped, adopted where measured
Why it kept coming back
Each habit below was measured while fixing "opening Settings is slow" (4× CPU throttle, profiles mapped to source).
| Habit | Where it showed | Gate |
|---|---|---|
| Subscribe to the route for a click handler | The sidebar list sorted and redrew every conversation on each navigation | Lint; render count |
| Change what a hidden panel shows | The file tree was rebuilt for the default project on every Settings visit | Render count |
| One full redraw per arriving value | One tree redraw per folder size | Render count |
| Construct per call | A new Intl.DateTimeFormat per row | Lint |
| Measure inside the commit | Rect reads in layout effects laid the page out twice | Lint; forced-layout count |
| Persist everything, synchronously | 2.1 MB of tab favicons rewritten on each tab change | Storage-bytes count |
| Read again what is held | A conversation's older pages fetched again on return | Request count |
Two more causes grow without any code change: data (more conversations, tabs and memory files make every O(n) pass slower) and the Worker under load (a blocking call inside an async route stalls every reply and socket push while an agent runs).
Rules
Thresholds come from RAIL (input answered in 100 ms, idle work in 50 ms chunks), Interaction to Next Paint (200 ms good, 500 ms poor) and long tasks (over 50 ms).
| Rule | Meaning |
|---|---|
| Budget | A navigation paints its new page with no task over 50 ms at 1× and within 200 ms at 4× CPU throttle. |
| Shell stays still | The sidebar, tab strip and right sidebar do not render on a route change unless what they draw depends on it. A handler that needs the path or a store value reads it when it runs (window.location, store.getState()). |
| Hidden does nothing | A panel under a hidden ancestor keeps its props and state and does no drawing; it catches up once when shown. |
| One pass per frame | Values arriving together are applied once per frame, never one full redraw each. |
| Read, then write | Layout is read before the DOM is written and once per frame; observers use the sizes they report (layout thrashing). |
| Small storage | Persisted UI state holds no full-size images, and an unchanged payload is not written again. |
| Scale | A list that grows with use is virtualized past about a hundred rows; work per interaction does not grow with the number of conversations or tabs. |
| Worker | No blocking call in an async route; repeated reads within a request share one snapshot. |
| Desktop | The Electron performance checklist: no synchronous IPC, no blocking file or process calls in the main process, nothing loaded before it is needed. |
Desktop
| Part | Choice |
|---|---|
| First frame | A window is created with the OS appearance (--openprogram-system-dark), so the preload answers it without a round trip; a reloaded page confirms it asynchronously. A tab drag mints its own transfer token. |
| Main process | web auth-url (about a second of Python), ps, folder listings, browser imports and the browsing history run asynchronously. Tiny reads before the first window and the fsynced tab-transfer decision stay synchronous. |
| Loading | Browser import and Windows signature checks load when first used. |
| Web pages | A window keeps at most eight web pages running, as many as it shows. Past that the least recently used idle page sleeps and wakes with its address, icon and scroll position. A desktop check opens thirty tabs and counts the live ones. |
| Startup | Each start logs its steps from process start to the first frame, locally, in startup-timings.json (last twenty runs). |
Gates
A gate fails on counts, not times. Times vary with what else the machine is doing (several sessions build and test here at once), so a time is checked only against a generous absolute limit, and its trend is reported.
Counts are close to fixed. Between runs most move by a few, because React batches replayed frames by when they arrive, so each budget is the largest count of six runs plus a recorded tolerance.
| Gate | Fails on | Runs in |
|---|---|---|
| Lint rules | ESLint (apps/web/scripts/lint/plugin.mjs): no route hook in a part that stays mounted across routes (sidebar, center tabs, right sidebar, file explorer and tree, app-shell.tsx) without a shell-route: reason; no new Intl.* or option-taking toLocale* inside components and hooks; no rect or size read in useLayoutEffect without a layout-read: reason; no localStorage write outside lib/storage/local-storage.ts; the five React Compiler rules. Python (scripts/checks/async_blocking.py): no blocking call (time.sleep, requests.*, subprocess.run, webbrowser.open…) directly in an async def under openprogram/ without a blocking-ok: reason. | affected_tests, on the changed files |
| Interaction scenarios | Render counts of shell parts, requests sent, storage writes, forced layouts and style recalculations, DOM nodes over budget, or a count that should stay flat growing from N to 10N; time or heap over its absolute limit; a request the replay cannot answer. | Development deploy, after the build and before switching |
| Bundle budget | Initial JavaScript or a route's chunk over its size. | Development deploy, with the scenarios |
| Worker budget | Expensive operations per request (as the catalog test counts credential enumerations). | affected_tests |
| Coverage | A route under apps/web/app/(shell) with no scenario. | affected_tests |
Scenarios
| Part | Choice |
|---|---|
| Command | python -m scripts.testing.perf: the profiling build, the bundle budget, every scenario at both scales in four parallel browsers, the comparison. About three minutes. --no-build reuses the last build, --flows chat runs one flow, --runs 3 lists the counts that moved, --update-budgets writes today's counts. |
| Driver | Playwright drives the profiling export in headless Chromium at 4× CPU throttle, served through request routing from a made-up origin, so no port is opened. |
| Backend | scripts/testing/perf/replay.py answers /api and /ws inside the browser. Lists, transcripts, history pages, file-tree pages and the streamed reply come from a generator; the other replies were recorded once from the development instance (only reads pass, writes are dropped) and stored with every text, path, name and key replaced (apps/web/tests/perf/fixtures/traffic.json, refused if it holds this computer's user name, home path or host name). |
| Data | N is 60 conversations in 6 projects, 30 open tabs, a 40-turn transcript and a 2-level tree; 10N is ten times each (a 20-level tree). |
| Paths | 37 scenarios: cold start, type in the composer, scroll a transcript up, a 300-delta reply streaming in, switch chats, open the file tree, expand it to the bottom, open Settings, each of its 13 tabs, back to a chat, each of the 14 other shell routes, and fifty chat switches. |
| Render counts | A profiling build (OPENPROGRAM_WEB_PROFILING=1, exported to apps/web/out-profiling) swaps in react-dom/profiling and wraps the sidebar, tab strip, transcript, composer, right sidebar and file tree in <Profiler> (apps/web/lib/perf/profiled.tsx). The production build compiles the wrapper away. Commits and the components each one rendered are counted from React's DevTools hook. |
| Memory | Heap after fifty chat switches and three garbage collections, limit 400 MB; today 41 MB at N and 49 MB at 10N. |
| Coverage | python -m scripts.testing.perf coverage lists each page.tsx under apps/web/app/(shell) without a scenario; affected_tests runs it when anything under apps/web/app/ changes. All 29 routes are covered. |
Budgets
apps/web/tests/perf/perf-budgets.json holds each count per scenario and scale.
- A count fails above its budget plus the tolerance for its kind: 10% or 2 for counts, 25% or 12 for forced layouts and style recalculations, 25% or 50 for components rendered, 10% or 1 KB for storage bytes, 1% or 5 for DOM nodes, none for requests leaving the origin.
flatlists the counts that must not grow from N to 10N;growsnames each exception with its reason;unsteadynames counts that are reported and not held.- A scenario with no budget, or a new part or metric, fails until it is given one.
Some of today's budgets, at N except the DOM nodes:
| Scenario | Renders | Requests | Storage writes | DOM nodes N / 10N |
|---|---|---|---|---|
| Cold start | sidebar 10, tabs 5, transcript 9, composer 14 | 36 HTTP, 30 socket | 12 | 2,674 / 6,631 |
| Open Settings | sidebar 2, transcript 2, composer 5 | 21 HTTP, 2 socket | 1 | 2,695 / 6,653 |
| Back to a chat | sidebar 4, transcript 7, composer 7 | 7 HTTP, 10 socket | 1 | 2,673 / 6,631 |
| Switch chats | sidebar 4, transcript 7, composer 8 | 10 HTTP, 13 socket | 2 | 2,384 / 6,344 |
| Type 48 characters | composer 48, nothing else | none | 1 to 3 (under 4 KB) | 2,669 / 6,629 |
| Stream 300 deltas | transcript 107, composer 3 | 8 HTTP, 1 socket | 0 | 4,782 / 6,695 |
| Open the file tree | sidebar 1, transcript 2 | none | 4 | 2,385 / 6,345 |
The exceptions are today's known costs:
- The tab strip draws every tab (past its width the strip scrolls), and the windowed sidebar keeps a same-height placeholder for each conversation outside its window, so DOM nodes grow with the data (6,631 nodes at 10N against 2,674 at N), as do the strip's components when it mounts and the sidebar's on each of its commits.
- After the strip mounts, a tab renders again only when its own props change (
TabItemis memoized and the strip hands it stable handlers), so a chat switch renders 73 strip components at both scales. - Every tab-state write rewrites the whole tab list: 5 KB at N, 47 KB at 10N. Typing writes no tab state.
- Expanding the tree and scrolling the transcript grow because the 10N data has more levels and pages to reach.
- Typing writes the window's draft state (
session-draft-persistence.ts) after 300 ms of quiet, and at least once a second while typing goes on. Reading that state, another draft write, a send, page hide, a hidden window and quit write it at once: a crash loses at most the last second of typing. - Over fifty switches the sidebar commits 150 times at N and at 10N. A row does not render on hover: the long-title marquee moves the title through the DOM, not React state.
Ratchet and budget changes
Each rule started with its violations recorded per file, as scripts/docs_site/governance/baseline.json does for docs; the count may only fall.
| Part | Behavior |
|---|---|
| Baselines | apps/web/scripts/lint/baseline.json for ESLint, scripts/checks/async_blocking_baseline.json for the Worker. |
| Fails on | A count above its entry, or a file or rule with no entry. |
| A count fell | Reported with the command that lowers the entry (--lower). |
| Scope | The changed files, under a second for a few. A change to the rules, the ESLint config or a baseline checks every file: about 35 s for ESLint, 4 s for the Worker. |
| New rule | ratchet.mjs --all --record <rule> records its starting counts. |
A baseline or budget is raised only by editing its file, with the reason in the commit. The weekly summary lists every raise with npm run lint:raises -- --since "1 week ago" (in apps/web) and python -m scripts.checks.async_blocking --raises --since "1 week ago", which compare each commit of the file with its parent.
Watch
Both installed Apps log, locally and never on screen, long animation frames over 50 ms with their scripts, Worker event-loop lag over 50 ms, and replies over 100 ms, one JSON line each in logs/performance.jsonl under the profile's data folder (~/.openprogram or ~/.openprogram-dev).
openprogram performance report (--profile dev for the development App) prints the worst of the last seven days; each one becomes a scenario or a rule.
| Part | How |
|---|---|
| Long frames | A PerformanceObserver for long-animation-frame (longtask where it is missing) keeps each frame's duration, blocking time, route with ids folded, and its three longest scripts: URL, function name, character position, invoker. At most 30 frames a minute; they go together to POST /api/performance/frames when the page is idle, at most every 10 s, and at once when it is hidden. |
| Loop lag | A task on the Worker's loop sleeps 100 ms at a time and logs how late it woke. While it is late, a thread looks at the loop thread's stack at 50 ms, 250 ms and 1 s; a loop found waiting in its selector is logged with the threads that held the interpreter instead. |
| Slow replies | An ASGI middleware times each HTTP request to its response headers and logs it by route pattern; the WebSocket dispatch logs each action over 100 ms by name. |
| The log | Lines are queued and written by one thread, so the measured code never waits on the disk. Each kind is capped per minute (frames and lag 60, replies 120) and the next line counts what the cap dropped. The file rotates at 4 MB and keeps three older files, 16 MB at most. |
| Source maps | The browser bundle is built with hidden source maps (no sourceMappingURL, so the browser never fetches them). After the export, apps/web/scripts/runtime/move-source-maps.mjs moves them out of the served out/ into out-maps/ with a copy of each chunk (about 45 MB of maps and 16 MB of chunks), kept 30 days. The development deploy copies them to ~/.openprogram-dev/runtime/source-maps/; a release package carries none, so the official App's frames show minified positions. |
| Summary | Frames are grouped by their longest script, mapped to function (file:line) when a map is found, and by route; lag by the innermost product call the loop was in; replies by route and by action. Each group has its count, p50, p95 and largest duration, ordered by the total time it cost. |
| Cost | The loop monitor and its thread use about 3 ms of processor time a second; a long frame costs one entry in memory and a share of one idle request. |
Stack
No framework change: every cause measured was a habit, and rewriting 1,078 files in another framework would carry the same habits over.
| Part | Choice |
|---|---|
| One React | react and react-dom 19.3.1, the release nearest the canary Next 16.4 bundles, and @types/react 19, pinned in apps/web/package.json and the workspace root: unit tests and the CLI run the React the App ships. apps/web/tests/_support/linkedom-react19.mjs gives the test DOM what React 19 uses and linkedom lacks (a textarea's defaultValue, lowercase attribute names). |
| React Compiler | reactCompiler: true in apps/web/next.config.mjs (babel-plugin-react-compiler 1.0, infer mode): the production build caches calculations and JSX inside every component and hook the compiler can prove safe, and leaves the rest as written. No component is opted out with "use no memo". It does not stop a component that subscribes to the route or a store from rendering; that is the lint rule and the render count. 380 compiler diagnostics in 148 files are recorded in the lint baseline; hand-written memoization stays. |
| Transitions | Route changes are transitions already: Next's router runs router.push and the history.pushState the sidebar and tab strip use inside startTransition. A store update (useSyncExternalStore) always renders at once, so wrapping one changes nothing. The sidebar window brings rows in ahead of the view as a transition. scheduler.yield() is for a long loop a scenario finds. |
| Deferred values | useDeferredValue lets a search field take each key at once while its list filters a render behind: History, Abilities, the harness sessions in Settings and the provider picker. It pays only in a component the compiler caches, where the urgent render reuses the list; the command palette filters inside cmdk's own store. |
<Activity> | Only for a surface whose state is expensive to rebuild and whose props stay the same while hidden. Hidden, its effects are cleaned up and run again when shown, so xterm, CodeMirror, fabric and pdf.js panels are checked one by one; its DOM stays in memory, which the memory scenario limits. |
| Windowing | A long list renders only the rows near its view. The transcript keeps its rows live by measured height (lib/chat/history/message-window.ts); the sidebar's conversation list does the same past 100 rows (components/sidebar/sessions/use-row-window.tsx): a row out of view is an empty box of its height in its place, so section headers, gaps, drag offsets and the scroll position stay, and the open chat, the selection, the dragged row and the focused row always render. |
| CSS | content-visibility: auto with remembered sizes on the transcript's rows while the chat's width settles (app/styles/chat/pane/transcript.css). Nowhere else: a row never drawn has no remembered height, and its estimate would move the scrollbar and the scroll position; long lists are windowed instead. |
| Storage | One module owns localStorage writes. Only large or frequently written keys move to IndexedDB. |
| Web Worker | Not adopted: no measured cost comes from Markdown, highlighting or parsing. The streaming scenario decides. |
Implementation status
| Phase | Content | State |
|---|---|---|
| 0 | Fix the measured costs (sidebar, file tree, Settings, back to chat, tab storage, startup endpoints) | Done |
| 1 | Watch in both Apps; lint rules with the ratchet in affected_tests; the existing bundle budget wired into the deploy | Done. Initial JavaScript is 618,268 bytes against 665,600. The app shell's on-demand code is cut into files of at most 700 KB raw (splitChunks.maxAsyncSize), fetched in parallel; the largest chunk is 134,718 bytes against the 358,400 cap |
| 2 | Replay recorder, scenarios at two scales, profiling build with render counts, route coverage check; today's counts become the budgets | Done |
| 3 | One React version, React Compiler through the ratchet, transitions, virtualized sidebar list | Done |
| 4 | Electron: no synchronous IPC, blocking main-process calls made asynchronous, startup steps to the first frame logged, at most eight live web pages per window (a desktop check opens thirty tabs and counts them) | Done |
Gates hold only what a scenario or rule covers; the coverage check and the weekly summary are what widen them.