Skip to content

Frontend state model

  1. Layout Tree — LayoutModel and localTreeStateAtom
  2. Pane-State Reducers
  3. Reducer-Stack Initiative — Discussion #707
  4. Focus / Selection Visual Highlight — 3-Source Color Resolution
  5. MuxObject Store (MOS) — Block and Tab Persistence
  6. One Writer for LayoutState
  7. Boundary Summary

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.)

layoutModel.ts
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):

FieldTypeDescription
rootNodeLayoutNodeRoot of the binary layout tree
focusedNodeIdstring?ID of the currently focused leaf node
magnifiedNodeIdstring?ID of the magnified leaf node (if any)
leafOrderLeafOrderEntry[]?Ordered leaf list (top-left to bottom-right)
pendingBackendActionsLayoutActionData[]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.

model.treeState.focusedNodeId ← authoritative in LayoutTreeState
model.focusedNodeIdStack ← ordered history stack (most recent first)
model.focusedNodeId (getter) ← returns focusedNodeIdStack[0]
model.focusedNode (memo) ← reactive accessor → LayoutNode

focusedNodeIdStack (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:

layoutModel.ts
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);
});

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 node

FocusNode 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:

  1. Bootstrap (layoutFocus.ts): if neither treeState.focusedNodeId nor focusedNodeIdStack has a value (fresh tab, never persisted focus), auto-focus the first leaf (defaultFocusLeaf, layoutFocus.ts: the first pane in leafOrder that isn’t an agent picker, else leafOrder[0]). This is the fix shipped as part of the 2026-06-12 border fix (docs/specs/pane-highlight-fix-plan.md).

  2. Reconcile (layoutFocus.ts): if treeState.focusedNodeId diverges from focusedNodeId (e.g. a node was deleted), prune stale IDs from the stack and promote the next viable entry.

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:

layoutNodeModels.ts
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.

frontend/layout/lib/types.ts
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.

LayoutModel (purple) owns six children: localTreeStateAtom (steel-blue, holds focusedNodeId/magnifiedNodeId/rootNode/leafOrder), treeState (gray, mutable scratch), focusedNodeIdStack (gray), muxObjectAtom (steel-blue, a read-only view of the layout row srv stores), nodeModels (steel-blue, per-node isFocused/isMagnified), and treeReducer (purple, mutates state, triggers fan-out and queues a layout intent for srv).

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.

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 Command union (what the caller wants) and Event union (what happened, for audit/subscribers).
  • recordDispatch() writes to the command-source audit ring.

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.

FieldTypeDescription
initPhaseInitPhaseInitPending → InitReady|InitFailed — history load lifecycle
turnPhaseTurnPhaseSingle SoT for turn lifecycle (PR A–G series)
streamingStreamingStateagentId, bufferSize, lastEventTime
lastEventMsnumber | nullWall-clock of last stream activity; !== null ↔ stream subscribed
sessionStatsSessionStats | nullCumulative token usage for the session
currentToolstring | nullName of the tool currently executing
turnTokensTurnTokens | nullPer-turn input/output token deltas (cleared at TurnEnd)
contextContextReading | nullThe 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
pendingPendingMessage[]Messages queued but not yet acknowledged by backend
detailsOpenbooleanWhether the composer’s Shell drawer is open
TurnPhase state machine: Idle → Submitting → Streaming → Interrupting, each with arrows to terminal Done (steel-blue) or Disconnected. Purple arrows show timeout/error transitions: SubmitTimeoutElapsed (30s) and InterruptTimeoutElapsed (5s).

Selectors (types.ts):

SelectorReturns 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):

ConstantValuePurpose
STUCK_THRESHOLD_MS45 000 msDiagnostic-only stream-stuck event; no state change
SUBMIT_TIMEOUT_MS30 000 msSubmitting → Done.errored if no stream activity
INTERRUPT_TIMEOUT_MS5 000 msInterrupting → Done.interrupted if no ack
LIVENESS_RECOVERY_MS180 000 msHung Streaming turn (no activity, no tool running, not rate-limited) → Idle
  • 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)

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.

