Skip to content

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. Its webPreferences hold 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.ts empties every session's spellchecker language list from a session-created listener registered before app.whenReady. Bounds, maximised and full-screen state are remembered across launches in window-state.json under 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 to idle, so the next gesture flushes and asks again (issue #3335)
  • Context Menu: Composes the right-click menu from Chromium's context-menu params 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.setLoginItemSettings on Windows and macOS; on Linux, where Electron's call does nothing, an XDG autostart entry at $XDG_CONFIG_HOME/autostart/vayu.desktop naming 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 (RegisterApplicationRestart through koffi, with --restarted-after-reboot and 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.ts ignores the argument, and main.ts logs 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 the file: builds persisted to vayu-app://app (legacy-storage-migration.ts, #2380). Before the window exists, main reads every entry from a script-less stub page on the file:// origin in a WebContentsView that is never attached to a window (so nothing appears, and no window closing can raise window-all-closed), keeps the vayu-, vayu. and vayu: keys, and flags the window's command line; the preload, which runs before index.html's pre-paint script, takes them over a sendSync and 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 sets done in legacy-storage-migration.json under 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 with webSecurity: false, because with the GrantFileProtocolExtraPrivileges fuse off Electron refuses localStorage to a file: document otherwise; it is the one place the app loads a file: 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 /health on 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 raises EngineNotReadyError instead, which the launch path treats as "not yet" rather than as fatal
  • Lifecycle (#3336): One EngineLifecycle value - idle, choosingPort, replacing, spawning, ready, slow, crashed, stopping, stopped - written only by transition(), which publishes each change to onLifecycle() listeners and is readable through getLifecycle(). slow is a spawned child past the readiness budget and still probed; when it answers it becomes ready and the onReadyAfterSlow() hooks run. crashed carries the exit code, signal, stderr tail or error message of the current child leaving without being asked: a child leaving during replacing or stopping, or a previous child's late exit, is not a crash. Once the app is quitting, nothing but stopped follows stopping
  • Operation queue: start, stop, restart and shutdown run one after another, so two never drive the child at once. A restart requested 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 -e and docs/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 /health is stopped and replaced, a free one is taken, a held one is skipped (a live lock PID that is silent on /health is waited for on the same budget, then replaced). A Vayu engine reporting another dataDir, 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 raises EnginePortInUseError, naming what holds the first (another program or another Vayu engine): the app stays up on the disconnected state with the reason, and Retry runs engine:restart again (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 SidecarSystem interface (defaultSidecarSystem in production), so sidecar.test.ts can 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:

  1. Zustand Stores (stores/ and lib/): UI state, navigation, temporary data
  2. tabs-store.ts: Active tab state; determines which feature module renders in the main content area
  3. layout-store.ts: Drawer and sidebar visibility/state
  4. session-store.ts: Active environment id (mirrored from the engine) and the last-used collection
  5. engine-store.ts: Engine health, connectivity status
  6. dashboard-store.ts: Load test metrics (retained by time window, see state-management.md), the run phase
  7. response-store.ts: The last response per request id - status, headers, body, script results. LRU-bounded at twice MAX_OPEN_TABS and by a 256 MiB byte budget (RESPONSE_CACHE_MAX_BYTES, #2544), since each entry holds a body plus its raw copy
  8. client-settings-store.ts: Renderer preferences (editor, charts, auto-save, notifications)
  9. toast-store.ts: The transient notification queue
  10. save-store.ts: Auto-save orchestration and progress
  11. entity-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 persisted
  12. import-modal-store.ts: Import dialog visibility and state
  13. env-switcher-store.ts: Whether the title bar's environment menu is open, so a toast action can open it
  14. import-report-store.ts: The loss report of each applied import, by root collection id, until dismissed
  15. oauth-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 it
  16. lib/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 schema
  17. lib/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
  18. Module-local stores (e.g., modules/collections/collections-store.ts) co-locate with their feature

  19. TanStack Query (queries/): Server state, caching, synchronization

  20. Collections, Requests, Environments, Globals
  21. Runs, Health checks
  22. 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 symmetry services/curl/ opens by parsing curl in. Pure functions over a SnippetRequest, fed POST /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 complete event, and transient errors are left to the browser's EventSource retry. That frame normally carries the run's status (issue #2140). A CLOSED stream without it is not taken as the run's end: it reaches the subscriber as onClose(null, { frame: false }), and the load-test service reads the stored report's metadata.status to learn whether the run ended at all (issue #1925). A bare frame, which the engine's 60 s settle timeout sends, is onClose(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 metrics ticks; a scenario (collection) run publishes step events, on the same ring with the same monotonic ids, and both end with complete. The step listener is registered only when a caller passes onStep - a load run never emits one, so an unconditional listener would be dead wiring. parseStepEvent narrows the payload and drops a malformed one rather than defaulting it: the step list keys on (iteration, stepIndex), so a defaulted 0:0 would 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. connect displaces whoever held the socket and invokes that subscriber's onSuperseded before opening the new stream (issue #1417). It is not a variant of onClose: 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's complete frame, 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 - LoadTestService through stopMonitoring, ScenarioRunService inline at the top of startMonitoring - 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.startMonitoring for the same run and resumes the ticks, unless a collection run is streaming, whose stream it would take (canReattachLoadRun, #3351). It never shows Completed: setFinalReport refuses a report whose metadata.status is running or pending, whichever caller fetched it
  • Metrics go to dashboard-store (via loadTestService); steps go to scenario-run-store (via scenarioRunService)

  • 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 of lib/mcp-invalidation.ts), coalesced over 200ms and held while a mutation is in flight
  • Asks POST /changes/subscriptions for a single-use id before every connection and opens GET /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; a reset refetches everything the feed covers. Opened by useChangeFeed only while the engine is connected. See state-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 stop
  • useVariableResolver(): Resolve {{variables}} in strings/objects for previews (the engine resolves what is sent)
  • useSaveManager(): Auto-save orchestration with debouncing
  • useEntityDraft(): The manual counterpart - draft, isDirty, reset, for editors that save on a button; the draft is kept in entity-draft-store by entity, so it outlives the editor (#3459)
  • useChangeFeed(): Mounted once in App.tsx; holds the change feed open while the engine is connected

Data Flow

Request Execution Flow

  1. User clicks "Send" in RequestBuilder
  2. useEngine().composeRequest() sends the editor state to POST /compose; the engine resolves {{variables}} and inherit auth and returns an execute-ready payload
  3. Request is transformed to backend format (camelCase)
  4. apiService.executeRequest() sends the composed payload to POST /execute
  5. Response is transformed back to frontend format (snake_case)
  6. Response is displayed in ResponseViewer

Load Test Flow

  1. User configures load test and clicks "Start Load Test"
  2. The composed request plus the load config go to POST /runs via apiService.startLoadTest()
  3. Engine returns runId
  4. useDashboardStore().startRun() initializes dashboard state
  5. loadTestService.startMonitoring(runId) connects to the /runs/:runId/live SSE endpoint
  6. Metrics stream in real-time and update dashboard
  7. When test completes, final report is fetched via GET /runs/:id/report, and the dashboard swaps the live view for History's LoadTestDetail over that report, so the run reads the same there as when it is reopened from History later (issue #2220)

Collection Run Flow

  1. User picks Run collection in a collection row's ⋯ menu and confirms RunCollectionDialog (Recursive, Iterations)
  2. useStartScenarioRunMutation() sends a scenario block to the same POST /runs; the engine resolves the whole plan first, so an empty collection or a step that will not compose comes back as a 400 with no run created
  3. Engine returns runId (202), and the dialog attaches scenarioRunService.startMonitoring(runId) and opens the run's tab
  4. step events stream into scenario-run-store and ScenarioRunView renders them live
  5. On complete the service invalidates the run and fetches GET /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.

  1. useVariableResolver() fetches globals, collections, and environments
  2. Builds a flat map with resolution priority
  3. resolveString() replaces {{variableName}} with resolved values
  4. 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-eslint parser (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() over engine:lifecycle and onEngineLifecycle(callback) (returns the unsubscribe), the sidecar's EngineLifecyclePayload (electron/engine-lifecycle.ts, mirrored in preload.ts and src/types/electron.d.ts): the invoke answers the current state for a window that loaded or reloaded after the last push, and the push carries every change after it. For crashed it adds the exit code, signal, stderrTail and error; useEngineLifecycle (mounted once in App) writes that into engine-store's engineCrash, which the Dock explains and offers Restart for (#3336), and invalidates the health query so the poll looks again at once (#3493); only ready, slow, stopping or stopped clear 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 that config/network.ts resolves once into ENGINE_BASE_URL (issue #2118); getEngineStartFailure() over engine:startFailure, the main process's own sentence when a start failed in a way the user can fix (every engine port held), or null, 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 polls GET /health directly (src/queries/health.ts) and that poll alone classifies engineStatus, so there is one answer rather than two. A recorded crash outranks a stale connected only on read (selectKnownEngineStatus, which the Dock and useEngineServing share), never by writing engineStatus
  • Theme Management: getTheme(), setTheme(), onThemeChanged() for OS theme synchronization
  • Window Controls: windowMinimize(), windowMaximize(), windowClose(), windowIsMaximized(), onWindowMaximized() for custom titlebar
  • Auto-update: useAppUpdate listens to onUpdateAvailable() (strategy, install command) and, for the silent platforms' download, to onUpdateState() plus a getUpdateState() read on mount (issue #3338); it derives the progress bar, Restart & install, the attestation failure (issue #2372; a refused state, which useAppUpdate also writes to update-verification-store so Settings > Updates can show it) and a failed download (the banner says so and offers Retry, a fresh checkForUpdates()) from that one state. A state read on mount never fires the "ready" notification, only a live arrival in verified does; after a reload the version comes from the state, since update:available is 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. Also restartToInstallUpdate(), openReleasePage(). On the silent platforms the download is one state in electron/updater.ts, none | downloading | verifying | verified | refused | failed (issue #3338): onUpdateState() receives it on update:state at every change, including a download that fails after its announcement, and getUpdateState() asks for it over update:getState, so a reloaded renderer still sees verified. Restart-to-install and the quit-time install (autoInstallOnAppQuit) follow that state and act only in verified. The five update:* invoke channels (restartToInstall, openReleasePage, check, quitForUpdate, getState) are registered in setupIpcHandlers ahead of the engine wait and forward into the lazily loaded updater; getState alone does not wait for the updater to arm, and answers none while 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 template createMenu installs was accelerators and nothing else (issue #1361). The decision (which platform, which point) is electron/app-menu.ts; macOS is refused, its menu bar being the same template already drawn
  • Navigation History: onNavigateHistory() delivers a menu:navigate step, sent by the View menu's Back/Forward items, the mouse's back/forward buttons where the OS reports them as app-command, and the macOS three-finger swipe (issue #1245)
  • Context Menu: setContextTarget() announces what the pointer landed on over the context-menu:target channel, sent synchronously (the only sendSync a 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 the context-menu:command events 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: platform constant and getAppPaths() for OS and directory detection
  • Request-body files: getFilePath(file) turns a picked or dropped File into its absolute path inside the preload, and reports a non-empty one to main on the internal file:picked channel, which main records as a picked file with the engine (electron/file-grants.ts, #2356) - no electronAPI method sends on it, and preload-grant-channel.test.ts holds 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, answers null and 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, and removeAllowedFolder(id) stops allowing one - both writes need the engine's grant secret, which only main holds. The channels are file:stat, file:allowFolder and file:removeAllowedFolder (electron/file-ipc.ts); the two folder channels and file:picked answer 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) over file: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. fileName is 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 a Uint8Array or exceed 1 GiB (the ceiling of maxDesignResponseBodyBytes), and records no file grant for what it wrote. The renderer side is lib/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 on before-quit-flushed beside the flush id main sent on before-quit, which is how main drops an answer to an earlier flush (issue #3335)
  • Running Services: setRunningServices(services), one-way over the services:running channel, 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.ts owns the dialog's wording and the platform rule, and electron/quit-flow.ts decides when it is asked and how long a yes counts (one gesture's way out; Cancel and Keep working forget it); the renderer side is modules/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 in electron/power-save.ts; the renderer side is services/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 - sseClient tells 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, which useHostSleepRecorder records 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 }. setLoginItem rejects a non-boolean. See electron/login-item.ts
  • Notifications: showNotification(), notificationAvailability(), sendTestNotification(), onNotificationActivated() over the notify:* 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 is services/notify.ts, which reads the opt-in and decides what is worth saying; a click is opened by the useNotificationActivation hook. 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:show is a closed door: main keeps its own list of the ten kinds in NOTIFY_KINDS (held equal to the renderer's by electron/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 the runs:progress channel, 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 and BrowserWindow.setProgressBar now covering Windows and macOS only. electron/run-progress.ts owns the platform rules; the renderer side is services/run-progress.ts, which decides which run the one indicator is for - the SSE client is a singleton, so a second startMonitoring supersedes 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 keeps window.electronAPI off a third-party origin. The app's own document is vayu-app://app/ in production, a privileged scheme electron/app-protocol.ts answers with files under dist/ and nothing else (#2380), compared by scheme and host because Node gives a custom scheme the same opaque origin as every file: 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 the openExternalUrl IPC 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 whose form-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, so electron/engine-origin.ts is the renderer's CORS. Installed on the default session before the main window is created, it removes Origin and Referer from requests to http://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 adds Access-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 its Origin and is refused, so every call is built from ENGINE_BASE_URL. Both renderers depend on it: the Vite origin in development and vayu-app://app packaged, each a real origin that sends an Origin and a preflight. Electron keeps one listener per webRequest event per session, so another concern joins this module instead of registering its own, and engine-origin.test.ts fails 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's webUtils call, 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.ts declares no manual chunk groups, because the react-vendor and charts groups 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 a modulepreload (#1147). Shell mounts every tab surface except RequestBuilder through React.lazy behind 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 keep graphql and graphql-language-service off 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.ts statically. ensureMonaco() brings it in when a CodeEditor mounts, which is also what keeps loader.config({ monaco }) ahead of @monaco-editor/react's loader.init() - an init() that runs first fetches Monaco from the jsDelivr CDN instead of using the bundled copy. The app-level completion providers subscribe through useLoadedMonaco(), 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 - editor alone 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 an exports map, so the esm/vs/... paths the composition used to spell - and edcore.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 of css.worker and html.worker into 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 a maxRetainedTicks backstop - a memory bound, not a rendering one
  • Metrics Bucketing: Charts collapse ticks into chartBucketSeconds buckets (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