Vayu App Architecture¶
The Vayu Manager is an Electron-based desktop application built with React and TypeScript. It provides a user interface for designing API requests, executing them, and running load tests. The app communicates with the Vayu Engine (a C++ daemon) via HTTP on 127.0.0.1:9876 (a fallback port when another program holds it).
High-Level Architecture¶
┌─────────────────────────────────────────────────────────┐
│ Electron Main Process │
│ ┌──────────────────────────────────────────────────┐ │
│ │ main.ts │ │
│ │ - Creates BrowserWindow │ │
│ │ - Manages EngineSidecar lifecycle │ │
│ │ - Handles app lifecycle events │ │
│ └──────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ sidecar.ts │ │
│ │ - Spawns/manages C++ engine process │ │
│ │ - Monitors engine health │ │
│ │ - Handles binary path resolution │ │
│ └──────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
│
│ IPC (preload.js)
▼
┌─────────────────────────────────────────────────────────┐
│ Electron Renderer Process (React) │
│ ┌──────────────────────────────────────────────────┐ │
│ │ App.tsx │ │
│ │ - Root component │ │
│ │ - Initializes health checks │ │
│ │ - Prefetches data │ │
│ └──────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Shell.tsx │ │
│ │ - Main layout (sidebar + content) │ │
│ │ - Routes to screens based on state │ │
│ └──────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Components │ │
│ │ - RequestBuilder, LoadTestDashboard, etc. │ │
│ └──────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ Services Layer │ │
│ │ - api.ts: HTTP client for engine API │ │
│ │ - sse-client.ts: Server-Sent Events │ │
│ └──────────────────────────────────────────────────┘ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ State Management │ │
│ │ - Zustand stores (UI state) │ │
│ │ - TanStack Query (server state) │ │
│ └──────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
│
│ HTTP/SSE (localhost:9876)
▼
┌─────────────────────────────────────────────────────────┐
│ Vayu Engine (C++ Daemon) │
│ - HTTP Server (cpp-httplib) │
│ - Request Execution (libcurl) │
│ - Load Testing │
│ - SQLite Database │
└─────────────────────────────────────────────────────────┘
Core Components¶
Electron Main Process (electron/main.ts)¶
The main process is responsible for:
- Window Management: Creates and manages the Electron
BrowserWindow. ItswebPreferenceshold the renderer's security posture - no Node integration, context isolation on, and Chromium's spellchecker off (spellcheck: false), so no field in the request builder draws underlines. No dictionary is fetched over the network either, but that is a session setting, not the window option:electron/spellcheck.tsempties every session's spellchecker language list from asession-createdlistener registered beforeapp.whenReady. Bounds, maximised and full-screen state are remembered across launches inwindow-state.jsonunder the user-data directory (window-state.ts, issue #2100); a maximised or full-screen window keeps its previous normal bounds, and full screen is re-entered after the window is shown - Engine Lifecycle: Starts and stops the C++ engine via
EngineSidecar - App Lifecycle: Handles app ready, window close, and quit events. A close and a quit go through one state machine,
quit-flow.ts: a close or quit that would stop a running inbox, mock server or mock issuer is intercepted first and names what it stops, so a window-scoped service is never taken silently (service-stop-guard.ts, issue #1363); then the renderer flushes its saves, and a flush that did not land is asked about (save-flush.ts, issue #1489). Cancel or Keep working returns the flow toidle, so the next gesture flushes and asks again (issue #3335) - Context Menu: Composes the right-click menu from Chromium's
context-menuparams and the target the renderer announces (context-menu.ts, issue #1359) - Start at login: Reads and writes whether Vayu opens when the user signs in, on the OS's own state and never a copy (
login-item.ts, issue #2098).app.setLoginItemSettingson Windows and macOS; on Linux, where Electron's call does nothing, an XDG autostart entry at$XDG_CONFIG_HOME/autostart/vayu.desktopnaming the running binary (the AppImage path), which reads as off once the binary moves or a desktop environment disables the entry in place (Hidden=true,X-GNOME-Autostart-enabled=false). Reports unsupported for an unpackaged build, whose executable is Electron itself - Windows restart registration: On a packaged Windows build, asks Windows to relaunch Vayu after a restart (
RegisterApplicationRestartthroughkoffi, with--restarted-after-rebootand the no-crash, no-hang and no-patch flags, since renderer recovery and the updater own those cases;restart-registration.ts, issue #2098). Called, not awaited, after the engine and MCP are up, and it never rejects: a failed binding costs only the feature, and the relaunch is an ordinary launch that takes the single-instance lock.open-intent.tsignores the argument, andmain.tslogs it - Notifications: Shows or refuses an OS notification for what finished while the user was elsewhere, and reports the platform's willingness to the settings row (
notify.ts, issue #1358) - Saved state from a
file:build: localStorage is per origin, so the first packaged launch that finds Chromium's Local Storage from an earlier run hands what thefile:builds persisted tovayu-app://app(legacy-storage-migration.ts, #2380). Before the window exists, main reads every entry from a script-less stub page on thefile://origin in aWebContentsViewthat is never attached to a window (so nothing appears, and no window closing can raisewindow-all-closed), keeps thevayu-,vayu.andvayu:keys, and flags the window's command line; the preload, which runs beforeindex.html's pre-paint script, takes them over asendSyncand writes every key, over one the new origin already holds (0.46.0 shipped without the hand-off, and what it saved since is almost all first-launch defaults, #3021), then reports. Only that report setsdoneinlegacy-storage-migration.jsonunder userData. A fresh install (no Local Storage directory before the profile opens) is marked done without opening anything, and development builds skip it. A failed read is logged and retried on the next launch, three launches in all, and never holds the window back (a 10 s ceiling); the window that starts after a failed read persists its own defaults, and the retry writes over those defaults too. The stub page runs withwebSecurity: false, because with the GrantFileProtocolExtraPrivileges fuse off Electron refuses localStorage to afile:document otherwise; it is the one place the app loads afile:URL, and it goes when the hand-off is retired - Process Footprint: Sizes libuv's threadpool to one worker before any other module loads (
threadpool-size.ts). On Windows each worker commits its 8 MB stack, and nothing here hands the pool more than one file at a time; the MCP port is bound at launch with the SDK behind it loaded by the first request (mcp/listener.ts)
Key Responsibilities:
- Spawns the engine binary as a child process
- Watches the engine child process and publishes its lifecycle to the window (engine:lifecycle); restarts only when asked (engine:restart), never on its own
- Ensures graceful shutdown (stops engine before quitting)
Engine Sidecar (electron/sidecar.ts)¶
The EngineSidecar class manages the C++ engine process:
- Binary Resolution: Locates the engine binary (dev vs production paths)
- Process Management: Spawns, monitors, and terminates the engine process
- Health Checking: Polls
/healthon a ramped interval - 50ms doubling to a 500ms ceiling - so a healthy engine is caught in tens of milliseconds instead of paying a flat poll quantum, while the 45-second budget it spends against a live child is unchanged. It still gives up the moment the spawned child exits rather than spending the rest of that budget against a dead port, and that failure carries the exit code/signal and the engine's last stderr lines. A child still alive when the budget runs out raisesEngineNotReadyErrorinstead, which the launch path treats as "not yet" rather than as fatal - Lifecycle (#3336): One
EngineLifecyclevalue -idle,choosingPort,replacing,spawning,ready,slow,crashed,stopping,stopped- written only bytransition(), which publishes each change toonLifecycle()listeners and is readable throughgetLifecycle().slowis a spawned child past the readiness budget and still probed; when it answers it becomesreadyand theonReadyAfterSlow()hooks run.crashedcarries the exit code, signal, stderr tail orerrormessage of the current child leaving without being asked: a child leaving duringreplacingorstopping, or a previous child's late exit, is not a crash. Once the app is quitting, nothing butstoppedfollowsstopping - Operation queue:
start,stop,restartandshutdownrun one after another, so two never drive the child at once. Arestartrequested while another is queued or running joins it and returns the same promise (hasRestartPending()); one requested during the first start waits for that start instead of killing the child its health poll is watching - Build guidance: A missing binary names
python build.py -eanddocs/building.md- the single build entry point, not per-platform scripts - Port Management: Walks
ENGINE_PORT_CANDIDATES(9876, then 9880-9889). A candidate where an engine serving this app's data directory answers/healthis stopped and replaced, a free one is taken, a held one is skipped (a live lock PID that is silent on/healthis waited for on the same budget, then replaced). A Vayu engine reporting anotherdataDir, or none, counts as held and is never stopped (issue #3328). The first start fixes the choice for the app's lifetime (electron/engine-endpoint.ts), and the window is created after it, with the port on its command line. With every candidate held it raisesEnginePortInUseError, naming what holds the first (another program or another Vayu engine): the app stays up on the disconnected state with the reason, and Retry runsengine:restartagain (issue #2118) - Ownership: The engine this session talks to is always one it spawned,
because only that one holds the session's grant secret (#2356). An engine
serving this app's data directory found running at startup is asked to shut
down (
POST /shutdown), waited for, and killed by its lock-file PID if it lingers; it is held as adopted only while it is being stopped, so a quit landing mid-replacement still stops it. See Ownership model - System seam: The process/port/clock calls sit behind a
SidecarSysteminterface (defaultSidecarSystemin production), sosidecar.test.tscan drive replacement, shutdown and the restart-versus-quit race without real engines or 45-second health waits
Development vs Production:
- Development: Binary at ../engine/build/vayu-engine (or Debug/vayu-engine.exe on Windows)
- Production: Binary at resources/bin/vayu-engine (packaged with Electron app)
Beside bin/, electron-builder.json's extraResources also ships
icon.png and THIRD_PARTY_NOTICES.txt loose in resources/ (outside the
asar, so the OS can open them). electron/third-party-notices.ts resolves the
notices: process.resourcesPath when packaged, and in development
app/build/ only if a build has staged a copy there - otherwise it answers
with a sentence rather than a path. The app:openThirdPartyNotices channel
(no argument) and the Help menu item both go through it.
React Application (src/)¶
The React app follows a component-based architecture:
Application Structure¶
src/
├── components/ # Shared UI components
│ ├── layout/ # Shell, TitleBar, TabStrip, ActivityRail, Drawer, Dock, ContextBar, ContextRail
│ ├── shared/ # Cross-feature shared components
│ └── ui/ # UI primitives (Radix UI)
├── lib/ # Shared libraries
│ ├── graphql/ # GraphQL support: diagnostics, introspection, schema cache, Monaco providers, variables JSON Schema, explorer tree + insertion
│ ├── monaco-setup.ts # Monaco entry composition + local-bundle config + GraphQL provider registration (loaded on the first editor mount)
│ ├── monaco-loader.ts # The lazy boundary in front of it: ensureMonaco() / useLoadedMonaco()
│ ├── monaco-api.ts # The Monaco surface that composition yields, and what it leaves out
│ └── utils.ts # General utilities (cn, etc.)
├── modules/ # Feature modules
│ ├── request-builder/ # API request editor and execution
│ ├── dashboard/ # Load test metrics and visualization
│ ├── history/ # Run history and reports
│ ├── collections/ # Collections and requests tree
│ ├── variables/ # Environment and variable editors
│ ├── settings/ # App settings
│ └── welcome/ # Onboarding screen
├── stores/ # Cross-cutting Zustand stores (UI state)
│ ├── tabs-store.ts # Active tab state (determines main content)
│ ├── layout-store.ts # Drawer/sidebar visibility
│ ├── session-store.ts # Session and user info
│ ├── engine-store.ts # Engine health and connectivity
│ ├── dashboard-store.ts # Live metrics and test state
│ ├── response-store.ts # Response viewer state
│ ├── save-store.ts # Auto-save orchestration
│ ├── import-modal-store.ts # Import dialog state
│ ├── env-switcher-store.ts # Whether the title bar environment menu is open
│ ├── import-report-store.ts # What an applied import left undone
│ └── oauth-signin-store.ts # Which OAuth 2.0 configs have a sign-in running
├── queries/ # TanStack Query hooks (server state)
├── hooks/ # Custom React hooks
├── services/ # API client, SSE client, HTTP client
├── types/ # TypeScript type definitions
└── config/ # Configuration (API endpoints, metrics thresholds)
State Management¶
The app uses a dual-state management approach:
- Zustand Stores (
stores/andlib/): UI state, navigation, temporary data tabs-store.ts: Active tab state; determines which feature module renders in the main content arealayout-store.ts: Drawer and sidebar visibility/statesession-store.ts: Active environment id (mirrored from the engine) and the last-used collectionengine-store.ts: Engine health, connectivity statusdashboard-store.ts: Load test metrics (retained by time window, seestate-management.md), the run phaseresponse-store.ts: The last response per request id - status, headers, body, script results. LRU-bounded at twiceMAX_OPEN_TABSand by a 256 MiB byte budget (RESPONSE_CACHE_MAX_BYTES, #2544), since each entry holds a body plus its raw copyclient-settings-store.ts: Renderer preferences (editor, charts, auto-save, notifications)toast-store.ts: The transient notification queuesave-store.ts: Auto-save orchestration and progressentity-draft-store.ts: The unsaved drafts of the manual-save collection editors (useEntityDraft), by entity key, so a draft outlives the screen that holds it (#3459); dropped with its save, its Reset, its tab or its collection, and never persistedimport-modal-store.ts: Import dialog visibility and stateenv-switcher-store.ts: Whether the title bar's environment menu is open, so a toast action can open itimport-report-store.ts: The loss report of each applied import, by root collection id, until dismissedoauth-signin-store.ts: Which OAuth 2.0 configs have an interactive sign-in running, by token cache key, with its abort handle and the rows showing itlib/graphql/schema-cache.ts: Introspected GraphQL schemas, keyed by resolved endpoint URL + collection + environment + a digest of the resolved credentials (so an upstream auth or variable edit is a different entry, not a stale hit). LRU-bounded, and a failed refresh keeps the last good schemalib/graphql/explorer-store.ts: The schema explorer's view - whether the pane is open, and per schema identity the search text, expanded rows, scroll position and whether descriptions are shown in full. Read-only over the schema cache: the explorer renders whatever that store holds and triggers no introspection of its own beyond its Refresh button-
Module-local stores (e.g.,
modules/collections/collections-store.ts) co-locate with their feature -
TanStack Query (
queries/): Server state, caching, synchronization - Collections, Requests, Environments, Globals
- Runs, Health checks
- Automatic caching, refetching, and optimistic updates
The context bar's section registry¶
The right-hand context bar renders a list rather than a component tree it owns:
components/layout/context-bar/registry.ts holds one ordered array of
{ id, title, appliesTo(tab), useRelevance?(tab), Component }, and both the bar
(what to draw) and the Dock's toggle (whether the button has anything to light up
for) read appliesTo through the same sectionsForTab / contextBarHasContent
pair. Keeping those two answers in one place is the point: they were a hardcoded
tab type in one file and a return null in another, and they drifted.
appliesTo stays a pure, synchronous function of the tab alone: the Dock's
toggle calls it on every render, including while the bar is closed, so it can
never read a query.
useRelevance is a second, orthogonal function a section can opt into, asked
only by the bar and only while it is open: whether the section has anything to
say about this request, once its own data is in, rather than just this tab
type. See docs/app/COMPONENTS.md for the three verdicts it can return and why
the question was split off appliesTo rather than widening it (#1310).
A section is a leaf component over the ordinary query layer - no bar-wide shared
state - and is mounted only while its section is expanded, so a collapsed
section registers no queries; its useRelevance hook is the one thing that still
runs collapsed, and only for a query its section already makes. That is what
makes it safe for the bar to stay open on every tab the registry has entries
for - request, collection and run. See docs/app/COMPONENTS.md for the
sections themselves.
Services Layer¶
api.ts: HTTP client wrapper for all engine API endpoints- Transforms between frontend (snake_case) and backend (camelCase) formats
-
Handles error transformation and user-friendly messages
-
codegen/: Snippet generation (curl, JS fetch, Python requests, HTTPie, PowerShell) - the outbound half of the symmetryservices/curl/opens by parsing curl in. Pure functions over aSnippetRequest, fedPOST /compose's output, so a generated snippet is what Vayu would actually send rather than the template it was written as -
sse-client.ts: Server-Sent Events client for a run's live stream - Connects to
/runs/:runId/live(replayable tick topic - no attach race) - No custom reconnect loop: the engine sends an explicit
completeevent, and transient errors are left to the browser'sEventSourceretry. That frame normally carries the run'sstatus(issue #2140). ACLOSEDstream without it is not taken as the run's end: it reaches the subscriber asonClose(null, { frame: false }), and the load-test service reads the stored report'smetadata.statusto learn whether the run ended at all (issue #1925). A bare frame, which the engine's 60 s settle timeout sends, isonClose(null, { frame: true }): the service waits for the report to settle (500 ms polls, 30 s bound) before it concludes the stream was lost - Two event types, one client and one stream. A load run publishes
metricsticks; a scenario (collection) run publishesstepevents, on the same ring with the same monotonic ids, and both end withcomplete. Thesteplistener is registered only when a caller passesonStep- a load run never emits one, so an unconditional listener would be dead wiring.parseStepEventnarrows the payload and drops a malformed one rather than defaulting it: the step list keys on(iteration, stepIndex), so a defaulted0:0would collide with the real first step's row rather than merely say nothing. - One client, so a new run takes it from the old one - and the old one is told.
connectdisplaces whoever held the socket and invokes that subscriber'sonSupersededbefore opening the new stream (issue #1417). It is not a variant ofonClose: a close means the run ended and the subscriber converges on the stored report, where a takeover means only that nobody is watching a run the engine is still executing. A subscriber that hangs up on itself (disconnect), or whose stream ended on the engine'scompleteframe, is not superseded by the next run to start. Nor is a service superseded by itself: each one ends the run it is replacing and disconnects before connecting the next -LoadTestServicethroughstopMonitoring,ScenarioRunServiceinline at the top ofstartMonitoring- so the hand-off only ever reaches a different subscriber. Skip that and the service is handed its own newly started run, and gives up the wake lock, the indicator claim and the run id it took two lines earlier - A load run that is superseded or dropped is still running, and the dashboard says so (issue #1925). Both paths leave the dashboard in its running layout with the Stop button, under the "Lost the live metrics stream" callout, whose Reconnect calls
loadTestService.startMonitoringfor the same run and resumes the ticks, unless a collection run is streaming, whose stream it would take (canReattachLoadRun, #3351). It never shows Completed:setFinalReportrefuses a report whosemetadata.statusisrunningorpending, whichever caller fetched it -
Metrics go to
dashboard-store(vialoadTestService); steps go toscenario-run-store(viascenarioRunService) -
change-feed-service.ts: The engine's change feed (GET /changes, issue #3420), one stream for the app's life - Every committed write of a collection, request, example, environment, the globals or a trash entry, whoever made it, becomes an invalidation of the query keys that read it (
lib/change-feed-invalidation.ts, through the MCP families oflib/mcp-invalidation.ts), coalesced over 200ms and held while a mutation is in flight - Asks
POST /changes/subscriptionsfor a single-use id before every connection and opensGET /changes?subscription=<id>(a page cannot hold the engine's stream slots, so the app's stream is never the one refused) -
Reconnects on its own backoff and resumes by
?lastEventId=, the inbox stream's shape; aresetrefetches everything the feed covers. Opened byuseChangeFeedonly while the engine is connected. Seestate-management.md -
http-client.ts: Low-level fetch wrapper - Request/response transformation
- Error handling and timeout management
- Base URL configuration
Custom Hooks¶
useEngine(): Compose (POST /compose), execute, and stopuseVariableResolver(): Resolve{{variables}}in strings/objects for previews (the engine resolves what is sent)useSaveManager(): Auto-save orchestration with debouncinguseEntityDraft(): The manual counterpart - draft,isDirty, reset, for editors that save on a button; the draft is kept inentity-draft-storeby entity, so it outlives the editor (#3459)useChangeFeed(): Mounted once inApp.tsx; holds the change feed open while the engine is connected
Data Flow¶
Request Execution Flow¶
- User clicks "Send" in RequestBuilder
useEngine().composeRequest()sends the editor state toPOST /compose; the engine resolves{{variables}}andinheritauth and returns an execute-ready payload- Request is transformed to backend format (camelCase)
apiService.executeRequest()sends the composed payload toPOST /execute- Response is transformed back to frontend format (snake_case)
- Response is displayed in ResponseViewer
Load Test Flow¶
- User configures load test and clicks "Start Load Test"
- The composed request plus the load config go to
POST /runsviaapiService.startLoadTest() - Engine returns
runId useDashboardStore().startRun()initializes dashboard stateloadTestService.startMonitoring(runId)connects to the/runs/:runId/liveSSE endpoint- Metrics stream in real-time and update dashboard
- When test completes, final report is fetched via
GET /runs/:id/report, and the dashboard swaps the live view for History'sLoadTestDetailover that report, so the run reads the same there as when it is reopened from History later (issue #2220)
Collection Run Flow¶
- User picks Run collection in a collection row's ⋯ menu and confirms
RunCollectionDialog(Recursive, Iterations) useStartScenarioRunMutation()sends ascenarioblock to the samePOST /runs; the engine resolves the whole plan first, so an empty collection or a step that will not compose comes back as a400with no run created- Engine returns
runId(202), and the dialog attachesscenarioRunService.startMonitoring(runId)and opens the run's tab stepevents stream intoscenario-run-storeandScenarioRunViewrenders them live- On
completethe service invalidates the run and fetchesGET /runs/:id/report; the view switches to the stored per-step rows, which are the ones carrying an exchange to expand
Variable Resolution Flow¶
Variables are resolved with priority: Bound data row (while one is picked) > Environment > Collection > Global
The engine owns resolution for anything that is sent (POST /compose). The
renderer's useVariableResolver() is a preview of the same rules - tab titles,
the variable popover, unresolved-token painting, and, where a caller passes a
picked row (boundRow), the bind itself - pinned to the engine's by a
cross-language conformance fixture. See variable-resolution.md.
useVariableResolver()fetches globals, collections, and environments- Builds a flat map with resolution priority
resolveString()replaces{{variableName}}with resolved values- Used for previews in RequestBuilder, never as the payload
Build System¶
Development¶
- Vite: Dev server on port 5173 with HMR
- TypeScript: Type checking and compilation
- Electron: Runs renderer process, connects to Vite dev server
Production¶
- Vite Build: Bundles React app to
dist/ - Electron Builder: Packages app with engine binary
- Platform Targets: macOS (DMG), Windows (NSIS), Linux (AppImage/Deb)
Key Technologies¶
- React 19: UI framework
- TypeScript: Type safety - 7 compiles and checks, 5.9 stays installed for the
typescript-eslintparser (see building) - Electron 44: Desktop app framework
- Zustand: Lightweight state management
- TanStack Query: Server state and caching
- Radix UI: Accessible component primitives
- Tailwind CSS: Utility-first styling
- Monaco Editor: Code editing - scripts, JSON body, and GraphQL (with syntax diagnostics, autocomplete, hover, and formatting via
graphql-language-service);{{variable}}tokens are coloured and explained on hover in the body and GraphQL editors too - uPlot: Charts for metrics visualization (all dashboard/history charts centralize on one Canvas primitive; see
modules/dashboard/components/charts/uplot/) - Vite: Build tool and dev server
Electron Preload Bridge¶
The preload script (electron/preload.ts) exposes a minimal, context-isolated API bridge via window.electronAPI:
- Engine Management:
restartEngine()for engine lifecycle control;getEngineLifecycle()overengine:lifecycleandonEngineLifecycle(callback)(returns the unsubscribe), the sidecar'sEngineLifecyclePayload(electron/engine-lifecycle.ts, mirrored inpreload.tsandsrc/types/electron.d.ts): theinvokeanswers the current state for a window that loaded or reloaded after the last push, and the push carries every change after it. Forcrashedit adds the exitcode,signal,stderrTailanderror;useEngineLifecycle(mounted once inApp) writes that intoengine-store'sengineCrash, which the Dock explains and offers Restart for (#3336), and invalidates the health query so the poll looks again at once (#3493); onlyready,slow,stoppingorstoppedclear the crash, so a restart that fails before it spawns keeps its Restart button;enginePort, the port the sidecar settled on (9876 or a fallback), a constant read from the renderer's command line thatconfig/network.tsresolves once intoENGINE_BASE_URL(issue #2118);getEngineStartFailure()overengine:startFailure, the main process's own sentence when a start failed in a way the user can fix (every engine port held), ornull, which the health poll reads on a failed poll. The lifecycle carries facts only, so engine liveness is still not on this bridge - the renderer pollsGET /healthdirectly (src/queries/health.ts) and that poll alone classifiesengineStatus, so there is one answer rather than two. A recorded crash outranks a staleconnectedonly on read (selectKnownEngineStatus, which the Dock anduseEngineServingshare), never by writingengineStatus - Theme Management:
getTheme(),setTheme(),onThemeChanged()for OS theme synchronization - Window Controls:
windowMinimize(),windowMaximize(),windowClose(),windowIsMaximized(),onWindowMaximized()for custom titlebar - Auto-update:
useAppUpdatelistens toonUpdateAvailable()(strategy, install command) and, for the silent platforms' download, toonUpdateState()plus agetUpdateState()read on mount (issue #3338); it derives the progress bar, Restart & install, the attestation failure (issue #2372; arefusedstate, whichuseAppUpdatealso writes toupdate-verification-storeso Settings > Updates can show it) and a failed download (the banner says so and offers Retry, a freshcheckForUpdates()) from that one state. A state read on mount never fires the "ready" notification, only a live arrival inverifieddoes; after a reload the version comes from the state, sinceupdate:availableis not replayed, and a dismissal is not kept across a reload. The download's progress, its completion and a refused installer have no channels of their own; they are fields of that state. AlsorestartToInstallUpdate(),openReleasePage(). On the silent platforms the download is one state inelectron/updater.ts,none | downloading | verifying | verified | refused | failed(issue #3338):onUpdateState()receives it onupdate:stateat every change, including a download that fails after its announcement, andgetUpdateState()asks for it overupdate:getState, so a reloaded renderer still seesverified. Restart-to-install and the quit-time install (autoInstallOnAppQuit) follow that state and act only inverified. The fiveupdate:*invoke channels (restartToInstall, openReleasePage, check, quitForUpdate, getState) are registered insetupIpcHandlersahead of the engine wait and forward into the lazily loaded updater;getStatealone does not wait for the updater to arm, and answersnonewhile it is not loaded - Menu Integration:
onOpenSettings()to receive open-settings commands from the app menu;windowAppMenu(point)asks the main process to pop the installed application menu at the title-bar icon, which is the only route to it on Windows and Linux - a frameless window draws no menu bar there, so the templatecreateMenuinstalls was accelerators and nothing else (issue #1361). The decision (which platform, which point) iselectron/app-menu.ts; macOS is refused, its menu bar being the same template already drawn - Navigation History:
onNavigateHistory()delivers amenu:navigatestep, sent by the View menu's Back/Forward items, the mouse's back/forward buttons where the OS reports them asapp-command, and the macOS three-finger swipe (issue #1245) - Context Menu:
setContextTarget()announces what the pointer landed on over thecontext-menu:targetchannel, sent synchronously (the onlysendSynca page can reach; the preload's other is the one-time legacy-storage hand-off at load) so it pairs with the native menu event that follows;onContextMenuCommand()delivers thecontext-menu:commandevents for the two offers only the renderer can run - importing a pasted curl/wget command and opening a variable's popover (issue #1359) - Platform & Paths:
platformconstant andgetAppPaths()for OS and directory detection - Request-body files:
getFilePath(file)turns a picked or droppedFileinto its absolute path inside the preload, and reports a non-empty one to main on the internalfile:pickedchannel, which main records as a picked file with the engine (electron/file-grants.ts, #2356) - noelectronAPImethod sends on it, andpreload-grant-channel.test.tsholds that;statFile(path)answers{size, mtimeMs}for the binary body editor's file line and never reads the contents, and only for a file the user picked, dropped or opened or one under an allowed folder (electron/file-grants.ts,electron/file-roots.ts, #2357) - any other path, including one typed into the field that was never picked and sits outside every allowed folder, answersnulland the line shows Not found on this machine;allowFolder(key)opens the system folder picker - the renderer names only the dialog, by key, and main owns its title and where it opens (#2378) - and has main allow the chosen folder, andremoveAllowedFolder(id)stops allowing one - both writes need the engine's grant secret, which only main holds. The channels arefile:stat,file:allowFolderandfile:removeAllowedFolder(electron/file-ipc.ts); the two folder channels andfile:pickedanswer only the app window's main frame (electron/ipc-sender.ts). The engine reads the file at send time and owns the allowed-folder list - Saving a file:
saveFile(contents, suggestedName)overfile:save(electron/save-file-ipc.ts, #3246) opens the system save dialog and writes text (as UTF-8) or bytes to the path the user confirms, resolving{outcome: "saved", fileName},{outcome: "cancelled"}or{outcome: "failed", fileName, message}for a write that failed after a path was chosen.fileNameis the last segment of the path the user confirmed, which the dialog lets them change from the suggestion (#3607); it is never the full path, and a toast names it rather than the suggested name (the<a download>fallback cannot learn it and answers the suggestion). The renderer suggests a name and nothing else: main keeps its last path segment on either separator, replaces what Windows refuses in a name, and opens the dialog in the user's Downloads folder. It answers only the app window's main frame, refuses contents that are neither a string nor aUint8Arrayor exceed 1 GiB (the ceiling ofmaxDesignResponseBodyBytes), and records no file grant for what it wrote. The renderer side islib/download-text-file.ts, which every export and Download goes through and which falls back to an<a download>click outside Electron - Graceful Shutdown:
onBeforeQuit()to allow the renderer to flush state (saves, pending requests) before app termination. The callback resolves to what the flush did ({ saved, failed, pending, reason? }); the preload sends it back onbefore-quit-flushedbeside the flush id main sent onbefore-quit, which is how main drops an answer to an earlier flush (issue #3335) - Running Services:
setRunningServices(services), one-way over theservices:runningchannel, publishes what the engine is currently holding for this window - inboxes by port, mock servers by the collection they serve, mock issuers by port. The main process cannot read the queries this is derived from, and a question asked at close time would land on the gesture the user is already waiting on, so the snapshot is pushed on every change instead.electron/service-stop-guard.tsowns the dialog's wording and the platform rule, andelectron/quit-flow.tsdecides when it is asked and how long a yes counts (one gesture's way out; Cancel and Keep working forget it); the renderer side ismodules/services/useRunningServices.ts, whose list the Dock's indicator is now counted from so the two cannot disagree (issue #1363) - Wake Lock:
holdWakeLock(reason)/releaseWakeLock(token)keep the machine from suspending under a streaming run (issue #1357). Ref-counted inelectron/power-save.ts; the renderer side isservices/wake-lock.ts, one keyed holder both run services call. A run hands its key back on every path that stops it being watched, the takeover by the other service's run included -sseClienttells the displaced service, which releases there (issue #1417) - so no key outlives the session that took it.onHostSuspended()/onHostResumed()report a sleep the lock could not prevent, whichuseHostSleepRecorderrecords against the run - Start at login:
getLoginItem()/setLoginItem(on)read and write the OS login item (issue #2098); both resolve to{ supported, reason, openAtLogin, needsApproval }.setLoginItemrejects a non-boolean. Seeelectron/login-item.ts - Notifications:
showNotification(),notificationAvailability(),sendTestNotification(),onNotificationActivated()over thenotify:*channels, for the OS notifications a run finishing, an engine dropping out or an update landing raise while the user is elsewhere. The renderer side isservices/notify.ts, which reads the opt-in and decides what is worth saying; a click is opened by theuseNotificationActivationhook.sendTestNotification()is the Settings preview: the one path that ignores both the focus check and the opt-in, and the only way to learn whether this build can post at all without waiting for a run to end (issue #1358). A capture landing on a webhook inbox raises one too, behind a second per-inbox toggle and a coalescing window, since it is the one kind whose rate the app does not set (issue #1388).notify:showis a closed door: main keeps its own list of the ten kinds inNOTIFY_KINDS(held equal to the renderer's byelectron/notify.test.ts) and rejects any other, caps the title at 80 and the body at 240 characters (cut with an ellipsis, not refused), and drops control characters (newlines and tabs become spaces) (issue #2378) - Run Progress:
setRunProgress(update), one-way over theruns:progresschannel, mirrors a live run's progress onto the Windows taskbar button and the macOS Dock icon; Linux paints nothing, Electron 44 having dropped Unity launcher support andBrowserWindow.setProgressBarnow covering Windows and macOS only.electron/run-progress.tsowns the platform rules; the renderer side isservices/run-progress.ts, which decides which run the one indicator is for - the SSE client is a singleton, so a secondstartMonitoringsupersedes the first run's stream, and that run's own calls are then ignored rather than painting on a bar it no longer owns (issue #1362). The displaced service is told it lost the stream and gives its claim up there (issue #1417). That release names the run it speaks for, which in a takeover makes it a no-op: the incoming run claims the indicator before it connects, so the bar is transferred rather than cleared and the displaced run finds a claim it no longer holds. It is there so the rule holds at the service level instead of resting on the order the other service happens to use, and the claim guard still stands behind it, for the batched flush that lands after the hand-off and for a run of the same kind as the one that took over. The claim is one run, not one kind of run: a run takes the indicator by id when the renderer starts watching it, and every report, failure and stop names the run it speaks for, so neither a second run of the same kind nor a superseded run's last buffered flush can repaint the bar of the run being watched (issue #1405)
Security Considerations¶
- Context Isolation: Enabled in Electron (renderer cannot access Node.js APIs)
- No Node Integration: Renderer runs in isolated context
- Preload Script: Minimal IPC bridge through
contextBridge.exposeInMainWorld() - Window Navigation: The main window refuses any navigation that is not the app's own document and denies
window.open(electron/window-navigation.ts). The preload re-runs on whatever the window navigates to, so this is what keepswindow.electronAPIoff a third-party origin. The app's own document isvayu-app://app/in production, a privileged schemeelectron/app-protocol.tsanswers with files underdist/and nothing else (#2380), compared by scheme and host because Node gives a custom scheme the same opaque origin as everyfile:URL; in development it is the dev server's origin, where a Vite full reload is a real navigation. Outbound links go to the user's browser through theopenExternalUrlIPC instead, which accepts http(s) only, only while the window is focused, and one open per second (#2378). The built document carries a Content-Security-Policy<meta>, whose'self'names that one origin and whoseform-action 'none'refuses a form submission before it becomes a navigation (see Security). - Engine Origin Bridge: The engine emits no CORS header and refuses any request carrying an
Origin, soelectron/engine-origin.tsis the renderer's CORS. Installed on the default session before the main window is created, it removesOriginandRefererfrom requests tohttp://127.0.0.1:<port>/*for the port the engine took (the filter names every candidate port because Chromium registers it once; only the chosen one is bridged) and addsAccess-Control-Allow-Origin: *to the responses, plus the method and headers a preflight asked for. The filter is the whole boundary: a renderer call to the engine under any other spelling (localhost:<port>,[::1]:<port>) keeps itsOriginand is refused, so every call is built fromENGINE_BASE_URL. Both renderers depend on it: the Vite origin in development andvayu-app://apppackaged, each a real origin that sends anOriginand a preflight. Electron keeps one listener perwebRequestevent per session, so another concern joins this module instead of registering its own, andengine-origin.test.tsfails on a registration anywhere else - File trust is written by main alone (#2356): adding an allowed folder, removing one and recording a picked file need the engine's per-start grant secret, which the main process holds (
electron/file-trust-client.ts) and the renderer never sees. The renderer can ask main to open the folder picker and can remove a folder by id; it cannot name a folder or a file to trust. A picked file's path comes from the preload'swebUtilscall, and each of those channels answers only the app window's main frame - Local Communication: Engine runs on localhost only (127.0.0.1, port 9876 or the fallback the app chose)
Performance Optimizations¶
- Code Splitting: every chunk boundary here is a dynamic import -
vite.config.tsdeclares no manual chunk groups, because thereact-vendorandchartsgroups it used to declare were measured against rolldown's own chunking and moved nothing, and a group added for monaco actively pulled the 3.7MB editor chunk back onto the startup path as amodulepreload(#1147).Shellmounts every tab surface exceptRequestBuilderthroughReact.lazybehind one Suspense boundary; Monaco (lib/monaco-loader.ts), the markdown pipeline (ui/markdown-renderer.tsx), the GraphQL body pane and the context bar's GraphQL section each sit behind their own boundary - the last two are what keepgraphqlandgraphql-language-serviceoff the startup path, since both are reached from surfaces that are otherwise eager. The entry chunk is what the window needs in order to appear - everything else arrives with the tab, editor or description that wants it (#1146) - Monaco loads with the first editor, not at startup: nothing imports
lib/monaco-setup.tsstatically.ensureMonaco()brings it in when aCodeEditormounts, which is also what keepsloader.config({ monaco })ahead of@monaco-editor/react'sloader.init()- aninit()that runs first fetches Monaco from the jsDelivr CDN instead of using the bundled copy. The app-level completion providers subscribe throughuseLoadedMonaco(), which never triggers the load. That file also composes the Monaco entry rather than importing the package root: the editor core (features/register.all, which is what carries the find, folding, suggest and hover widgets -editoralone is the API surface with no contributions), the JSON and TypeScript language services the app drives, and one Monarch grammar per language id it can open. Those are monaco 0.56's entry points; 0.56 put the package behind anexportsmap, so theesm/vs/...paths the composition used to spell - andedcore.main, which no longer exists - stopped resolving (#1342). The CSS and HTML language services are the two it leaves out, since they pulled 1.7MB ofcss.workerandhtml.workerinto every installer that nothing could reach; their grammars stay, so an HTML or CSS response body is still highlighted, it just no longer carries language-service validation or completions (#1147) - Query Caching: TanStack Query caches server responses
- Optimistic Updates: UI updates immediately, syncs with server
- Debounced Saves: Auto-save waits for user to stop typing
- Metrics Retention: Dashboard store trims live ticks to the configured window (
liveWindowSeconds, 5m default) with amaxRetainedTicksbackstop - a memory bound, not a rendering one - Metrics Bucketing: Charts collapse ticks into
chartBucketSecondsbuckets (0.5s default) before uPlot sees them, so a full window reaches the canvas as a few thousand points - Throttled SSE commits: Every tick is buffered; store commits are throttled to
METRICS_UI_THROTTLE_MS