FieldTypeDescription
nodesDocumentNode[]Ordered message/tool nodes for the conversation
sessionPhase"loading-history" | "active" | "ended"Stream lifecycle phase
sessionStartedAtnumber | nullWall-clock of last SessionStart
nodeIdSetSet<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.

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 fieldDescription
tabsBrowserTab[] — ordered list of browsing contexts
activeTabIdID of the active tab (invariant: always in tabs[] or null)
recentlyClosedBounded stack (max 10) for Ctrl+Shift+T re-open
closedTerminal 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.

File: frontend/app/store/editor-pane-state-store.ts

Models the multi-file Editor pane tab strip.

State fieldDescription
tabsEditorTab[] — ordered list with id, filePath, language, dirty, readOnly, contentLoaded, isPreview
activeTabIdID of active tab (invariant: always in tabs[] or null)
recentlyClosedBounded 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.

ReducerSliceModelsDoes NOT model
agent-document#1Message nodes, session phase, dedupFocus, tokens, streaming
agent-pane-state#4Turn lifecycle, streaming, tokens, pending msgsFocus, message content, position
browser-pane-state#9Tab list, active tab, nav state, load stateFocus, pane position
editor-pane-state#10File tab list, active tab, dirty flagsFocus, CodeMirror state
LayoutModel / layoutTree—Tree topology, focus, magnify, resize, leaf orderTurn phase, streaming, content

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.

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 facts
Host (L2) → CEF browser/pane/drag/pool/quit state
Srv (L3) → workspace/tab/block/layout app domain
Frontend → per-pane ephemeral state

Cross-process dispatch (CPD-1 through CPD-5) is shipped for launcher→host communication.

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:

PhaseWhatStatus
5Reducer arms calling pure helpers✅ shipped, including LayoutApplyIntent (crates/srv-core/src/reducer/layout/intent.rs)
6Persist subscriber arms for layout events✅ shipped: tree, focus, magnify and the backend-action queue (crates/srv-core/src/persist_subscriber.rs)
7Move 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.


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 gate

There 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.

The memo that performs the resolution is blockAgentColor in BlockFrame_Default_Component (blockframe.tsx):

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"

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”

autotitle.ts:

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.

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:

NameHex
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.

Three rules keep the focus border correct (design notes in docs/specs/pane-highlight-fix-plan.md):

  1. The border does not depend on a pane count. A pane keeps its focus border whatever the tab’s blockids hold; no class (such as the removed block-no-highlight) suppresses it when a tab has one pane.

  2. A fresh tab gets a focused node. validateFocusedNode bootstraps focus when both treeState.focusedNodeId and focusedNodeIdStack are undefined: it focuses leafOrder[0], the first non-picker leaf (defaultFocusLeaf, layoutFocus.ts).

  3. A tab dragged out disposes its model. deleteLayoutModelForTab (frontend/layout/lib/layoutModelHooks.ts) calls model.dispose() after the tab moves to the other workspace, so no reactive root outlives it. It is called on drag-out from frontend/app/drag/CrossWindowDropOverlay.tsx.


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 }).

FunctionPurpose
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).

The LayoutModel reads its row through getLayoutStateAtomFromTab (layoutAtom.ts), a plain accessor over the MOS entry:

layoutAtom.ts
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):

  1. 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’s layoutOutbox (frontend/layout/lib/layoutModel.ts). intentForAction maps each tree action to one intent: move, swap, resize, insert, insertatindex, delete, replace, splithorizontal, splitvertical, minimize, restore or clear. FocusNode and MagnifyNodeToggle become a view intent, which changes no tree (frontend/layout/lib/layoutIntentActions.ts).
  2. Send in order. flushLayoutOutbox sends the outbox one item at a time (frontend/layout/lib/layoutIntents.ts). Each intent goes as LayoutApplyIntentCommand (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 with queueLayoutCommand (layoutIntents.ts, called by sendStackCommand, frontend/layout/lib/layoutPersistence.ts).
  3. srv applies and stores it. apply_layout_intent (crates/srv/src/server/service/layout_intents.rs) dispatches Command::LayoutApplyIntent while 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 emits LayoutTreeReplaced, FocusedNodeChanged and MagnifiedNodeChanged for what changed. apply_layout_intent writes 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 answers applied: false.
  4. 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), reconcileWithStoredLayout compares 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).

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 title
  • meta["pane-title:color"] — user-set title color
  • meta["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 linked LayoutState object

LayoutState is a MuxObj of type "layout". Persisted fields:

  • rootnode — serialized layout tree
  • focusednodeid — focused node ID
  • magnifiednodeid — magnified node ID
  • leaforder — 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.


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):

