Overview
The thread system is built into themessagesSlice and provides:
- Thread isolation: Each thread maintains its own message history
- Backward compatibility: Existing code continues to work with the main thread
- Persistent storage: Threads can be persisted using storage adapters
- UI components: Ready-to-use thread management components
Core Concepts
Thread Structure
Each thread contains:Default Thread
Cedar automatically creates a default thread with IDDEFAULT_THREAD_ID that serves as the main conversation thread.
Using Thread Management
Basic Thread Operations
Thread-Aware Message Operations
All message operations support an optionalthreadId parameter. If not provided, they operate on the current thread:
useThreadController Hook
TheuseThreadController hook provides a convenient interface for thread management:
Return Values
string
The ID of the currently active thread
string[]
Array of all thread IDs (memoized to prevent re-renders)
Methods
(threadId?: string, name?: string) => string
Creates a new thread and returns its ID. If no threadId provided, generates a
unique one.
(threadId: string) => void
Deletes a thread. Cannot delete the default thread or current thread.
(threadId: string, name?: string) => void
Switches to a thread, creating it if it doesn’t exist.
(threadId: string, name: string) => void
Updates the name of an existing thread.
(threadId: string) => void
Sets the main thread ID (ensures thread exists first).
() => string[]
Returns all thread IDs.
ChatThreadController Component
Cedar provides a ready-to-use UI component for thread management:Props
string
Optional CSS class name for styling
(threadId: string) => void
Callback fired when thread changes
boolean
default:"true"
Whether to show the create new thread button
boolean
default:"true"
Whether to show the thread history dropdown
MessagesSlice Thread API
ThemessagesSlice provides the core thread management functionality:
State Structure
Thread Safety
Storage Integration
Threads integrate with Cedar’s storage system for persistence:Auto-Thread Creation
When using storage adapters, Cedar can automatically create threads:Best Practices
Thread Management
Memory Management
Efficient Updates: The thread system uses memoization to prevent unnecessary re-renders:
Error Handling
Migration from Single Thread
Existing Cedar applications automatically work with the thread system:1
Backward Compatibility
The
messages property continues to work and reflects the current thread’s messages.2
Gradual Migration
You can gradually adopt thread-specific operations:
tsx // Old way (still works) const messages = useCedarStore(state => state.messages); // New way (thread-aware) const messages = useCedarStore(state => state.getThreadMessages()); 3
Enhanced Features
Add thread management UI when ready:

