Frontend state model
Table of Contents
Section titled “Table of Contents”- Layout Tree — LayoutModel and localTreeStateAtom
- Pane-State Reducers
- Reducer-Stack Initiative — Discussion #707
- Focus / Selection Visual Highlight — 3-Source Color Resolution
- MuxObject Store (MOS) — Block and Tab Persistence
- One Writer for LayoutState
- Boundary Summary
1. Layout Tree
Section titled “1. Layout Tree”1.1 LayoutModel — Class Overview
Section titled “1.1 LayoutModel — Class Overview”LayoutModel (frontend/layout/lib/layoutModel.ts) is the per-tab class that owns the entire tile-layout state at runtime. One instance is created per tab and cached per tab (layoutModelMap in frontend/layout/lib/layoutModelHooks.ts). The class holds both the runtime tree and all reactive accessors; the rendering component (TileLayout) is a pure consumer.
Key invariant: LayoutModel lives in its own createRoot scope (frontend/layout/lib/layoutModel.ts). All memos — including the isFocused memo on every NodeModel (frontend/layout/lib/layoutNodeModels.ts) — are created under this root and survive component mount/unmount cycles during tab switching. Without this root, the isFocused memo dies when TileLayout unmounts and the focus border freezes. (Bug analysis: docs/specs/focus-border-tab-switch-bug.md.)
1.2 localTreeStateAtom
Section titled “1.2 localTreeStateAtom”this.localTreeStateAtom = createSignalAtom<LayoutTreeState>({ rootNode: undefined, focusedNodeId: undefined, magnifiedNodeId: undefined, leafOrder: undefined, pendingBackendActions: undefined,});localTreeStateAtom is a SolidJS SignalAtom<LayoutTreeState> (frontend/layout/lib/layoutModel.ts). It is the in-memory runtime source of truth for the layout tree during a session. It is distinct from the persisted MuxObject (muxObjectAtom, which points at LayoutState in the backend store).
The shape of LayoutTreeState (frontend/layout/lib/types.ts):
| Field | Type | Description |
|---|---|---|
rootNode | LayoutNode | Root of the binary layout tree |
focusedNodeId | string? | ID of the currently focused leaf node |
magnifiedNodeId | string? | ID of the magnified leaf node (if any) |
leafOrder | LeafOrderEntry[]? | Ordered leaf list (top-left to bottom-right) |
pendingBackendActions | LayoutActionData[] | Queued backend-to-frontend layout mutations |
Write path: all mutations flow through treeReducer() (frontend/layout/lib/layoutModel.ts), which calls one of the pure tree functions in layoutTree.ts, then calls this.localTreeStateAtom._set({ ...this.treeState }) (frontend/layout/lib/layoutModel.ts).
Persistence: the frontend never writes the layout row. treeReducer() applies a tree edit to the local tree at once and also queues it as a layout intent (frontend/layout/lib/layoutModel.ts). The intent goes to srv, whose reducer applies the same edit to its own copy of the tree and stores the result. The frontend then shows what srv stored. See §5.3 for the steps and §6 for who writes each field.
1.3 focusedNodeId and the Focus Stack
Section titled “1.3 focusedNodeId and the Focus Stack”model.treeState.focusedNodeId ← authoritative in LayoutTreeStatemodel.focusedNodeIdStack ← ordered history stack (most recent first)model.focusedNodeId (getter) ← returns focusedNodeIdStack[0]model.focusedNode (memo) ← reactive accessor → LayoutNodefocusedNodeIdStack (frontend/layout/lib/layoutModel.ts) is a plain string[] on the model. It tracks focus history so that when the currently focused node is deleted, focus falls back to the previous node rather than going to leafOrder[0].
The getter focusedNodeId (frontend/layout/lib/layoutModel.ts) simply returns this.focusedNodeIdStack[0].
The reactive memo focusedNode (frontend/layout/lib/layoutModel.ts) re-derives from localTreeStateAtom on every change:
this.focusedNode = createMemo(() => { const ephemeralNode = this.ephemeralNode(); const treeState = this.localTreeStateAtom(); if (ephemeralNode) { return ephemeralNode; // ephemeral node always wins focus } if (treeState.focusedNodeId == null) { return null; } return findNode(treeState.rootNode, treeState.focusedNodeId);});1.4 FocusNode Reducer Path
Section titled “1.4 FocusNode Reducer Path”Dispatching focus goes through a dedicated action type:
User click / keyboard nav → model.focusNode(nodeId) layoutFocus.ts → model.treeReducer({ type: FocusNode, nodeId }) → focusNode(this.treeState, action) layoutTree.ts (sets treeState.focusedNodeId) → localTreeStateAtom._set(...) reactive update fans out → flushLayoutOutbox(model) layoutIntents.ts (a "view" intent to srv) → focusManager.requestNodeFocus() (only after state has committed) → focusedNode memo re-evaluates → NodeModel.isFocused() returns true for the new nodeFocusNode is special: it skips updateTree() (no topology change) but it still updates focusedNodeIdStack inline (frontend/layout/lib/layoutModel.ts). Like every tree edit it is queued for srv, as a view intent: no tree change, just the focused and magnified node (frontend/layout/lib/layoutIntentActions.ts).
1.5 validateFocusedNode — Bootstrap and Stack Reconciliation
Section titled “1.5 validateFocusedNode — Bootstrap and Stack Reconciliation”validateFocusedNode (layoutFocus.ts) runs inside updateTree() on every leaf-order recompute. It has two jobs:
-
Bootstrap (
layoutFocus.ts): if neithertreeState.focusedNodeIdnorfocusedNodeIdStackhas a value (fresh tab, never persisted focus), auto-focus the first leaf (defaultFocusLeaf,layoutFocus.ts: the first pane inleafOrderthat isn’t an agent picker, elseleafOrder[0]). This is the fix shipped as part of the 2026-06-12 border fix (docs/specs/pane-highlight-fix-plan.md). -
Reconcile (
layoutFocus.ts): iftreeState.focusedNodeIddiverges fromfocusedNodeId(e.g. a node was deleted), prune stale IDs from the stack and promote the next viable entry.
1.6 isFocused — Per-Node Derivation
Section titled “1.6 isFocused — Per-Node Derivation”Every NodeModel carries an isFocused accessor (frontend/layout/lib/types.ts). It is created as a createMemo inside model.runInModelRoot() so it outlives component lifecycles:
isFocused: createMemo(() => { const treeState = model.localTreeStateAtom(); return treeState.focusedNodeId === nodeid;}),This is a pure equality check against localTreeStateAtom().focusedNodeId. There is no secondary signal. When treeReducer(FocusNode) fires and localTreeStateAtom._set(...) is called, every isFocused memo across all mounted nodes re-evaluates in the same reactive batch.
1.7 LayoutNode Shape
Section titled “1.7 LayoutNode Shape”export interface LayoutNode { id: string; // stable UUID for this tree node data?: TabLayoutData; // { blockId: string } on leaf nodes only children?: LayoutNode[]; // set on branch nodes; absent on leaves flexDirection: FlexDirection; // "row" | "column" size: number; // proportional size in parent flex container}Leaf nodes have data.blockId set and no children. Branch nodes have children and no data. The tree is always a binary flex tree where flexDirection alternates.
1.8 Layout Tree
Section titled “1.8 Layout Tree”2. Pane-State Reducers
Section titled “2. Pane-State Reducers”These reducers are entirely separate from the layout tree. They own what a pane is doing (streaming, loading, tabs open, etc.) — not where it sits or whether it is focused. Focus and highlight are layout-tree concerns only.
2.1 Shared Reducer Pattern
Section titled “2.1 Shared Reducer Pattern”All frontend reducers follow the conventions from docs/specs/frontend-reducer-conventions-2026-05-03.md:
- Pure
update(state, command) → { state, events }function. - Per-block or per-pane slot store (
Map<blockId, Slot>). dispatch(blockId, command)throws on unregistered id (silent drops would defeat the audit value).- Typed
Commandunion (what the caller wants) andEventunion (what happened, for audit/subscribers). recordDispatch()writes to the command-source audit ring.
2.2 agent-pane-state — Slice #4
Section titled “2.2 agent-pane-state — Slice #4”Files: frontend/app/store/agent-pane-state/types.ts, reducer.ts, frontend/app/store/agent-pane-state-store.ts
Models the per-agent-pane lifecycle. Does not model focus, highlight, or pane position.
AgentPaneState fields
Section titled “AgentPaneState fields”| Field | Type | Description |
|---|---|---|
initPhase | InitPhase | InitPending → InitReady|InitFailed — history load lifecycle |
turnPhase | TurnPhase | Single SoT for turn lifecycle (PR A–G series) |
streaming | StreamingState | agentId, bufferSize, lastEventTime |
lastEventMs | number | null | Wall-clock of last stream activity; !== null ↔ stream subscribed |
sessionStats | SessionStats | null | Cumulative token usage for the session |
currentTool | string | null | Name of the tool currently executing |
turnTokens | TurnTokens | null | Per-turn input/output token deltas (cleared at TurnEnd) |
context | ContextReading | null | The context meter’s reading (tokens in context, the model’s window, and where each came from); set by TokensIn, survives TurnEnd, cleared on a reset, an invalidation or a compaction |
pending | PendingMessage[] | Messages queued but not yet acknowledged by backend |
detailsOpen | boolean | Whether the composer’s Shell drawer is open |
TurnPhase discriminated union
Section titled “TurnPhase discriminated union”Selectors (types.ts):
| Selector | Returns true when |
|---|---|
isWorking(state) | turnPhase.kind ∈ {Submitting, Streaming, Interrupting} |
isDisconnected(state) | turnPhase.kind === "Disconnected" |
isInitReady(state) | initPhase.kind === "InitReady" |
Watchdog constants (types.ts, from STUCK_THRESHOLD_MS):
| Constant | Value | Purpose |
|---|---|---|
STUCK_THRESHOLD_MS | 45 000 ms | Diagnostic-only stream-stuck event; no state change |
SUBMIT_TIMEOUT_MS | 30 000 ms | Submitting → Done.errored if no stream activity |
INTERRUPT_TIMEOUT_MS | 5 000 ms | Interrupting → Done.interrupted if no ack |
LIVENESS_RECOVERY_MS | 180 000 ms | Hung Streaming turn (no activity, no tool running, not rate-limited) → Idle |
What this reducer does NOT model
Section titled “What this reducer does NOT model”- Whether the pane is focused (layout tree)
- The pane’s position or size (layout tree)
- The pane’s border color (layout tree + CSS)
- The message list content (agent-document reducer, separate slice)
2.3 agent-document — Slice #1
Section titled “2.3 agent-document — Slice #1”Files: frontend/app/store/agent-document/types.ts, frontend/app/store/agent-document/reducer.ts, frontend/app/store/agent-document-store.ts
Models the per-agent-pane message list. Separate from agent-pane-state per the “no god-reducer” rule.
| Field | Type | Description |
|---|---|---|
nodes | DocumentNode[] | Ordered message/tool nodes for the conversation |
sessionPhase | "loading-history" | "active" | "ended" | Stream lifecycle phase |
sessionStartedAt | number | null | Wall-clock of last SessionStart |
nodeIdSet | Set<string> | Authoritative dedup index; kept in lockstep with nodes |
Key commands: SessionStart, SessionEnd, HistoryLoaded, HistoryRestored, StreamFlush (bulk append + in-place update), ToolChunkAppend, ShellChunkAppend, StreamTruncate (with 5 s grace window — TRUNCATE_GRACE_MS), UserClear, ScrubOrphanedInProgress.
This reducer does not model streaming state, token counts, or focus.
2.4 browser-pane-state — Slice #9
Section titled “2.4 browser-pane-state — Slice #9”Files: frontend/app/store/browser-pane-state/types.ts, frontend/app/store/browser-pane-state/reducer.ts, browser-pane-state-store.ts
Models the multi-tab Browser pane.
| Pane-level field | Description |
|---|---|
tabs | BrowserTab[] — ordered list of browsing contexts |
activeTabId | ID of the active tab (invariant: always in tabs[] or null) |
recentlyClosed | Bounded stack (max 10) for Ctrl+Shift+T re-open |
closed | Terminal flag set by Disposed; all subsequent commands are no-ops |
Per-tab (BrowserTab): id, url, title, faviconUrl, loading, error, canGoBack, canGoForward, titleOverridden, faviconOverridden, isPreview, backendCreated.
Echo-loop guard: backend-driven commands carry source: "backend", suppressing the navigate event emission that would re-trigger a CEF navigation in an infinite loop.
This reducer does not model focus state or border highlight.
2.5 editor-pane-state — Slice #10
Section titled “2.5 editor-pane-state — Slice #10”File: frontend/app/store/editor-pane-state-store.ts
Models the multi-file Editor pane tab strip.
| State field | Description |
|---|---|
tabs | EditorTab[] — ordered list with id, filePath, language, dirty, readOnly, contentLoaded, isPreview |
activeTabId | ID of active tab (invariant: always in tabs[] or null) |
recentlyClosed | Bounded ring (max 10) for Ctrl+Shift+T |
Preview semantics: at most one tab may have isPreview: true per pane (VS Code single-click behavior). MarkDirty auto-pins the preview tab. Per-tab CodeMirror state lives outside this reducer (held by the view in a Map<tabId, EditorView>).
This reducer does not model focus or highlight.
2.6 Reducer Comparison Table
Section titled “2.6 Reducer Comparison Table”| Reducer | Slice | Models | Does NOT model |
|---|---|---|---|
agent-document | #1 | Message nodes, session phase, dedup | Focus, tokens, streaming |
agent-pane-state | #4 | Turn lifecycle, streaming, tokens, pending msgs | Focus, message content, position |
browser-pane-state | #9 | Tab list, active tab, nav state, load state | Focus, pane position |
editor-pane-state | #10 | File tab list, active tab, dirty flags | Focus, CodeMirror state |
| LayoutModel / layoutTree | — | Tree topology, focus, magnify, resize, leaf order | Turn phase, streaming, content |
3. Reducer-Stack Initiative
Section titled “3. Reducer-Stack Initiative”3.1 Discussion #707
Section titled “3.1 Discussion #707”GitHub Discussion #707 (“Reducer-stack architecture: long-term tracking thread”) is the umbrella tracking thread for the multi-layer reducer migration across launcher, host, srv, and frontend. References in codebase: docs/specs/SPEC_OBJ_UPDATE_BRIDGE_2026-05-14.md, docs/analysis/LIFECYCLE_DISPATCH_LEAK_2026_05_15.md.
3.2 Initiative Overview
Section titled “3.2 Initiative Overview”The reducer-stack is a cross-process architecture where each process layer owns a canonical reducer for its domain:
Launcher (L1) → OS process/window/pool/monitor factsHost (L2) → CEF browser/pane/drag/pool/quit stateSrv (L3) → workspace/tab/block/layout app domainFrontend → per-pane ephemeral stateCross-process dispatch (CPD-1 through CPD-5) is shipped for launcher→host communication.
3.3 The Agent-Pane Layout Reducer
Section titled “3.3 The Agent-Pane Layout Reducer”The pane-state reducer agent-pane-layout (Slice #11) is live: every phase of docs/specs/SPEC_AGENT_PANE_LAYOUT_REDUCER_2026_06_02.md shipped, and the agent view’s rows use it. It unifies three sources of truth for row heights in the agent document virtual list: the size cache, per-component expansion state, and CSS zoom.
The agent-pane-state reducer (Slice #4) and the agent-document reducer (Slice #1) are live too.
3.4 SRV-Side Layout Reducer — Phases 5–7
Section titled “3.4 SRV-Side Layout Reducer — Phases 5–7”Phases 5 to 7 of the srv layout reducer are in the code:
| Phase | What | Status |
|---|---|---|
| 5 | Reducer arms calling pure helpers | ✅ shipped, including LayoutApplyIntent (crates/srv-core/src/reducer/layout/intent.rs) |
| 6 | Persist subscriber arms for layout events | ✅ shipped: tree, focus, magnify and the backend-action queue (crates/srv-core/src/persist_subscriber.rs) |
| 7 | Move rootnode writers off wcore-direct | ✅ for every edit a window makes; srv refuses a whole-row UpdateObject of a layout row (crates/srv/src/server/service/object_helpers.rs). One direct write is left: the default layout a first launch seeds before the reducer has loaded. |
docs/specs/SPEC_STRONG_REDUCER_AUTHORITY_LAYOUT_2026_06_30.md records the same, phase by phase. §6 below describes the single writer.
4. Focus / Selection Visual Highlight
Section titled “4. Focus / Selection Visual Highlight”4.1 Color Resolution
Section titled “4.1 Color Resolution”The focused pane border color is resolved at render time from the block’s own meta, in this order:
Priority 1 (highest): the pane's own pick └── block.meta["frame:color"] (a palette slot; the older "frame:hue" number is read as the nearest slot) set by the pane header's "Pane Color" picker
Priority 2: the agent's identity color └── block.meta["frame:activebordercolor"] (seeded once when the agent launches) └── gated by isUsableFocusRingColor() — luminance ≥ 0.03 and alpha ≥ 0.5
Priority 3 (lowest / fallback): theme accent └── CSS var(--accent-color) └── always visible; used when the first two fail the usability gateThere is no tab-level tier: a tab’s color (§4.5) colors the tab only. A plain terminal pane gets an identity color only when it really is an agent’s block, never from an exported AGENTMUX_AGENT_ID alone.
4.2 Resolution Code Path
Section titled “4.2 Resolution Code Path”The memo that performs the resolution is blockAgentColor in BlockFrame_Default_Component (blockframe.tsx):
const blockAgentColor = createMemo(() => { if (!props.preview && paneTabCapability(blockData()?.meta?.view, "hueBorder")) { const isLightTheme = isLightThemeActive(); const color = computeBlockActiveBorderColor(blockData()?.meta, isLightTheme); if (isUsableFocusRingColor(color)) { return color; } } return null;});The result is injected as a CSS custom property (blockframe.tsx):
--block-agent-color: <color> | "transparent"4.3 CSS Application
Section titled “4.3 CSS Application”In block.scss:
// block.scss:298-320&.block-focused { .block-mask { border-color: var(--accent-color); // theme fallback z-index: 50; } // Agent-loaded terminals override with agent color &.has-agent-color .block-mask { border-color: var(--block-agent-color); }}The has-agent-color class is added when blockAgentColor() is truthy (blockframe.tsx). block-focused comes from NodeModel.isFocused() which tracks localTreeStateAtom().focusedNodeId (see §1.6).
4.4 isUsableFocusRingColor — The Luminance Gate
Section titled “4.4 isUsableFocusRingColor — The Luminance Gate”export function isUsableFocusRingColor(color: string | null | undefined): boolean { const rgba = parseCssColor(color); if (!rgba) return false; // unparseable color → theme accent if (rgba.a < 0.5) return false; // near-transparent → theme accent return relativeLuminance(rgba) >= MIN_FOCUS_RING_LUMINANCE; // 0.03}MIN_FOCUS_RING_LUMINANCE = 0.03 (autotitle.ts). This deliberately low threshold accepts dark-but-visible agent colors (e.g. #1e3a5f, L≈0.041) while rejecting near-black (#000, L=0) that would erase the border on a dark background.
4.5 Tab Color System
Section titled “4.5 Tab Color System”Tabs get no color at creation; a user picks one from the shared 14-color palette (PALETTE in frontend/app/theme/palette.ts, read from schema/color-palette.json): 12 hues, then Black and White, the same colors panes, agents, widgets and browser profiles use:
| Name | Hex |
|---|---|
| Rose | #e47696 |
| Red | #e8796e |
| Orange | #e38149 |
| Amber | #cd9219 |
| Yellow | #a7a425 |
| Green | #77b154 |
| Jade | #33b981 |
| Teal | #00b5b3 |
| Sky | #00afdc |
| Blue | #61a0f4 |
| Violet | #9e8eef |
| Magenta | #cd7dc9 |
| Black | #000000 |
| White | #ffffff |
The stored hex only names a slot: a window tab is drawn in the pane-tab pill tones for that slot (frontend/app/tab/tab.tsx), so picking a tab color never recolors a pane border. A stored hex that is not in the table is read as the nearest hue, and a grey as Black or White.
Tab color is stored in tab.meta["tab:color"] (a MuxObject meta field, srv-types.d.ts). The startup tab is intentionally left without a color (tabbar.tsx). Tab color feeds the tab bar indicator, not the pane border directly — tab colors are a separate visual affordance from the pane focus ring.
4.6 The focus border rules
Section titled “4.6 The focus border rules”Three rules keep the focus border correct (design notes in docs/specs/pane-highlight-fix-plan.md):
-
The border does not depend on a pane count. A pane keeps its focus border whatever the tab’s
blockidshold; no class (such as the removedblock-no-highlight) suppresses it when a tab has one pane. -
A fresh tab gets a focused node.
validateFocusedNodebootstraps focus when bothtreeState.focusedNodeIdandfocusedNodeIdStackareundefined: it focusesleafOrder[0], the first non-picker leaf (defaultFocusLeaf,layoutFocus.ts). -
A tab dragged out disposes its model.
deleteLayoutModelForTab(frontend/layout/lib/layoutModelHooks.ts) callsmodel.dispose()after the tab moves to the other workspace, so no reactive root outlives it. It is called on drag-out fromfrontend/app/drag/CrossWindowDropOverlay.tsx.
5. MuxObject Store (MOS)
Section titled “5. MuxObject Store (MOS)”5.1 Architecture
Section titled “5.1 Architecture”MOS (frontend/app/store/mos.ts) is the frontend in-memory cache of all backend-persisted objects. Each object is identified by an oref of the form "otype:oid" (e.g. "layout:abc123").
muxObjectValueCache: Map<oref, MuxObjectValue<T>>Each MuxObjectValue holds a SolidJS signal pair (getData / setData) wrapping a MuxObjectDataItemType<T> ({ value: T, loading: boolean }).
5.2 API
Section titled “5.2 API”| Function | Purpose |
|---|---|
getMuxObjectAtom<T>(oref) | Returns a SignalAtom<T> — call to read (reactive), ._set() to write locally |
useMuxObjectValue<T>(oref) | SolidJS hook — returns [valueAccessor, loadingAccessor], manages refCount |
setObjectValue<T>(value, pushToServer?) | Write cache; if pushToServer=true calls ObjectService.UpdateObject |
updateMuxObject(update) | Merge an inbound waveobj:update WS event; deduplicates on version (mos.ts) |
loadAndPinMuxObject<T>(oref) | Pin (refCount++) + return the fetch promise |
reloadMuxObject<T>(oref) | Force re-fetch from backend |
Cache eviction: cleanMuxObjectCache() runs every 30 s and removes entries with refCount === 0 and holdTime < now (mos.ts).
5.3 How LayoutState is Persisted
Section titled “5.3 How LayoutState is Persisted”The LayoutModel reads its row through getLayoutStateAtomFromTab (layoutAtom.ts), a plain accessor over the MOS entry:
export function getLayoutStateAtomFromTab(tabAccessor: () => Tab): () => LayoutState | undefined { return () => { const tabData = tabAccessor(); if (!tabData) return undefined; return MOS.getMuxObjectAtom<LayoutState>(MOS.makeORef("layout", tabData.layoutstate))(); };}It has no setter: the row changes only through srv. A layout edit travels the other way, as a layout intent (frontend/layout/lib/layoutIntents.ts, docs/specs/SPEC_STRONG_REDUCER_AUTHORITY_LAYOUT_2026_06_30.md §4):
- Apply it here, queue an intent.
treeReducer()applies the action to the local tree at once, as a prediction of srv’s result, and pushes the matching intent onto the model’slayoutOutbox(frontend/layout/lib/layoutModel.ts).intentForActionmaps each tree action to one intent:move,swap,resize,insert,insertatindex,delete,replace,splithorizontal,splitvertical,minimize,restoreorclear.FocusNodeandMagnifyNodeTogglebecome aviewintent, which changes no tree (frontend/layout/lib/layoutIntentActions.ts). - Send in order.
flushLayoutOutboxsends the outbox one item at a time (frontend/layout/lib/layoutIntents.ts). Each intent goes asLayoutApplyIntentCommand(layout.applyIntent), with the focused and magnified node as they are when it leaves. A failed send is tried up to three times, and a resend of the same action id is a no-op on srv (layoutIntents.ts). Pane-tab commands (activate, close or move a tab in a pane) go through the same queue withqueueLayoutCommand(layoutIntents.ts, called bysendStackCommand,frontend/layout/lib/layoutPersistence.ts). - srv applies and stores it.
apply_layout_intent(crates/srv/src/server/service/layout_intents.rs) dispatchesCommand::LayoutApplyIntentwhile it holds the reducer lock. The reducer arm (crates/srv-core/src/reducer/layout/intent.rs) applies the intent to a copy of the tab’s tree, normalizes it, takes the focused and magnified node from the request, and emitsLayoutTreeReplaced,FocusedNodeChangedandMagnifiedNodeChangedfor what changed.apply_layout_intentwrites those events to SQLite before it lets go of the lock, so rows are written in the order intents are applied. A failed write puts the tab back as the row has it (crates/srv/src/server/service/layout_intents.rs). A refused intent changes nothing and answersapplied: false. - Show what srv stored. When the model is quiet (nothing queued or sending, no drag or resize preview) and the row includes every intent it sent (
layoutVersionFloor),reconcileWithStoredLayoutcompares the stored tree with the local one. If they differ, srv refused an edit or computed it differently, and the stored tree replaces the local one. Focus stays the frontend’s while its pane exists (layoutIntents.ts).
Edits srv makes on its own, such as placing a new block, a tear-off or a redock, go the other way round. srv applies them to its own tree first, then queues them in the row’s pendingbackendactions for the window to mirror (place_block, crates/srv/src/server/service/layout_intents.rs). The window applies them locally and sends nothing back (processPendingBackendActions, frontend/layout/lib/layoutPersistence.ts). The queue keeps the latest 32 actions, and an action older than 10 minutes is dropped; a window that missed one shows srv’s stored tree anyway (crates/srv-core/src/persist_subscriber/layout_queue.rs).
The window never writes the layout row back: srv refuses a whole-row UpdateObject of a layout row (crates/srv/src/server/service/object_helpers.rs).
5.4 How Blocks and Tabs Are Persisted
Section titled “5.4 How Blocks and Tabs Are Persisted”Blocks are MuxObj objects of type "block". They are loaded via MOS.getMuxObjectAtom("block:<blockId>"). The block.meta field is the primary store for per-block configuration:
meta.view— the pane type ("agent","browser","term","editor", etc.)meta["cmd:env"]— environment variables (used for agent color detection)meta["pane-title"]— user-set titlemeta["pane-title:color"]— user-set title colormeta["frame:title"],meta["frame:icon"],meta["frame:text"]— frame overrides
Blocks are mutated via RpcApi.SetMetaCommand(TabRpcClient, { oref, meta }).
Tabs are MuxObj objects of type "tab". Key meta fields:
tab.meta["tab:color"]— tab bar color (a palette hex)tab.layoutstate— ID of the linkedLayoutStateobject
LayoutState is a MuxObj of type "layout". Persisted fields:
rootnode— serialized layout treefocusednodeid— focused node IDmagnifiednodeid— magnified node IDleaforder— ordered leaf list. Written only when a layout is seeded; the frontend computes its own and doesn’t read this one.pendingbackendactions— queued backend→frontend mutations
Only srv writes these fields; §6 lists which code writes each.
6. One Writer for LayoutState
Section titled “6. One Writer for LayoutState”6.1 The Writer
Section titled “6.1 The Writer”Every write to the layout row comes from srv, which refuses a whole-row UpdateObject of a layout row (crates/srv/src/server/service/object_helpers.rs):
| Writer | Fields | When |
|---|---|---|
apply_layout_tree_replaced (crates/srv-core/src/persist_subscriber.rs) | rootnode. Also clears focus or magnify when the tree empties or a delete removed that node, and writes every column when a seeding LayoutSetTree carries them | LayoutTreeReplaced, LayoutNodeDeleted |
apply_focused_node_changed (crates/srv-core/src/persist_subscriber.rs) | focusednodeid | FocusedNodeChanged |
apply_magnified_node_changed (crates/srv-core/src/persist_subscriber.rs) | magnifiednodeid | MagnifiedNodeChanged |
apply_layout_backend_actions_queued (crates/srv-core/src/persist_subscriber/layout_queue.rs) | pendingbackendactions, appended | LayoutBackendActionsQueued |
resync_tab (crates/srv-core/src/persist_subscriber/resync.rs) | rootnode, focus and magnify, from the reducer’s own state | The event bus lagged and dropped events |
write_default_three_pane_layout (crates/srv-core/src/backend/wcore/mod.rs) | The whole row | A first launch, before the reducer has loaded |
apply_focused_node_changed is how a focus change reaches focusednodeid. A click sends a view intent carrying the focused node; the reducer sets it on the tab and emits FocusedNodeChanged; the subscriber writes it.
User clicks pane → LayoutModel.treeReducer(FocusNode) → localTreeStateAtom updated (frontend, at once) → layout.applyIntent { type: "view", focused_node_id } → srv reducer: tab.focused_node_id = …, emits FocusedNodeChanged → apply_focused_node_changed writes focusednodeid (once, in order) → MOS update reaches the window; nothing to correctEach event is applied twice on the normal path: once right after dispatch, by the code that dispatched it, so a follow-up read sees the write, and again when the subscriber gets the broadcast. Every arm compares before it writes, so the second apply changes nothing and doesn’t bump the version (crates/srv-core/src/persist_subscriber.rs, persist_subscriber.rs).
6.2 Consistency
Section titled “6.2 Consistency”- Version races: there is one writer. The frontend ignores an update older than the value it holds (
mos.ts), and compares its tree with the stored one only once the row’s version includes every intent it sent (layoutVersionFloor,layoutIntents.ts). - Two tree implementations: the frontend predicts each edit with its own tree functions, and srv computes it with its Rust port. When they disagree, srv’s tree wins at the next quiet moment (§5.3, step 4), and the console logs “the local layout differs from srv’s stored one” (
layoutIntents.ts).
7. Boundary Summary
Section titled “7. Boundary Summary”┌─────────────────────────────────────────────────────────────────────────────┐│ LAYOUT TREE (LayoutModel / layoutModel.ts) ││ ││ Owns: tree topology, focused node, magnified node, leaf order, resize, ││ drag/drop, ephemeral nodes ││ ││ Does NOT own: what a pane is doing, token counts, message content, ││ browser URL, editor file contents, agent streaming state ││ ││ Focus signal path: ││ user click → focusNode() → treeReducer(FocusNode) ││ → localTreeStateAtom._set() ││ → "view" intent to srv (layoutIntents.ts) ││ → NodeModel.isFocused() memo ││ → "block-focused" CSS class ││ → CSS border resolution (color cascade) │└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐│ PANE-STATE REDUCERS (agent-pane-state, browser-pane-state, etc.) ││ ││ Owns: per-pane ephemeral runtime state ││ • agent-pane-state : TurnPhase, streaming, tokens, pending msgs ││ • agent-document : message node list, session phase ││ • browser-pane-state: tab list, URL, load state ││ • editor-pane-state : file tab list, dirty flags ││ ││ Does NOT own: focus, highlight, border color, position, size ││ ││ Connection to layout: blockId is the join key; NodeModel.blockId links ││ the layout leaf to the pane-state slot │└─────────────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────────────┐│ MUXOBJECT STORE (MOS / mos.ts) ││ ││ Owns: in-memory cache of all backend-persisted MuxObj records ││ • Blocks (type: "block") — pane configuration and meta ││ • Tabs (type: "tab") — tab meta including tab:color ││ • Layout (type: "layout") — layout tree snapshot ││ • Workspace, Window, Agent, Identity, … ││ ││ LayoutState writes: srv only (see §6) ││ window: treeReducer() → layout intent → layout.applyIntent ││ srv: reducer applies it → events written to SQLite → MOS update ││ window: shows srv's stored tree if it differs from its own │└─────────────────────────────────────────────────────────────────────────────┘