WriterFieldsWhen
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 themLayoutTreeReplaced, LayoutNodeDeleted
apply_focused_node_changed (crates/srv-core/src/persist_subscriber.rs)focusednodeidFocusedNodeChanged
apply_magnified_node_changed (crates/srv-core/src/persist_subscriber.rs)magnifiednodeidMagnifiedNodeChanged
apply_layout_backend_actions_queued (crates/srv-core/src/persist_subscriber/layout_queue.rs)pendingbackendactions, appendedLayoutBackendActionsQueued
resync_tab (crates/srv-core/src/persist_subscriber/resync.rs)rootnode, focus and magnify, from the reducer’s own stateThe event bus lagged and dropped events
write_default_three_pane_layout (crates/srv-core/src/backend/wcore/mod.rs)The whole rowA 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 correct

Each 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).

  • 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).

┌─────────────────────────────────────────────────────────────────────────────┐
│ 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 │
└─────────────────────────────────────────────────────────────────────────────┘
ConcernFile
LayoutModel classfrontend/layout/lib/layoutModel.ts
localTreeStateAtom initfrontend/layout/lib/layoutModel.ts
focusedNodeId getterfrontend/layout/lib/layoutModel.ts
focusedNode memofrontend/layout/lib/layoutModel.ts
FocusNode reducer armfrontend/layout/lib/layoutModel.ts
validateFocusedNode (bootstrap + reconcile)frontend/layout/lib/layoutFocus.ts
isFocused memo (per-node)frontend/layout/lib/layoutNodeModels.ts
Tree action → layout intentfrontend/layout/lib/layoutIntentActions.ts
Intent outbox, send, compare with srv’s treefrontend/layout/lib/layoutIntents.ts
srv: apply and store an intentcrates/srv/src/server/service/layout_intents.rs
srv: LayoutApplyIntent reducer armcrates/srv-core/src/reducer/layout/intent.rs
MOS getMuxObjectAtomfrontend/app/store/mos.ts
LayoutState atom from tabfrontend/layout/lib/layoutAtom.ts
AgentPaneState / TurnPhase typesfrontend/app/store/agent-pane-state/types.ts
AgentDocumentState typesfrontend/app/store/agent-document/types.ts
BrowserPaneState typesfrontend/app/store/browser-pane-state/types.ts
EditorPaneState / reducerfrontend/app/store/editor-pane-state-store.ts
blockAgentColor memofrontend/app/block/blockframe.tsx
isUsableFocusRingColorfrontend/app/block/autotitle.ts
block-focused CSS (border)frontend/app/block/block.scss
Layout row writers (persist subscriber)crates/srv-core/src/persist_subscriber.rs
Strong layout authority (design, status)docs/specs/SPEC_STRONG_REDUCER_AUTHORITY_LAYOUT_2026_06_30.md
Reducer-stack master statusdocs/specs/MASTER_REDUCER_STACK_STATUS_2026-05-05.md
Discussion #707 refdocs/specs/SPEC_OBJ_UPDATE_BRIDGE_2026-05-14.md
Border fix plandocs/specs/pane-highlight-fix-plan.md
Focus border tab-switch bugdocs/specs/focus-border-tab-switch-bug.md
Agent-pane-layout reducer (Phase 0)docs/specs/SPEC_AGENT_PANE_LAYOUT_REDUCER_2026_06_02.md