State Management¶
The Vayu app uses a dual-state management approach: Zustand for UI state and TanStack Query for server state. Cross-cutting stores (tabs, layout, session, engine, save, response, dashboard, client settings, toasts, import modal, environment menu) live in app/src/stores/ and are exported via the barrel app/src/stores/index.ts. Module-local UI stores co-locate in app/src/modules/<feature>/<feature>-store.ts (collections, history, variables, settings) to keep feature-specific UI state decoupled from global app state.
Architecture Overview¶
┌─────────────────────────────────────────────────┐
│ State Management Layers │
├─────────────────────────────────────────────────┤
│ UI State (Zustand) │
│ - Cross-cutting: tabs, layout, session │
│ - Domain: engine, save, response, dashboard │
│ - Module-local: collections, history, vars │
└─────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────┐
│ Server State (TanStack Query) │
│ - Collections, Requests, Environments │
│ - Runs, Metrics, Global Variables │
│ - Automatic caching & synchronization │
└─────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────┐
│ Services Layer │
│ - HTTP Client (api.ts) │
│ - SSE Client (sse-client.ts) │
└─────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────┐
│ Vayu Engine (C++ Daemon) │
│ - SQLite Database │
│ - HTTP API (localhost:9876) │
└─────────────────────────────────────────────────┘
Zustand Stores¶
Cross-Cutting Stores (app/src/stores/)¶
tabs-store.ts - Open Tabs & Navigation¶
Manages all open tabs (welcome, request, collection, dashboard, run, variables, settings) and active tab focus. Enforces a maximum of 12 open tabs with LRU eviction for non-exempt types.
State:
{
openTabs: Tab[] // Each tab has unique id, type, and optional entityId
activeTabId: string | null
tabFocusedAt: Record<string, number> // Tab id -> when it was last focused (epoch ms)
navIntent: NavIntent | null // What the navigation in flight asked of the screen it opened (session-only)
navHistory: TabLocation[] // Visited locations this session, oldest first
navIndex: number // Cursor into navHistory; -1 before anything is visited
}
Key Features:
- Deduplication: Singleton types (welcome, variables, settings, inbox) only allow one tab at a
time. Opening one that is already open with a different entityId retargets it - same tab
id, new address - rather than focusing whatever it was showing. The inbox tab is the case that
needs it: every Services drawer row opens that one tab pointed at its own inbox (issue #554).
The other three are always opened with a null entityId, for which this is a no-op
- LRU eviction: when over the limit, the least recently focused non-active, non-exempt,
clean tab is closed - "oldest" is by tabFocusedAt, not strip order, with an unstamped
tab ranking first and ties kept in strip order. The tab being opened is never a
candidate, so a strip whose other tabs are all dirty runs past the cap. Every path that
makes a tab active stamps it, a close that activates a survivor included
- Integration with save-store: dirty tabs are never selected for eviction. The
guard resolves each tab's save-context key by tab type (isTabDirty),
because the registry is keyed by editor and the two do not line up: settings
and variables are singletons with no entityId, so a request-${entityId}
lookup read them as clean and the 13th tab could close a dirty Settings tab.
A variables tab counts any dirty variable-editor context as its own, since
a Tab does not record which editor the sidebar has selected - over-matching
keeps a tab that could have closed, under-matching loses work. Nothing is
flushed during eviction; the predicate already refused the tab
- Bulk close (issue #1360): closeOtherTabs, closeTabsToRight and
closeSavedTabs - the tab strip's right-click menu - go through the same
closeTabs core as closeTab and closeTabsForEntities, so "which tab
takes the place of the one that was showing" stays one rule. A bulk close is
one set and at most one recorded navigation visit, never a loop of single
closes: closing tabs one at a time would focus and record a visit for every
intermediate tab on the way to the last, leaving Back to walk the user
through places they never went. closeOtherTabs and closeTabsToRight carry
closeTab's #1489 guard (issue #3324): while engineStatus is not
connected, a dirty tab (isTabDirty) is left out of the set to close, the
clean ones still close, and one "Not saved - Vayu's engine is unreachable;
kept N unsaved tabs open" toast says how many stayed (none when nothing was
kept). closeSavedTabs never selects a dirty tab, so it needs no guard
- Reorder (issue #2038): moveTab(tabId, toIndex) puts a tab at the index it
occupies afterwards, clamped to the list, and returns without a set when
the tab is unknown or already there. It writes openTabs and nothing else:
the active tab, tabFocusedAt and the navigation history name tabs by id and
location, never by position, so a move is not a navigation and records no
visit. The Tab objects are reused, not copied, because TabItem's memo
compares prev.tab === next.tab. The order persists with no extra work:
partialize writes openTabs and migrateTabs reads it back in order.
- Response eviction: closeTabsForEntities clears each id's entry in
response-store. Both callers reach it after a delete - the map's own LRU
bound would get there eventually, but a response nothing can reach again
should go at the delete, not twenty-four sends later. MAX_OPEN_TABS is
exported for that bound: the cache retains twice it
- Focus recency: tabFocusedAt stamps openTab and focusTab, and is read by
the command palette, which lists open tabs most-recently-used first. It cannot
come from openTabs, which is insertion order - the tab you were just in sits
wherever it was opened. Session-scoped on purpose (absent from partialize):
tabs are restored across launches, so a persisted copy would rank a restored
list by yesterday's attention, and an empty map falls back to strip order.
Entries for closed tabs are dropped on the next focus rather than in every
close path - nothing reads a stamp for a tab that is not open
- Pointing into a screen: navIntent is the one hand-off from a navigation
to the screen it opened, because openTab can only name a tab. It is a
NavIntent - { kind: "spec" | "dataRow" | "compare" | "focusUrl", target, ... }, with
target the id of the collection, request or run it is for - and at most one
is pending. openCollectionSpecTab(collectionId) issues spec: the import
dialog's Sync for an already-bound document (issue #680), which
CollectionDetail answers by opening on Spec. openRequestWithDataRow issues
dataRow, carrying the rowIndex a failed step of a collection run bound
(issue #730): "reproduce this step" means its request and the row, and the
UrlBar selects the row and opens the picker on it. A non-integer or negative
index throws rather than being stored. openRunComparison(runId) issues
compare, the History row's "Compare with…" (issue #2164), which
LoadTestDetail answers by opening the run's report on its compare view.
openRequestFocusingUrl(requestId) issues focusUrl for a request just
created blank (issue #3400): ⌘N, the palette command, the Launcher tile and
the sidebar's "+" all leave the caret in the new request's URL field, which
UrlInput answers once it mounts - the builder mounts after the tab opens, so
a focus call made with it would find no field. A request created from a preset
(the demo, an import, a saved agent run) issues none
- A screen takes its intent with takeNavIntent(kind, target), which returns it
and clears it only when both match - another kind or another target gets
null and leaves it pending - so it fires once, on the screen it was for. The
UrlBar takes its own whether or not the request can bind rows. The intent
belongs to the navigation that issued it (issue #3355), not to the entity it
names: the tab and the intent are set in one set, so the screen sees both on
the same render, and any later openTab, focusTab, focusAdjacentTab,
goBack or goForward replaces or clears it, as does closing the tab it
names (a single close, a bulk close or closeTabsForEntities). An intent
whose screen never rendered therefore cannot fire on a later visit.
Session-scoped like tabFocusedAt (absent from partialize): a persisted
copy would jump the user to Spec, a data row or a comparison for a choice made
in a previous launch, and a data row points into a file whose rows are
deliberately never persisted
- Navigation history (issue #1245): navHistory is a TabLocation per visit
(a Tab without its instance id, so a closed tab's place survives it), with
navIndex as the cursor - -1 before anything is visited. openTab and
focusTab record each visit themselves, coalescing a repeat of the current
location and truncating the forward half on a new one; capped at 50 entries
(MAX_NAV_HISTORY), oldest dropped first. goBack() / goForward() move the
cursor and show what it lands on - focusing the open tab if there is one,
reopening it through openTab otherwise - without recording a step of their
own. Closing the active tab now activates the most recent history entry
whose tab is still open, falling back to the old left-neighbour rule, and
leaves the closed location ahead of the cursor so Forward can reopen it;
closeTabsForEntities prunes history entries for deleted entities, so Back
never lands on one. Session-scoped like tabFocusedAt and navIntent
(absent from partialize), and NOT persisted: tabs are restored across
launches, and a persisted history would offer a Back that walks yesterday's
route through today's window
- Persistence: vayu.tabs (v1), with a pass-through migrate. zustand discards
a payload whose stamped version differs from the store's when no migrate
is supplied, so the stub is where the next bump goes; it also refuses a
payload of the wrong shape rather than handing a non-array to every reader
Key Methods:
const { openTab, closeTab, focusTab, closeTabsForEntities } = useTabsStore();
openTab({ type: "request", entityId: "req-123" });
closeTabsForEntities(["req-123"]); // after a delete: closes tabs, drops responses
const { closeOtherTabs, closeTabsToRight, closeSavedTabs } = useTabsStore();
closeOtherTabs("tab-1"); // keeps tab-1, one set-and-visit for the rest
closeTabsToRight("tab-1");
closeSavedTabs(); // keeps every dirty tab
openCollectionSpecTab("col-123"); // opens the collection, on its Spec tab
openRequestWithDataRow("req-123", 500); // opens the request, on row 501 of its data file
const { goBack, goForward } = useTabsStore();
goBack(); // step back through navHistory; reopens the tab if it was closed
goForward(); // never records a visit - only openTab/focusTab do that
// canGoBack / canGoForward are exported selectors, not store methods - read
// by the title-bar buttons and the palette's go-back / go-forward commands
canGoBack(useTabsStore.getState());
canGoForward(useTabsStore.getState());
layout-store.ts - Drawer, Context Bar, & Response Position¶
Manages the left drawer (collections/history/variables/settings), the right context bar, and where the response pane sits - beside the request or below it - with one split ratio per arrangement.
State:
{
drawerOpen: boolean // Is the left drawer visible?
drawerView: DrawerView // "collections" | "history" | "variables" | "services" | "settings"
drawerWidth: number // One width for every view
contextBarOpen: boolean // Is the right context bar visible?
contextBarWidth: number
contextBarCollapsedSections: string[] // Section ids the user collapsed (`code` by default)
responsePosition: ResponsePosition // "beside" | "below" | "auto" (default beside, #1711)
autoResponseArrangement: "beside" | "below" // What auto resolves to right now - written by the builder's measurement, not persisted
requestSplitRatioBeside: number // 0-1; the request pane's share while the response is beside it
requestSplitRatioBelow: number // 0-1; the request pane's share while the response is below it
scriptSnippetsCollapsed: boolean // Default a fresh script row's snippets list starts from (collapsed); each row keeps its own state after that
scriptEditorHeights: Record<string, number> // Height (px) of a script.pre/script.post element's editor box, keyed by the element's own id - capped at 200 entries, oldest set evicted first
scriptEditorHeightDefault: number // Height a script row with no entry above starts at - the last height set on any row
recentElementKinds: string[] // Last 5 kinds added through the Add-element picker, most recent first
paletteOpen: boolean // Is the ⌘K command palette showing?
}
Key Methods:
const {
drawerOpen, setDrawerOpen, toggleDrawer,
drawerView, setDrawerView, activateDrawerView, revealDrawerView,
drawerWidth, setDrawerWidth,
contextBarOpen, setContextBarOpen, toggleContextBar,
contextBarWidth, setContextBarWidth,
contextBarCollapsedSections, toggleContextBarSection,
responsePosition, setResponsePosition, toggleResponsePosition,
setRequestSplitRatio
} = useLayoutStore();
activateDrawerView("variables"); // Open drawer to variables, or toggle closed if already there
revealDrawerView("variables"); // Open drawer to variables, never closes it - for anything that points at a view
setDrawerWidth(300); // Clamped to [PANEL_MIN_WIDTH, PANEL_MAX_WIDTH] (constants/layout.ts)
toggleResponsePosition(); // beside <-> below; from auto, the opposite of what auto currently shows
setRequestSplitRatio("below", 0.6); // Into the ratio for the arrangement that was dragged, clamped 0.2..0.8
resolveResponseArrangement(useLayoutStore.getState()); // The arrangement on screen: the setting, or auto's pick
One drawer width, not one per view. v2 stored a width per view, so switching
from Collections to History resized the main content under the user; the v3
migration collapses them onto a single drawerWidth, keeping whatever
Collections (the default view) had. Re-introducing a per-view width re-introduces
that bug. setRequestSplitRatio clamps to [0.2, 0.8]; both panel widths clamp to
PANEL_MIN_WIDTH / PANEL_MAX_WIDTH.
setDrawerWidth / setContextBarWidth are not called per pointermove.
PanelResizeHandle (app/src/components/layout/PanelResizeHandle.tsx) holds a
drag's live width outside the store, painting it onto the panel's own inline
style.width once per animation frame, and calls the setter - the one write
partialize persists - exactly once, on pointerup. A store write on every
pointermove was a synchronous JSON.stringify + localStorage.setItem of the
whole persisted slice 120-240 times a second (#1715).
paletteOpen is here, and is not persisted. The palette lives in Shell
while the things that open it - the welcome Launcher's Search tile, the title
bar's search bar - are in other subtrees, so the flag has to be shared state
rather than the dialog's own. It is deliberately absent from partialize: a
dialog that reopened itself on every launch is not a layout preference.
Context-bar sections are collapsed by exception. The store holds the ids the
user closed (contextBarCollapsedSections); anything not listed is expanded. Two
consequences worth keeping: a section added in a later release ships expanded
for existing users, because a blob written before it existed cannot name it; and
it is an array rather than a Set because persist serializes with JSON, which
writes a Set as {} - a collapse would survive exactly until the next launch.
code is the one section allowed to break the ships-expanded rule
(CONTEXT_BAR_DEFAULT_COLLAPSED, constants/layout.ts, currently ["code"]):
an expanded Code section issues a POST /compose on mount, so with the bar open
the app composed a snippet on every request tab opened, whether or not anyone
looked at it. That default needs both the initial state and the v3 -> v4
migration to actually reach an existing user, and neither alone is enough:
persist merges a missing key onto the initial state, never a missing
element into an array that is already there, so seeding
contextBarCollapsedSections: ["code"] in the initial state only reaches a
fresh install - a user who has ever collapsed anything already has the key, with
an array persist treats as complete. The migration writes code into that
array directly, and at the same time prunes any id in
RETIRED_CONTEXT_BAR_SECTIONS (environment, retired the same release), so a
persisted collapse list never keeps naming a section that no longer exists. It
is a default, not a policy: once migrated, a user's own toggle on code
overrides it exactly like any other section.
Persistence: vayu.layout (v6, with a real migration for every bump -
the one store in the app doing persistence versioning end to end; v6 carries
the old single requestSplitRatio forward as the Beside ratio, seeds Below
even and keeps the position at Beside, so an upgrade re-arranges nothing)
session-store.ts - Active Environment¶
Tracks the active environment (for variable resolution) and the collection the user last worked in (a new-request target only), persisted across sessions.
State:
Key Methods:
const { activeEnvironmentId, setActiveEnvironmentId } = useSessionStore();
setLastCollectionId(collectionId);
Persistence: vayu.session (v2)
A persisted id must not outlive what it names. activeEnvironmentId rides
on every composed payload, so a dangling one is not cosmetic - the switcher
renders "No Environment" through a defensive find() while the wire still
carries a deleted id. It is cleared at both ends:
useDeleteEnvironmentMutation clears it when the active environment is the one
deleted (in the mutation, so both delete flows are covered), and
useActiveEnvironmentGuard() - mounted once in App.tsx - clears an id the
engine's environment list does not contain. That guard keys on the query's
isSuccess, never on the list being empty: an unreachable engine produces an
empty list too, and clearing on that would discard a good selection whenever
the app started before the engine did.
A delete is soft since #2970 - the environment goes to the Trash - and the id
stays cleared through a restore. The engine clears is_active in the same
write that stamps the row and a restore clears only the stamp, so a restored
environment comes back inactive; neither useRestoreTrashMutation nor the
delete's Undo toast writes activeEnvironmentId. Making it active again is
the user's choice, through the switcher or Set active.
activeCollectionId was removed in v2. It had a reader (the resolver's
fallback scope) and no writer, so it was permanently null on a fresh install
and, on an older one, rehydrated a collection the user had long left and
silently scoped {{var}} previews to it. The persist migrate drops the
stored key. lastCollectionId is the field that looks similar and is not: it
has a real writer and feeds only the welcome screen's new-request target - it
must never feed the resolver.
The migration rebuilds the payload from the fields v2 knows rather than deleting
that one key, which is also the shape check: a hand-edited or half-written entry
degrades to defaults instead of handing a non-string id to the switcher. That
whitelist is where the next bump goes - zustand discards a payload whose
stamped version does not match when no migrate is supplied, which is the
same reason tabs-store carries one.
activeEnvironmentId is a cache of engine state, not the source of truth.
The engine owns which environment is active (environments.is_active, at most
one row, enforced in its DB layer). The store holds the same id so the
switcher, the resolver and every composed payload can read it synchronously,
and two pieces of wiring keep the two in step:
useSetActiveEnvironmentMutation(queries/environments.ts) is the only writer. It PUTsisActiveand updates the store optimistically, rolling the store back if the engine refuses - a selection the engine did not accept must not survive in the UI, or the next launch silently disagrees with this one. It invalidates the environments list rather than patching the response into it, because the deactivated row changed server-side without appearing in any response body. Switches made before an earlier one settles are numbered and their PUTs run one at a time (a mutationscope), so the engine ends holding the last switch that landed. The hook also keeps the environment the engine is known to hold (settledActiveId: the store's value when no switch is in flight, then each PUT that succeeded). A refusal rolls the store back to that, and only while it is still the latest switch: a newer one has already replaced the optimistic value, and the store's value at the time the refused switch started may be an earlier switch the engine also refused. A clear deactivates the same environment, not the one the store was showing when the clear was issued (#3355).useActiveEnvironmentRestore(hooks/, mounted inApp.tsx) reconciles on launch: adopt the engine's active environment if it has one, otherwise push a persisted id that names an environment that still exists - once per session, so a write the engine keeps rejecting is a failed write and not a request loop. Both directions wait onisSuccess; an unreachable engine returns an empty list that is indistinguishable from "no environments exist", and adopting from that would clear a good selection on every cold start. A third direction was added with the MCP state tools (#758): once this session has seen the engine hold a selection, an engine that reports none is adopted as a clear rather than pushed back at. Otherwise anactivate_environmentwith"none"- or any other client's deactivate - would be undone on the very next refetch by this window's memory of the id it used to hold. The upgrade push stays for the case it was written for: an engine that has never held a selection at all.
It composes with useActiveEnvironmentGuard above rather than replacing it, and
is mounted after it: the guard answers "does this id still exist", this hook
answers "which id does the engine hold". Order matters only in the one case
where both would act - a dangling id should be dropped, not pushed back at the
engine as a selection.
Editing an environment's variables deliberately sends no isActive
(absent means "keep" on a PUT): echoing a cached value back would let a
variable edit re-activate an environment from a stale read, deactivating
whichever one the engine actually holds.
data-file-store.ts - Where Each Collection's Data File Lives¶
Each collection's data-file binding, by collection id, so the Run dialog can
pre-fill the file instead of asking for it every run (issue #599). Since #2765
the binding is a column of the collection's engine row (Collection.dataFile,
{path, fileName, hash?, castNumbers?}), so a workspace backup carries it, a
trashed collection keeps it and a restore brings it back. This store is a
mirror of the collections list, not a record: useFileBindingMirror
(mounted in App.tsx) subscribes to the query cache
(installFileBindingMirror, queries/file-bindings.ts) and rebuilds the map
from queryKeys.collections.list() inside every write to it, before any
observer re-renders, so a component that reads the contract off the list and
the file off the store never sees one without the other. An unchanged binding
keeps its object and an unchanged map keeps its identity, so a refetch
republishes nothing. A reader that holds the Collection (the Data tab) reads
collection.dataFile directly; the store is for readers that hold only an id
(the run dialogs' pre-fill, Send-with-row, useDataFileStatus).
State:
{
locations: Record<string, {
path: string; fileName: string; hash?: string; castNumbers?: boolean
}> // keyed by collection id, rebuilt from the collections list
}
Writes go through the collection update, never through the store:
// useDataContractWriter: the binding rides the same PUT as the columns
mutate({ id, dataSchema: { columns, declaredAt, fileName }, dataFile: { path, fileName, hash, castNumbers } });
mutate({ id, dataSchema: null, dataFile: null }); // Clear / Remove
// useDataFileReadingMutation: the binding is built when the write is sent
mutateReading({ id, path, castNumbers }); // rememberReading
recordDataFileHash(path, hash); // queries/file-bindings.ts: every binding at that path whose hash moved
A collection's binding writes go out one at a time (queries/file-bindings.ts).
The engine replaces a binding object whole, so a hash write built from the
binding before a pick or a toggle landed would put the old one back. Every
update that carries specFile or dataFile waits for the same collection's
earlier binding writes (writeFileBinding, which the update hook routes them
through, and which stores the answered row itself); the two that change one
member of the binding - a re-read's hash and a toggle's castNumbers - are
built from the store only once those have landed (reviseDataFileBinding), and
send nothing if the binding no longer names their file by then.
Persistence: none here; the engine row.
Two things the binding deliberately is not. It is not the contract - the
declared columns (dataSchema) travel through import and export; a path is
true of one filesystem only, so POST /import/apply refuses one and neither
export writes one. Its one reader outside the renderer is the app's own MCP
server: useDataFileLocationMirror (mounted in App.tsx, after
useFileBindingMirror) publishes the whole map to the main process over
dataFile:locations on launch and on every change, and list_collections
names a collection's file from that copy (issue #1742; a fields: "full" row,
the summary names none). useAppFocusMirror (also mounted in App.tsx) does
the same for the active tab and environment over app:focus, publishing only
when the snapshot changes, so get_app_focus can answer "the request I have
open" (issue #2045). And it never holds rows: a data file's contents are
user data of unknown sensitivity and are persisted nowhere in Vayu, which
useDataContractWriter.test.tsx and DataTab.test.tsx assert against the
update payload - what the row stores - rather than against a surface.
The binding is written when the user declares a contract by picking a file, on
the Data tab or in either run dialog (hooks/useDataContractWriter.ts), in
the same update as the columns, with the path obtained through the preload's
existing getFilePath bridge; and dropped, in the same update, when the
contract is cleared (Clear or Remove) or a later pick carries no path. A
delete or a purge writes nothing: the row goes to the trash with its binding
and the store's entry leaves with the row's place in the list, and a restore's
refetch brings both back. A write of specFile / dataFile alone does not
invalidate cached compositions (useUpdateCollectionMutation): nothing
composes against a file location. Reading the file back needs the gated
dataFile:read IPC (electron/data-file.ts), because the renderer otherwise
cannot name a path. The gate includes the main process's grant registry
(#2357): a path is read only if the user picked, dropped or opened it through
the app, which getFilePath records with the engine (file_grants, so it
survives a restart). A stored path is not a grant. A data file declared
before that registry existed holds no grant and must be picked once more; a
path restored from a backup on another machine names a file that is usually not
there. Either way dataFile:read rejects with a "pick the file again" message
(naming the path when the file is not there), dataFile:hash answers
{ status: "missing" }, and the Data tab shows the bound path struck through
beside the reason. The renderer does not seed grants from stored paths - that
is the input being gated.
hash is the SHA-256 of the file's bytes the last time the app read it (issue
2051), the same digest a run records as dataFileHash. A pick writes it with¶
the path; every re-read through readDeclaredDataFile calls
recordDataFileHash, which writes the new digest to every binding at that path
whose hash moved - nothing when it did not, so re-reading an unchanged file
writes nothing - and logs a failed write rather than failing the read. It is
optional because a binding written before hashes were recorded has none until
its next read. Nothing that only compares writes it: useDataFileStatus and
MCP's list_collections ask the main process for the file's current digest
(dataFile:hash, which answers { status: "found", hash } or
{ status: "missing" } for a file that has moved or holds no grant) and fall
back to this one only when they cannot.
castNumbers is how the file's CSV/TSV values are read (issue #2540), the
picker's Read numbers as numbers: absent or false reads every cell as
text, true reads an unquoted integer or decimal as a number. It describes
this file, so a pick writes it as the picker read the file (off for a fresh
pick) and Remove takes it with the path. Toggling the checkbox writes it
through useDataContractWriter's rememberReading, a binding-only update
that is sent only while the binding still names the toggled file's path and
reads it the other way when the write goes out; a hash refresh keeps it. Every re-read
(readDeclaredDataFile, which requires the flag) parses with it, so the Run
dialog's pre-fill, the load dialog's, Send-with-row and the Data tab all read
the file the way the user last chose. A run sends it beside the rows as
dataFileCastNumbers and its snapshot records it, so a re-run that reads the
binding reads the file the way the recorded run did.
A row's binding is normalized in CollectionTransformer
(toDataFileLocation): anything but a {path, fileName} pair of non-empty
strings is no binding, so a value that got in another way never reaches the
read IPC as a path; a malformed hash drops only the hash, and a
non-boolean castNumbers reads as off. An engine that predates the column, or
answers {}, reads as unbound.
Bindings from an older Vayu. Before #2765 both stores were zustand
persist stores, under the localStorage keys that are now
LEGACY_FILE_BINDING_KEYS (vayu.spec-files, vayu.data-files).
useLegacyFileBindingImport (mounted in App.tsx) reads them once, after the
first collections list arrives (importLegacyFileBindings,
queries/legacy-file-bindings.ts): each entry goes through the row's
normalizer and is written, binding-only, to the collection it named - but only
to one the engine still lists and that holds no binding of that kind, so a
binding already on the row is never overwritten. An entry for a collection
the list does not name - one deleted, or sitting in the trash, before the
upgrade - is dropped, so restoring such a collection later brings it back
unbound. A key is removed once every write it asked for has landed; a launch
that cannot reach the engine keeps it and the next one finishes the move. A
key that is not a payload the old store could have written is logged and
dropped.
spec-file-store.ts - Where Each Collection's Spec File Lives¶
Each collection's picked spec file, by collection id, for the specs that were
picked as files rather than fetched from a URL (issue #638). The binding is
Collection.specFile ({path, fileName}) on the engine row (#2765), and this
store mirrors it the way data-file-store above mirrors dataFile, from the
same cache subscription.
State:
Writes: useBindSpecMutation writes specFile after the bind lands and
before the collections refetch ({ specFile: null } for a URL or a paste, which
forgets an earlier file); Unbind clears it in the same update as
openapi: null; a file-picked OpenAPI import writes it to each root that bound
a spec, after the apply (queries/import.ts: the collection has no id until
then, and POST /import/apply refuses a file binding), logging a failed write
rather than failing an import that committed.
Persistence: none here; the engine row.
The same two-halves law as data-file-store above, one contract over: the
document is engine state (spec_documents.content, hashed there, bound by
collection.openapi.specId) and travels through import; a path is true of
one filesystem only, so a backup keeps it and no export or import carries it.
A URL-sourced spec has no binding at all - its origin is
spec_documents.source_url, which is portable and is what a re-fetch will use.
And it never holds spec content, which spec-bind.test.tsx and
SpecTab.test.tsx assert against the update payload.
The Spec tab reads collection.specFile and shows the bound file's path as
the document's source. Reading the file again (the Sync section's Check) and
the files a picked document references needs the gated specFile:read IPC
(electron/spec-file.ts), which takes the document's path plus the reference
and resolves one against the other in the main process. The document path must
be one the user picked, dropped or opened (the grant registry, #2357) - a
stored path is refused with a "pick the file again" message, so a binding made
before grants existed needs one more pick - and the reference may not leave
that document's directory. The same grant gate holds dataFile:read. A check
that fails to read the bound file strikes the path through (SpecSync's
onFileRead), learned from the attempted read rather than from an existence
check of its own. A delete, a restore and a purge write nothing, as for the
data-file binding.
bound-row-store.ts - The Row The Open Builder Is Bound To¶
One slot: the data row a Send-with-row has picked, and the id of the request it was picked for (issue #1074).
State:
Key Methods:
const setBoundRow = useBoundRowStore((s) => s.setBoundRow);
setBoundRow({ requestId, row }); // or null for "bound to none"
Persistence: none, deliberately - see below.
Why a store at all. RequestBuilderProvider already gives the picked row to
its own resolver, which covers every preview inside the builder (issue #1062).
The tab strip is the one that is not below it: useTabDescriptors labels every
open tab from a single list-wide resolver, so it cannot take the row off the
builder's context and, left alone, labelled a tab from the environment while the
bar one row beneath it showed the file's value.
One slot, not a map, and it names its request. The builder binds a row for
the request it is showing, so that is the only request an on-screen preview can
be bound for; a row per remembered index would be a row out of a file that is no
longer the one loaded. Carrying the request id is what lets a reader check
rather than assume, so a slot left standing cannot relabel the next tab -
boundRowFor(bound, requestId) is that check, named once rather than repeated
at each call site.
Never persisted, and cleared with the builder. Rows are user data of unknown
sensitivity and are persisted nowhere in Vayu, the same law data-file-store
states above; the builder also clears the slot when it unmounts, so a row cannot
outlive the send that justified it.
recovery-notice-store.ts - Which Data-Loss Notice Was Already Seen¶
One timestamp: the at of the startup-recovery record the user has already been
told about (issue #922).
State:
Key Methods:
Persistence: vayu.recovery-notice (v1)
The record is the engine's - a marker file beside the database, reported on
GET /health for as long as it stands, because a record that cleared itself as
soon as something read it would be lost whenever the engine restarted before the
app polled. Showing a notice about it exactly once is this side's job, and one
timestamp is the whole of it: a later recovery carries a later at and is a
different event, so it surfaces again with no per-event bookkeeping. Persisted
rather than session state because "does not repeat on the next launch" is the
point - a window reopened against an already-running engine would otherwise
re-announce a wipe the user had dismissed. A stored value that is not a finite
number reads as "nothing acknowledged", the safe direction: a notice shown twice
is an annoyance, one suppressed by a garbage value is silent data loss again. It
is normalized through both migrate and merge: migrate runs only on a
version mismatch, while merge runs on every rehydrate, so only the pair reaches
the same-version payload that is the common case.
engine-store.ts - Engine Connection & Restart State¶
Merged store managing engine connection status and restart-required notifications (for config changes that need an engine restart).
State:
{
engineStatus: EngineStatus // "starting" | "connected" | "unreachable"
engineError: string | null
engineStartFailure: string | null // The main process's sentence when no engine can start (every port held), or null
engineCrash: EngineCrash | null // How the engine's process left on its own ({ code, signal, stderrTail, error }), or null
engineRestarting: boolean // A restart is in flight, shared by every surface that offers one
recovery: EngineRecovery | null // What the engine's startup did to the database
workers: number | null // The `workers` setting's effective value, or null before the first poll
engineStartWindow: number | null // When the engine now coming up began, or null
pendingRestart: boolean
restartRequiredKeys: string[] // Config keys requiring restart
}
Key Methods:
const {
engineStatus, setEngineStatus,
engineError, setEngineError,
engineStartFailure, setEngineStartFailure,
engineCrash, setEngineCrash,
engineRestarting, setEngineRestarting,
recovery, setEngineRecovery,
workers, setWorkers,
engineStartWindow, openEngineStartWindow, closeEngineStartWindow,
pendingRestart, addRestartRequiredKey, clearRestartRequired,
} = useEngineStore();
recovery is the optional recovery node from GET /health (issue #922),
written by the same poll that writes engineError and read by RecoveryBanner.
null is a clean start; a value means the engine restored the database from its
backup or deleted it as unrecoverable.
engineStartFailure is the main process's own account of why no engine is
coming, when the user can fix it: another program holding every port the engine
may use (issue #2118). useHealthQuery asks for it (getEngineStartFailure) on
a failed poll and writes it here; the poll an engine answers clears it, and so
does useEngineRestart when Retry is pressed. A reply that lands after a
restart opened its start window is dropped, because it describes the start
Retry just cleared. While it is set the status is unreachable whatever the
startup grace says, and the Dock shows it in place of engineError and offers
Retry.
engineCrash is the main process's account of how the engine's process left
when nobody asked it to (issue #3336): the exit code, signal, stderrTail
and error of the sidecar's crashed lifecycle state, as engine:lifecycle
carries them. useEngineLifecycle (mounted once in App, after
useHealthQuery) writes it: a crashed push sets it, and only ready, slow,
stopping and stopped clear it (an engine that is up, alive but slow, or
stopped on purpose). The transient kinds idle, choosingPort, replacing and
spawning leave it standing, so a restart that fails before it spawns a child
(the sidecar ends on idle) still leaves the Dock its sentence and its Restart
button, and while the restart runs the button reads Restarting... through
engineRestarting. The one-time read of the current state
yields to a push that landed while it was in flight and to a restart that
opened a new start window, so a late reply cannot put a crash back over the
engine replacing it. It is a fact, not a status: useHealthQuery stays the
only classifier of engineStatus, and engineCrash never writes it. A
crashed push invalidates queryKeys.health.status(), and nothing else, so the
poll's verdict follows within a retry rather than a whole healthy interval
(issue #3493). For the gap until it does, selectKnownEngineStatus (exported
beside the store) derives the status the app shows: unreachable when a crash
was pushed after the poll's last verdict and that verdict is connected,
engineStatus itself otherwise. engineCrashAheadOfPoll carries the "after":
setEngineCrash sets it with a crash, and every setEngineStatus clears it,
including the one useHealthQuery makes for each answered poll, an unchanged
answer too (structural sharing would otherwise keep the sync effect from
running). The crash alone cannot decide, because it stays until ready, which
can trail the poll that already sees a restarted engine answer. The Dock's light and useEngineServing (the gate behind the
running-services count, the Services drawer's rows, and the inbox and mock-server
tabs' Running/Stopped state and Stop action, issue #3506) read it, as do the
dirty-tab close guards in tabs-store and the change feed's open/close
(useChangeFeed), so none of them says "connected" beside the Restart a crash
put there. The health poll's own gating (queries/health.ts) and the store's
internals read engineStatus directly: they are the poll's own verdict. The Dock reads engineCrash
for the connection tooltip (describeEngineCrash, engineCrashOutput in lib/engine-crash.ts:
the sentence, then the last three non-empty stderr lines) and ignores it while
engineStatus is starting; engineStartFailure takes precedence over it in
both the tooltip and the button (Retry, not Restart).
engineRestarting is whether a restart is in flight, held here rather than in
each useEngineRestart instance so that the Dock's button and the Settings
banner share it: a second click, or the other surface's button, finds it set and
asks the main process for nothing. The hook reads it from the store, not from
its render's value, because two clicks in one frame both see a stale false
there.
workers is the workers field from the same poll (issue #1508) - the
workers setting's effective value, not the machine's raw core count - read by
the Dock's version-string tooltip. null before the first poll answers; it is
not cleared on a later disconnect, so a hover during a brief drop still shows
the last known count.
engineStatus is starting while no poll has succeeded since the engine now
coming up began coming up and it is still inside its grace window, connected
once a poll has answered ok, and unreachable once a poll fails past that
window or an engine that had answered stops answering with nothing starting.
engineError is what the failed health poll recorded (queries/health.ts), and
it is null in every state but unreachable: an engine still inside its grace
window has no failure to report. The Dock's connection indicator renders it in a
tooltip, for unreachable alone - "Disconnected" on its own read the same for a
refused connection, a timeout and a TLS failure.
engineStartWindow is the evidence that decision is made against: the moment
the engine now coming up began coming up, or null when none is. It is a
window rather than a "has ever connected" flag because a cold start is not only
the app's first (#1227) - useEngineRestart kills the running engine and spawns
a fresh one that repeats the whole startup housekeeping, with the port down for
all of it, and a flag called that silence a failure on the evidence of an engine
that no longer existed. Two paths open it - useHealthQuery on mount and the
restart path before it invokes the IPC - and it is deliberately evidence rather
than a status, so useHealthQuery stays the only writer of engineStatus. It
is closed by the poll an engine answers, and by a restart the main process
reports as failed, after which the next failed poll owes the user its reason
again. A window nobody closes is spent rather than cleared - an engine that
never arrives leaves its opening time in place, expired - so this is not an "is
something starting" flag and must not be read as one: only
engineStatusAfterFailedPoll (lib/engine-start-window.ts) interprets it, and
to that an expired timestamp and a null mean the same thing. Two things ask
it: useHealthQuery, for engineStatus, and the shared query retry policy,
which keeps queries loading rather than failed while it answers starting.
Non-persisted (cleared on app restart).
save-store.ts - Centralized Auto-Save¶
Orchestrates saving across the app. Every surface that saves reports where its own edit stands, the Dock's status is derived from all of those reports, and a registry of saveable contexts (request tabs, environment editors, Settings) backs Ctrl/Cmd+S and the quit and reconnect flushes.
State:
{
unsaved: ReadonlyMap<string, UnsavedEdit> // every id with an edit not on disk
status: "idle" | "pending" | "saving" | "saved" | "error" // derived from `unsaved`
lastErrorMessage: string | null // derived: the newest failure's message
activeContextId: string | null
contexts: Map<string, SaveContext> // Saveable entities
}
type UnsavedEdit =
| { kind: "pending" }
| { kind: "saving" }
| { kind: "failed"; message: string; diskFull: boolean }
Each surface reports under its own id, and nothing writes status (#3350).
The store used to hold one status that every surface wrote through public
setters (setStatus, markPendingSave, startSaving, failSave, reset), so
one surface's write erased another's: switching request tabs ran a reset()
that wiped the variables editor's "Not saved", Settings' clean branch published
idle over another context's error, and the autosave retry read another
surface's failure as its own. Those setters are gone. A surface reports:
| Report | Meaning |
|---|---|
reportPending(id) |
The edit id holds is not on disk. Does not demote a failure: the edit that failed is still unsaved. |
reportSaving(id) |
A write for id is in flight. |
reportSaved(id) |
id is on disk; opens the "Saved" window. |
reportFailed(id, message, cause?) |
id's write failed. Raises the error toast, once, and records whether cause was the engine's 507. For an id discarded while the write was out, the toast is all it raises (below). |
discard(id) |
id's edit was thrown away, not written: nothing to report as saved. Only for an edit that is gone, because it also abandons a write still out for it. |
An id with nothing unsaved has no entry, so "clean" is absence. The
derivation: any failure wins, and the newest one is described, because a
failed report moves its id to the end of the map; then a save in flight; then an
edit not yet sent; only with none of those does a recent save show saved, for
TIMING.SAVED_STATUS_DURATION_MS, before idle. A report under one id cannot
touch another's entry, which is the whole fix: a rename landing, Settings
mounting clean, a tab switch - none of them can make the Dock stop saying "Not
saved" while some other edit is still unsaved. resetSaveStoreForTests is the
only thing that clears every report, and only tests call it.
An entry is keyed by id, not by registration: it outlives unregisterContext
until its id is reported saved or discarded. That is how the entity-switch
flush of a pane that has already unregistered still reaches the Dock.
The ids. useSaveManager reports under its context id (request-<id>),
useDraftSaveContext under the id it registers, VariableTableEditor under
its context id (globals-editor, environment-<id>, collection-<id>),
SettingsMain under settings, the inbox reply under inbox-reply, and the
context bar's variables section under context-bar-variables. A surface that
drops its draft discards its id: VariableTableEditor, and useDraftSaveContext
for an editor that passes no stored draft (the inbox reply), when the id changes
or they unmount (the draft is component state, so nothing holds it after that),
useDraftSaveContext for a stored draft (the collection editors, #3459) when
that stored draft is dropped or its entity is gone, which an unmount alone does
not do (see
entity-draft-store.ts),
SettingsMain when its staged edits are gone (reverted,
or flushed with every one of them invalid) and no write is in flight, and
useSaveManager when the request's edit is gone without a save (reverted, or
the request deleted elsewhere while dirty) and no write is in flight, which also
cancels the autosave retry. Settings reports an invalid staged edit as pending
too: it is unsaved, held back the way a blocked save is, and its save resolves
pending for it, so a Ctrl/Cmd+S on an invalid edit does not read as "Saved".
A write that settles after its id was discarded describes no edit. The
editor that dropped the edit (an id switch, an unmount, a Reset) is gone or
holds something else, but the write it started still lands, and recorded under
that id its failure or its "still unsaved" would hold the Dock with nothing ever
to clear it. So a discarded id is abandoned until a save starts for it
(reportSaving) or a context registers under it: a failure reported for it is a
toast only, and reportPending counts only from a context registered under the
id, which is a new edit. A goodbye flush never discards first, so its failure is
recorded and stays "Not saved" until a later flush saves it - except for an
entity that was deleted (below).
A deleted entity's edit is dropped, not saved (#3444). The tree's delete of
a request, or of a collection above it, awaits the engine and then closes the
tabs, and a tab's unmount flushes its draft. Saved into the deleted row that
PUT answers 404, toasts "Couldn't save - Request not found" and leaves a retry
context nothing can land, so the Dock stays "Not saved" and the quit prompt
warns about an edit nobody can keep. useTreeCrud therefore calls
markRemoved(ids) with the context ids (request-<id>, a collection's
descendant requests included) after the delete lands and before
closeTabsForEntities. The set behind it is module-local like abandoned, not
store state, and isRemoved(id) is what the goodbye flush asks: a removed id
is discarded without a save. A context registering under the id clears the
mark, so a restore (Undo brings the same id back) saves normally. The backstop
for a delete the tree did not make (another window, an MCP client) is the
flush's own answer: a goodbye flush whose save fails with a 404 discards the id
instead of re-registering a retry. The failure toast has already been raised by
then and is not taken back.
A failure that leaves no unsaved edit is a toast, not reportFailed.
reportFailed holds the Dock on "Not saved" until that id saves again, so it is
for a failed write whose edit is still on screen. A failed create, duplicate or
delete (collections, requests and environments alike) leaves nothing pending and
nothing retries; a failed rename (the collection tree's two, the environment
tree's) puts the stored name back; a failed context-bar variable commit puts the
stored value back in its input; a refused blank name (reportBlankNameRefused,
lib/blank-name.ts) restores the stored name; a failed SettingsMain
category-switch or unmount flush wrote edits that had already left the screen
with their category, so nothing staged is left for a Save to retry. Each raises
its own error toast.
Reported to the store, any of them would park the Dock on "Not saved" describing
no edit, under an id nothing would ever report saved.
Direct writers are the surfaces that write without going through the store's
runSave, and they report the same way. The tree renames register no save
context: each reports saving under rename-collection-<id>,
rename-request-<id> or rename-environment-<id> while the PUT is out, then
saved, or a discard and the toast. The rename field stays mounted until the
PUT settles, so a failure is reported over the typed name rather than after the
row has snapped back. SettingsMain's Save button and category-switch flush,
and the inbox's CannedResponseControls Apply (#1450), report around the PUT
themselves, because a direct click reaches no registered context's save
through the store. Each of them reports pending rather than saved for an
edit staged while its write was in flight, as useSaveManager does. A direct
writer also cannot report "Saved" over another surface's unsaved edit (#1385):
a rename landing while the open request holds an unsaved script reports saved
under the rename's id, and the request's pending outranks it.
VariablesSection also registers a context (context-bar-variables). A
variable commit is a plain mutation rather than a draft, so it registers one
entry for the whole section whose hasPendingChanges tracks whether any commit
is outstanding and whose save() resolves when the last one settles - without
it flushAll had nothing to wait for, and the renderer could be torn down
mid-PUT with the input already showing the value as committed. It reports
saving while any commit is out; when the last one settles it reports saved,
or withdraws the report if one of them failed (the toast has said so, and the
input is back on the stored value). A commit settles from the mutation's own
promise (mutateAsync), never mutate's per-call callbacks: a TanStack
observer holds one set of those, replaced by the next mutate and never called
once the host unmounts, so a second quick commit in the same scope, or a tab
switch mid-PUT, left "Saving…" up until restart. Its save() resolves with the commits'
verdict, failed, or disk-full when every failure was a 507, which is what
the quit prompt counts.
completeSave, completeSaveThenIdle and the hand-rolled
setTimeout(() => setStatus("idle"), …) timers went with the setters. The
"Saved" window is the store's own: reportSaved opens it and any later report
closes it, so a success two seconds ago cannot clear a failure reported since,
and two saves a second apart cannot end each other's indicator early. Its
lifetime is TIMING.SAVED_STATUS_DURATION_MS, in one place, for every surface
that saves.
lastErrorMessage is the reason behind an "error" status, for the Dock's
persistent line - see below. It went through the same fate as errorMessage
once: the field existed for the Dock's error line, that line was removed in
favour of the toast, and the field went with it as one nothing read any more.
It is back because the toast turned out not to be the whole answer (next
paragraph), and this time it has a second reader. Whether that failure was a
507 is kept on its entry (diskFull), not beside it: flushAll reads it per
context, and no screen reads a store-wide copy.
There is no lastSavedAt or pendingSaveId, for the same reason that field
almost went a second time - every match on either name was a write inside
save-store.ts. status is still the store's main public surface, and all
five of its values have a reader: the Dock renders pending as "Unsaved
changes", which is the only place in the app that says so. That matters
because auto-save is a setting the user can turn off, and with it off nothing
was written back and nothing said as much (the tab strip carries no
unsaved-dot on purpose).
"error" has two readers now, not one. The toast reportFailed raises
expires after TIMING.TOAST_DURATION_MS.error (10s), and a failed save can leave
a draft unsaved for as long as the engine stays down - far longer than that. The
Dock's ambient status line (Dock.tsx) renders an "error" status as "Not
saved", coloured with --destructive-text, with lastErrorMessage in a
tooltip on hover - the same shape EngineStatus uses for its own error, rather
than a second way of saying "hover for the reason." It stays until the failed
id is reported saved or discarded, so it outlives the toast for exactly as long
as the edit stays unsaved.
A failed save retries itself. Two surfaces do, on one backoff:
saveRetryDelayMs (lib/save-failure.ts) re-arms with the auto-save delay,
doubling on each further failure and capped at TIMING.SAVE_RETRY_MAX_DELAY_MS
(one minute). useSaveManager's debounced timer is the only one of its callers
that retries, cancelled on unmount, on an entity switch, and by the next
ordinary edit. VariableTableEditor retries any failed save of its own (its
saves are all blur, toggle or flush commits, with no debounce to re-arm), while
it is still dirty; the retry is cancelled on unmount and on an entity switch,
superseded by any save that starts, and armed only by the last of a run of
queued saves, since one queued behind a failure is already its retry. A 4xx is
final (#1889): the engine rejected the payload itself (a 400, a 413), so both
report it as "final" (saveFailureOutcome, which asks isFinalError, the
predicate the query and mutation retry rules share) and no retry is armed. The
status stays error - the Dock keeps saying "Not saved" - and the next edit
re-arms the debounce (the editor's next blur or toggle saves again). A 5xx, a
timeout or an unreachable engine keeps retrying. So does a 507, the engine's
answer to a write the data folder's volume has no room for (#2423): both report
it as "disk-full"; the toast is the generic "Couldn't save - Retry-After. In useSaveManager, Cmd/Ctrl+S and
the entity-switch/quit goodbye flush still call performSave directly and
report their own outcome once - retrying either would save into a pane the user
has already left, or double a save they just asked for by hand.
A reconnect flushes every dirty context, not just the one that failed.
useHealthQuery's automatic-reconnect branch and useEngineRestart's manual
one both call flushAll() right after invalidateQueries() - the same move,
for the same reason: a dirty editor's own retry can be backed off up to a
minute behind an engine that just came back, and nothing else pokes it sooner.
Every registered context is safe to flush here, unlike the quit flush's
urgency: a context with nothing pending is a no-op, and one that has never
failed loses nothing by saving now instead of on its own schedule.
A reconnect also names the services the outage stopped (issue #3493).
Inboxes, mock servers and OAuth issuers live in the engine process, so the
engine that comes back runs none of them. recordServicesBeforeOutage
(lib/services-stopped-by-restart.ts) reads queryKeys.inbox.list(),
queryKeys.mockIssuer.list() and queryKeys.mockServer.list() out of the
cache at the outage's first sign, useHealthQuery's first failed poll or
useEngineRestart before it asks for the restart, because the lists' own
poll can reach the new engine before any reconnect is noticed. What counts as
running is runningServicesIn, the definition useRunningServices shares.
Both reconnect branches then call reportServicesStoppedByOutage, which takes
the one pending snapshot (the second caller finds none), fetches the three
lists fresh, and raises one warning toast for the services that were running
and are absent or running: false now, compared by id: it names at most three
and counts the rest ("and 2 more"). A list read that another refetch cancels
(the reconnect's own invalidate, a mutation's) is read again, up to three
times. A failed fetch raises nothing and puts the snapshot back, marked
restored, for the other path's report of the same outage; the next outage's
first record replaces it. A list change with the engine up (an MCP stop, a
Stop in the drawer) records nothing on its own; only one the cached lists had
not shown yet when an outage began is named as if the restart had done it.
triggerSave will not report a success the context did not have. A
registered context can report its own failure under its id and then resolve
rather than reject (SettingsMain), so runSave cannot take a resolved promise
for a success. Without that a failed Cmd/Ctrl+S showed "Saved" beside its own
failure toast.
A context's save can report its own verdict (SaveOutcome: "saved",
"failed", "final", "disk-full" or "pending"; useSaveManager,
useDraftSaveContext, VariableTableEditor and the context bar's variables
section do), and that verdict is what runSave and flushAll count - never a
status read back from the store, which charged one context's failure to another
when the status was a single shared slot. A reported "saved" or "pending" that the context did not
also report under its own id during the save is filled in for it (the draft
editors report nothing on success), and a failure it reported is never
published a second time. pending is a save that settled without persisting
its edit: a SaveBlockedError (the editor declined to send an incomplete
element; the request builder still sends the rest of the request, #3048) or an
edit that landed while the write was in flight. It is not a failure - no toast,
no "Not saved", no retry - and flushAll counts it in pending. "final" is a
failure that will not retry (a 4xx); flushAll counts it in failed.
"disk-full" is a failure that retries like any other and knows its cause (a
507, #2423); flushAll counts it in failed too, and sets reason:
"disk-full" on its result only when every failed context was disk-full. One
failure of another kind beside it leaves the key out, because then "the disk is
full" would be only part of the story. The key is absent, not undefined, when
there is no cause. Three places turn a failed save into "disk-full", all
through isDiskFullError (lib/disk-full.ts): saveFailureOutcome
(lib/save-failure.ts, read by useSaveManager's performSave and by
VariableTableEditor), the useDraftSaveContext save (the collection editors,
whose saves reject) and runSave's own catch in the store.
A context that resolves with nothing (SettingsMain) is judged by what it
reported under its own id during that save: an entry that replaced the one
present when the save started. A failed entry reads failed, or disk-full
when its cause was a 507; a pending one reads pending (#1381), because a
context that saw an edit land mid-write reports it for the payload that went
out not holding that edit; no report is a success, which runSave then reports.
So a context that reports and resolves names a 507 by handing the error over as
the cause, reportFailed(id, message, error); a call that omits it reads
failed (#2685). A context that reports and then rejects is judged the same
way: runSave's catch publishes a rejection only when the context did not
report a failure during that save, so the failure is toasted once rather than
once by the editor and again by the store. That is counted (each id's failure reports, toast-only ones included),
not read from the entry, because an editor that switched away mid-save has
discarded the entry its failure would have replaced. The inbox's CannedResponseControls (whose persist
catches its own rejection, so it must not rethrow: the wrapper would toast a
second time) returns the verdict from persist instead, which
useDraftSaveContext forwards; a bare resolution there would read saved,
which is also why a draft that collect refuses resolves pending.
A goodbye flush is retired by the flush that saves it. An entity switch or
unmount flushes the pane's edit after its context has unregistered
(settleGoodbyeFlush in useSaveManager.ts). A failure re-registers a retry
context under the same id, so the reconnect flush (#1479) and the quit flush
(#1489) can send it again; that retry unregisters itself once its save lands,
and the landing reports the id saved. Before #3350 nothing marked it clean, so
the Dock sat on "Unsaved changes" and every reconnect re-sent the stale draft. A
save the editor held back has nothing left to send it (the provider reseeds
from the next entity), so its id is discarded, and so is one the engine
answered 404 or that the tree marked removed (#3444): the entity is gone and no
retry can land. A pane that came back to the entity owns the id again and is
left alone.
SaveContext:
{
id: string
name: string
save: () => Promise<SaveOutcome | void> // SaveOutcome: "saved" | "failed" | "final" | "disk-full" | "pending"
hasPendingChanges: boolean
}
Key Methods:
// One selector per member: a bare `useSaveStore()` subscribes to every field (#1714).
const reportFailed = useSaveStore((s) => s.reportFailed);
// Reports, under the caller's own id - see the table above:
// reportPending, reportSaving, reportSaved, reportFailed, discard
// markRemoved(ids) / isRemoved(id) an entity's delete landed; its goodbye flush
// is skipped and discarded (#3444)
// Registry:
// registerContext, unregisterContext, updateContext,
// setActiveContext, getActiveContext
// triggerSave() Ctrl/Cmd+S - saves the active context, else the first dirty one
// flushAll() saves every dirty context (quit, reconnect); resolves to
// { saved, failed, pending, reason? } - see above
Non-persisted. See useSaveManager (debounced-autosave editors) and
useDraftSaveContext (draft editors, whether they commit on blur or on a
button) for registration details.
Between them every dirty editor in the app is in this registry, which is what
flushAll walks on quit - a surface that is not registered is not merely
unsaved on quit, it is invisible.
The collection tree does not read the registry: a request whose open tab has unsaved edits drags like any other row (#3447). A move rewrites the row's owner and order, and the builder's save is a merge-patch of the fields that changed, so neither writer carries what the other owns and neither needs to wait.
entity-draft-store.ts - Unsaved Collection Drafts That Outlive Their Editor¶
A Map<entityKey, { draft, baseline }> holding every useEntityDraft draft
outside the component that edits it (#3459). Shell.tsx mounts only the tab on
screen, so a look at a request unmounted the whole collection screen, and a
draft in component state went with it: no prompt, the Dock idle, the old
script still sent.
Key Methods:
entityDraftKey(collectionId, "elements") // "<entityId>:<field>"; also "info", collectionAuthDraftKey(id) for "auth"
put(key, { draft, baseline }) // useEntityDraft's setDraft / adopt, while the draft is dirty
drop(key, only?) // reset, a draft edited back clean, a save that landed
dropForEntities(entityIds) // closing a collection tab, deleting a collection subtree
const draftAuth = useCollectionAuthDraft(collectionId); // the Auth tab's unsaved pick, mounted or not
Clean is absence. An entry exists only while its draft differs from the
persisted value. baseline is the persisted value the draft diverged from, so
a change that lands while the editor is unmounted still arrives on the remount
as externalValue, a conflict, rather than replacing the draft; an entry whose
draft the persisted value has caught up with is a save that landed and is
dropped.
Who drops an entry. The editor (useEntityDraft's reset, an edit back
to the persisted value, the persisted value catching up after a save, or
markSaved for a save that lands once the editor has gone), the save context's
detached save once it lands (useDraftSaveContext), and tabs-store:
every close path (closeTabsNow, LRU eviction) drops the closed collection
tabs' drafts, and closeTabsForEntities drops every id the delete names,
descendants included, beside clearEntity. The delete path cannot rely on
markRemoved, whose ids are request-scoped, and a draft left behind would
send its save at the deleted row on quit.
A detached draft is read against the collections list. Once its editor is
gone, nothing on screen compares the draft with what is stored, so the
detached context does (useDraftSaveContext's stored, built by
useStoredCollectionDraft in CollectionDetail/collection-drafts.ts, which
also defines the value each editor drafts against). It watches the
collections.list cache: a collection that leaves the list (an MCP
delete_collection, a trash purge, another window) or a stored value that
catches up with the draft drops the entry and discards the id, and a 404 from
the detached save does the same after its failure toast. A stored value that
moved away from the draft's baseline is a conflict (#1437): the detached
save declines as pending rather than write over it unseen, so the quit asks
and the remount shows "Changed elsewhere".
It replaced collection-auth-draft-store.ts (#1483). The Inheritance Chain
card and the context bar's CollectionAuthSection read the stored collection,
which says nothing about a mode picked and not yet saved. AuthTab used to
mirror its draft into a store of its own and clear it on unmount, so with the
draft now outliving the tab the context bar would have described the saved
auth while the tab stayed dirty. Both read the entity draft store through
useCollectionAuthDraft instead; withDraftAuth
(modules/request-builder/utils/auth-resolution.ts) substitutes the pick into
an ancestor chain before either reader calls resolveAuthSource, so a dirty
pick and its own inheritance chain agree. A reader tells "unsaved" from a
just-saved entry with isUnsavedAuthDraft (same module), which compares the
way the tab's isDirty does; both readers append "(unsaved)" only while that
holds, because the engine composes from the stored row and a request below
sends that until Save.
Non-persisted, deliberately: a draft can carry a credential, and an unsaved edit does not outlive the app - the quit flush saves it or asks.
response-store.ts - Response Cache¶
In-memory storage of responses per request ID, persisted across view/tab switches but not to disk.
State:
{
responses: Map<string, StoredResponse>,
lru: string[] // request ids, least-recently-written first
}
StoredResponse: Includes status, headers, body, bodyRaw, a binary body's rawBytes, execution time, script results, and console logs.
Key Methods:
Eviction by identity: clearResponse runs from useDeleteRequestMutation
(the delete is what makes the response unreachable), from tabs-store's
closeTabsForEntities (the collection cascade, which knows every descendant id),
and from RequestBuilderProvider's stream-flagged Send (#1876). The stream Send
clears the entry because the provider's mount initialiser and request-switch
reset read the store back, so a finished stream's stored result would return on
the next switch and suppress the Events tab's live placeholder, which is only
built when there is no stored response.
Eviction by count and by bytes: RESPONSE_CACHE_MAX_ENTRIES (24) bounds the map (#1156).
Those two delete seams were once the only ones, so the map grew with every
distinct request a session sent - each entry a body plus its raw copy - until
the app quit. What the map holds is the 24 most recently sent requests, not
the open tabs: this store cannot ask tabs-store what is open, since that
store imports this one. The cap is twice MAX_OPEN_TABS so that recency covers
tab reach in practice - a full set of tabs can each be re-sent and every one of
them still re-opens on its full-fidelity body. The gap is a tab held open
without being re-sent while 24 other requests are, which tab eviction allows
only for a dirty tab; it falls back like any older request. Order comes from
lru, not from executedAt, which a restored response carries from the run
that produced it and which therefore says nothing about when this session last
touched the entry; setResponse is the only writer, and it moves a re-sent
request back to the recent end, so the entry just stored is never the one
evicted. Past the cap nothing is lost, only unabridged: the request re-opens
against the backend's stored run, whose body the engine truncated at
maxTraceBodyBytes.
RESPONSE_CACHE_MAX_BYTES (256 MiB) is the second limit (#2544), because a count
says nothing about size: 24 responses of 20 MB each is a gigabyte held for tabs
nobody is looking at. setResponse sums estimateResponseBytes over the map and
evicts least-recently-written first until both limits hold, so whichever is hit
first decides. The estimate is a documented upper bound, not a measurement: a
string counts two bytes per UTF-16 code unit (V8 stores Latin-1 text in one, so
this errs toward evicting early), a binary body counts its byteLength, and
body and bodyRaw count once when they are equal - past the pane's formatting
threshold paneBody hands the raw string back as body. Headers and the small
fields are not counted. The response just written is never evicted, even when it
alone exceeds the budget: it is the one on screen, and the next write evicts it.
So "the 24 most recently sent" is the ceiling, and a session that sends large
bodies holds fewer.
Non-persisted (responses are reloadable from backend).
tab-selection-store.ts - Active Sub-Tab And Open Element Rows Per Entity¶
Four independent maps remembering per entity id which sub-tab is showing (the
request builder's tab, the response pane's tab, the collection screen's tab) and
which ElementList rows are expanded.
State:
{
requestTab: Map<string, RequestTab> // keyed by request id
responseTab: Map<string, ResponseTab> // keyed by request id
collectionTab: Map<string, CollectionTab> // keyed by collection id
openElementRows: Map<string, ReadonlySet<string>> // request or collection id -> expanded element ids
}
Key Methods:
const { getRequestTab, setRequestTab } = useTabSelectionStore();
const { getResponseTab, setResponseTab } = useTabSelectionStore();
const { getCollectionTab, setCollectionTab } = useTabSelectionStore();
const { getOpenElementRows, setElementRowOpen } = useTabSelectionStore();
useTabSelectionStore.getState().clearEntity(id); // drops id from all four maps
useTabSelectionStore.getState().clearAll();
setElementRowOpen(entityId, elementId, open) replaces the entity's set with a
copy (a subscriber holds it by reference) and is a no-op when the row is already
in that state. ElementsPanel and the collection's ElementsTab read the set
by selector through useOpenElementRows and hand it to ElementList as
openIds; a host with no entity id passes nothing and the list keeps local
state.
Why a store at all. Shell.tsx mounts one workspace tab's surface at a
time, so RequestBuilderProvider, ResponseViewer, CollectionDetail and the
ElementList rows inside the Elements tabs all unmount whenever the user looks at a different tab and remount when they come
back - and each held its active sub-tab in a bare useState, which is gone
the moment the component is. The same three components also serve every
open tab of their own type without remounting (RequestBuilder is not
recreated per request tab, nor CollectionDetail per collection tab), so a
tab-id change reaching the same component instance needed the same lookup a
mount-time initializer already had to do - both call sites read and write
through this store rather than through two different mechanisms.
In memory only, like response-store.ts above, and for the same reason: a
sub-tab pick, or which cards are open, is not worth persisting across a
relaunch (a persisted set would also carry ids of elements deleted in an earlier
session). Unlike that store, this one carries no LRU cap - an entry is one enum
value or a handful of element ids rather than a response body, so bounding it
buys nothing.
Eviction by identity: clearEntity runs from tabs-store's
closeTabsForEntities, unconditionally rather than gated on type the way
the response clear is - a collection id keys collectionTab exactly as a
request id keys requestTab / responseTab, so a collection cascade has to
evict here too, and clearEntity is a harmless no-op for whichever of the
four maps never held a given id.
appearance-store.ts - Pre-Paint Interface Preferences¶
The UI font, the interface scale, the corner roundedness and the interface
density - the four preferences index.html's pre-paint script applies before
React mounts. Seeded from localStorage at module load and written back one
key per preference (vayu-ui-font, vayu-ui-font-custom, vayu-ui-scale,
vayu-ui-radius, vayu-ui-density), not through zustand's persist: the
pre-paint script reads those exact keys, and SETTINGS_STORAGE_KEYS clears
them on "Reset app settings".
Density (issue #1670) differs from the other three in mechanism: font, scale
and radius each resolve a stored value to something applyX computes and
writes with style.setProperty, while applyDensity only toggles a
data-density attribute on documentElement - the two densities are whole
--spacing values declared directly in index.css
(:root / [data-density="comfortable"]), so there is nothing to compute.
State:
{
font: UiFontChoice // a preset or "custom"
fontCustom: string // used when font === "custom"
scale: number // page-zoom factor, 0.8-2.0 in 0.1 steps
radius: UiRadius
}
Each action both persists and applies (--font-sans, --radius,
webFrame.setZoomFactor), so there is one write path per preference rather than
a state update and a separate effect that has to agree with it.
Why a store and not useState in useAppearance: scale has two inputs. The
Appearance panel's slider and the View menu's Ctrl/Cmd + - 0 move the
same value, and useAppearance is mounted twice (the app shell and the panel).
Per-instance state let the panel keep reading "Default" while the window
rendered 133%. The menu bridge (onZoomCommand → nudgeScale/resetScale)
lives in useMenuActions, which mounts exactly once - subscribing from
useAppearance would move the zoom two steps per keypress.
The scale range, the legacy-preset migration and the clamp/snap live in
constants/appearance.ts (clampScale, parseScale, nudgeScale). The
pre-paint script duplicates them by necessity - it runs before any module - and
appearance.prepaint.test.ts executes the real script to keep the duplicate
honest.
theme-store.ts - Light/Dark Mode and Accent Scheme¶
The theme source (system / light / dark), the manual accent colour
scheme, the last accent the OS reported and the "match system accent"
preference, with isDark, supportsAccent and isLoading. Like
appearance-store.ts it is written one localStorage key per preference by the
action (vayu-theme-source, vayu-color-scheme, vayu-match-system-accent,
vayu-system-accent), not through zustand's persist: the pre-paint script in
index.html reads all four, and SETTINGS_STORAGE_KEYS clears all four on
"Reset app settings".
State:
{
themeSource: ThemeSource // "system" | "light" | "dark"
colorScheme: ColorScheme // the manual pick; the OS accent never overwrites it
systemAccent: ColorScheme | null // last scheme the OS reported; null until one has
isDark: boolean
isLoading: boolean // until the first persisted + OS read lands
matchSystemAccent: boolean
supportsAccent: boolean // Windows/macOS only; Linux resolves no OS accent
}
Two accent fields (#1861). The scheme on screen is derived, not stored:
effectiveColorScheme(state) is systemAccent while matchSystemAccent is on
and the OS has reported one, colorScheme otherwise. Turning matching on
fetches the OS accent into systemAccent and never calls setColorScheme, so
vayu-color-scheme keeps the user's pick and turning matching off returns to
it. Every OS accent report, at launch or live through onAccentSchemeChanged,
is written to vayu-system-accent whether or not matching is on, so a later
toggle starts from the current accent and the pre-paint script can paint it.
The pre-paint script applies the same rule to the stored keys: the system
accent when vayu-match-system-accent is "true" and the accent key is set,
vayu-color-scheme otherwise. useElectronTheme returns both colorScheme
(the manual pick, what the tile grid writes) and effectiveColorScheme (what
is painted, what the Appearance panel displays while matching).
One DOM writer. Every action and every OS event updates the store and then
calls writeDocument with the store's own state (dark class and
data-color-scheme on <html>, the latter from effectiveColorScheme). Nothing passes it a value of its own, so the
document cannot be set from a copy.
Why a store and not useState in useElectronTheme (#1855): the hook is
mounted three times - the app shell, the Appearance panel and the command
palette (useCommandSurfaces). With per-instance state each held the scheme it
read at mount and re-applied it on every theme:changed broadcast (an OS
light/dark flip, or any setTheme round trip), so an instance that had not
seen the panel's pick wrote the stale scheme over it, and the palette's
"Toggle theme" decided its direction from an isDark only its own setTheme
updated. The same rule as appearance-store.ts above: state that more than one
mounted consumer reads or writes belongs in a store.
Subscriptions are reference-counted. useElectronTheme calls attach() in
an effect and releases on unmount; the first holder reads the persisted and OS
state and registers onThemeChanged / onAccentSchemeChanged (or the
prefers-color-scheme listener outside Electron), and the last to release
removes them. Three hook instances therefore share one set of listeners, and
no consumer has to know which mount is "the" mount. Listeners are registered
after the first read, so an event cannot apply the default scheme over the one
the pre-paint script chose.
client-settings-store.ts - Renderer Preferences¶
Central home for renderer-only preferences that aren't part of the pre-paint appearance set (theme/color/UI-font/scale/radius live in their own localStorage keys so index.html can apply them before React mounts). Holds editor behavior, the monospace/code font, chart granularity, the p99 threshold, the live refresh rate, auto-save preferences, reduced motion, the notification preferences and the load-test dialog's ceilings. Backs the Settings panels (modules/settings/main/panels/). Non-React consumers (services, the dashboard store) read via getState().
State:
{
editor: EditorPrefs // fontSize, wordWrap, minimap, lineNumbers, tabSize
monoFont: MonoFontChoice // a preset or "custom"
monoFontCustom: string // used when monoFont === "custom"
chartBucketSeconds: number // time-bucket width for the dashboard charts
sloThresholdMs: number // p99 latency the breakpoint is judged against, for every mode but capacity (a capacity run uses its own sloMs); never the line the charts draw (that is the run's own, `runOwnSloMs`)
liveRefreshMs: number // how often live metrics commit into the store
autoSave: AutoSavePrefs // { enabled, delayMs }
reducedMotion: boolean // mirrored onto <html data-reduced-motion>
keepAwakeDuringRuns: boolean // standing answer on the run wake lock; default off
systemNotifications: boolean // opt-in for OS notifications while Vayu is in the background; default off
notifications: NotificationPrefs // position, durationScale, maxVisible, minSeverity
loadTestCeilings: LoadTestCeilings
approvedEndpoints: string[] // origins the user has contacted; the GraphQL schema loads on its own only for these
}
import { SETTINGS_STORAGE_KEYS } from "@/stores"; // localStorage keys reset by "Reset app settings"
monoFont and reducedMotion also touch the DOM (--font-mono,
data-reduced-motion), so their setters and onRehydrateStorage both apply
them - a preference that only lands on the next reload reads as a broken
setting.
Start at login is not a field here (issue #2098). The login item lives in the OS - the user can remove it from Task Manager, System Settings or a desktop's startup list without Vayu knowing - so StartAtLoginCard reads it through electronAPI.getLoginItem() on mount and after each setLoginItem(), and nothing joins SETTINGS_STORAGE_KEYS. resetAll is the one place the store touches it: it calls setLoginItem(false) before it clears the keys and reloads, so a reset to defaults does not leave Vayu starting at login.
keepAwakeDuringRuns is the user's standing answer to whether a run may ask the
OS to stay awake (issue #1357). It is read when a run starts rather than
watched, by LoadTestService and ScenarioRunService, so the answer that
governs a run is the one that was true when it began - flipping the row mid-run
does not reach a stream already going. Off is the shipped default: with it off a
load run of ten minutes or more asks once (KeepAwakePrompt), and that grant
takes the same wake-lock key the service releases, so it ends with the run.
systemNotifications is the opt-in for the OS notifications services/notify.ts
posts (issue #1358). It is read at the moment an event fires, not watched,
by the same reasoning as keepAwakeDuringRuns: every call site is a service or
an event handler with no hook to hang a subscription on. Off is the shipped
default, and it is persisted through partialize like the rest of this store's
top-level preferences.
loadTestCeilings is the one slice with a bound outside the app: each value is clamped to LOAD_TEST_CEILING_BOUNDS (constants/load-test.ts) on write and on rehydrate, because the bounds are the engine's crash guards and a build that tightens one must not keep offering a stored ceiling above it. The load dialog turns them into its field ranges via resolveLoadTestLimits; nothing else reads them.
approvedEndpoints is the list of origins (scheme, host, port) the user has chosen
to contact: useEngine().composeRequest adds the composed URL's origin on every
Send, Load test and History re-run, and a manual schema load adds the one it
reached (lib/graphql/approved-endpoints.ts). The GraphQL body's automatic
introspection reads it and nothing else does. It is a list of strings, not an
object, so the rehydrate merge filters it to strings rather than completing it.
Persisted to localStorage (via zustand/persist), version: 1 with a
pass-through migrate; workspace/session state (open tabs, layout, active
environment) is deliberately excluded from the reset, as is the live chart
window - that one is engine config, so it resets with the engine's settings.
Nested preferences are completed against their defaults on rehydrate
(mergeWithNestedDefaults). zustand's merge is a shallow top-level spread, so a
stored editor / autoSave / notifications / loadTestCeilings object
replaces its defaults whole and a key added after that payload was written
arrives undefined - notifications.maxVisible feeds slice(-maxVisible) in
toast-store, and slice(-undefined) caps nothing. Adding an object-valued
preference means adding a line to that merge; the store's test enumerates them
rather than trusting the list.
Closed-list pickers snap on rehydrate. A stored autoSave.delayMs,
chartBucketSeconds or liveRefreshMs outside its option list (a retired
option, a hand-edited payload) is snapped in onRehydrateStorage - to the
nearest option for the delay, to the default for the other two - because
migrate runs only on a version mismatch and would miss a same-version payload.
dashboard-store.ts - Load Test Metrics & State¶
Manages live load test run state: streaming metrics, final reports, and running aggregates (peak concurrency, SLO breakpoint). Retention is time-based, not a fixed point count: addMetricsBatch trims ticks older than the user-configurable live window (liveWindowSeconds, default 5m, null = full run), backstopped by a maxRetainedTicks ceiling (default 50,000). Both are kept in sync by useLiveWindowSync, mounted once at the App root (not scoped to Settings, so a run streaming with the panel never opened still uses the engine's values), and drive what the live charts plot. (app/src/config/metrics.ts now only holds the SSE commit throttle, METRICS_UI_THROTTLE_MS.)
The window is engine config, not a renderer preference. It is stored as the engine's liveReplayWindowMs entry (milliseconds; 0 = full run), so useLiveChartSettings (the picker's editor) reads it from useConfigQuery and writes it with useUpdateConfigMutation - there is no localStorage key. The engine needs the same number: it sizes the in-memory SSE tick ring that GET /runs/:runId/live replays - from offset 0 for a first attach, which is what rebuilds these charts when the dashboard attaches mid-run, and from the last frame held for a Reconnect (#3571). Two settings would let the retained span and the displayed span disagree, with the engine replaying less than the chart is configured to show. constants/live-window.ts owns the option list and the liveWindowToMs / liveWindowFromMs mapping. The Dashboard picker is its only editor: the engine settings list rendered a second one until #586, under a different label and a different save model, and ENGINE_SETTINGS_EDITED_IN_APP (modules/settings/engine-settings-edited-in-app.ts) is what keeps that row out of it now.
The tick ceiling is shared the same way, as liveMaxRetainedTicks (default 50,000). It is a memory bound, not a rendering one - bucketColumns collapses ticks into chartBucketSeconds buckets (0.5s by default) before uPlot sees them, and uPlot draws to canvas, so a full window reaches the screen as a few thousand points however many ticks back it. It also costs nothing at stock settings, since the window is what sizes the retained history; it only binds when window / tick-interval exceeds it. DEFAULT_MAX_RETAINED_TICKS here and DEFAULT_MAX_LIVE_TICKS in the engine are the pre-config defaults and must move together.
Because the value arrives asynchronously, the store seeds liveWindowSeconds with the module default rather than reading it synchronously at creation; useLiveWindowSync corrects it once the config query resolves.
State:
{
currentRunId: string | null
phase: DashboardPhase // Where the held run stands; see below (#3351)
currentMetrics: LoadTestMetrics | null
historicalMetrics: LoadTestMetrics[] // Trimmed to liveWindowSeconds (cap: maxRetainedTicks)
monitorSamples: MonitorSample[] // Server vitals scraped this run (cap: maxRetainedTicks)
liveWindowSeconds: number | null // Live retention window; null = full run
isStopping: boolean // A Stop request for the held run is in flight
stopArrivedLate: boolean // The engine answered Stop completed/failed: the run had finished first (#3367); the finished view says so unless the report carries `summary.drainCut` (#3538)
loadTestConfig: LoadTestRunConfig | null // Config snapshot during run; `runOwnSloMs(loadTestConfig)` (capacity `sloMs`, else the `latencyP99Ms` budget, else undefined) is the SLO line the live charts draw
requestInfo: LoadTestRequestInfo | null // Request snapshot during run
peakConcurrency: number // Running max (monotonic)
breakpoint: Breakpoint // SLO crossing (latched on first breach); carries the sloMs it was judged against (a capacity run's own `loadTestConfig.sloMs`, read through `setRunConfig` too for a run started by an MCP agent; the Settings threshold in every other mode), its `sloSource` (`"run"` only where that number is the run's own p99 line, else `"settings"`, which the labels word as "threshold in Settings", not "SLO") and atRunStart (no reading under it came first)
}
Key Methods:
startRun(runId, config?, requestInfo?, sourceRequestId?) // The one writer that replaces the held run
// Every writer below names its run and is dropped for any other:
setRunConfig(runId, config, requestInfo) // Fill in loadTestConfig / requestInfo of a run started without them (agent runs)
streamOpened(runId) // Stream attached, or re-attached by Reconnect -> streaming
streamLost(runId, message) // Error, drop or takeover while the engine runs on -> streamLost
streamClosed(runId) // streaming -> awaitingReport
stopRun(runId) // The engine confirmed Stop took effect (answered `stopped`) -> awaitingReport, stopped
noteLateStop(runId) // The engine answered Stop completed/failed: records stopArrivedLate; a lost stream awaits the report
addMetricsBatch(runId, batch) // Fold a batch into history and update aggregates
addMonitorSamples(runId, batch) // Append scraped server vitals, bounded by maxRetainedTicks
setFinalReport(runId, report) // -> finished, unless the report says the run is still live
reportFailed(runId, message) // The report fetch gave up -> reportError
retryReport(runId) // Retry -> awaitingReport
setStopping(runId, stopping)
setLiveWindowSeconds(seconds) // Update the live retention window (from useLiveWindowSync)
setMaxRetainedTicks(ticks)
phase is the one encoding of where the held run stands (issue #3351). It replaced four fields - mode, isStreaming, error and finalReport - that could disagree: a stream error left isStreaming true beside its message, so the pill said Running over a dead stream; a superseded or dropped stream left neither streaming nor settled, so the pill vanished while Stop still showed; and "awaiting the report" was only the absence of every other flag. Each phase carries only its own payload, in the style of SpecSync.tsx's CheckState:
type DashboardPhase =
| { phase: "idle" }
| { phase: "streaming" }
| { phase: "streamLost"; message: string } // The engine runs on; the callout's body
| { phase: "awaitingReport"; stopped: boolean } // `stopped`: the engine confirmed the user's Stop; the report still decides the ending
| { phase: "reportError"; message: string; stopped: boolean }
| { phase: "finished"; kind: "completed" | "stopped" | "failed"; report: RunReport }
Two pure derivations are exported beside it, and every reader asks them rather than the phase. isDashboardRunLive(phase) is whether the run may still be executing on the engine: true for streaming, streamLost and an awaitingReport the user did not stop. The header's Running pill and Stop button (Finishing and Stop waiting while the latest frame's phase is draining, #3568: the engine's word, carried on every live frame through mapSseMetrics, read from currentMetrics and never inferred from elapsed against the duration), the keep-awake prompt and the single-run gate (canStartLoadRun, below, which the URL bar's Load test swap and the Run Collection dialog follow) all read it, so a lost stream keeps the run live everywhere, Running beside the "Lost the live metrics stream" callout. A reportError is not live: the stream had already closed, and holding the builder on a read that cannot answer would lock out every new run until the engine did. dashboardRunEnding(phase) is how the run ended as far as the dashboard knows - the report's kind, or "stopped" from the engine's confirmed Stop before the report lands - and is what the pill names when the run is not live. useHostSleepRecorder is the one reader that wants the stream itself rather than the run, and reads phase === "streaming": a lost stream's last tick is not where the run had got to.
Every writer but startRun is addressed to a run, and a write for a run the store is not holding is dropped, as in execution-events-store below. A continuation can outlive its run - handleClose's awaited report fetch, a Stop request, a buffered flush - and landing on the run that replaced it was the defect #1925 and the finishing-run-A-starting-run-B race both were. A transition that does not apply from the current phase is dropped too: a close after a lost stream keeps the callout, a re-attached stream does not raise a stopped or settled run back to Running, and nothing moves a finished run but the next startRun.
setFinalReport ignores a report for a run that is still live (issue #1925). The engine answers GET /runs/:id/report for a running run too, with metadata.status saying so, and taking that answer as final painted Completed and removed the Stop button while the run kept generating load. A report whose status is running or pending leaves the store untouched, whichever caller fetched it; a report with no status at all is still taken as final. A report that lands settles the run as finished, with the engine's status as its kind: failed stays failed (#1932), and a Stop the user pressed does not override it (#3367), so the dashboard reads the run as History and the report do. Any of the three renders History's LoadTestDetail over the report (#2136, #2220); until one lands the live view stays, carrying the report Retry. isRunInProgress (lib/run-status.ts) is the one test, shared with LoadTestService and the dashboard's report effect. Its counterpart isRunTerminal (completed, stopped or failed) is the one spelling of the settled set; an unrecognised status is neither.
A view of a stored run asks useRunLiveness(runId, status) (hooks/useRunLiveness.ts, #3351) whether that run is live: ScenarioRunView (Stop, the live progress line, the waiting empty state), HistoryDetail (the in-progress pane in place of a load run's report) and HistoryList (whether the delete confirm says it stops the run first). It joins the status the caller already holds, from useRunQuery or a runs list, with whichever live surface in this window holds the run: the dashboard, by isDashboardRunLive, or a collection run's stream. The rule is isRunLive in lib/run-status.ts: a terminal stored status is final whatever a stream that has not caught up says, an in-progress one keeps the run live through a lost stream, and only a status not read yet, or not recognised, defers to the streams. The caller passes the status rather than the hook reading the run's query, because a second observer of runDetailOptions would be a second poll of the same run. The dashboard's own surfaces (the header pill, the keep-awake prompt) ask isDashboardRunLive directly, since the run they describe is whichever the dashboard holds. The in-progress pane's Stop waiting label (#3568) reads phase from that same runDetailOptions observer (GET /runs/:id carries it for an active run only, read through runPhaseOf so an unrecognised value is absent), so it adds no poll.
The load-test dialog seeds its scrape cadence and bounds its metric list from
the engine's monitorIntervalMs / monitorMaxSeries settings, through
useMonitorSettings - the same read-the-engine's-copy arrangement
useLiveChartSettings uses above, and for a sharper reason: this dialog always
sends an explicit intervalMs, so a renderer-local default would mean the
setting never applied to a run started here at all.
monitorSamples is kept beside the ticks rather than merged into them: the
two are sampled by different clocks (the engine's tick cadence and the user's
scrape interval), so they are joined onto one x axis at render time by
joinMonitorToTimeline - which is also where a failed scrape becomes a gap in
the line rather than a plateau. The array is empty for a run that configured no
monitor, and that emptiness is what keeps the vitals chart row off the dashboard
entirely. It carries its own copy of the tick ceiling because a scrape can be
configured faster than the tick cadence.
There is deliberately no store-wide reset: startRun already wipes the series,
the report and the aggregates, and a reset on top of it nulls currentRunId -
the dashboard then shows no active test while one streams.
Non-persisted (fresh per session).
update-verification-store.ts - An Installer That Would Not Verify¶
The downloaded update whose build-provenance attestation did not verify (issue
2372), or null.¶
State:
{
failure: { version: string; reason: string } | null
setFailure: (failure) => void
clear: () => void
}
Non-persisted. useAppUpdate writes it from every download state it receives
(update:state, and getUpdateState() on mount, so a reload keeps it): refused
sets it and any other state clears it. It is a store
rather than hook state because the banner receives the state for the whole
session while UpdatesCard mounts only when Settings opens, and a per-instance
hook would show it nothing. Both read it with a selector.
host-sleep-store.ts - When The Machine Slept Under A Run¶
The intervals the host spent asleep while a run was streaming (issue #1357), keyed by run id. The app holds a system wake lock for the length of a run, but that lock is a request to the OS: a closed lid or a critical battery overrides it, and the run's series is then missing a stretch that nothing in it explains.
The record lives here rather than in the run report because the engine was
suspended too and knows nothing about it. useHostSleepRecorder writes it -
the main process's power:suspended carries the anchor (where the run had got
to, read off dashboard-store on the way down, since the renderer is frozen in
between) and power:resumed carries the duration.
State:
{
byRun: Record<string, HostSleep[]> // { at, durationMs, startSeconds }, oldest first
runOrder: string[] // first-annotated order, for eviction
}
Two readers, both by run id through the useHostSleeps(runId) selector rather
than one prop drilled to both: MetricsView and PerformanceTab mark the
sleeps on the charts, OverviewTab states them in RunEvents. The selector
returns one frozen empty array for a run with no sleeps, so a dashboard
rendering at 10 Hz is not re-rendered by a stable absence.
Persisted, bounded to the newest MAX_RUNS (20) runs and
MAX_SLEEPS_PER_RUN (20) intervals each: the gap outlives the session that
produced it, and a user who finds the hole tomorrow needs the same answer, but
localStorage is a fixed budget shared with the workspace. migrate and merge
both normalize, as recovery-notice-store does and for the same reason.
inbox-notify-store.ts - Which Inboxes May Notify On A Capture¶
Whether a capture landing on one inbox may raise an OS notification while Vayu
is in the background (issue #1388), keyed by inbox id. Off for an inbox nobody
has decided about, and off even when systemNotifications is on: a capture is
the one relevant event with no natural rate, and a webhook source that retries
would otherwise teach the user to turn the whole feature off, taking the
run-finished notification with it.
It lives here rather than on the engine's inbox record, the way
host-sleep-store keeps a run's annotation beside a report with no field for
it: the engine's inbox is in-memory state that never outlives the process that
opened it, and it does not act on this flag - only the desktop app does.
State:
Four readers. Two at the moment a capture arrives:
modules/inbox/capture-notifier.ts gates on it (the second gate;
services/notify.ts reads the global opt-in), and the header toggle in
modules/inbox/index.tsx writes it. The third is hooks/useInboxWatchers.ts,
which reads the whole map continuously to decide which inboxes
services/inbox-watch-service.ts should hold a live stream for: the toggle
promises a notification while Vayu is in the background, and the inbox tab is
mounted only while it is the active tab (issue #1400). The fourth is the
Services drawer's inbox row (modules/services/ServicesPanel.tsx), which reads
one inbox's entry to decide whether to say the promise is not currently being
kept - a stream that gave up, or one the stream cap left out (issue #1412). It
reads rather than writes, and an inbox whose toggle is off gets no note, because
there is nothing to say about a promise that was never made.
Persisted, and pruned: an inbox id belongs to the engine process that minted
it, so retainInboxes drops every id a successful GET /inbox no longer names,
called from useInboxWatchers on a list read the engine actually answered - a
failed read leaves the map alone, because "no inboxes" and "could not ask" are
not the same list. It was called from InboxView until #1400, which pruned the
map only while that tab happened to be open. migrate and merge both
normalize, as host-sleep-store does.
scenario-run-store.ts - Live Collection-Run Steps¶
The live half of a scenario (collection) run's tab. ScenarioRunService pushes the step SSE events in here and ScenarioRunView reads them, so the stream survives navigating away from the tab and back - the same split, for the same reason, as LoadTestService and dashboard-store.
It holds one run. A scenario is sequential and the app starts one at a time, so startRun replaces the previous run's steps rather than accumulating; a tab for an older run reads an empty list rather than whatever is streaming now. Every other writer - addSteps, setPlan, setStreaming, streamLost, runEnded - names its run and is dropped for any other (issue #3351), as execution-events-store does: the stream is replayable, so a step from a replaced run can still land on a socket that has not finished closing, and a release for one run must not lower a successor's flag. ScenarioRunService builds its step batcher per run for the same reason, the shape useExecutionEvents uses: handleClose flushes after it has let go of activeRunId, so the commit carries the run it was built for.
State:
{
runId: string | null // The run being streamed, or null
steps: ScenarioStepRow[] // Reported so far, in plan order
summary: StepListSummary // The outcome counts, plus how many steps are
// past the first pass and how many bound a data row
appendEpoch: number // Moves whenever the list changed by anything other
// than growing at its end
plan: ScenarioRunPlanEvent | null // The opening `plan` frame: stepsPerIteration,
// iterations, stepsExpected. Null until it arrives
isStreaming: boolean // Between startRun and the stream closing or failing
error: string | null // A transport failure on the stream
endedAs: TerminalRunStatus | null // How the run ended, once this window knows
thresholdValidation: RunReport["thresholdValidation"] | null // The stored
// report's budget block, written with endedAs
}
runEnded(runId, status, thresholdValidation) records endedAs and the stored report's budget block and lowers isStreaming in one write. ScenarioRunService.handleClose calls it once the report refetch below has answered: with the engine's completion frame, or, for a stream that closed without one (#1415), with the stored report's status when it reads as terminal; a run the report still calls running only lost its stream, and endedAs stays null. The wait is for the budgets (#3539): the frame carries a status alone, and one write is what lets RunAnnouncer (#3498) say the ending once with a missed budget in it, rather than the counts first and the budget in a second announcement. A refetch that failed records no block, and the ending is still said with the counts. The terminal notification is posted at the same point and from the same block. Both fields' one reader is RunAnnouncer; the run tab reads the stored record, not these.
streamLost(runId, message) records a transport failure and lowers isStreaming in one write. The run keeps executing on the engine, and ScenarioRunView's "is it live" is useRunLiveness(run.id, run.status), so once the stream says nothing more the run's stored status answers, instead of a Running spinner standing beside "Live updates stopped".
A batch per flush, not a commit per event (issue #1153). ScenarioRunService buffers arriving step events and commits what it collected on the user's liveRefreshMs cadence, the same throttle LoadTestService puts on its ticks. The premise for having none - that a scenario's step rate is bounded by request latency - does not hold: the engine's scenario loop is sequential with no pacing, so a local target returns hundreds of steps per second, and each one used to cost a full copy of the step list, a store notify and a re-render of the run tab. The buffer is committed on the leading edge of a window and again on a trailing timer, and drained when the stream closes or fails; a run replaced mid-flight discards whatever it left buffered, since those rows belong to a list the store has already cleared. That mechanism - buffer, leading edge, trailing timer, and the liveRefreshMs read behind it - is one implementation, services/throttled-batcher.ts (issue #1206), and now has a third caller: useExecutionEvents buffers a design-mode request's streamed events through it the same way (issue #1158). When to flush and when to discard stay each caller's own, because the lifecycles genuinely differ - the design-mode hook flushes on teardown rather than discarding, because a teardown there is as often the builder unmounting mid-stream as it is a replacement, and the store's run guard is what drops the leftovers in the second case.
Steps are folded in by foldStepEvents (modules/history/main/scenario-steps.ts), which keys on (iteration, stepIndex) rather than arrival order: the engine's SSE ring replays from Last-Event-ID, so a reconnect re-delivers events already rendered and an append-only list would double every row it re-saw. A whole batch costs one array copy, and the fold returns the state it was given when every event in the batch was an idempotent replay, so a reconnect's replay does not re-render the list.
summary is maintained by that same fold rather than recounted by the view - the dashboard-store aggregate stance, for the same reason: a scan per commit is a scan over a list that grows for the length of the run. ScenarioRunView is its reader, for the four count chips and for the two whole-list questions its rows answer. It does not displace the report: once report.scenario can give the run's own totals those win, because thinning drops passes and the stored rows undercount them (see docs/app/COMPONENTS.md). summarizeSteps answers for the stored rows, which arrive complete, and is the oracle the incremental summary is tested against.
appendEpoch is the second thing that fold publishes, and the reason it has to (issue #1205). Every commit hands the view a new array - immutability, which zustand's change detection depends on - so from the rows alone an appended row and a replaced one look alike, and a reader that wants to keep anything derived from the list has to compare the two lists to find out. The fold already knows, so it says: foldStepEvents returns appendedOnly beside the fold, and the store turns it into a monotone counter that moves for a replay that replaced a row, a gap-resume that spliced one in, and a startRun that emptied the list. useFilteredSteps (modules/history/main/) is its reader: it counts what the batch that arrived added to a chip's or the search box's match, and produces rows only as far as the growing window it owns has to show them, so a narrowed live list costs one predicate pass over the batch rather than over the whole run per flush - and, once that window is full, no array copy at all (issue #1297). Monotone matters - React may render once for two commits, and a value that could return to one a reader had already seen would let a stale prefix through.
plan is the engine's plan frame, which opens the stream before the first step (#1398). ScenarioRunService.handlePlan keeps stepsExpected for the OS progress bar and hands the whole frame to setPlan, addressed to its run, which startRun clears and which is dropped for any other run, the way addSteps drops a stray batch. ScenarioRunView reads it, scoped to its own run id, for the live "Iteration k of N" line (docs/app/COMPONENTS.md); it is meaningful only while the run streams, and the report's scenario block is what says how the run ended.
Once a run reaches a terminal status its stored results rows are the complete record and the view reads those instead. ScenarioRunService.handleClose invalidates runs.detail(runId) and refetches runs.report(runId) through the query cache - the same keys the tab reads, so a bare fetch would leave the pane on the stale copy. It also invalidates runs.lists() (the History row still says "running") and runs.lastCollectionRuns() (the context bar's Last run section says it too, from its own family, and is not polled at all). The run's scripts and extractors may have written environment, globals or collection variables, so it also invalidates environments.all, globals.all, collections.all and compose.all, as Send, history replay and the MCP map do (#3250); unconditional, since a run that wrote nothing costs three GETs.
That report fetch carries staleTime: 0, and the feature rides on it. The tab mounts the moment the run starts and asks for the report immediately, when the engine has written no step rows yet - they go to SQLite in one batch at the end - so the cache holds a report with an empty results[], seconds old. Under the hook's own five-minute RUNS_STALE_TIME_MS that entry reads as fresh and fetchQuery resolves from it without a request, which left the step list on the live rows for the life of the tab and made every step expand into an empty panel, since only a stored row carries the exchange. This is the one fetch in the app that knows the data just changed, so it is the one that must not honour the cache. The engine writes the rows, then the summary, then the terminal status, and publishes complete after all three, so the refetch cannot race the write it exists to pick up.
There is deliberately no stopMonitoring on the service and no clear on the store: the stream ends on its own when the engine sends complete, and nothing in the app stops a collection run mid-flight yet. Both belong with the stop control that would need them.
Non-persisted (fresh per session).
execution-events-store.ts - Live Streaming-Request Events¶
The live half of a streaming design request (issue #574): POST /execute with stream: true answers 202 {runId, eventsUrl} and the upstream's own events arrive over GET /runs/:id/events. modules/request-builder/hooks/useExecutionEvents buffers the relayed frames through services/throttled-batcher.ts and commits a batch per flush window on the user's liveRefreshMs cadence, so the store pays one copy and one notify per window rather than per frame (issue #1158) - the same batcher LoadTestService and ScenarioRunService commit through, now with three callers. The response pane's Events tab reads the store, so the rows survive switching to another request tab and back - the same split, and the same reason, as scenario-run-store above.
It holds one stream: a second Send is what closes the first's feed, so two live feeds are not a state the builder can reach. It closes the feed and not the run: the engine's consumer worker keeps going until the stream's own end rule. So when the provider's stream branch empties the store (handOver) while another request's stream is live, that request's run is held as displaced and startStream records it in replacedFeeds (request id to run id, #3352) once the new stream has opened, so a Send whose stream is refused or never starts claims nothing; replacedFeeds outlives the stream fields; that request's response pane reads it to say its live feed was taken over, and the request's own next Send drops it (beginSend, which also counts the send in sendCounts). It also holds the request the stream belongs to, not only the run - one RequestBuilderProvider serves every request tab, so "are these rows mine?" is a question about the request on screen and a run id alone cannot answer it. Both the provider and the viewer select against requestId, which is what stops a stream started elsewhere appearing under a request that never streamed.
State:
{
requestId: string | null // Whose Send started this stream
runId: string | null // The run the engine created; what a Stop names
eventsUrl: string | null // Engine-relative, exactly as the answer gave it
open: StreamOpen | null // What the stream connected to (the `open` frame)
events: StreamEvent[] // Received so far, oldest first
totalEvents: number | null // The engine's own count, from the `complete` frame
isStreaming: boolean
endReason: StreamEndReason | null
error: string | null // A transport failure on the relay
leftOut: LeftOutElement[] // Draft elements this Send left out (#3066)
sent: ExampleSentRequest | null // This Send's snapshot (#1763), put on the stored response
finalized: boolean // Claimed by its finalisation: fetching or landed (#3382)
replacedFeeds: Record<string, { runId; sent; leftOut; finalized }> // Request id -> run whose live feed another request's stream took over
sendCounts: Record<string, number> // Sends begun per request; a newer one overtakes a late finalisation
displaced: { requestId; runId; sent; leftOut } | null // Live feed `handOver` emptied, recorded by the next `startStream`
}
Every write is addressed to a run, and a write for a run the store is not holding is dropped. Not defensive tidiness: the relay replays its retained ring on connect, so a frame from a stream that has already been replaced can still arrive on a socket that has not finished closing - and those rows landing under the send that replaced it is the worst failure here, because such a timeline looks real.
totalEvents is set only from the complete frame (falling back to what arrived, so it is never left null once a stream has ended). While the stream runs, the arrived-so-far count is events.length; reporting anything else would be a total nothing had counted. It matters because it is not the row count once a list has been capped, and the Events tab's truncation disclosure compares the two.
Once the run reaches a terminal status the stored trace is the complete record: the provider fetches the report, restore-response.ts maps its events node onto ResponseState, and the tab reads that instead - the two-sources-one-list handoff ScenarioRunView makes. That finalisation (modules/request-builder/context/stream-finalization.ts) is addressed to the request that streamed, not the one on screen (#3382): it writes the stored response under that request id, touches the live pane only when that request is still showing, and invalidates runs.lists(), runs.recentDesign(id) and runs.lastDesign(id). It covers two kinds of run: the held stream once endReason is set, and every replacedFeeds run, which nothing relays any more and which the builder therefore polls through runDetailOptions until the engine reports a terminal status. Everything it needs is kept here rather than in the provider, because Shell.tsx unmounts the builder on every tab that is not a request: the Send snapshot travels with the run (sent and leftOut on the stream, on displaced and on the replacedFeeds entry), and claimFinalization sets the run's finalized claim and answers its snapshot only to the first caller, so a re-render, a StrictMode double effect or a remount never fetches twice. The held stream's claim is a stream field, so startStream, handOver and clear reset it with the rest; a replaced feed's goes with its entry. A report that cannot be fetched is given back (releaseFinalization) and the next mount retries it. It is not cancelled when another request's handOver empties this store mid-fetch, and a newer send of the same request overtakes it: the claim carries the owner's sendCounts entry and the landing compares it. Only the request builder's provider finalizes (the one given a stream handler); the History run view's detached copy leaves this store alone. What lives here is only ever what arrived on the socket, and it is not bounded by the engine's retained ring: that ring (sseMaxRetainedEvents, 2,000 by default) is only what a reconnect replays, and a client that stays connected is replayed the ring once and then tails the rest of the stream. What actually bounds the list is the per-stream cap instead - sseMaxStreamEvents (100,000 by default, 10,000,000 at the ceiling) or sseMaxStreamDurationMs (600,000 ms / 10 minutes by default), whichever the stream reaches first - which is orders of magnitude bigger than the ring and why the Events tab cannot assume the list stays short. That is also why the tab (ResponseEvents.tsx) renders through useGrowingWindow with memoized rows rather than the whole list at once, and why a live stream passes its runId as the window's listKey - the default reset key is the row count, which would snap the window back to its first slice on every batch a growing-in-place list receives.
Non-persisted (fresh per session).
import-modal-store.ts - Import Modal UI¶
Simple modal state for the collection import dialog.
State:
Key Methods:
env-switcher-store.ts - Title Bar Environment Menu¶
Whether the title bar's environment menu is open (issue #2115). The menu is a Radix
DropdownMenu, which owns its open state unless handed one; TitleBar's EnvSwitcher
binds open / onOpenChange to this store so a toast action raised elsewhere (the
import's Choose environment) can open it.
State:
Non-persisted.
import-report-store.ts - What An Import Left Undone¶
The loss report of a successful import, kept after the dialog that showed it
closes (issue #2109). The preview lists everything an import dropped or altered,
one line each (importNotices); on success the dialog resets and that list used
to go with it. announceImport (modules/collections/import-report.ts) records
one ImportReport per applied file here, keyed by the real id of each root
collection the file created, so a file that created several roots stores the
same report under each. announceImport also folds the outcome of the import's
environment activation (import-environment.ts) into the toast it raises.
State:
{
reports: Record<string, ImportReport> // by root collection id
}
// ImportReport: { title, fileName, notices, fileNeeds, counts, rootIds }
fileNeeds is fileReferenceNeeds' answer computed at apply time, not the
drafts it was read from: those hold every request body and the spec document,
and FileReferenceNeedsView (ImportFileFolders.tsx) draws the same list from
the answer. A report with nothing in it, or a file that created no collection,
is not stored.
Key Methods:
const report = useImportReportStore(selectImportReport(collectionId));
useImportReportStore.getState().dismiss(collectionId); // drops the file's report from every root
Non-persisted (in memory, like import-modal-store): a report is about the
import just made, and a reload has nothing to compare it with.
oauth-signin-store.ts - Which Configs Are Signing In¶
The interactive OAuth 2.0 sign-in running per token cache key (#3354). A sign-in
belongs to the config rather than to the TokenStatusRow that started it: the
Auth tab, the context bar and the collection editor can each show a row for one
config, and they must share one pending state and one browser tab. Modelled on
request-builder/context/send-tracker.ts: the store holds only what renders, and
the AbortControllers and owner counts sit in module maps beside it.
State:
Key Methods:
oauthSignin.begin(key) // AbortSignal, or null if one is already running
oauthSignin.end(key, signal) // flow over; no-op for a signal that is no longer the key's
oauthSignin.cancel(key) // abort and clear at once
const release = oauthSignin.acquire(key) // a row showing the key; the last release cancels
useIsSigningIn(key) // reactive; false for a null key
Non-persisted. A sign-in cannot outlive the window that is waiting on it.
toast-store.ts - Transient Notifications¶
The queue behind the toasts. It holds what to show; the Radix primitive in
components/ui/toast.tsx owns when - the dismiss timer, pausing on hover,
focus and window blur, swipe, and the open/closed state the exit animation keys
off. There is no setTimeout in the store.
State:
Key Methods:
const { showToast, dismissToast } = useToastStore();
showToast("Run history cleared", "success"); // string form, still supported
showToast({ // returns the toast id
message: "Couldn't stop the run",
variant: "error",
action: { label: "Try again", onClick: retry },
});
Variants are info | success | warning | error, with base durations of 4s
/ 4s / 6s / 10s from TIMING.TOAST_DURATION_MS. warning is for a refusal ("A
load test is already running.", runningRunSentence) as distinct from a failure.
Three of the policies are user preferences (notifications on
client-settings-store, shapes in constants/toast.ts), applied here on the way
in:
minSeverity- a floor, compared bypassesSeverityFloor. Below itshowToastreturns an id and shows nothing.durationScale- a multiplier over the per-variant duration (scaledDuration), not a replacement for it, so halving keeps the ratio between a confirmation and a failure.neverbecomesNEVER_DISMISS_MSrather thanInfinity, which the primitive'ssetTimeoutwould coerce to 1.maxVisible- the stack cap, defaulting toMAX_TOASTS(4); past it the oldest is dropped.
Two more policies live here because the primitive has no opinion on them: an
identical message and variant already on screen is collapsed rather than
stacked, and an explicit duration from the caller wins over the scale.
Removal is driven by
the primitive's onOpenChange(false), which covers timeout, close button and
swipe alike, so there is one removal path rather than three - but it closes
the toast rather than dropping it, and the entry leaves the queue
TIMING.TOAST_EXIT_MS later so the exit animation has frames to run in.
The values are not in the store. Delays live in config/timing.ts
(TOAST_DURATION_MS, TOAST_EXIT_MS) with every other UI-facing delay in the
app, and the stack cap in constants/toast.ts (MAX_TOASTS). The store holds
behaviour, not configuration.
See docs/design-system.md -> Toasts for the visual tokens.
Module-Local Stores¶
Module-local UI stores co-locate in app/src/modules/<feature>/<feature>-store.ts and manage feature-specific UI state that should not leak into the global store tree.
modules/collections/collections-store.ts - Collections Tree Expansion¶
UI-only: Which collections are expanded/collapsed in the tree.
State:
Key Methods:
const {
expandedCollectionIds,
toggleCollectionExpanded, expandCollection, expandCollections
} = useCollectionsStore();
Every action here has a caller, and expanding is idempotent. expandCollection
(one id) and expandCollections (an ancestor chain) both return the same Set
when nothing changes, because it is passed down the whole tree and listed in
effect dependencies - a fresh Set for a no-op re-renders every row and re-runs
the reveal effect. That is why the tree calls them instead of hand-rolling
if (!expanded.has(id)) toggle(id), which reads the set it writes and so drags
expandedCollectionIds into the dependencies of everything that expands.
collapseCollection and reset used to live here with no callers at all;
collapsing goes through toggleCollectionExpanded.
modules/history/history-store.ts - History Filter & Sort¶
UI-only: Search, filter (type/status/pinned/origin), and sort (newest/oldest) for the history tab.
State:
{
searchQuery: string
filterType: "all" | "load" | "design" | "scenario"
filterStatus: "all" | "pending" | "running" | "completed" | "stopped" | "failed"
pinnedOnly: boolean
filterOrigin: "all" | "app" | "mcp"
filterClient: string | null // an MCP client's display name; client-side only
sortBy: "newest" | "oldest"
}
Helper: filterRuns(runs, filters) re-applies the type, status, pin and origin
filters the engine already applied, then narrows by MCP client and sorts, over the
loaded pages. Search is not handled here: searchQuery is
debounced into the server-side q param (see useRunsQuery) so it covers all
runs, not just the pages loaded into the sidebar.
pinnedOnly is server-side for the same reason - it drives
GET /runs?baseline=true, so a pin older than the loaded pages is still
findable - and applied again in filterRuns. That second pass is not
redundant: unpinning patches the loaded pages in place rather than refetching
them (see useSetRunBaselineMutation below), so the row just unpinned would
otherwise sit in the pinned-only list until the next poll. The param decides
what is fetched; the pass decides what is shown. false is never sent: the
engine reads baseline=false as "only unpinned runs", so the off state omits
the param entirely.
filterOrigin has the same two halves (#1817): a kind other than "all" is
sent as GET /runs?origin=<kind> through useRunsQuery's third argument, and
filterRuns re-applies it on run.origin?.kind - a run from an engine older
than the field has no origin and shows under neither entry. filterClient
narrows "mcp" to one client and is client-side only; the engine filters on
kind, not on a client's name. It holds the client's display name
(mcpClientDisplayName, lib/mcp-client-names.ts), so two spellings of one
product are one entry, and setFilterOrigin clears it because a client belongs
to the kind it was picked under. mcpClientNames(runs, selected) lists the
Select's per-client entries from the rows before the client narrowing, so
choosing one client does not hide the others.
Key Methods:
const {
searchQuery, setSearchQuery,
filterType, setFilterType,
filterStatus, setFilterStatus,
pinnedOnly, setPinnedOnly,
filterOrigin, setFilterOrigin,
filterClient, setFilterClient,
sortBy, setSortBy,
resetFilters
} = useHistoryStore();
modules/variables/variables-store.ts - Variables Category Selection¶
UI-only: Which category (globals/collection/environment) is selected in the variables tree.
State:
{
selectedCategory: VariableCategory | null
// VariableCategory = { type: "globals" } | { type: "collection"; collectionId }
// | { type: "environment"; environmentId }
}
Key Methods:
A variable-map write merges onto the freshest map, never onto its own copy¶
PUT /environments/:id, PUT /globals and PUT /collections/:id replace the
whole variables map, so any writer holding less than the freshest map risks
carrying a key it never touched back to its pre-write value. Two surfaces write
these maps and both go through lib/variable-merge.ts's mergeVariableChanges
rather than each re-deriving the read-fresh-merge-write shape (#1439):
- The context bar's
useVariableCommit(components/layout/context-bar/ variable-commit.ts) commits one key.CommitScope.read()re-reads the query cache at commit time, not the value the input was rendered with, andmergeVariableChangesapplies the one changed key onto it beforewrite/mutate. VariableTableEditor(modules/variables/main/) commits every row the user has actually edited.planSavediffs the current rows againstbaselineRef- the map the table last agreed with the server on - to get aVariableChangesof only the touched keys, then merges that ontofreshMapRef, the freshest map the editor knows: the query cache'sdataVariables, which stays current even while the row-init effect below is refusing to reseed, with each landed save's own changes applied over it until that save's cache echo arrives. A key nobody touched - an MCP agent'supdate_environmentlanding while the table has an unrelated unsaved edit - therefore survives the next save regardless of what the editor's own copy of it says.
The editor's saves run one at a time (#3353). A blur followed by a toggle
asks for two saves; the second waits for the first, and a third asked for while
one is already waiting joins it. A waiting save binds its entity (the context id
and the mutation that writes it) when it is asked for, but reads the rows, the
baseline and the fresh map when it starts, so it carries everything typed
meanwhile and merges onto the map the first save left in freshMapRef - its own
diff against the advanced baseline no longer names the first save's keys. Two
saves in flight could land out of order and leave baselineRef at the older
map, so a later external write was compared against the wrong pre-image; and a
second mutate on one TanStack mutation stops the first call's callbacks from
firing, so that save's promise never settled. Those per-call callbacks also
never fire once the editor has unmounted (TanStack runs them only while the
observer has listeners), so a save settles from mutateAsync's promise as well,
whichever answers first: a save in flight at unmount still settles, and the one
queued behind it still goes out. A throw before the request is sent settles the
save as a failure, so the queue is never left waiting on nothing. If the editor
switches entity
before a waiting save starts, the save computes from the snapshot taken when it
was asked for and, when it lands, touches nothing of the scope now on screen. It
reports nothing under the id the editor discarded either: a reportSaving would
take the abandoned id back, and its failure would then sit on the Dock as "Not
saved" for rows no editor holds. Its failure is a plain toast, the rule for any
write that lands after its editor let go. A
save for an environment or collection that is no longer there reports
Couldn't save - this environment no longer exists (or collection) and resolves
"final" rather than sitting on "saving" until the quit flush's ceiling. Every
save resolves with its SaveOutcome and never rejects, so the blur and toggle
callers, which do not await it, cannot leave a rejection unhandled.
A key both sides touched is a conflict, not a coin flip. While the table is
dirty, the row-init effect recomputes the same diff against baselineRef on
every dataVariables change purely to call findVariableConflicts, which
reports a key only when the fresh map and the user's edit both moved it away
from the baseline to different values. The table renders one Callout per
conflicting key naming it, with "Keep mine" and "Take theirs" actions, and a
save leaves a conflicted key out until the user picks one (#3353): the other
writer's value stays on disk, the user's stays on screen, and the editor stays
dirty, so the Dock says "Unsaved changes". Saving the user's value by default
would be choosing for them. Both actions set the key's baseline to the other
writer's value and save at once: "Keep mine" then reads the row as the user's
change over it, "Take theirs" first replaces the row with it. That is the row
standing for the stored key (rowIndexFor): one the user renamed away from it
is renamed back, and a name is compared trimmed, as it is saved - matched by its
raw name, a renamed row was missed and the save still sent the user's delete.
Deleting a conflicted row is "Keep mine" for that key. baselineRef itself only advances
on a full reseed, on this editor's own successful save (to the map that save
wrote, so a later write is never compared against this save's own history -
except a key the save held back, which keeps its baseline so its conflict stays
open; conflicts are then recomputed against the new baseline, never cleared),
and when the user picks a side - never merely because the table was dirty when
a fresh write arrived, since a key nobody has touched needs no conflict
bookkeeping at all.
modules/settings/settings-store.ts - Settings Category Selection¶
UI-only: Which settings category (e.g., "ui") is selected in the sidebar.
State:
Key Methods:
lib/graphql/explorer-store.ts - GraphQL Schema Explorer View¶
UI-only, in memory: whether the schema explorer pane is open, and per schema identity the search text, the expanded row ids, the scroll position and whether rows show their full description or one clipped line.
State:
{
open: boolean,
byKey: Record<
string,
{ search: string; expanded: string[]; scrollTop: number; showDescriptions: boolean }
>,
lru: string[]
}
Key Methods:
const { open, setOpen, view, setSearch, toggleExpanded, setScrollTop, toggleDescriptions } =
useExplorerStore();
showDescriptions is per schema like everything else here: how much
documentation a user wants on screen is a property of the schema being read, and
an endpoint that documents nothing has nothing to answer for.
A store rather than component state, because the pane is unmounted for no reason the user did. Radix tears the whole Body tab down on every glance at Headers or Auth - the same unmount the body drafts exist for - and a component-state explorer comes back collapsed to its roots with an empty search box.
Keyed by schema identity, using the schema cache's own schemaCacheKey, so
two requests against one endpoint share the tree they have opened and the same
URL reached with different credentials does not. Deliberately not persisted and
capped at EXPLORER_VIEW_MAX_ENTRIES (8, matching the schema cache): an
expansion set is a description of a schema that may not exist next launch.
lib/graphql/reveal-store.ts - GraphQL Outline Click-to-Scroll¶
UI-only, in memory: one slot holding the operation the context bar's GraphQL outline asked the query editor to scroll to, until something serves it.
State:
Key Methods:
A store because the two ends cannot see each other. The outline lives in the
context bar, outside RequestBuilderProvider; the Monaco instance lives inside
GraphQLBody and stays there, the way the insert machinery applies its edits
in-component rather than handing the editor out. What crosses the boundary is a
request to reveal, not an editor.
Consume-and-clear, for the reason the insertion effect records: a command
left in the slot is replayed on the next render and the next remount, and Radix
remounts the Body tab on every glance at Headers. GraphQLBody clears it once
served and when it cannot serve it (the operation was renamed away, which it
says out loud); the provider clears one naming another request or a request
whose body is no longer GraphQL, since nothing under it can ever serve those.
The provider's other half is bringing the Body tab forward - the editor does not
exist while another tab is on screen.
A command names its request for the reason the body drafts do: only one request builder is mounted at a time, so a mismatch takes a click and a tab switch in the same tick, and the cost of not carrying the id is another request's editor jumping to a line number that means nothing there.
TanStack Query (Server State)¶
TanStack Query manages server state with automatic caching, refetching, and synchronization. It is the source of truth for collections, requests, environments, globals, and runs.
Query Hooks¶
Located in app/src/queries/, one file per resource family, all re-exported
from app/src/queries/index.ts, which is what callers import from. The key
factory lives beside them in app/src/queries/keys.ts. A couple of hooks with a
single consumer are imported from their file directly (useRunTimeSeriesQuery
from @/queries/runs); everything with more than one is in the barrel.
Collections & Requests¶
useCollectionsQuery()- Fetch all collections (there is no single-collection query: a collection is read out of this list)useCollectionName(collectionId)- A run's collection by name, read out of that list; the id stands in once the collection is deleted, never a blankuseRequestsQuery(collectionId)- Fetch requests in a collection, asRequestSummaryrows (types/domain.ts, #2546):id,collectionId,name,method,url,order,createdAtandspecOperation, fromGET /requests?fields=summary(apiService.listRequestSummaries). EverylistByCollectioncache holds that shape, and its type is what makes a reader that wants a body, headers, auth or scripts fail to compile rather than readundefined.createdAtiscompareTreeOrder's tie-break andspecOperationthe Spec tab's mapping count; the rest is what a tree row, the palette and "Copy for agent" draw. A write that already holds the whole row (a create, a reorder's settle) stores it as it stands, since aRequestis aRequestSummaryuseMultipleCollectionRequests(collectionIds)- The same list for several collections at once, as parallel queries. ItsrequestsByCollectionmap is referentially stable while the underlying results are unchanged (built inuseQueries'combine, which TanStack memoises only for acombineof stable identity - hence theuseCallback). Callers list it in effect dependencies; when it was rebuilt on every call, the collection tree's reveal effect (useRevealActiveSelection) re-ran on every render and re-expanded a collection the user had just collapseduseFullCollectionRequests(collectionIds)- The same map over wholeRequestrows (GET /requests?collectionId=), for the column audit (useColumnAudit), which reads what each request sends. Mounted only by the audit's callers (the Data tab, the run dialog), so nothing fetches whole rows at launch. Its key,requests.fullListByCollection(id), sits under that collection'slistByCollectionkey, so every invalidation of the tree's list reaches it; a reorder therefore removes a moved request from every list its old collection has cached, not the first one a scan oflists()meetsuseRequestQuery(requestId)/requestDetailOptions(requestId)- One request by id (GET /requests/:id): what a request tab opens, what a restored tab and a design-run copy read on cold start, and what the tree's Duplicate copies (queryClient.fetchQuery(requestDetailOptions(id))inuseTreeCrud.ts). Never seeded from a list row - a summary is not the request. The detail route also never substitutes a default for a column over the field cap, where a full list row can (truncatedFields, #1485), so a copy made from it is the whole request. Only anApiErrorwithstatusCode === 404becomesRequestNotFoundError(test it withisRequestNotFound); a 5xx or an unreachable engine is rethrown untouched, because a transport failure must not read as "this request was deleted"useCollectionAncestors(collectionId)- The collection's ancestor chain including itself, root first, derived from the collections list rather than fetchedusePrefetchCollectionsAndRequests()- Warm-cache pass over every collection's requests at startup: oneGET /requests?fields=summaryfor the whole workspace (10.7 MB of whole rows on a 6,000-request workspace before #2546), split into each collection'slistByCollectionentry
Sorting: every tree list - roots, a collection's children, a collection's
requests - sorts with the single exported compareTreeOrder (types/domain.ts):
order, then kind (a sub-collection before a request), then createdAt, then
id byte-wise. There were two comparators with two different tie rules and
neither matched the engine's, so "run this folder" could execute in an order the
sidebar had never shown. The rule is pinned to the engine's comparator
(engine/include/vayu/db/sibling_order.hpp) by
engine/tests/fixtures/tree-order-conformance.json, read by
types/tree-order.conformance.test.ts and by the engine's tree_order_test.cpp
- change one side and the other suite fails.
A folder's sub-collections and its requests are one list in one order
space (#2535), so a request can sit between two folders. The kind is only a
tiebreak, and only a merged list states it: childrenOf
(modules/collections/tree-children.ts) builds a parent's children from the
collections list and the parent's request list, flattenVisibleRows lists each
expanded folder's children through the same merge (mergeSiblings), and the
drag, the keyboard move and "Move to…" all read that one list
(CollectionTree.sibling-order.test.tsx). A recursive collection run executes
the same sequence - a request where it sits, a sub-folder's whole subtree where
the sub-folder sits - which is pinned across the render and the engine's plan by
engine/tests/fixtures/recursive-run-order-conformance.json, read by
modules/collections/CollectionTree.run-order.conformance.test.tsx and by the
engine's scenario_plan_test.cpp (issues #431, #2535).
Mutations:
- useCreateCollectionMutation() - Create collection: appends the row to
the collections list and seeds the new collection's request list with [],
so the tree mounting it makes no list call and no other list refetches
- useUpdateCollectionMutation() - Update collection (with cache update,
storeUpdatedCollection). An update carrying specFile / dataFile goes
through writeFileBinding, behind the collection's earlier binding writes.
Invalidates every cached composition unless the update carries only
specFile / dataFile, which nothing composes against (#2765)
- useDataFileReadingMutation() - Change how a bound data file is read
(castNumbers, #2540) through rememberDataFileReading, the binding built
when the write is sent
- useDeleteCollectionMutation() - Soft-delete a collection into the trash
rather than removing it (issue #988); invalidates coarsely, see below, and
also invalidates the trash list so the Trash view picks it up, and the
running-mock list (mockServer.list()): the engine stops the mocks of the
subtree as part of the delete, whichever client sent it (#3449), so the app
sends no stop of its own and only refreshes what it shows. It writes no
file binding: the spec-file and data-file bindings stay on the trashed row
(#2765), the stores that mirror the list drop the entry with the row, and the
tree's Undo - a restore - brings them back with nothing captured
client-side (captureClientState in useTreeCrud.ts keeps only the focused
tab). Every mutation
that invalidates all the request lists does it through
invalidateAllRequestLists (queries/collections.ts): prefetch.allRequests()
before requests.all, so the per-collection lists that refetch join the one
GET /requests?fields=summary instead of each making a call of their own. It is used by this
mutation, useImportMutation, useBindSpecMutation, useSyncSpecMutation,
useRestoreTrashMutation and the MCP collection family
- useCreateRequestMutation() - Create request: appends the engine's row
to the tree's list, to the whole-row list only where one is cached, and
writes its detail
- useUpdateRequestMutation() - Update request (invalidates only the lists
that can have changed, see below)
- useDeleteRequestMutation() - Soft-delete a request into the trash (also
clears the response, and invalidates the trash list). Refetches only the
owner's list, read from the request's cached detail before it is removed and
from the list caches failing that; with no owner known it falls back to
invalidateAllRequestLists
- useReorderMutation() - Reposition collections and requests through
POST /reorder in one transaction, optimistically (see below)
- useImportMutation() (queries/import.ts) - Apply a parsed import through
POST /import/apply in one transaction. Resolves with
{ idMap, rootIds }: the engine's temp-id map, plus each root
collection's temp id mapped to its real id, which is
what lets the caller expand and open what it created
Reordering (useReorderMutation) is the one mutation that writes its caches
three times, because a drag is only believable if the row is where the pointer
left it before the write returns:
onMutatesnapshots every key the plan can touch and draws the plan into the caches - the same two steps the engine performs, normalize each named parent to0..n-1in sibling order, then position each move. A normalized parent spans two caches, its sub-collections in the collections list and its requests in its own list, renumbered as one run; both are snapshotted. A cross-collection move crosses list caches and updatesrequests.detail(which carriesstaleTime: Infinity, so a stalecollectionIdthere would outlive every refetch).onSuccessre-applies the rows the engine actually wrote, which the response carries. They are normally what was drawn, but a normalization is authoritative from the engine, so the tree settles on real positions rather than a guess.onErrorrestores the snapshots wholesale and reports throughuseToastStore.showToast, notreportFailed: the drop is rolled back, so no edit is unsaved, andreportFailedwould park the Dock on "Not saved" with nothing pending (a failure that is not an unsaved edit raises its own toast, persave-store.ts). The mutation owns this rather than its caller, so the gesture layer cannot forget it.onSettledinvalidates the affected keys once - the collections list only if a collection moved or a parent was normalized, and only the request lists the plan named or normalized.
Every write goes through setQueryData with a fresh array, never a mutation in
place: the map useMultipleCollectionRequests builds is compared by reference by
the reveal effect, so an in-place edit would move a row on screen that the tree
never notices. The plan itself comes from
modules/collections/reorder-math.ts - a pure module, node-tested, that turns
a parent's merged sibling list and a drop index into the minimal set of rows to
rewrite, each written as the kind it is.
Trash¶
The read side of the same soft delete (issue #989): useDeleteCollectionMutation,
useDeleteRequestMutation, useDeleteEnvironmentMutation (#2970),
useDeleteRequestExampleMutation (#2971, for a saved example) and
useDeleteClientCertificateMutation (#2973) stamp a row
rather than removing it, and these are how the app sees what got stamped
(queries/trash.ts).
useTrashQuery()- Every deleted root, newest first (GET /trash). NostaleTime: the list changes only through the two mutations below, the five delete mutations, and the startup retention purge, so the default is already the cheapest correct answer.useRestoreTrashMutation()- Put one deleted root back (POST /trash/:id/restore). Invalidatestrash.all,collections.alland every request list throughinvalidateAllRequestLists- the same coarse invalidationuseDeleteCollectionMutationdoes, and for the same reason (see the cascade delete note below) - plusenvironments.alland every composition (invalidateCompositions) andclientCertificates.all, whatever kind came back: a restored environment reappears in the Variables tree and its variables can resolve again, and a restored client certificate reappears in the Settings card (and is presented to its host again on the next send). A restore the engine refuses with a 409 - a live certificate has since claimed the same host and port - shows the engine's message, from the Trash view's Restore and from the delete toast's Undo alike. A restored example reappears in its request's Examples panel through the samerequests.allinvalidation:requests.examples(id)sits under it. It leavesactiveEnvironmentIdalone (see the session store above).usePurgeTrashMutation()- Destroy one deleted root for good (DELETE /trash/:id). Invalidates onlytrash.all: every other cache already stopped serving these rows when they were stamped, so purging them changes nothing a live read can see. The purged collection's file bindings go with its row, engine-side (#2765); nothing here holds a copy to clear.
Both mutations also invalidate trash.all on failure (#1438). The row
either acted on is one this list said existed, so the likeliest failure is that
it no longer does - an agent's purge_trash_entry or restore_trash_entry
landed between the drawer's last read and the click. Leaving the list alone
there keeps a phantom row on screen that fails the same way on every further
click; refetching either removes it or proves it real.
Environments & Variables¶
useEnvironmentsQuery()- Fetch all environmentsuseGlobalsQuery()- Fetch global variablesuseCookiesQuery()/useClearCookiesMutation()(queries/cookies.ts) - The engine's cookie jars, one per environment, read and cleared byCookiesCardin Settings. The mutation invalidates rather than patching the cache: a clear that raced a request in flight would otherwise leave the panel claiming an empty jar the engine has already refilleduseClientCertificatesQuery()and the create / update / delete mutations (queries/client-certificates.ts) - the engine's host-to-certificate registry for mTLS endpoints (issue #707), read and edited byClientCertificatesCardin Settings > Network & connectivity. The list's rows carryusableand, when false,problem(#3260): whether the engine would present the entry against the files as they are now, which only the list answers. The mutations invalidate rather than patching: the engine refuses a second entry for a host+port pair already taken, so the list is the authority on what a new entry may claim. The delete is soft (#2973): it also invalidatestrash.all, the card raises the shared "Moved to the Trash" toast with Undo throughuseTrashUndo(kindclientCertificate, read aloud as "client certificate"), and the Trash lists the entry by its target,hostorhost:portuseFileRootsQuery(),useAllowChosenFolderMutation()anduseDeleteFileRootMutation()(queries/file-roots.ts) - the folders a request-body file may be sent from without a per-file pick, read by Settings > Files, the binary body editor and the import preview. The list is a plainGET; both writes go through the main process, which holds the engine's grant secret (#2356): the allow mutation takes no argument - neither a folder nor a title nor where the picker opens (#2378) - and resolves with the engine's answer (cancelledincluded). An allow that lands invalidates rather than appending: the engine stores the canonical path, which can differ from the one picked
Mutations:
- useCreateEnvironmentMutation()
- useUpdateEnvironmentMutation()
- useSetActiveEnvironmentMutation() - The only writer of the active
environment; PUTs isActive and mirrors it into session-store, rolling the
store back if the engine refuses
- useDeleteEnvironmentMutation() - A soft delete into the Trash (#2970).
Patches the environment out of the list cache, removes its detail cache,
clears activeEnvironmentId when it was the active one, and invalidates
trash.all so an open Trash view lists it
- useUpdateGlobalsMutation()
Runs & History¶
useRunsQuery(q?, pinnedOnly?, origin?)- Run history as an infinite query over the paginatedGET /runs{data, pagination}envelope, newest first.fetchNextPagepages older runs in on demand, by keyset cursor (#2978): the first page carries no cursor, and each next page is asked forbefore=<the previous page's pagination.nextBefore>, the engine's own value rather than one derived from the rows, with nooffset. A cursor page costs the same at any depth and does not shift when a run starts between two pages;nextBefore: nullends the paging.qis the optional server-side search;origin("app"or"mcp",undefinedfor all) isGET /runs?origin=.- Polling is gated to the unpaged state (
runsPollInterval): 5s while only page 1 is loaded, off once the user has paged older runs in. Refetching an infinite query re-fetches every loaded page in sequence, so a user ten pages deep drove ~10 engine requests per tick. Only page 1 can gain rows (start_time DESC) anyway; a paged list refreshes on the next mutation or invalidation instead of on a timer. - Only a surface that renders runs mounts it. The interval belongs to the
hook, so it runs for as long as any observer is mounted - and the App root
used to be one, which kept the poll alive with History closed, nothing
running and nothing at the root reading the result (#1150). The root now
calls
usePrefetchRuns()instead: oneprefetchInfiniteQueryoverrunsListInfiniteOptions(), which warms the same cache entry without observing it.HistoryList,WelcomeScreenand the palette'suseEntityItemsobserve the key while they are visible and drive the cadence themselves. runsListInfiniteOptions(q?, pinnedOnly?, origin?)- the key, fetcher and page params (the cursor,string | undefined), shared by the hook and the warm-up so the entry one writes is the entry the other reads.originjoins the key only when set, so the unfiltered list stays the entry the warm-up and the other observers share.prefetchInfiniteQuery, notprefetchQuery: the readers are infinite queries and the cache entry has to be inInfiniteDatashape.flattenRunPages(data)- flatten the pages into a de-dupedRun[](a refetch walks the pages in order and reads each cursor off the page it just fetched, so pages abut and a run cannot sit in two; dedupe by id is the cheap guard that keeps a doubled row out regardless).runsTotal(data)- the server's total from the first page.useRunsCountQuery()- How many runs are stored, for Settings' "N stored runs": onelimit=1read of the list envelope, answering itspagination.total, so opening Settings costs one request and one row however long the history is (#2979). Not polled. Clear run history does not read rows either: when it is pressed it askslimit=1counts for the pinned baselines and the running / pending runs (baseline=true, andbaseline=falsewith eachstatus), which is all its dialog needs to say what goes and what is kept. Thecount()key sits outsideruns.lists(), because it caches a bare number and the delete patch walks that prefix asInfiniteData.useLastDesignRunQuery(requestId)- The most recent completed design run for a request, in one filtered call (?requestId=&type=design&status=completed&limit=1) - the server sortsstart_time DESC, so its single row is the answer. No client-side download-and-filter. It caches a plainRunListResponse, so it has its own key family (queryKeys.runs.lastDesign(requestId)) and deliberately does not sit underruns.lists():RequestBuilderProvidermounts it for every open request tab, and the delete-run patch walks that prefix asInfiniteData. Keeping the two shapes apart at the root is the rule - a prefix patch must never meet a cache shape it did not write. Under thelastDesigns()prefix, like the three families below it, so a delete, a cleared history or an MCPrunevent reaches it without knowing which request it belonged to (#776): a run id gives no way back to one, and until the prefix existed a deleted design run went on being restored into the tab that had it open.useRecentDesignRunsQuery(requestId)- The lastRECENT_DESIGN_RUN_LIMIT(5) design runs of a request, newest first, behind the context bar's Recent sends section. One filtered call (?requestId=&type=design&limit=5) and no report fetch: each row carries its ownresultSummary(statusCode+latencyMs) from the engine, and the report path would load and JSON-parse every result'strace_data, per row. Deliberately unfiltered by status, unlikeuseLastDesignRunQuery-statustakes one value, so filtering tocompletedwould hide every failed send, which is most of what a trend is read for. Own key family (queryKeys.runs.recentDesign(requestId)) under therecentDesigns()prefix, outsideruns.lists(), for the same shape reason aslastDesign. Not polled: the builder's send path,DesignRunView's replay, the MCPrunevent,useDeleteRunMutationanduseInvalidateRuns(Settings' Clear run history) each invalidate it, and a new run-writing path has to as well or the section keeps showing the sends from before it.useLastCollectionRunQuery(collectionId)- The most recent run of one collection, behind the context bar's Last run section. One filtered call (?collectionId=&limit=1) over the engine'scollectionIdfilter, which matches a scenario snapshot's ownscenario.collectionIdas JSON rather than its text - the lookup that did not exist, which is why the section was deferred twice (#377 → PR #394 → PR #400 → #422). Unfiltered by status for the same reasonuseRecentDesignRunsQueryis: a failed run is the one worth surfacing. Own key family (queryKeys.runs.lastCollectionRun(collectionId)) under thelastCollectionRuns()prefix, outsideruns.lists(), for the third time and the same shape reason. Invalidated byuseStartScenarioRunMutation(the new run is the last run),useDeleteRunMutationanduseInvalidateRuns.useRunQuery(runId)/runDetailOptions(runId)- Fetch a single run (fullconfigSnapshot). Same 404 contract asrequestDetailOptions: only anApiErrorwithstatusCode === 404becomesRunNotFoundError(test it withisRunNotFound, never by message), and that error is never retried - a run tab is persisted and outlives its run, so a deleted run used to retry forever behind a "Try again" that could not work. Everything else - a 5xx, an unreachable engine - is rethrown untouched and keeps the default retry budget.HistoryDetailrenders the two cases differently: "this run no longer exists" with Close tab, versus "couldn't load this run" with Try again. The options carry a function-formrefetchIntervalthat polls (3s) only while the cached run's status isrunningorpending: this object is spread into every open tab's query bytab-descriptors, and a run opened mid-run (from another window, an agent or a relaunch) has nothing else that tells it the run ended (#1934).-
useRunReportQuery(runId, status?)- Fetch a run's report. The engine answers the report endpoint for a live run too, so a copy is final only when the run is. Pass the run'sstatuswhen it is known:runningorpending(isRunInProgress,lib/run-status.ts) makes the reportstaleTime: 0and re-read every 3s; any other status, or none, keepsRUNS_STALE_TIME_MSand no timer. Also written byLoadTestServiceat stream end viaqueryClient.fetchQuerywithstaleTime: 0- the one fetch that knows the data just changed, so it must not resolve from a mid-run copy a History tab cached (#1934). The service then invalidatesruns.detail,runs.report,runs.timeSeriesandruns.monitorSeriesfor the run, so a mounted tab refetches in place and one opened later finds stale entries. A stream that dropped while the run was still going invalidates the report alone: nothing ended, so the status and series are still current. -
useRunTimeSeriesQuery(runId, status?)(@/queries/runs) - The stored series behind the History charts, in one request:GET /runs/:id/metrics?maxPoints=HISTORY_SERIES_MAX_POINTS(2,000,config/network.ts). A run with at most that many ticks comes back raw; a longer one comes back folded into buckets, withbucketed: trueandticksPerBucketon the envelope (#2547), which the Performance tab's charts state in a note. It is a plain query, never paged: a 24 h soak used to be 18 pages of raw ticks. Keyedruns.timeSeriesDownsampled(id, maxPoints), under theruns.timeSeries(id)prefix the run-scoped invalidation and removal use. A finished run's ticks cannot change, sostaleTime: Infinity; with an in-progressstatusthe ticks written so far are stale at once.gcTimeis the shortRUN_SERIES_GC_TIME_MS(1m): the entry is small and one request to read again. Not polled; the live ticks have the dashboard's stream. useRunMonitorSeriesQuery(runId, enabled, status?)(@/queries/runs) - The server vitals scraped during the run, in one request the same way:GET /runs/:id/monitor?maxPoints=HISTORY_SERIES_MAX_POINTS(#2611). A run with at most 2,000 scrapes comes back raw; a longer one is folded into buckets (each series the bucket's max, the timestamp its last scrape's) withbucketed: trueandticksPerBucket, which the Server vitals card states in its own note, apart from the tick series' note. A plain query keyedruns.monitorSeriesDownsampled(id, maxPoints), under theruns.monitorSeries(id)prefix the run-scoped invalidation and removal use, with the time series' staleness andRUN_SERIES_GC_TIME_MS.enabledis the report'smonitor.samples > 0, so a run that scraped nothing issues no request. A failed read is amonitorFailurewhose Try again refetches it; nothing requests it again on its own.
Mutations:
- Stopping a run is not a mutation hook. It is
useEngine().stopLoadTest(runId), which calls apiService.stopRun and
returns a boolean rather than throwing - the dashboard's Stop button reports
the refusal itself.
- useDeleteRunMutation() - Delete a run. Patches every infinite-list cache
variant in place (drops the row, decrements the mirrored total), invalidates
the stored-run count, and evicts the run's report. The list updater shape-guards
(!Array.isArray(old.pages)) as a belt to lastDesign's braces. The
recentDesigns() and lastCollectionRuns() families are invalidated rather
than patched: a deleted run gives no way back to the request or collection
their sections are keyed by, and refetching a few rows beats carrying a
run-to-owner map to patch them.
Deleting a run closes its tabs. Both delete flows - HistoryList's row
delete and Settings' Clear run history - call
closeTabsForEntities(ids, "run") for the runs the engine actually removed. For
the row delete that is the run it named, unless the call was refused (a 409'd run
keeps its tab, because the run is still there); for Clear run history it is the
deletedIds that DELETE /runs answers with, so a pinned baseline or a run still
in flight keeps its tab (#2429). Tabs are persisted, so
a run tab left open after its run is gone is not merely stale: it rehydrates
into a pane that can never load on every restart.
Engine Health, Config & OAuth¶
useHealthQuery()- Health check, polled everyTIMING.HEALTH_CHECK_INTERVAL_MS; it is what setsengineStatus/engineErroronengine-store, and is where the starting-vs-unreachable decision gets made, so the connection indicator follows it. It reads that decision offengineStartWindow, whichuseEngineRestartalso opens - the restart supplies the evidence, the poll still does the classifyinguseConfigQuery()/useUpdateConfigMutation()- Engine configuration (QUERY_CACHE.CONFIG_STALE_TIME_MS); also the home of the live chart window, which is engine config rather than a renderer preferenceuseScriptCompletionsQuery()/useScriptTypeDefinitionsQuery()- thepm.*completion list and the engine-generated.d.tsbehind Monaco's hover text and diagnostics. Both derive from one engine-side table that changes only with the engine binary, so both takeQUERY_CACHE.SCRIPT_COMPLETIONS_STALE_TIME_MSand the same gc time; the type definitions also cap retries atSCRIPT_COMPLETIONS_RETRY, since losing them costs hover text rather than the editoruseOAuth2TokenStatusQuery(cacheKey),useFetchOAuth2TokenMutation(),useClearOAuth2TokenMutation()- the engine-side OAuth 2.0 token cachequeryKeys.compose.forRequest(requestId, environmentId, source)-POST /composefor a request, behindcompositionOptions(code-composition.ts), which the context bar's Code section, the Params tab's "Sends" line and the tab strip all build their query from, so they share one entry (#2741). The Code section fetches it on expand. The Sends line fetches it only for a URL, path row or query-placed API key or OAuth 2.0 token name, or GraphQL GET document, holding a{{token}}(default mount behaviour, so a tab switch back is a cache hit), for thedeferredVariablesit needs.RequestBuilderProviderreads it too, once per builder and only while the request holds a{{token}}anywhere (requestHasTokens), so the token painters can leave those names unpainted as resolved. A builder holding such a request therefore asks/composewhen it opens and again after each invalidation (every autosave), where before only an open Code section did - a deliberate cost of painting deferred tokens (#2741). The strip only reads it: a disabled observer per request tab, editor entry first, never a fetch. Keyed by environment as well as request, because the same request composes differently per environment and one key for both would serve the wrong snippet after a switch.sourceis"editor"while the mounted request builder publishes that request's draft (theeditorDraftlive surface, #2638) and"saved"otherwise: the query function composes the draft inline throughbuildComposeBody, as Send does, or the stored row by id, so a builder taking the request on is a new key and a fresh compose rather than the saved row's answer kept understaleTime: Infinity. The draft is read when the query runs, never subscribed, so the key does not move per keystroke; the autosave PUT's invalidation below reruns the same function, which reads the draft again.staleTime: Infinitywith an explicit recompose: the section is only mounted while expanded, so this is the "compose on expand, not per keystroke" rule. The section also ships collapsed by default (CONTEXT_BAR_DEFAULT_COLLAPSED), so that round trip now happens on first expansion rather than on every request tab opened (#1310).queryKeys.compose.allForRequest(requestId)is the per-request invalidation root, andforRequestis built from it rather than beside it so the prefix relationship holds by construction - that is the key a write to one request drops, the renderer's own PUT (useUpdateRequestMutation) and an MCP one alike (#1438, #1877). Both reach it through one helper,invalidateCompositions(queryClient, requestId?)inqueries/compose-invalidation.ts, the only place outsidekeys.tsthat names a compose key; without arequestIdit dropscompose.all, which is what the environment, globals and collection PUTs and their MCP counterparts take.staleTime: Infinitydoes not stand in its way: it gates the cost of composing, not the correctness, becauseinvalidateQueriesrefetches a mounted observer whatever itsstaleTime
Query Keys & Cache Invalidation¶
Centralized in app/src/queries/keys.ts, using TanStack Query's hierarchical key
factory pattern. Copy the shapes from that file rather than hand-writing a
key - a key that differs by one segment is not an error, it is a silent cache
miss that presents as a data bug:
// app/src/queries/keys.ts (abridged)
collections: {
all: ["collections"], // a constant, not a call
lists: () => ["collections", "list"],
list: () => ["collections", "list"],
details: () => ["collections", "detail"],
detail: (id) => ["collections", "detail", id],
},
requests: {
all: ["requests"],
lists: () => ["requests", "list"],
listByCollection: (collectionId) => ["requests", "list", { collectionId }], // RequestSummary[]
fullListByCollection: (collectionId) => ["requests", "list", { collectionId }, "full"], // Request[], the column audit's
details: () => ["requests", "detail"],
detail: (id) => ["requests", "detail", id],
examples: (id) => ["requests", "detail", id, "examples"], // saved example responses (#481)
},
trash: {
all: ["trash"],
list: () => ["trash", "list"], // no per-entry detail cache - the list is the only read
},
runs: {
all: ["runs"],
lists: () => ["runs", "list"],
list: (filters = {}) => ["runs", "list", filters], // keyed by its server-side filters (q, baseline, origin, type, status)
lastDesigns: () => ["runs", "lastDesign"], // prefix: invalidate every request's last run
lastDesign: (requestId) => ["runs", "lastDesign", requestId],
recentDesigns: () => ["runs", "recentDesign"], // prefix: invalidate every request's list
recentDesign: (requestId) => ["runs", "recentDesign", requestId],
lastCollectionRuns: () => ["runs", "lastCollectionRun"], // prefix: invalidate every collection's row
lastCollectionRun: (collectionId) => ["runs", "lastCollectionRun", collectionId],
baselines: () => ["runs", "baseline"], // prefix: invalidate every request's and collection's pin
baseline: (requestId) => ["runs", "baseline", requestId],
collectionBaseline: (collectionId) => ["runs", "baseline", "collection", collectionId],
requestRuns: () => ["runs", "requestRun"], // prefix: invalidate every request's and collection's compare picker
requestRun: (requestId) => ["runs", "requestRun", requestId],
collectionRun: (collectionId) => ["runs", "requestRun", "collection", collectionId],
count: () => ["runs", "count"], // Settings' stored-run count, a bare number
detail: (id) => ["runs", "detail", id],
report: (id) => ["runs", "report", id],
timeSeries: (id) => ["runs", "timeSeries", id], // prefix: every read of the run's tick series
timeSeriesDownsampled: (id, maxPoints) => ["runs", "timeSeries", id, { maxPoints }], // the History charts' one read
monitorSeries: (id) => ["runs", "monitorSeries", id], // prefix: scraped server vitals, when the run had a monitor
monitorSeriesDownsampled: (id, maxPoints) => ["runs", "monitorSeries", id, { maxPoints }], // the History charts' one read
samples: (id) => ["runs", "samples", id], // captured response bodies, fetched lazily
},
// environments mirrors collections; globals / cookies / health / config /
// scriptCompletions / scriptTypes / oauth / prefetch each own a root.
The lists() / details() levels exist to be invalidated as prefixes; what a
query is keyed on is list() / detail(id). requests.examples(id) sits
under detail(id) rather than beside it, because examples are owned by the
request: invalidating one request's subtree drops its examples with it, which is
what a request delete needs, and what a restored example needs, since
requests.all reaches it by prefix (#2971). runs.lastDesign,
runs.recentDesign, runs.lastCollectionRun, runs.baseline and
runs.requestRun (and the collectionBaseline / collectionRun keys beside
them) sit under runs.all but deliberately not under runs.lists() - see below.
runs.baseline(requestId) caches the run pinned as that request's (or collection's) baseline
(GET /runs?baseline=true&requestId=&limit=1), which the history report's
vs-baseline strip reads. A collection load run has no requestId, so its pin is
cached under runs.collectionBaseline(collectionId)
(GET /runs?baseline=true&type=load&collectionId=&limit=1), a segment of its own
inside the same baselines() prefix, so no id can read as the other kind and
every invalidation below reaches both. Which key a run uses is
runIdentity(run) (lib/run-reference-input.ts: requestId, else the scenario
collectionId), and usePinnedBaseline and RunComparisonView look the pin up
by the same identity. Pinning, unpinning and deleting a run all invalidate
the baselines() prefix rather than patching it: the pin moves, and a run id
gives no way back to the request whose baseline it was - a run of an unsaved
request has no requestId at all. The pin flag on the loaded list rows is
patched in place from the mutation's response, the same way a delete patches
them, because the sidebar polls only its first page and a refetch would leave a
pin invisible on any page the user had scrolled to.
runs.requestRun(requestId) caches the load runs of one request
(useRequestRunsQuery: GET /runs?requestId=&type=load&limit=50, newest first),
which the History compare view's run picker and the run trend read. A collection
load run's list is runs.collectionRun(collectionId)
(GET /runs?collectionId=&type=load&limit=50), under the same requestRuns()
prefix. A plain RunListResponse, so
its own family for the sixth time and the same shape reason as the five above it,
and under the requestRuns() prefix that a delete, a pin, a cleared history
(useInvalidateRuns) and an MCP run event all invalidate. The query returns
the rows whole: which are comparable (completed or stopped, never the open run)
is comparableRuns's rule, and the pinned baseline is added to the picker even
when it is older than the page, because that is what a pin is for.
specs.detail(id) and specs.meta(id) are the same document under two keys
(issue #712): the full read carries content and both extracted indexes, the
meta read describes the row and nothing else. They are kept apart rather than
merged so a cached description can never satisfy a reader that needs the text -
and holding one row twice is safe here precisely because a document is immutable,
which is also why both carry staleTime: Infinity. The Spec tab's card reads
meta; the import dialog's bound-spec match and the Sync section's Check read the
full document, each on the action that needs it. Export reads neither since it
moved engine-side (issue #855) - specs.export(collectionId, format, opened)
holds the finished document instead, keyed by format because the dialog toggles
between two serializations of one answer, and by the moment the dialog mounted
because a collection changes under its id in a way a document never does:
that is what makes it fresh on every open and cached across a toggle, which
neither staleTime alone can say. A key per format also means a switch is a
cache miss, so this read carries placeholderData:
keepPreviousData (issue #1311): the counts the dialog prints belong to the
collection rather than to the serialization, and are the same either way, so
the previous answer is the honest thing to hold while the next one assembles.
The dialog gates Copy and Download on isFetching for that window - the text
under them is still the previous format's - and shows a placeholder shaped like
its summary card on the first read, when there is nothing to keep.
exports.postman(collectionId, includeSecrets, opened) is the same read for the
Postman Collection v2.1 export (usePostmanExportQuery in queries/exports.ts),
on the same terms: keyed by the dialog's one toggle and by the moment it mounted,
with placeholderData: keepPreviousData so the summary stays while the other
answer assembles. It is not under specs because a Postman document reads no
binding.
The run report export (useRunReportExport in queries/exports.ts, issue
2127) is a mutation and has no key: a click asks again, the answer is¶
downloaded the moment it arrives, and its generatedAt makes every document a
new one, so there is nothing a cache could serve.
specs.match(collectionId, fingerprint) is the third of that family and the one
that names no document (issue #761): the pairing of a collection's requests
against a picked document's operations, answered by POST /specs/match since
the matcher moved engine-side. There is no id to key it by - the document has
not been stored, because the tab asks before the user commits to the bind - so
the key carries a fingerprint of both inputs, exactly the fields the matcher
reads off them (a request's id, method and URL; an operation's identity; the
document's server base paths, issue #3030). That
is what makes its staleTime: Infinity honest: an answer cannot go stale while
both inputs are pinned in its key, and either of them changing is a different
key rather than a stale entry under this one.
Automatic Invalidation:
- Mutations automatically invalidate related queries (e.g., creating a request invalidates the collection's request list)
- Some mutations use optimistic updates and cache updates for instant UI feedback
- A cascade delete invalidates coarsely, on purpose. Deleting a collection
deletes its descendant collections and all their requests engine-side, and
which rows those are is engine-side knowledge - a client that re-derives the
subtree to patch caches surgically will drift from the engine's definition of
"descendant". So useDeleteCollectionMutation invalidates
collections.all + requests.all wholesale. requests.detail entries carry
staleTime: Infinity, so without this a deleted request stays fresh forever
and keeps feeding restored tabs. useRestoreTrashMutation invalidates the
same two families for the same reason, in the other direction: which rows a
restore brought back is just as much engine-side knowledge - the cohort is
defined by a timestamp the client never sees - so it takes the same wholesale
invalidation rather than a client guess at which requests came back with a
restored collection.
- A single-request update invalidates narrowly, for the same reason. Which
lists a request write can affect is client-side knowledge: the request's own
collection, plus the one it left if the write was a move. So
useUpdateRequestMutation invalidates requests.listByCollection(id) per
affected collection rather than requests.lists(). It used to refetch every
collection's list on any rename, which a reorder (a run of sibling PUTs) turns
into one full-tree refetch per row. The source collection of a move is read
from the requests.detail cache, which still holds the pre-update row at that
point - the response carries only the new owner.
- The warm-cache prefetch is a query too. usePrefetchCollectionsAndRequests
is keyed as queryKeys.prefetch.allRequests() rather than an inline key, so a
write that can change any collection's requests re-runs it as one call
(invalidateAllRequestLists). Creating a collection does not: a new
collection holds no requests, so its list is seeded empty instead (#2546).
- ...but warming a polled list must not be a query. usePrefetchRuns is a
one-shot prefetchInfiniteQuery on mount, not an observer, because
useRunsQuery carries a refetchInterval and observing it from the root
bought the warm cache at the price of a poll that never stopped (#1150). An
invalidation of runs.lists() then marks the warm entry stale without
refetching it, which is the wanted behaviour: nothing is displaying it.
Writes from outside the renderer: mcp:data-changed. An MCP tool call
mutates the engine from the Electron main process, so no mutation runs here
and no query notices - and with refetchOnWindowFocus: false (below) nothing
ever catches up on its own. A request an agent created stayed invisible in the
collection tree until some unrelated renderer mutation happened to invalidate
the lists. The main process now sends one event per data family a successful
call touched; useMcpDataInvalidation() (registered once, in App.tsx) maps it
to keys through lib/mcp-invalidation.ts:
| Entity | Invalidates | Why that key |
|---|---|---|
collection |
collections.all, requests.all, trash.all, mockServer.list(), compose.all, prefetch.allRequests() |
Declared by the writes that can reach any collection's requests: delete_collection, move_item, import_document, bind_spec, sync_spec, restore_trash_entry and purge_trash_entry (the two trash tools declare request, environment and clientCertificate too). A delete_collection cascades through descendants and their requests, and which rows those were is engine-side knowledge - the same reason useDeleteCollectionMutation invalidates coarsely. The event's collectionId is not read: each tool names a different collection by it (the one deleted, a move's destination, a spec's binder), and none changes that collection's list alone. trash.all because a delete is what adds a row the drawer lists and a restore or purge is what takes one away; mockServer.list() because the engine stops the mocks of a deleted collection and its descendants as part of the delete (#3449), so the Dock's and the Services drawer's running-mock list must refetch rather than show a mock that is gone; compose.all because a collection write moves the chain every descendant inherits auth, headers and scripts from, and this event carries no way to name them; prefetch.allRequests() ahead of requests.all (invalidateAllRequestLists), so the mounted lists join one GET /requests rather than each fetching (#1438) |
collectionRow |
collections.all, compose.all |
Declared by create_collection, update_collection and unbind_spec, which write one collection row and nothing beneath it: a new collection holds no requests, an update cannot reach a trashed row, and an unbind leaves the requests' operation stamps in place. So no request list, trash row or warm-cache pass is read - an agent renaming 50 collections refetches the collections 50 times and the workspace's request lists not at all. The two reads are the ones useUpdateCollectionMutation refreshes (#2546) |
request |
requests.listByCollection(collectionId), or requests.lists() when the call named no collection, trash.all, plus requests.detail(requestId) and compose.allForRequest(requestId) when the call named one row |
The same narrowing useUpdateRequestMutation does; without a named owner the owner is unknowable here. The detail key is for update_request / delete_request: it is staleTime: Infinity, so a restored tab would otherwise keep serving the copy it read on open, and it is also the prefix the request's examples list sits under, so delete_request_example reaches an open Examples panel through it. trash.all because delete_request and delete_request_example (a saved example goes to the Trash since #2971) declare this family alone and stamp a row the drawer lists. The compose key is the per-request prefix, not compose.all: every tool that can change a composition either names the row it wrote or declares collection too, create_request composes nothing yet, and invalidateQueries refetches a mounted observer whatever its staleTime - so the wide key would re-compose an open snippet once per write in an agent's loop over rows it never touched. Every compose cell in this table is invalidateCompositions, the helper the renderer's own PUTs call. prefetch.allRequests() is deliberately not here for the same reason: it is one workspace-wide GET /requests?fields=summary, too costly to repeat per row, and this is the family an agent loops over row by row (#1438) |
environment |
environments.all, globals.all, trash.all, compose.all |
Variables are read through the detail cache as well as the list; POST /compose substitutes those same variables, and a composition refetches only when told to, so invalidateCompositions is what useUpdateEnvironmentMutation and useUpdateGlobalsMutation call too (#1877). globals.all rides along because update_globals (#758) declares this family - same resolution order, same blob shape, and an entity of its own would have had exactly one reader. trash.all because delete_environment declares this family alone and, since #2970, stamps a row the drawer lists; restore_trash_entry and purge_trash_entry declare it beside collection and request, so a restored environment reappears in the Variables tree. An update_environment pays a refetch of the trash list while the drawer is open - the trade the request family takes |
run |
runs.lists(), runs.count(), runs.baselines(), runs.requestRuns(), runs.recentDesigns(), runs.lastCollectionRuns(), runs.lastDesigns() - and a removal of runs.detail/report/samples/timeSeries/monitorSeries for a named runId |
The history list polls, but Settings' count, the vs-baseline strip, Recent sends, Last run and every open tab's last design run do not. The five prefixes rather than per-row keys because a run id gives no way back to the request or collection it belonged to - the same trade useDeleteRunMutation makes |
cookie |
cookies.all |
One key for every jar - the engine reports them together |
config |
config.all, requestDefaults.all |
requestDefaults is a second endpoint over the same entries rather than a slice of the first: five of them (negotiateCompression, loadNegotiateCompression, sendExpectContinue, correlationIdEnabled, correlationIdHeader) decide what a send adds on its own and the engine resolves the answer, so the declared set is re-read rather than derived here - which is why useUpdateConfigMutation drops both keys. At the root, because design and load are separate cache entries and one write can move both (#1438) |
service |
inbox.list(), mockServer.list(), mockIssuer.list(), plus a removal of inbox.captures(inboxId) for a named inbox and of mockServer.routes(mockId) for a named mock |
The drawer and the Dock's count poll, so the lists are about immediacy; the captures cannot be invalidated, because useInboxCapturesQuery merges its fetched page into the cache and would union back the rows a clear_inbox_captures just destroyed, and a stopped mock's route table has no id left to refetch from |
clientCertificate |
clientCertificates.all |
The registry the Settings card lists, which reads live entries only. No MCP tool writes it - an entry is added and removed by the user - so the only declarers are restore_trash_entry and purge_trash_entry: a restored certificate must reappear in an open card. Its own family rather than a fold into config (whose invalidator also refetches every config and request-default read) or environment; trash.all is not repeated because collection, declared beside it, already takes it (#2973) |
oauth |
oauth.all |
The whole prefix, not the one key: useOAuth2TokenStatusQuery is keyed per cache key, and the key a fetch_oauth2_token writes under is derived engine-side and appears only in the answer, so the event carries no hint to narrow by. The query polls at 30s on its own, so this is immediacy - an agent that clears a token must not leave the row saying it is valid |
variables |
environments.all, globals.all, collections.all, compose.all |
The design-mode runners (run_request, run_collection_smoke, run_collection) persist variables a script or extractor set, and the event cannot say which of environment, globals or collection moved. The first three are the reads the renderer's own Send invalidates after the same write; compose.all for the reason environment gives. Not the coarse collection family: a variable write changes no request row and adds nothing to Trash, so requests.all, trash.all and prefetch.allRequests() would only cost a refetch per send in an agent's loop (#1916) |
The event carries no engine data, only which family went stale, so a row still
reaches the UI by exactly one path: the query layer. Per-run reports and time
series are still never invalidated wholesale - a new run cannot have changed
an existing run's report, and those are the expensive fetches in the family.
They are dropped only for the one run a call named: stop_run,
set_run_baseline and delete_run each take a runId, and the event carries
it as a third scope hint. Removal rather than invalidation, because samples
and both series are staleTime: Infinity - a deleted run would otherwise go on
rendering under an open History tab until its entry was garbage collected.
runs.detail goes with them so the pane refetches, takes its 404 and shows
HistoryDetail's "This run no longer exists" state instead of a run the sidebar
no longer lists. The hint says which run changed, not how, so a set_run_baseline
costs an open detail pane one refetch of data it already had; a stale answer is
a lie and a refetch is a wait. runs.lastDesigns() is taken at its prefix and
never per request (#776): delete_run and set_run_baseline name a runId and
no request, so the narrow key could not reach the tab whose run went away, and
the cost of the prefix is that a run_request refetches one filtered row per
mounted tab instead of one. The service family (issues #756, #757) takes the
same shape one level down, with two scope hints instead of one. inboxId: a
named inbox has its capture list removed rather than invalidated for a reason
the run family does not have - three writers share that one cache entry (the
fetch, the load-more pages and the live SSE stream), so every write to it is a
union by capture id, and a refetch into a cache still holding cleared rows puts
them straight back. The app's own clear mutation writes an empty page first for
exactly this; from the main process the equivalent is to drop the entry.
mockId: a named mock has its route table removed for the mirror reason - the
table is a start-time snapshot held at staleTime: Infinity, so an invalidation
would not refetch it, and after a stop_mock_server there is nothing to refetch
from, since a mock's record dies with its listener. Both are what
useDeleteInboxMutation and useStopMockServerMutation already do app-side.
All three lists are invalidated on every service event rather than one per
kind, because the entity is deliberately one family: the drawer and the Dock's
count ask "what is listening", not "which kind".
One field on that event is not about the cache at all. startedRun rides
the run event of start_load_run and run_collection and names the run those
tools just created, plus which of the two run services owns its stream
({runId, kind}, issue #1419). useRunWatchers() - registered once in
App.tsx, beside useMcpDataInvalidation() - reads it and calls
loadTestService.startMonitoring or scenarioRunService.startMonitoring, which
is the same path the dashboard and the Run Collection dialog take, so the wake
lock, the OS progress bar and the finished notification all begin when an
agent's run does rather than when someone opens its tab. A load run is adopted
only while canStartLoadRun() allows a run to start (#3351, #3381), and so is a
collection run. While another run holds the stream the hook attaches nothing for
either kind, leaving the dashboard, the stream and the user's run alone, and shows
an info toast ("An agent started a run in the background and it will be in History
when it finishes.") whose View run opens the agent's run; the run executes
unwatched and its row converges on the runs poll. Once
adopted, it
points dashboard-store at the run first, exactly as those surfaces do:
startMonitoring states that its caller has registered the run, and a store
left unpointed would collect the ticks of a run it does not name. The event
carries no config, so the hook then reads the run's row (GET /runs/:id) and
hands its configSnapshot to setRunConfig (issue #1935): the mode, duration,
rate, concurrency and ramp the dashboard's cards and the keep-awake prompt read,
and the method and URL it shows, mapped by lib/run-config-snapshot.ts.
setRunConfig sets those two fields and nothing else - startRun would clear
the ticks already gathered - and, being addressed to the run like every writer
but startRun, it is dropped if another run has taken the dashboard by the
time the row arrives. A row that cannot be read is
swallowed, never streamLost, which would raise the lost-stream callout over a
stream that is fine; the dashboard then keeps its config-less look. Every other run
event names a run that already exists (a stop, a baseline change, a delete) and
starts no watcher; run_collection_smoke sends its requests one at a time and
has no run to watch at all.
The entity list is duplicated across the process boundary
(MCP_DATA_ENTITIES in electron/mcp/tools/contract.ts, McpDataEntity in
types/domain.ts) because production code under electron/ cannot import from
app/src; data-changed.conformance.test.ts is what keeps the copies equal,
and the map above is a Record over the union so a new family fails to compile
until it names a reader. The emitting side is documented in
docs/engine/mcp.md.
Writes from any client: the engine's change feed. mcp:data-changed covers
only the MCP server the app itself hosts. The stdio MCP CLI, vayu-cli, a
script against the engine API and a second window write the same rows with no
channel to this renderer, so an open request kept the version it had read
until a reload, and Send sent it (#3420). The engine publishes one event per
committed write of a collection, a request, an example, an environment, the
globals or a trash entry on GET /changes (see
the API reference), and
services/change-feed-service.ts holds that stream for the app's life;
useChangeFeed(), beside useMcpDataInvalidation() in App.tsx, opens it
while the engine store says connected and closes it otherwise.
lib/change-feed-invalidation.ts maps each event onto the families in the
table above, so there is one key table for both producers:
| Kind | Families | Why |
|---|---|---|
collection |
collectionRow for a create or update; collection for every other op, one this build does not know included |
A delete, restore or purge is one event on the root for the whole subtree, which is the cascade collection takes coarsely |
request |
request, with the event's collectionId and the request's id, once more with the collection the cache still holds it in when that differs |
A move's event names only the destination; the source is read from the request's detail entry, then the tree's lists, when the event arrives (ownerOfRequest). An owner the cache never saw is in no list on screen |
example |
request named by the example's requestId, narrowed the same way |
What the MCP example tools declare: the Examples list sits under the request's detail key, and the family takes the Trash list |
environment, globals |
environment |
Globals ride on the environment family (#758) |
clientCertificate |
clientCertificate, and trash.all |
The feed carries only a certificate's delete, restore and purge, and no MCP tool declares this family alone, so its invalidator leaves the Trash list to collection; here nothing else would refetch it |
A kind this build does not know is passed over (its id still moves the resume
point), and so is a frame that does not parse. A reset (a resume the engine's
ring no longer covers, an id from an engine process that has since restarted,
or a reader that fell a whole ring behind) invalidates collection,
environment and clientCertificate together, which between them reach every
read a single event can. A resume's ready invalidates nothing, because the
missed events follow it. A fresh subscription's ready (the first stream of the
app's life, opened with no resume point) follows the launch's reads, so a write
another client committed between the two is never reported; it re-reads what
the open tabs show instead (invalidateOpenRows): requests.details() and
compose.all, the two staleTime: Infinity reads a restored tab and Send
depend on, and collections.lists(), environments.all and globals.all,
what an open collection or environment tab reads. Each is one call, and only an
observed entry is refetched; the rest are marked stale for their next mount.
The request lists are left alone: the workspace-wide GET /requests is the
launch's heaviest call, and the tree reads a name and a method from it, never
what Send sends.
The feed reports the app's own writes too, so invalidations are coalesced and
held. FeedInvalidationBatch collects a burst into one invalidation per
family and collection over CHANGE_FEED_COALESCE_MS (200ms), fixed from the
first event rather than restarted by each. A request event contributes a
collection-scoped request family, which carries no row id and so dedupes (one
list read and one Trash read per collection however many rows a reorder wrote,
3448), plus the row's own detail and compositions, which are never coalesced¶
away. So a bulk import is one flush and a client
writing without pause is still shown every 200ms. A flush waits while
queryClient.isMutating() is above zero: the autosave PUT's echo then
refetches after the PUT's own answer is in the detail cache, where structural
sharing makes the refetch a no-op for the open tab, and an event arriving while
a reorder is in flight cannot refetch the lists from under the drop's
optimistic draw. The wait is bounded by CHANGE_FEED_MUTATION_HOLD_MAX_MS (5s):
those two writes are one local round trip, so a mutation still pending past it
is a hung or long one (an import, a spec sync, an OAuth sign-in), and the batch,
a reset included, lands anyway rather than waiting for it. The in-app MCP channel stays a second producer for the in-app
server's writes, so those are invalidated twice; an invalidation twice over is
a refetch, never a wrong answer.
The stream is the inbox stream's shape: every drop is closed and reconnected on
the service's own backoff (CHANGE_FEED_RETRY_BASE_MS doubling to
CHANGE_FEED_RETRY_MAX_MS, 15s, which is the Retry-After the engine sends
with 503 change_feed_full; an EventSource cannot read the status or the
header), resuming by ?lastEventId= from the last id seen. Each connection, a
reconnect included, first asks POST /changes/subscriptions for a single-use id
and opens GET /changes?subscription=<id>: the engine takes a stream slot only
on such an id, so a web page cannot hold every slot and leave the app's stream
refused; a failed request for the id is retried on the same backoff, and a
stop() while one is in flight drops it on arrival. It never gives up,
since nothing renders a stopped feed; the engine-status gate is what stops it
asking a downed engine.
An open request reaches the merge (#1436) through its detail key: a refetch
delivers a new fetchedRequest, and the builder adopts the fields the user has
not touched and keeps a touched one, with the incoming value in
fieldConflicts (RequestBuilder.change-feed.test.tsx).
Retry policy: the shared default is shouldRetryQuery (lib/query-client.ts),
not a bare count. A 4xx from the engine is a verdict, not a hiccup - a 404 for a
deleted row answers identically every time, so retrying it only delays the error
the caller is waiting on. 4xx is never retried; everything else (5xx, timeout,
unreachable engine - which http-client.ts throws as an EngineUnreachableError,
not an ApiError) keeps the DEFAULT_QUERY_RETRY budget. The one exception is
an engine that is still starting: while engineStartWindow is open, an
EngineUnreachableError is retried without counting against the budget, every
ENGINE_START_RETRY_DELAY_MS (queryRetryDelay), so a launch shows loading
rather than error panes until the engine answers or the window expires
(docs/app/api-integration.md, Health Checking).
Cache policy lives in config/cache.ts (QUERY_CACHE), not in the call
sites. Name the constant when you need a duration; restating the number here
is how this section drifted before. The current shape:
| Query | Policy |
|---|---|
| Collections, requests lists, environments, globals, runs list | DEFAULT_STALE_TIME_MS (30s) via the shared client |
Request detail (requestDetailOptions) |
staleTime: Infinity - a restored tab reads it once; its own mutations and the change feed (a write by any other client) invalidate it |
| Run detail, run report | RUNS_STALE_TIME_MS (5m); completed runs are immutable. While the run's status is running or pending the detail polls every 3s, and a report given that status is staleTime: 0 and polls too (#1934) |
| Run time series (downsampled, one request) | staleTime: Infinity, RUN_SERIES_GC_TIME_MS (1m); staleTime: 0 when given an in-progress status. Invalidated by LoadTestService when the run ends |
| Run monitor series (downsampled, one request) | staleTime: Infinity, RUN_SERIES_GC_TIME_MS (1m); staleTime: 0 when given an in-progress status. Invalidated by LoadTestService when the run ends |
| Engine config | CONFIG_STALE_TIME_MS (1m) |
| Script completions | SCRIPT_COMPLETIONS_STALE_TIME_MS (1h), same gc time |
| Health | staleTime: 0, refetched every TIMING.HEALTH_CHECK_INTERVAL_MS (30s) |
Polling intervals are separate from staleness: the runs list polls every 5s
only while unpaged (runsPollInterval), health polls on
TIMING.HEALTH_CHECK_INTERVAL_MS, and the shared client sets
refetchOnWindowFocus: false - a desktop app that refetched everything on focus
would fight the editor the user just came back to.
Custom Hooks¶
useEngine() - Compose, Execute, Stop¶
Wraps the three engine calls that are not queries, with error for the caller
to render. Whether a send is in flight is not here: the request builder holds
that per request (RequestBuilderProvider's isExecuting, #3352).
API:
const {
composeRequest: (params: ComposeRequestRequest) => Promise<ComposedRequest>
executeRequest: (params: ExecuteRequestRequest, environmentId?: string, signal?: AbortSignal) => Promise<SanityResult | null> // null once `signal` cancelled it
stopLoadTest: (runId: string) => Promise<boolean>
error: string | null
} = useEngine();
composeRequestisPOST /compose- the engine resolves{{variables}}andinheritauth and hands back the execute-ready payload (issue #226). It throws on failure; the caller surfaces it like an execute failure.executeRequesttakes an already composed payload. It never throws: a failure comes back as aSanityResultwithstatus: 0and anerrorCode, because the response pane renders the failure the same way it renders a response.stopLoadTestreturnsfalserather than throwing when the engine refuses.- Starting a load test is not here. The request builder composes, then calls
apiService.startLoadTest()(POST /runs),useDashboardStore().startRun()andloadTestService.startMonitoring()in that order, at one call site - registering the run before attaching the stream is what keeps the dashboard from showing a stream with no run behind it.
Live Metrics Streaming - loadTestService + sseClient¶
There is no React hook that owns the metrics stream, on purpose. The stream has to
outlive whichever view is mounted (navigate away from the dashboard mid-run and
the run keeps streaming), so it is a module singleton, and the hooks that ask
about a run (useRunLiveness, useCanStartLoadRun) only read the stores it
writes:
services/load-test-service.ts holds the state machine and
services/sse-client.ts the EventSource.
import { loadTestService } from "@/services/load-test-service";
loadTestService.startMonitoring(runId); // after useDashboardStore().startRun(...)
loadTestService.stopMonitoring();
- Connects to
GET /runs/:runId/live, a replayable tick topic. A first attach reads it from offset 0, so a run that finishes before the client attaches, or one attached to mid-run, rebuilds the charts rather than starting blank. A re-attach to the run the client already holds frames for (Reconnect, or the dashboard's re-attach on mount) resumes instead:SSEClientrecords thelastEventIdof every frame it receives - ticks, steps, plans and monitor scrapes share one id sequence - andconnectsends the last one as?lastEventId=, so the engine replays only what the dashboard has not seen (#3571). A resume keepscurrentMetrics, so the header does not flash zero. The client holds one slot, for the run it last served: attaching another run replaces it, and a run attached again after that starts from offset 0. - Every tick is buffered; commits into
useDashboardStore().addMetricsBatch()are throttled toMETRICS_UI_THROTTLE_MSsohistoricalMetricskeeps the full 10 Hz signal while renders stay bounded. The buffer, the leading edge and the trailing timer areservices/throttled-batcher.ts, shared withScenarioRunService(issue #1206) and withuseExecutionEvents(issue #1158) - a monitor scrape has no timer of its own and rides the next tick's flush, which is why that second buffer stays in the service rather than moving into the batcher. - The engine sends an explicit
completeevent, so aCLOSEDreadyState is a genuine failure. Nothing reconnects by itself:EventSourcecannot setLast-Event-IDon a fresh connection, which is why the resume point travels as?lastEventId=when the user's Reconnect asks. The browser's own intra-connection retry does carry the header and is left alone; once the browser gives up, the service converges onGET /runs/:id/reportin its close handler, and Reconnect is the way back to the stream. A close flushes the ticks buffered at the drop (their ids were recorded as they arrived, so the resume starts after them), and a release that discards them (stopMonitoring, a superseded run) is for a run that is not resumed.
useVariableResolver() - Variable Resolution¶
Resolves {{variableName}} patterns in strings and objects using environment, collection, and global variables.
API:
const {
resolveString: (input: string) => string
resolveField: (input: string, context?: DataFieldContext) => BoundField
resolveObject: <T>(obj: T) => T
getVariable: (name: string) => ResolvedVariable | null
getAllVariables: () => Record<string, ResolvedVariable>
getVariableOrigins: (name: string) => VariableOrigin[]
} = useVariableResolver({ collectionId?: string; boundRow?: DataFileRow });
// resolveString takes an optional per-call row (issue #1074), for the one
// caller that resolves for several requests at once - the tab strip.
resolveString(input: string, row?: DataFileRow): string
resolveField is the preview of one field of a known kind (issue #2639):
context is plain (the default), url, header, json or xml, and with
boundRow set a cell is written for it as the engine's bind writes it -
escaped in a JSON string or XML, encoded in a URL - while refusals carries
why the send would refuse the row over the field (a cell in an XML comment, a
line break bound into a header), naming it "the picked row". Without a row it
is resolveString's text with nothing refused. The request builder's context
carries it beside resolveString, and VariableSupport in its place; the Body
tab's Resolved view and the key/value peeks read it.
Resolution Priority (highest to lowest):
1. Bound data row (bare column names) - only while boundRow is passed and a
row is actually picked (issue #1062)
2. Environment variables
3. Collection variables
4. Global variables
Collection scope comes from the collectionId option and nowhere else - a
caller that passes none resolves against globals + environment. See
docs/app/variable-resolution.md for why the session-store fallback was
removed.
boundRow is optional and additive: without it resolveString /
resolveObject resolve exactly as before (composition only, both a bound
column and {{data.column}} deferred). With it, they resolve through
resolveTemplateWithRow instead, so a bare bound column and {{data.column}}
both read the row - the request builder's provider is the one caller that
passes it, deriving it from the picked-row index. See
docs/app/variable-resolution.md for the tier and its rules.
resolveString's second argument is the same row named per call instead of per
hook. It exists for useTabDescriptors, which labels every open tab from a
single resolver and therefore cannot name one row for the whole of it; it reads
the row out of useBoundRowStore for the tab it is labelling. Both spellings
render a row's cells through the same helper, so the two cannot disagree.
The environment is the one scope no option names. It is not passed in: the
hook reads useSessionStore().activeEnvironmentId itself, so every caller
resolves against the environment the user has actually selected and no caller
can scope a preview to a different one. This page documented an
environmentId option for a while; nothing has ever accepted one. The two
scopes are asymmetric on purpose - the active environment is app-wide state,
while the collection is a property of whatever the caller is rendering.
ResolvedVariable carries sourceId / sourceName - the specific environment
or collection the winning value came from (absent for global).
getVariableOrigins returns every definition of a name, lowest precedence
first, including disabled ones that never resolve. Display-only; the variable
popover renders it as "also defined". Since issue #1064 it also carries the
bound row on top when one answers the name, taking winner from whichever
scope it beat. See docs/app/variable-resolution.md for why the losers are
kept and why the MCP copy is not given the same accessor.
RequestBuilderContext - variable members¶
The request builder re-exposes the resolver plus two things only it can derive:
getVariableOrigins: (name: string) => VariableOrigin[]
updateVariable: (name: string, value: string, scope: VariableScope) => void
writableScopes: VariableScope[]
writableScopes lists the scopes updateVariable would actually write to.
Each of its branches opens with a guard (if (!activeEnvironmentId) return), so
a write to a scope with no active target is a silent no-op - the variable
popover uses this list so its "create in" picker cannot offer one.
A write through updateVariable always sets enabled: true. Setting a value
means "make this value apply"; enabling and disabling belongs to the variables
editor. Without it, creating a value for a name that was disabled everywhere
preserved enabled: false and the token stayed unresolved.
Usage:
const { resolveString } = useVariableResolver({ collectionId });
const resolvedUrl = resolveString("https://{{baseUrl}}/api/users");
RequestBuilderContext - body drafts¶
What the body modes you are not looking at were holding. A request stores
one body - the shape is a discriminated union, {"mode":"json","content":
"..."} - so JSON, text and GraphQL share request.body, and switching mode
handed the same string to a different reader. Switching from JSON to GraphQL
therefore read the payload as a raw query string and destroyed it.
Two buckets, not eight: json, text, jsonrpc and xml are one raw string
differing only in highlighting, so text carries between them deliberately;
graphql is an envelope this side parses into two panes and keeps its own; the
two form modes use formData / urlEncoded and binary uses binaryFile, and
none of the three touches body. jsonrpc
and xml sit in the raw bucket because nothing here reads their text as a
structure - JSON-RPC's frame is completed engine-side at wire time and an XML
document is sent byte for byte, so each pane holds one plain document. The rule lives in
modules/request-builder/utils/body-drafts.ts.
Two things about it are deliberate and easy to undo by accident:
- It lives in the provider, not in
BodyPanel. Radix unmounts an inactiveTabsContent, so a panel-local ref is discarded the moment you glance at the Headers tab, taking the stashed body with it. - The provider does not reset it on a request change. The drafts carry
their own
requestIdandswitchBodydrops any belonging to another request, so a second reset would duplicate that rule - and would fire on the request-change effect, which re-runs on more than the id.
Deliberately not persisted: a request has one body, and storing payloads it will never send would put them in exports and in the engine's schema.
RequestBuilderContext - the GraphQL Variables draft¶
The Variables pane's raw text, for the same reason and with the same lifetime.
The pane is a JSON editor over one key of the GraphQL envelope, and the
envelope cannot always hold what it shows: text that is neither JSON nor a
resolvable {{template}} is dropped by serializeGraphQLBody, deliberately, so
that the query pane keeps saving while the variables pane has an unclosed brace.
That makes the pane's own text the only copy - and GraphQLBody's component
state the wrong place for it, since the Radix unmount discards a half-typed
variables object exactly as it once discarded a stashed JSON body.
It is beside the mode drafts rather than inside them because it is not a mode's
body (GraphQL's body is already in the graphql bucket). It carries its own
requestId for the drafts' reason, and ownVariablesDraft - not a second reset
in the provider - is what drops one belonging to another request.
RequestBuilderContext - the headers a setting added¶
Two settings each own a header row: the body mode's Content-Type (written by
BodyPanel) and the Event stream toggle's Accept: text/event-stream (written
by SettingsPanel, issue #574). GraphQL is sent as a JSON envelope and
genuinely needs Content-Type: application/json, so BodyPanel appends one -
but nothing removed it, so a single visit to GraphQL left the header on the
request for good, including after switching back to none, which sends no
body at all.
Ownership of the row used to be a context-level record, { requestId, rowId,
value }, held in a ref the provider owned. That could not survive a reload: a
fresh mount started with an empty ref, so a stale auto-written row was then
indistinguishable from one the user typed, and neither withoutContentType
(nothing to remove) nor a later mode switch (an "existing" row, so nothing to
add) could tell the difference (issue #1481). Ownership now lives on the row
itself - KeyValueEntry.source?: HeaderRowSource, whose "body-mode" | "stream"
half (AutoHeaderSource) is what an app setting writes; the third value,
"legacy-default", is the engine's own header-strip repair pass marking a row
it disabled rather than deleted (issue #1491, docs/engine/db-schema.md's
"header-strip pass" section) and is never written from this side. There is no
context accessor for either app setting any more; switchAutoHeader in
modules/request-builder/utils/auto-header.ts reads and writes the marker
directly on the headers array it is handed, once per change: it removes the
marked row when the new setting does not need that same header, then adds
whatever the new setting does need - both halves in one pass over one array,
because two updateField("headers", …) calls would compute the second against
the array they had before the first. panels/body/content-type.ts is now just
the body-mode half: which Content-Type a mode requires, plus the delegation.
Two things it is deliberate about:
- By marker, not by value. A
Content-Typethe user typed and the row a setting wrote are identical apart from the marker, and only a marked row may be removed.KeyValueEditor'shandleUpdateclears the marker the moment a user retypes a row's key or value - once retyped, it is theirs, whatever the new value happens to be. Merely disabling a marked row does not clear it: the row is not sent while disabled, so there is nothing to have adopted. - A row already declaring the header - even a different value - is never overridden. Silently replacing it would be a worse version of the bug this exists to fix. A disabled declaration does not count: it is not sent, so the header the mode needs is still missing.
The setting that used to be the one slot left, AutoMethod, is not a header
row at all (issue #1228). A new request is a GET, and GraphQL over GET is a
different transport - the document travels as query parameters and a mutation
cannot be sent that way - so picking the GraphQL body mode on a request still
holding that default used to build one the server answered with a bare 400.
The mode now sets POST the same reversible way it sets the Content-Type
header above, and leaving the mode puts the method back. It has the same
reload gap issue #1481 fixed for the two header rows, closed the same way by
issue #1505: ownership lives on RequestState.methodSource?: MethodSource
("graphql", the domain type mirroring HeaderRowSource), a value on the
request itself rather than a ref-held record, so it is exactly as durable as
request.method beside it. switchGraphQLMethod in
panels/body/graphql-method.ts is the rule that reads and writes it, called
from BodyPanel.handleModeChange alongside switchAutoHeader, and it keeps
the same two guarantees stated as bullets above, read against a scalar field
instead of a row: a method the user has since chosen - methodSource no
longer "graphql" - is no longer this side effect's to revert, and
MethodSelector's onValueChange clears the marker in the same call that
sets the hand-picked method, the exact moment KeyValueEditor's handleUpdate
clears a header row's source on a retype. A GET still reaches GraphQL
through the door this side effect does not touch - the user picks GET back, or
an import wrote one - which is when the Query pane header's BadgeText names
the transport that will be used.
Which identity a builder files under is one value, resolved once (issue
1272): memoryKey ?? request.id ?? UNSAVED_AUTO_KEY, read by every¶
per-builder map the provider still holds - now only the Send-with-row picker's
row memory below, since the three reversible-setting records above all moved
onto the request's own state. A request tab is its request and passes
nothing. The editable copy History renders for a stored run passes the run
id, because design-run-seed.ts gives that copy id: null on purpose - a
null id is one of the two gates that stop an edited copy from rewriting the
saved request - so every open run copy used to share the id-less bucket
before issue #1272. That was not a near miss: the rules read a requestId of
null against another null as a match, so the second run tab's picked row
was handed the first one's record and read as its own. A prop rather than a
field on RequestState that only History would set: request.id stays
honestly null, and no request grows a "which run am I" field for one caller.
A run id names a tab, so that memory is bounded by the same sweep rather than
exempt from it.
UNSAVED_AUTO_KEY is what remains for a builder declaring neither - nothing in
the app today - and it is the one key the sweep cannot drop, since a key naming
no tab cannot be bounded by the tabs. It is kept rather than removed because the
alternative for such a builder is sharing whichever key was written last, which
the null === null ownership check hands out as owned rather than refusing.
The open tabs bound the Send-with-row picker's memory (issue #1271), the
provider's one remaining per-request map: which row index each request was
last sent with (rowIndexByRequest, issues #659 and #1062). It survives a tab
switch and a return, because neither of those is a send - and it goes when the
tab does, since the request it was picked for can no longer be switched to.
tabs-store is subscribed to rather than selected from, because a provider
that re-rendered on every tab focus would charge the request the user is
working in for it. MAX_OPEN_TABS caps the tab strip, so it caps the map, and
both request tabs and run tabs are swept, by their entityId - a request id
and a run id respectively, from different tables and so unable to collide. A
run tab holding no builder at all (a load test, a scenario) only ever keeps a
key nothing wrote.
The row memory is useState rather than a ref - lastRowIndex is read while
rendering - so its half of the sweep is a setState, and retainKeys
(context/retain-keys.ts) returns the map it was handed when every key is still
live. Without that identity guard the provider would re-render on every tab
focus, which is exactly the cost the subscription was chosen to avoid.
The two header markers and methodSource need none of this: what is
persisted is the row itself, in request.headers, or the method's own marker,
in request.methodSource - no provider-side map, no sweep, nothing a reload
can lose that a save does not already carry.
useSaveManager() - Auto-Save Manager¶
Orchestrates auto-save for a saveable entity (request, environment, etc.) with debouncing, context registration, and centralized save state tracking. Located in app/src/hooks/useSaveManager.ts.
API:
const {
forceSave: () => Promise<void>
status: "idle" | "pending" | "saving" | "error" // this entity's own entry, not the Dock's
isSaving: boolean // this entity's save is in flight
} = useSaveManager({
entityId: string | null // Unique ID for this entity
contextName?: string // Display name (e.g., "Request: GET /api")
onSave: () => Promise<void> // Function to persist changes
hasChanges: boolean // Whether unsaved changes exist
changeToken: number // Bumped by the caller on every edit
enabled?: boolean // Disable auto-save (default: true)
});
Features:
- Debounced auto-save: Triggers after the delay the user chose in Settings → General, defaulting to 5000ms (autoSave.delayMs in client-settings-store, options in constants/client-settings.ts)
- Context registration: Automatically registers with useSaveStore() for app-wide Ctrl/Cmd+S integration and tab LRU coordination
- Save status: Reports to the centralized save store under request-<id>, which the Dock derives "Saving…" and "Saved" from. The status it returns is that one entry's (idle when there is none), never the Dock's app-wide one: InfoPanel keeps the description source open on error, and another surface's failure is not this request's (#3350)
- Entity switching: Flushes pending saves when entity ID changes (in cleanup, before unmounting)
- Saves are queued, never skipped: a caller arriving while another save is in
flight waits behind it and gets its own write, so its promise resolves only
once its edits are persisted. Skipping (the old behaviour) meant Cmd/Ctrl+S,
the quit flush and the entity-switch flush all reported "saved" for edits that
were never in the flying snapshot - and the switch then reset the provider,
making them unrecoverable. performSave binds onSaveRef.current at call
time rather than when the queue reaches it, so a save queued by the
entity-switch cleanup still writes the entity being left
- No debounceMs parameter: the delay is a user preference, not a per-caller
one, so the hook reads it from the store rather than taking it as an option.
Turning auto-save off in Settings leaves the entity marked dirty - Ctrl/Cmd+S
still saves it - but schedules nothing.
- The delay runs from the last edit, and changeToken is what makes it a
debounce (#1381). hasChanges cannot carry that on its own: it is already
true by the second keystroke, so an effect keyed on it does not re-run and
the timer armed by the first keystroke runs to term. A save then went out
five seconds into every burst carrying a half-typed script. The token changes
on every edit, so each one tears the pending timer down and arms a fresh one
- A returning save reports "Saved" only for the edits it carried (#1381).
The saver and the token are bound together when performSave is called;
if the token has moved by the time the write lands, an edit arrived that the
payload does not hold, and the status goes back to pending rather than
flashing "Saved" over it. The caller is what re-arms the save - this only
refuses to mislabel it
app/src/config/timing.ts used to carry an AUTO_SAVE_DELAY_MS: 3000 that
nothing read and that this section documented as the source of truth. It is
deleted; timing-keys-have-readers.test.ts now fails on any TIMING key without
a reader, and useSaveManager.autosave-setting.test.tsx pins the Settings value
to the timer that actually runs.
Usage:
const { forceSave, status, isSaving } = useSaveManager({
entityId: requestId,
contextName: `Request: ${request.method} ${request.url}`,
onSave: () => apiService.updateRequest(requestId, changes),
hasChanges: JSON.stringify(draft) !== JSON.stringify(saved),
enabled: true
});
useEntityDraft() - Manual Draft/Save Model¶
The other save model, and the counterpart to useSaveManager(): an editable draft, a Save button gated on isDirty, and a Reset that discards it. Located in app/src/hooks/useEntityDraft.ts. CollectionDetail's AuthTab and ElementsTab (issue #1512) are its button users.
InfoTab uses the hook without the button: it wants the draft, the resync and the mutation reset, but commits when focus leaves the field, like the request builder. reset therefore has fewer callers than draft has; InfoTab reaches the discard path through adopt instead.
Why auth - and now Elements - keep the button (#446, #1512). Not because a credential or an element list outranks a plain field - the request builder autosaves its own auth through useSaveManager, and used to autosave its scripts the same way InfoTab still does. Because a blur is not a completion signal once a tab is more than one focus stop: an OAuth 2.0 config with Advanced open renders 20 focus stops, 9 of them non-value controls, and clicking reveal to check a half-typed password fires focusout while the draft is dirty - so a blur-commit would write half a credential to the record every descendant request inherits from. The old ScriptTab had exactly one focus stop (its Monaco editor), so leaving it meant what leaving a description means - but ElementsTab's ElementList is adding a kind, naming a row, toggling it, reordering it and editing its form, each a separate stop, and a script.* element's own editor inside the list would fire the identical half-typed-value blur. The fields only make sense saved together, which is what the button means on both tabs now. Should collection auth or elements ever persist by themselves, the mechanism is the debounce, not a blur - a different change from this one. Both tabs state their save model above the fields, since they are the ones on that screen that differ.
API:
const {
draft: T // The editable copy
setDraft: Dispatch<SetStateAction<T>> // Standard setState signature
isDirty: boolean // Draft differs from the persisted value
reset: () => void // Discard the draft, adopting the persisted value
adopt: Dispatch<SetStateAction<T>> // setDraft for taking a persisted value; landing on it from a dirty draft is a discard (#2033)
consumeDiscard: () => boolean // Was the last clean edge a reset or an adopt? Clears the answer (#1931)
markSaved: (sent: T) => void // Call from the editor's save once it lands; drops the stored draft if the editor has gone meanwhile (#3459)
baseline: T // The value the draft last agreed with the server on
externalValue: T | null // A persisted change pending while the draft is dirty
} = useEntityDraft<T>({
entityKey: string // Identity of the thing being edited, and its entity-draft-store key
value: T // The persisted value
mutation: { reset: () => void } // The save mutation this editor reports through
});
Behaviour:
- Seeds and resyncs while clean: a clean draft follows value when it changes - a save landing, a background refetch. In InfoTab this is what clears the post-trim divergence, since the tab persists name.trim(). The request builder needs the same property for the same reason and gets it a different way, since its state is not a draft: see the draft adopts an external write per field.
- A dirty draft is never silently overwritten (#1437). While the draft disagrees with baseline, an incoming change to value is held in externalValue instead of reseeding draft - an MCP update_collection landing mid-edit used to replace the user's unsaved text with whatever the agent wrote. ElementsTab and AuthTab treat externalValue as one value and show a "Changed elsewhere" Callout (CollectionDetail/shared.tsx's ExternalChangeCallout) whose action calls reset() to take it. InfoTab's draft has two independent fields, so it diffs draft and externalValue against baseline per key instead: a key the user has not touched adopts the external value immediately, the same as a clean tab; a key both sides touched surfaces its own conflict, named, and is left at the user's edit until they choose. Its per-key Take theirs calls adopt, not setDraft and not reset (which would take the other field too): while the draft stays dirty adopt leaves baseline and externalValue alone, so the other key's conflict survives, and it marks a discard only when the result equals the persisted value and the draft differed from it before - with the other field still dirty no clean edge follows to consume the mark, and the later real save would read as a discard.
- Tracks by JSON value, not identity: value may be a fresh object literal every render (InfoTab builds { name, description } inline); callers do not have to memoize it.
- entityKey is a switch, not an edit: a change shows that entity's own draft (its stored one, or its persisted value) and calls mutation.reset(). The entity switched away from keeps its draft in the store, so going back to it restores the edit (#3459). These editors render without a React key, so a different entity arrives via props on the same instance, and a TanStack mutation holds isError until the next mutate - without the reset, a failed save is reported against an entity the user never tried to save. The keys come from entityDraftKey: <collectionId>:elements for the whole element list, :info, and :auth (collectionAuthDraftKey, which the context bar reads too).
- Requiring the mutation is the point: the three hand-rolled copies this replaced had drifted, and the one that omitted the reset had exactly that bug.
Usage:
const { draft, setDraft, isDirty, reset } = useEntityDraft({
entityKey: collectionAuthDraftKey(collection.id),
value: collection.auth,
mutation: updateCollection,
});
The draft lives in entity-draft-store, not in the component (#3459).
Shell.tsx mounts only the tab on screen, so clicking a request unmounted the
whole collection screen and, with the draft in component state, threw an
unsaved script away without a prompt. The hook reads the draft from the store
by entityKey (falling back to value when there is none) and writes it there
on setDraft, adopt, reset and markSaved, so a remount picks up the edit
where it was, dirty, with baseline intact: a change that landed meanwhile
arrives as externalValue. useDraftSaveContext's draftKey keeps the save reachable
while the editor is gone; see
entity-draft-store.ts
for who drops an entry.
CollectionDetail still force-mounts the three draft-holding tabs (Info, Auth,
Elements) from their first visit onwards. The draft no longer needs it; what
does is what the store does not hold, the editors' own undo history and scroll
position, across a look at a sibling. The Variables tab is deliberately not
force-mounted: it autosaves and claims the store's active context on mount, so
keeping it alive behind another tab would point Ctrl/Cmd+S at the wrong editor.
useDraftSaveContext() - Registering a Manual Draft¶
The counterpart to useSaveManager's registration half, for editors using the
useEntityDraft model. Located in app/src/hooks/useDraftSaveContext.ts. Used
by InfoTab, AuthTab and ElementsTab.
useDraftSaveContext({
id: `collection-${collection.id}-auth`, // Unique per editor
name: `Collection auth: ${collection.name}`,
isDirty, // From useEntityDraft
isActive: active, // Is this the tab on screen?
save: persist, // Rejecting is how failure is reported
consumeDiscard, // From useEntityDraft
draftKey, // The entityKey: the context outlives the editor
});
Behaviour:
- Registration only. It schedules nothing; each editor decides when to call
its own save - AuthTab and ElementsTab on their Save button, InfoTab
when focus leaves the field. The defect it fixes is orthogonal to that
choice: the other ways to save - Ctrl/Cmd+S, the quit flush, tab eviction -
could not reach these editors at all, because none of the three tabs ever
called registerContext.
- isActive decides who owns Ctrl/Cmd+S. triggerSave prefers the active
context, and these editors stay mounted while hidden, so without it the last
sibling to mount would answer for the panel on screen.
- A failure toasts rather than resolving quietly. The editors render an
inline SaveFailed callout for a button press, but a quit flush has no callout
on screen, and a resolved promise reads as success - swallowing here would
report "Saved" for a write that failed. The registered save resolves with its
verdict: "failed" after the toast, "saved" on success, and "pending" for
a SaveBlockedError, which only marks the Dock "Unsaved changes" - no toast,
no "Not saved" (the same reading useSaveManager gives it).
- The save must carry its own validity guard. A disabled button does not stop
the store-driven paths, which is why InfoTab refuses a blank collection name
inside persist. With its buttons gone that guard is now the only one, and it
is silent by itself - the tab pairs it with reportBlankNameRefused()
(lib/blank-name.ts), a toast raised once the tab has put the stored name
back; with nothing left unsaved there is no "Not saved" to report.
- isDirty also drives the Dock's "Unsaved changes" line (#1483). The
registry's own hasPendingChanges is not what the Dock reads - only the
store's per-id reports are - so the hook calls reportPending(id) the moment
isDirty turns true and reportSaved(id) the moment it turns false again,
mirroring useSaveManager's autosave editors. Edge-triggered, and reset
rather than fired across an id change, so switching the entity a mounted
editor describes never reports the previous entity's save as this one's.
- A stored draft keeps its context after the editor goes (#3459). On an
unmount or an id switch, an editor that passed a draftKey and was dirty
leaves its context registered (detach): still hasPendingChanges, so
isTabDirty holds the tab and the quit flush and Ctrl/Cmd+S's fallback still
reach it, and its id stays reported, so the Dock keeps "Unsaved changes". Its
save is the editor's last save, which closed over the draft and over a
mutation observer that still works unmounted. When that save lands the
context and the stored draft both go; when the stored draft is dropped
another way (the tab closed, the collection deleted) the context goes and the
id is discarded. That includes a save the editor started on screen and that
landed after it went: the editor's save calls useEntityDraft's
markSaved, which drops the entry only when no editor shows it (one that does
sees the persisted value catch up instead, and dropping first would paint the
old value for a frame, since the query cache notifies on a later tick). A
remount under the same id takes the context back. Without
a draftKey (the inbox reply, whose draft is component state), or for a
clean draft or an id markRemoved names, the goodbye discards the id's
report as before. On a remount over a dirty stored draft the rising edge
reports it pending again.
- A discard is not a save (#1931, #2033). The clean edge is a save landing,
a useEntityDraft reset (the Reset button, an external change's "Take
theirs") or an adopt that lands on the persisted value (InfoTab's
per-field Take theirs). All three editors (InfoTab, AuthTab,
ElementsTab) pass the draft's consumeDiscard as the hook's
consumeDiscard option; when it says the edge was a discard the hook calls
discard(id) instead, so the Dock returns to idle rather than flashing
"Saved" for a write that never happened. discard removes only this id's
report, so another context's edit or failure stays on the Dock.
The request builder's draft adopts an external write per field¶
RequestBuilderProvider resets its whole draft when the request id
changes, and neither a rename, an MCP agent's update_request, nor a move to
another collection changes the id. Before issue #1436, only name adopted a
change that arrived this way - every other field held a snapshot taken when the
tab opened, so a debounced auto-save could write that snapshot back over
whatever an agent had just changed, a delete under a dirty tab flushed a doomed
PUT into a 404, and a move discarded the whole draft along with the id-based
reset it was routed through.
The fix generalizes the name's adoption into a per-field three-way merge, the
same shape useEntityDraft (below) already uses for the collection tabs:
baselineis the value the draft last agreed with the server on - not necessarilyrequest, which is whatever the user has typed, and not necessarily what a stray refetch just reported either, if that report conflicts with an edit (see below).touchedFieldsis which top-levelRequestStatekeyssetRequest/updateFieldhave written since that baseline. A successful save clears exactly the fields it sent;takeExternalField(below) clears one.- On every
initialRequestchange (the request query's copy, gated on its object identity so the diff runs once per refetch and not once per keystroke),mergeExternalWrite(app/src/lib/field-merge.ts) diffsinitialRequestagainstbaselineover every mergeable field (MergeableRequestField- everyRequestStatekey exceptid,collectionIdanddisabledDefaultHeaders, which have their own rules below): - a field the fetch did not change is left alone;
- a field the fetch changed and the user has not touched adopts the new
value into the draft, via
setRequestState(neversetRequest- adopting someone else's write is not an edit of ours, and marking it dirty would schedule a save that writes back what was just read) andbaselinemoves to match; - a field the fetch changed and the user has touched, to a different
value than the fetch reports, is a conflict: the draft keeps the user's
value,
baselineis deliberately left where it was (so the conflict keeps being detected until it is resolved), and the incoming value is exposed onfieldConflicts[field]; - a touched field the fetch now agrees with (the save's own echo, or a
coincidence) resolves quietly -
baselinemoves, nothing is shown.mergeExternalWritecompares by JSON content, not by reference:headers,paramsandauthare rebuilt into fresh arrays/objects on every fetch regardless of content, and===there would read every refetch as an external change - the same reasonuseEntityDraftcompares byJSON.stringify. fieldConflictsandtakeExternalField(field)are onRequestBuilderContextValue.ExternalChangeNotice(request-builder/components/) renders oneExternalChangeCalloutper logical group - the five fields the editor splits a request's body across (bodyMode/body/formData/urlEncoded/binaryFile) count as one "body" group, so a body conflict does not paint five callouts - and its "Take theirs" resolves every field in the group.collectionIdis not a mergeable field: acollectionId-only change with the same id (themove_itemcase) updates just that field in place, leaving the rest of a dirty draft untouched, in a dedicated branch beside the id-keyed full reset.- A request deleted elsewhere stops
index.tsxhanding the provider aninitialRequestat all, while keepingRequestBuilderProvidermounted (see below) so the draft is not lost. The provider noticesinitialRequestwent missing whilerequest.idis still set and flipsrequestGone, which feedsuseSaveManager'senabled- so a dirty draft's autosave timer, already armed or about to be, never fires a PUT against an id that now 404s. A delete made from the collection tree never reaches that state: it marks the ids removed (markRemoved) before the tabs close, and the tab's goodbye flush drops the draft instead of sending it (#3444). - The generation
handleSavechecks (changeTokenRef, see the save-manager walkthrough below) bumps on a foreign write too, not only on the user's own edits - an effect keyed onbaseline's identity, not a direct write inside the merge itself: a ref write during the render phase is unsafe under React's rules (a render can be discarded or replayed) and is what this repo'sreact-hooks/refslint rejects. Without the bump, a save already in flight when the merge adopts or conflicts a field could still clearhasUnsavedChangesover a value the merge just changed underneath its response. restoreStoredName()is unchanged in spirit but now readsbaseline.namerather than a name-only ref: the Info tab's blank-name refusal needs the stored name back, and the baseline already holds it for every field, not just this one.
The save payload only ever carries what touchedFields names
(buildUpdatePayload in request-builder/index.tsx): onSave receives
(request, changedFields), and an untouched field is omitted from the
PUT /requests/:id body entirely - which the engine's merge-patch already
reads as "leave the stored value alone" - rather than being resent unchanged.
The four body fields collapse into the wire's body/bodyType pair if any one
of them was touched. name keeps its own rule inside that: touched-but-blank
still omits the key (a blank name is refused, not saved), for the reason the
old comment gave - the debounced auto-save can fire while the field is briefly
empty.
useUpdateRequestMutation's cache write also learned to lose a race
(queries/collections.ts): a foreign write's own refetch can land in the
detail cache while this client's save is still in flight, and writing the
save's response into the cache unconditionally could then overwrite the
newer row with a stale one purely because the older write's round trip
finished second. The onSuccess handler now compares updatedAt
(a toISOString() string end to end, so lexical and chronological order
agree) and keeps whichever row is actually newer.
Guarded by RequestBuilderProvider.name-sync.test.tsx (the name-only case that
started this), RequestBuilderProvider.external-write-merge.test.tsx (the
general per-field merge, the move, the delete, and the generation bump),
field-merge.test.ts (mergeExternalWrite itself), save-request-name.test.ts
and request-builder.script-clearing.test.tsx (the partial payload), and
collections.update-request-race.test.ts (the cache race).
State Flow Examples¶
Executing a Single Request¶
- User clicks "Send" button in request builder
useEngine().executeRequest()is called with request and (optionally) environment IDuseVariableResolver()resolves any{{variables}}in the request URL, headers, body- Request is transformed (frontend → backend format) and sent via HTTP
- Response is stored in
useResponseStore()keyed by request ID - Response viewer component reads the response and displays it
- On request tab switch, the response persists in
response-storeand is displayed if the user returns - for the most recently sent requests (at most 24, fewer when their bodies are large - see the byte budget), past which the store's LRU bound has dropped the entry and the backend's stored run answers instead - If any script ran, the environment / globals / collection query families are invalidated so values the script wrote are visible in the variables editor and the resolver. The gate is
scriptsMayWriteVariables(pre, post)(request-builder/utils/execute-mapping.ts), shared by the builder's send path and the History run view's resend. Both script kinds count:pm.environment.setand friends persist engine-side from a Tests-tab script exactly as from a pre-request one, and withrefetchOnWindowFocus: falsenothing else is coming to correct a stale value
Starting a Load Test Run¶
One live run owns the live view at a time (#3351, #3381). canStartLoadRun() in stores/run-gate.ts is the one answer (the names say "load run" from before it covered both kinds), read by every place a run starts: the request builder (before its dialog opens, and again at Start), the Run Collection dialog in either mode, and useRunWatchers for an agent's run. It refuses while the dashboard's run is live (isDashboardRunLive, so a lost stream counts) or a collection run is streaming, because sseClient holds one EventSource and any run attaching would take it from either. The engine sets no limit of its own; this is renderer policy. The answer names the running run ({ kind: "load" | "collection", runId, label }, the label being the dashboard's method and URL when it holds them), and runningRunSentence / runningRunTab turn that into the refusal and the tab that shows the run. The builder opens that tab with a warning toast; the dialog shows a blocking callout with View run and Stop, and keeps Run disabled, following the gate through useCanStartLoadRun() so Run comes back when the run ends. Stop is useStopLiveRun (hooks/useStopLiveRun.ts), the one function that stops "the live run a RunningRun names": for the dashboard's run it raises isStopping, calls POST /runs/:id/stop and acts on the engine's status (stopped detaches the stream and settles the store; a run already finished is recorded as a late Stop, #3367), which is also what the dashboard's own Stop calls; for a collection run it stops the run and refreshes the History caches (useStopRun is a thin wrapper over it for the two History tabs). A failed stop is a toast with Try again, and Run stays disabled, since the run is still live. A stopped collection run keeps scenario-run-store.isStreaming true until the engine's complete frame, so Run reopens a moment after the stop answers, not with it. Both refuse before POST /runs, so no engine run is started past a refusal. An agent's run has already started on the engine, so it cannot be refused: when the gate is shut the app attaches nothing, for either kind, and shows one toast; see useRunWatchers under the MCP section. The URL bar's Load test button follows the same gate through useCanStartLoadRun(), so it never offers a start the click would refuse: View load test (the dashboard) while the dashboard's run is live, View collection run (that run's tab) while a collection run streams. Re-attaching the dashboard to its own run asks a narrower question, canReattachLoadRun() (reattachGateOf), which refuses only while a collection run streams: the dashboard's run being live is the reason to re-attach, not a reason to refuse. The lost-stream callout's Reconnect refused that way opens the collection run's tab with the same warning toast as the builder, and the dashboard's re-attach on mount, which nobody asked for, stays on the callout without one; either way the collection run keeps its stream.
- User configures load test in the dashboard modal (duration, concurrency, etc.)
- The request half is composed engine-side (
useEngine().composeRequest()), thenapiService.startLoadTest()sends the composed payload plus the load config toPOST /runs - Engine responds with
runId useDashboardStore().startRun(runId, config, requestInfo, requestId)initializes dashboard stateloadTestService.startMonitoring(runId)connects to/runs/:runId/live- As metrics stream in,
addMetricsBatch()folds them into historical metrics (trimmed toliveWindowSeconds, backstopped bymaxRetainedTicks) and updates running aggregates (peak concurrency, SLO breakpoint) - Dashboard view shows live metrics, request/response (from the SSE stream's final response), and aggregates
- When the run completes, the engine sends a
completeevent -
LoadTestService.handleClose()fetches the final report through the query cache (underqueryKeys.runs.report(runId), withstaleTime: 0so a mid-run copy a History tab cached is not served as final, #1934) and hands it tosetFinalReport(runId, report), which settles the phase asfinished- only if the dashboard is still showing that run. The write is addressed to the run the close was for, and the store drops it for any other: finishing run A and immediately starting run B otherwise landed A's report on B's dashboard, flipping a running test to "completed" with A's percentiles.A dashboard that mounts on a run whose stored report is already terminal calls
loadTestService.settleOnStoredReport(runId, report)(#3380), notstopMonitoring(): it releases the stream and posts how the run really ended (finished, failed or stopped), once.stopMonitoring()is the user's Stop only and would post "stopped" for a completed run.The dashboard's Stop reads the engine's answer (#3367).
POST /runs/:runId/stopanswersstopped(the Stop took effect),completedorfailed(the run had already finished when Stop arrived), orrunning(the strategy returned on its own and the run ends by its own verdict). Onstopped,handleStopcallsstopMonitoring()andstopRun()as before, so the Running pill and Stop drop at once. Oncompleted/failedit does neither: the stream's close or the report effect settles the run with the engine's status,noteLateStop()setsstopArrivedLate(cleared by the nextstartRun), and the finished view shows an info callout, "The run had already finished when Stop arrived.", between the header and the report, unless the stored report carriessummary.drainCut(read bydrainCutCancelledOf): that Stop cancelled requests during the drain, so it did something, the verdict line already says the run was not judged, and the callout would contradict it (#3538); from a lost stream, which nothing will close,noteLateStopalso awaits the report. Onrunningnothing changes: the run keeps streaming and no note is shown. 10. Dashboard settles asfinishedwith kind "completed" (or "failed" / "stopped", which lay out the same final report) showing the final report; the runs lists are invalidated so the terminal status lands without waiting for a poll, and so are the run's detail, report and series, which a History tab on the same run read while it was live 11. A stream that ends without acompletestatus is not a finished run (issues #1925, #2140). The engine'scompleteframe normally carries the run'sstatus, whichhandleClose(status, { frame })believes over the stored row. With no status it reads the same stored report, and if itsmetadata.statusis stillrunningorpendingthe two endings part ways. A dropped connection (frame: false) moves the phase tostreamLostinstead of landing the final report, posts no notification, and lets go of the run so Reconnect can start watching it again. Reconnect resumes the stream after the last frame the client received (?lastEventId=, #3571), so the series carries on without a repeated tick andcurrentMetricsis kept; the ticks buffered when the stream dropped are committed once by that close and are not delivered again. A barecompleteframe (frame: true, the engine's 60 s settle timeout) is waited out instead: the service re-reads the report every 500 ms for up to 30 s and finishes the run as soon as it is terminal, falling back to the report's own status to tell failed from finished, then loses the stream the same way only if the bound passes. That wait is cancelled by a generation counter on the service (settleGeneration), bumped bystartMonitoring,releaseRun(sostopMonitoringandhandleSuperseded) andhandleError; a bareactiveRunIdcheck could not do it, because Reconnect puts the same id back. A cancelled wait does nothing: no report, no notification, no error. A collection run taking the shared stream (handleSuperseded) loses the stream the same way, and fetches nothing, and so does a stream error (handleError). Either way the run stays live, so the dashboard keeps its running layout, the Running pill and Stop, under the "Lost the live metrics stream" callout. The dashboard's own report effect is the backstop for a stream that stopped with no report in the store: one retry-capped fetch armed only in theawaitingReportphase, so it holds off while that callout is up, and re-armed by the report callout's Retry. A fetch that keeps failing gives up toreportError, whose Retry re-arms it; a report that still says running after every attempt gives up tostreamLostinstead, with the body "The stream closed, but Vayu's engine still reports this load test as running.", becausereportErroris not live and would take the pill and Stop away while the engine still generates load. From there Reconnect is the user's to press, so nothing re-fetches on its own. A run whose Stop the engine confirmed is not raised back to live: its still-running report gives up toreportErrorlike a failed fetch.
Saving a Request with Auto-Save¶
- User opens or creates a request tab via
useTabsStore().openTab() - Component mounts
useSaveManager()with the request ID and save callback - Hook registers the context with
useSaveStore()for Ctrl/Cmd+S integration - User edits the request (URL, headers, body, etc.)
hasChangesis marked true andchangeTokenis bumped, arming the debounce timer -autoSave.delayMsfromclient-settings-store, 5s by default (Settings → General offers 5s / 30s / 1m)- A further change within that window bumps the token again, which tears the pending timer down and arms a new one, so the delay measures from the last edit
- After the delay elapses with no edit,
performSave()is called, which calls theonSavecallback - Save status updates in
useSaveStore(), and the Dock shows "Saving..." then "Saved" forTIMING.SAVED_STATUS_DURATION_MS - A save is only allowed to call the entity clean for the generation it sent (#1381).
onSave(request, changedFields)serialises the state - and the set of touched fields - as they were when the save started, so a keystroke landing during the round trip is not in that payload. The generation also moves on a foreign write the per-field merge adopts or conflicts, not only on the user's own edits (#1436): a save in flight when that happens must not clearhasUnsavedChangesover a value the merge just changed underneath its response. The provider records the generation beside the snapshot and clearshasUnsavedChanges- and the fields the snapshot named - only if the token has not moved when the write lands; the hook applies the same check to the "Saved" indicator. Clearing unconditionally marked that keystroke saved, left nothing dirty for the next timer to fire on, and lost the edit - The request builder's
onSavesends onlychangedFields(#1436, see the draft adopts an external write per field above) - an untouched field is omitted from thePUTrather than resent unchanged - On tab switch or unmount, any pending save is flushed before the context is unregistered - unless the entity is confirmed gone (
useSaveManager'senabled: false), which the request builder sets once its request is deleted elsewhere, so the flush never fires a doomed PUT. If that flush fails, the context is re-registered under the same id rather than left unreachable -flushAll's reconnect trigger (below) and a later quit both walk the registry, not the pane that just unmounted (#1489) - On app quit (Electron
before-quit; on Windows a logoff or shutdown reaches it through the window'squery-session-end, whichsession-end.tsturns into a quit) and on window close (the X button),useSaveStore().flushAll()saves all dirty contexts and resolves to{ saved, failed, pending }- what actually landed, not just that the round trip finished. Each count is the sum of the contexts' own verdicts:pendingis an edit that settled unsaved (a blocked save),failedone the engine refused
Both window-destroying paths flush, through one coordinator. before-quit
always did; close did not, and close is what the X button fires - it
destroys the WebContents and nulls the window handle, so the before-quit that
followed found no renderer to ask and skipped the flush entirely (on macOS,
close does not quit at all, so the edits were simply gone with the app still
running). electron/quit-flow.ts is the one state machine both gestures go
through - idle, confirmingServices, flushing, confirmingLoss,
proceeding - and owns the flush and its 2s ACK ceiling, which is why
"already flushed" is shared state: a quit that flushed and then closes the
window must not ask a dying renderer twice. It lives outside main.ts so it
can be tested - main.ts creates windows and starts the engine at import
time. Once a quit is let through, quit-shutdown.ts stops the engine and the
MCP server.
A running service is asked about before either path flushes (#1363). A close or quit that would stop an inbox, mock server or mock issuer names it and waits for an answer first, and Cancel leaves the window, the renderer and every pending save exactly as they were - a flush run ahead of the question would have told the renderer its work was ending. Confirm, and the flush runs as it always did on the way out. The yes lasts for that one way out: the close and the quit it turns into are not asked twice, but Cancel or Keep working forgets it.
The flush settling is not the same as the flush landing (#1489). Before,
both paths closed the window the moment the round trip finished - the ACK, or
the 2s ceiling if the renderer never answered - whether or not anything had
actually been saved: a refused write, a hung engine, or a save still running
when the ceiling gave up all looked identical to a clean quit. The renderer's
flushAll now carries its outcome back over the before-quit-flushed ACK
(FlushResult, electron/save-flush.ts), and a settle with no ACK at all (the
ceiling won) is treated the same as a failure - nothing is known to have
landed. Either case holds the close behind one native dialog,
buildFlushFailurePrompt: "Couldn't save N edits - the engine isn't
responding" for a failure or the unanswered ceiling, "Couldn't save N edits -
the disk is full" (detail: "Free up space, then keep working to save again")
when every failure was a 507 and FlushResult.reason says so (#2423), and "N
edits couldn't be saved as they are" when every loss is a blocked save (pending only, where the
engine is fine), Quit/Close anyway or Keep working. A clean flush still
closes with no dialog, exactly as before, and a quit from a signal never asks:
it logs the flush result at warn and proceeds (#1908). Keep working returns
the flow to idle (#3335): the flush and the services answer are both
forgotten, so the next quit or close flushes again and asks again rather than
going straight through with the edits the user chose to keep. Each flush
request carries a flush id on before-quit, the preload echoes it on
before-quit-flushed, and an ACK whose id is not the flush in flight is
dropped, so a late answer to the first flush cannot settle the second. A
renderer that is replaced - a crash recovered, a hung one reloaded from the
"not responding" dialog, a new window on macOS - resets the flow the same way. useTabsStore.closeTab
asks the same
question one tab early: closing a single dirty tab while the engine is not
connected keeps the tab and toasts instead of letting the unmount flush fail
into a pane that no longer exists; closeOtherTabs and closeTabsToRight hold
back their dirty tabs the same way (#3324).
Variable Resolution Priority¶
- User activates a request in a tab. The environment comes from
useSessionStore().activeEnvironmentId; the collection comes from the request's owncollectionId- not from the session store, which has held no collection scope since thevayu.sessionv2 migration - Component calls
useVariableResolver({ collectionId })- the environment is not passed, the hook reads it from the session store - Hook fetches globals, collection variables, and environment variables via TanStack Query
- When
resolveString("https://{{baseUrl}}/{{path}}")is called: - First, check environment variables for
baseUrlandpath - If not found, check collection variables
- If still not found, check global variables
- Replace with the first match found, or leave
{{variableName}}unreplaced if no match
Best Practices¶
-
Cross-cutting vs. module-local: Store cross-cutting UI state (tabs, layout, engine, save) in
app/src/stores/; store feature-specific UI state (collections tree, history filters, variables category, settings category) inapp/src/modules/<feature>/<feature>-store.ts. -
Zustand for transient UI state: Use Zustand for UI state that doesn't persist to disk (or is ephemeral per session). Decorate with
persistmiddleware to survive page reloads if needed (e.g., open tabs, drawer state). -
TanStack Query for server state: Use TanStack Query for collections, requests, environments, globals, runs, and reports. It is the single source of truth and ensures consistency across the app.
-
Save manager integration: Use
useSaveManager()in any component that edits a persistable entity (request, environment, etc.) that autosaves. It handles debouncing, context registration, and centralized save state. Do not manually calluseSaveStore()for auto-save. For an editor that holds a draft instead - committing it on blur or on an explicit button - useuseEntityDraft()plususeDraftSaveContext()- the first owns the draft, the second puts it in the registry - and do not hand-roll the draft/resync/isDirty/mutation-reset parts again. -
Centralized save on app quit: On Electron's
before-quitevent, calluseSaveStore().flushAll()to persist any pending changes before the app closes. An editor that is not registered is not merely unsaved here, it is invisible - which is how the collection tabs lost drafts silently for as long as they existed.flushAllreports what happened ({ saved, failed, pending }), and the main process (electron/quit-flow.ts) asks before discarding anything it did not save (#1489) rather than closing on faith - on the window's close as well as on quit.Corollary: an editing surface must never fail without saying so. There is no global
MutationCache.onErrorinlib/query-client.ts, so a baremutation.mutate(...)reports nothing at all. Route the failure throughreportFailed(toast + "Not saved") when the edit stays on screen, a toast when the surface rolls it back, or render the mutation'sisError, and roll an uncontrolled input back to the stored value while you are at it - the context bar's variables section did neither, so a rejected edit sat on screen looking committed. -
Leaving an editor saves or asks; it does not drop. A settings category switch, an unmount, a tab switch - each used to discard dirty state silently in at least one place. Settings flushes its valid edits on the way out (engine config writes are cheap merge-patches); the collection tabs keep their panels mounted so there is nothing to discard.
-
Tab LRU and dirty state: The tab store reads the save registry and refuses to evict a dirty tab (
isTabDirty, matched by tab type - the registry is keyed by editor and the two do not line up). Nothing is flushed during eviction, because the predicate has already declined to take unsaved work; over the cap with every candidate dirty, no tab closes at all. An explicit close (closeTab) is not eviction and used to have no such guard; it now applies the sameisTabDirtycheck but only refuses when the engine is notconnected(#1489) - a dirty tab closes and flushes as usual once the engine can actually take the write. -
Response persistence: Responses are stored in memory (not localStorage) so they survive tab switches but are cleared on page reload. This balances UX (quick switch back) with memory (responses can be large).
-
Live metric retention is a time window, not a point count.
addMetricsBatchtrims ticks older thanliveWindowSeconds(the engine'sliveReplayWindowMs, 5m by default,null= full run), withmaxRetainedTicks(DEFAULT_MAX_RETAINED_TICKS, 50,000) as a memory backstop. Both are engine config so the replayed span and the displayed span cannot disagree. The only knob inconfig/metrics.tsisMETRICS_UI_THROTTLE_MS, the SSE commit throttle; chart cost is bounded by bucketing (chartBucketSeconds), not by dropping ticks. -
Variable resolution priority: Always resolve variables in priority order: environment > collection > global. Use
useVariableResolver({ collectionId })to scope a preview to a collection; the active environment comes from the session store and is not a parameter. -
Lazy loading and prefetch: Use
usePrefetchCollectionsAndRequests()andusePrefetchRuns()on app init to warm up caches. Lazily fetch environments, globals, and run reports only when needed to reduce initial bundle size and API load. Warm a polled list with a prefetch, never by mounting its hook at the root - an observer that lives for the session polls for the session (#1150). -
Select fields, never the store. Calling a Zustand hook with no selector (
useTabsStore()) subscribes to the whole state object, so the component re-renders on everyset()to that store regardless of which field changed. Call the hook with a selector for each field the component reads (useTabsStore((s) => s.openTabs)), and read an action through the hook's owngetState()(e.g.useTabsStore.getState().focusTab(...)) inside a handler rather than selecting it in render - actions are stable references, so selecting one buys nothing and widens the read. When a component genuinely needs several fields together, wrap the selector inuseShallowfromzustand/react/shallowrather than returning a bare object literal, which fails Zustand's identity check and re-renders every time regardless of whether the picked fields changed; a selector that derives a fresh array or object (.filter(...),.map(...)) has the same problem and no wrapper fixes it, so derive downstream of a field selector withuseMemoinstead.app/src/stores/store-selectors.test.tsscansapp/srcfor all three shapes and fails on any it finds outside its allowlist (#1714).