Web state layer
A component reads "my draft", and the enclosing SessionScopeProvider decides whose, so rendering it twice against two sessions cannot collide.
Layers
| Layer | Contains | Access |
|---|---|---|
| Global store | wsStatus, agentSettings, conversations (the list), rowsByView, rightDock, and the durable per-session maps (composerDrafts, composerSettingsBySession, runningTasks) | useSessionStore |
| Per-session store instance | this session's draft, settings, running, contextPanelOpen | useSessionScope, inside a SessionScopeProvider |
| View state | tab strip, pane layout, split ratio, which pane has focus | center-tabs-store; belongs to the window, not a session |
Split by ownership, not storage shape.
Scope
| File | Holds |
|---|---|
lib/session-store/session-scope-registry.ts | Store factory and a module-level Map<sid, store>. Instances survive pane unmount; dropSessionStore drops them only when the session is deleted (removeConversation, dropChatDraft). |
lib/session-store/session-scope.tsx | SessionScopeProvider sid=…, useSessionScope(selector). With no provider it reads an empty scope (no session) and warns once in the console, never the focused session: that fallback is the bug this removes, and one misplaced component does not take the page down. |
| Providers | FocusedComposer in components/app-shell.tsx (single-session composer, focused chat key) and PeerSessionPane (each split pane) |
Scope and global stay in step
| Direction | How |
|---|---|
| Scope to global | A setter updates its instance first, so the pane repaints on the same tick, then writes through to the global keyed setter. Hooks come from installScopeWriteThrough at the global store's init, keeping the import one-directional. |
| Global to scope | setComposerInputFor, setComposerSettings, setRunningTaskFor call pushToSessionStore, so a WS frame, legacy bridge or tab transfer reaches the live instance. |
| Seeding | An instance seeds from the global maps on first render, so a remount after reload shows the persisted draft. |
No mirrors: the global store has no composerInput, composerSettings, runningTask or contextPanelFor. The focused draft is composerDrafts[activeChatKey], computed where needed. Anything that must outlive the tab (localStorage, tab-transfer wire format, cross-session sidebar views) stays in the global keyed maps.
Why instances rather than a keyed global slice
| Approach | Example | Trade-off |
|---|---|---|
| Store per instance (chosen) | VS Code editor groups; Zustand supports it | Strongest isolation. Shared data needs a separate layer. |
| One global store, keyed, with a scope tag | Redux normalization, TanStack Query, Slack-style multi-channel UIs | Easy debugging and cross-session features, but discipline by convention: one read of the global pointer regresses it. |
| Physical isolation | Chrome renderer processes | Justified by running untrusted code; process memory and IPC cost for no gain in an app's own split view. |
With a keyed slice every read and write supplies the key; a wrong one, or an omitted one meaning the focused session, stays type-correct. With an instance the provider supplies the key once. A keystroke also notifies only that session's subscribers. Parallel Record<sid, T> maps stay, with transcript rows keyed by view: instances persist through them.
The failure a global singleton produces
A component rendered twice reads state that exists once. Both copies show the same value or the last write wins. The type system allows it, and it shows only in split view after a specific interaction.
/context badge: a global boolean opens both popovers. A contextPanelFor: sid pointer fixes that, but each consumer must still compare the right id. In the scope it is a plain contextPanelOpen.
A mirror, a global copy of the focused session's keyed entry, is worse: every write updates both, every switch swaps it, components branch on whether they are bound, and the window-to-window transfer has to rebuild it.
Main store fields
apps/web/lib/session-store/index.ts, shape in ConvState.
Per session
Record<sessionId, T> maps.
| Field | What it holds |
|---|---|
conversations | sidebar summary per session (keyed, but see Group C — it is a list, not per-session view state) |
rowsByView | the transcript rows of each view (a conversation, or one sub-agent's transcript), keyed by view and row id; the same id in two views is two rows. Read through selectRow(viewKey, id), which draws a row with its overlays. Written only through apply-transcript-update.ts: applyRead for reads, numbered transcript_update changes and text frames for the server's live rows, and applyLocalChange for rows and overlays only this browser holds. |
messageOrder | ordered row-id list per view |
overlaysByView, heldFramesByView | fields this browser shows ahead of the server over a row, each with the event that ends it, and text frames waiting for the row they belong to |
pendingProjectsByChat | project chosen for an unsent chat, keyed by provisional chat key |
runningTasks | per-session running task; drives each composer's send/stop button |
trees | latest live context tree per session |
tokens | token usage per session |
contextWindow | context-window size per session |
heads | active DAG head (selected branch tip) per session |
additionalWorkingDirsBySession | extra working directories per session |
composerDrafts | unsent composer text per session, persisted to localStorage |
composerSettingsBySession | active-branch tool toggles / thinking effort and branch identity, keyed by session for the visible projection; durable settings belong to branch references |
pendingDecisions is a flat FIFO whose entries carry sessionId (session-store/types.ts); every consumer filters it, and a mis-scoped one would swallow or duplicate another session's question.
Global values that describe one session
Each moves onto SessionScopeState, as the table under Where they go sets out.
| Field | Why it should be scoped |
|---|---|
currentSessionId | "the" active session. With two panes there are two, and one is merely the focused one. |
activeChatKey | same, for unsent drafts using a provisional local_* id |
composerFocusTick | a counter bumped to ask "the" composer to focus its textarea; with two composers it is ambiguous which one obeys |
fnFormFunction | which function's parameter form has replaced the textarea. Belongs to one composer, not the app. |
fnFormPrefill | prefilled arguments for that form |
fnFormForkOf | fork anchor node for a re-run |
fnFormClosing | close-animation flag for that form |
welcomeVisible | whether the chat area shows the welcome screen — a per-pane condition |
transcriptLoadingId | holds one in-flight session id; two panes can be loading at once |
branchInfo | branch chip for "the current conversation" |
statusBadge | topbar status label; derived from one session's run state |
paused | pause flag, per running session in principle |
providerInfo | provider/model shown in the header for the current session |
detailNode | selected DAG node shown in the right rail |
nodeSelected | "a DAG node is selected" gate |
Genuinely global
| Field | What it is |
|---|---|
wsStatus | WebSocket connection state |
agentSettings | Chat model badge, mirrored from runtimeState._agentSettings |
conversations | the session list for the sidebar (a catalogue of all sessions, not one session's view state) |
rightDock | right sidebar open/collapsed and which view, persisted to localStorage |
Where the single-session fields go
| Field | Destination |
|---|---|
fnFormFunction, fnFormPrefill, fnFormForkOf, fnFormClosing | One fnForm property. Sidebar and favourites name an explicit target session. Consumers: resolve-mode.ts, use-fn-form-state.ts, use-fn-form-wrapper.ts, use-pending-run-function.ts, favorites-list.tsx, sidebar.tsx, runtime-block.tsx, functions-panel.ts |
welcomeVisible, transcriptLoadingId | Per-session booleans read by welcome-screen.tsx and message-list.tsx |
composerFocusTick | Per-session counter, so focusing one pane does not yank the other |
branchInfo, statusBadge, paused, providerInfo | Per session; the topbar reads the focused scope |
currentSessionId, activeChatKey | Stay global as focus pointers, meaning "the focused pane's session"; center-tabs-store tracks it through activeId |
Other stores
| File | Holds |
|---|---|
lib/tabs/center-tabs-store.ts, lib/tabs/store/ | Tab strip and pane layout: tabs, activeId, groups, splitWebTabId, splitRatio. Global view state; the scope tree gets its session ids here. |
lib/tabs/center-tab-groups.ts | Pure functions over the layout; no state |
lib/chat/history/chat-scroll.ts | Scroll position by chat key, through a storage interface |
lib/abilities/functions-store.ts, skills-store.ts, plugins-store.ts | Page catalogues and their filter, sort and search state; global |
lib/files/files-shared.ts | Project list, file reads, drafts by path; per file |
Legacy runtime state
runtimeState (lib/runtime-bridge/state.ts) is a module-level singleton predating the React store. WebSocket frames reach the runtime bridge, which updates it and writes through to the store; conv-store-mirror.ts keeps store.conversations authoritative. It is transitional.
| Field | Meaning |
|---|---|
currentSessionId | The legacy active session. Frames gated on session_id === runtimeState.currentSessionId in chat-handlers.ts and conversations.ts are dropped or misrouted for a non-focused session. |
conversations | Heavy per-session map with full messages, distinct from the store's summaries |
isRunning | One global flag |
It is still the default for message rendering outside split view, session switching, branch badge refresh and most frame routing. The split pane bypasses it: #chatView is a singleton addressed by hardcoded ids in about ten bridge modules, so AppShell hides it while split, each pane renders React off the store and sends its own load_session.
What removing it requires
- Every
currentSessionIdgate inchat-handlers.tsandconversations.tsis a store write keyed ondata.session_id, so background frames land. Needs the focus pointers first. runtimeState.conversationshas no readers the keyed maps do not cover, makingconv-store-mirror.tsunnecessary.isRunninghas no readers;runningTaskscovers it.- The
#chatViewshell is gone, replaced by the React pathPeerSessionPaneproves. The heaviest condition.
A wrong gate removal silently drops frames, so each pairs with a check that the frame still reaches its session.
Non-goals
| Stays | Why |
|---|---|
detailNode, nodeSelected, rightDock | The right sidebar and DAG are one dock following the focused session; nothing renders them twice |
| Topbar badge display, settings-page stores | Focused or global by definition |
Parallel Record<sid, T> maps | Instances seed from and persist through them |
| More than two panes | The mechanism allows it; nothing is designed or verified for it |
Implementation status
| Status | Items |
|---|---|
| Implemented | Scope registry and provider; mirrors removed; wire formats (SessionTransferSnapshot, ChatTransferState) carry no duplicates of focused keyed entries |
| Not yet | The single-session fields still sit in the global store: each is a move onto SessionScopeState, fn-form the largest with eight consumers. Retiring the legacy runtime state spans lib/runtime-bridge/, is sequenced last, and is done per module in one pass, since partial completion is worse than either endpoint. |
Center tabs and split layout · Composer modes · UI invariants · Interaction feedback