Session Storage Logic
Relevant source files
The following files were used as context for generating this wiki page:
Introduction
The Session Storage Logic in Claude Cowork provides a robust system for persisting and managing AI-driven collaboration tasks. It encompasses both a persistent backend storage layer using SQLite and a reactive frontend state management layer using Zustand. This architecture ensures that user conversations, tool usage histories, and environment configurations are maintained across application restarts while providing real-time UI updates during active streaming.
The system is responsible for tracking session metadata such as working directories (CWD), allowed tools, and execution statuses (e.g., idle, running, completed). It also handles the recording of granular stream messages, allowing users to resume previous work or review the AI's "thinking" process and tool outputs at a later time.
Sources: src/electron/libs/session-store.ts, src/ui/store/useAppStore.ts, README_ZH.md:88-93
Backend Persistence Layer
The backend utilizes the better-sqlite3 library in WAL (Write-Ahead Logging) mode to handle data persistence. The primary class, SessionStore, manages the lifecycle of sessions and their associated messages.
Database Schema
The storage logic relies on two primary tables: sessions for metadata and messages for the actual conversation and tool logs.
The diagram above illustrates the relationship between session metadata and the serialized stream messages.
| Table | Field | Type | Description |
|---|---|---|---|
| sessions | id | TEXT | Unique UUID for the application session. |
status | TEXT | Current state (idle, running, etc.). | |
cwd | TEXT | The working directory for the AI agent. | |
claude_session_id | TEXT | Internal ID for the Claude Agent SDK. | |
| messages | session_id | TEXT | Foreign key referencing the parent session. |
data | TEXT | JSON stringified StreamMessage object. |
Sources: src/electron/libs/session-store.ts:182-212
Key Store Operations
- Initialization: Sets up the SQLite database and loads existing sessions into an in-memory
Mapfor fast access. - Recording Messages: The
recordMessagefunction persists incoming AI stream events into the database. - Session Management: Includes methods for
createSession,updateSession,deleteSession, andgetSessionHistory.
Sources: src/electron/libs/session-store.ts:44-173
Frontend State Management
The frontend utilizes Zustand via useAppStore to manage session visibility and user interactions. This store acts as the single source of truth for the React UI.
Data Synchronization Flow
The UI synchronizes with the backend storage through Inter-Process Communication (IPC) events.
This flow ensures that session metadata is loaded first, while heavy message histories are fetched only when a session is activated.
Sources: src/ui/store/useAppStore.ts:65-154, src/ui/App.tsx:125-131
Session Views and Hydration
The store defines a SessionView type which extends stored data with UI-specific flags:
- hydrated: A boolean indicating if the message history has been loaded from the database.
- permissionRequests: Tracks active tool-use requests that require user approval.
Sources: src/ui/store/useAppStore.ts:13-24
Stream Message Handling
Storage logic distinguishes between metadata updates and real-time streaming data. While the sessions table is updated on status changes, the messages table grows as the AI agent provides output.
Message Recording Logic
When a stream.message event is received via IPC, the application performs two actions:
- Frontend: Appends the message to the
messagesarray in the corresponding session's Zustand state. - Backend: Triggers
recordMessagein the Electron main process to save the event to SQLite.
// Example of recording a message in the backend
recordMessage(sessionId: string, message: StreamMessage): void {
const id = ('uuid' in message && message.uuid) ? String(message.uuid) : crypto.randomUUID();
this.db
.prepare(
`insert or ignore into messages (id, session_id, data, created_at) values (?, ?, ?, ?)`
)
.run(id, sessionId, JSON.stringify(message), Date.now());
}
Sources: src/electron/libs/session-store.ts:128-135, src/ui/store/useAppStore.ts:178-189
Configuration and Environment Storage
Separate from session history, the system manages API configurations (Key, Base URL, Model) via config-store.ts. This configuration is stored in api-config.json within the user data path.
- Logic: The store ensures that the directory exists and validates that the API Key, Base URL, and Model are present before saving.
- Integration: The
SessionStoreoften uses these settings when initializing the Claude Agent SDK for a specific session.
Sources: src/electron/libs/config-store.ts:13-60, src/electron/main.ts:124-140
Conclusion
The Session Storage Logic effectively bridges the gap between persistent local storage and reactive UI state. By leveraging SQLite for long-term persistence and Zustand for transient UI state, the system provides a seamless experience for managing complex AI workflows, ensuring no data is lost during intensive streaming tasks or unexpected application exits.