Chat Interface & State
Relevant source files
The following files were used as context for generating this wiki page:
The Chat Interface & State represents the core interactive layer of the SecondLayer platform, facilitating real-time legal assistance through a combination of agentic LLM loops and specific Model Context Protocol (MCP) tools. It utilizes a modular architecture that separates UI components, application logic, and global state management to ensure scalability and performance.
The system transitioned from a monolithic "God Component" (ChatLayout) to a refined, service-oriented architecture. This evolution introduced a dedicated state management layer using Zustand for local persistence and React Query for server-side state synchronization, allowing chat messages and thinking steps to survive page refreshes.
Sources: lexwebapp/COMPLETE_REFACTORING_SUMMARY.md:16-45, lexwebapp/STATE_MANAGEMENT_GUIDE.md:6-25
Architecture Overview
The chat system is built upon a layered architecture where the frontend communicates with a backend service hosting various MCP tools. The interface supports two primary modes: AI Chat Mode (agentic loop) and Manual Tool Mode (direct tool execution).
The diagram shows the data flow from user input through the state management and service layers to the backend MCP tools.
Sources: lexwebapp/src/pages/ChatPage/index.tsx:75-95, lexwebapp/BUILD_SUMMARY.md:120-135
State Management
Global state for the chat interface is managed primarily via Zustand, specifically through the chatStore. This store handles the lifecycle of messages, streaming states, and the "thinking steps" generated by the AI.
ChatStore Actions & State
The store provides several critical actions to manage the conversation flow:
- Message Persistence: Messages are stored and persist across sessions via
localStorage. - Streaming Control: Tracks
isStreamingstatus and providescancelStreamto abort active requests. - Incremental Updates: Supports
updateMessagefor real-time text appending andaddThinkingStepfor progressive rendering of the AI's logic.
| Action/Property | Description |
|---|---|
messages | Array of message objects (User/Assistant). |
isStreaming | Boolean flag indicating an active API request. |
addMessage | Adds a new message to the thread. |
updateMessage | Updates content of an existing message (used in SSE). |
addThinkingStep | Appends a progressive step to the AI's reasoning chain. |
clearMessages | Resets the chat history. |
Sources: lexwebapp/src/stores/chatStore.ts, lexwebapp/BUILD_SUMMARY.md:138-145, lexwebapp/STATE_MANAGEMENT_GUIDE.md:145-165
AI Chat & MCP Tool Integration
The system supports 43 distinct MCP tools, ranging from court case searches to legislative monitoring. The ChatPage component acts as the orchestrator for these tools.
Execution Flow
When a user sends a query, the system determines the mode:
- AI Chat Mode: Initiates an agentic loop where the LLM decides which tools to call.
- Manual Mode: The user selects a specific tool (e.g.,
search_legal_precedents), and the input is parsed into tool-specific parameters.
The sequence diagram illustrates the Server-Sent Events (SSE) streaming mechanism used to provide real-time updates to the UI.
Sources: lexwebapp/src/pages/ChatPage/index.tsx:75-125, lexwebapp/BUILD_SUMMARY.md:110-125
Key Components
ChatPage Component
The ChatPage serves as the main route for conversation. It leverages useMCPTool and useAIChat hooks to interface with the backend. It also handles the "Regenerate" logic, which removes the last assistant/user pair and re-triggers the query.
Sources: lexwebapp/src/pages/ChatPage/index.tsx:18-35, lexwebapp/src/pages/ChatPage/index.tsx:130-145
ChatLayout / MainLayout
Following the refactoring, the MainLayout provides the structural shell (Sidebar, Header, RightPanel), while the ChatPage is injected via the Router's Outlet. The RightPanel is designed to auto-open when legal evidence, such as court decisions or citations, is detected in the message stream.
Sources: lexwebapp/src/components/ChatLayout.tsx:110-125, lexwebapp/COMPLETE_REFACTORING_SUMMARY.md:115-135
Data Parsing Logic
The interface includes dedicated parsing logic to transform unstructured user input into structured tool parameters based on the selected MCP tool.
const parseContentToToolParams = (toolName: string, content: string): any => {
switch (toolName) {
case 'search_legal_precedents':
return { query: content, limit: 10 };
case 'search_legislation':
return { query: content, limit: 5 };
case 'openreyestr_search_entities':
return { query: content, entity_type: 'all', limit: 10 };
default:
return { query: content };
}
};
Sources: lexwebapp/src/pages/ChatPage/index.tsx:50-90, lexwebapp/src/components/ChatLayout.tsx:150-180
Implementation Details
The transition to a Service Layer ensured that API logic is no longer scattered. LegalService handles the underlying HTTP/SSE communication, while the frontend components focus on UI rendering and state interaction.
| Feature | Implementation |
|---|---|
| SSE Client | Universal client managing connection, retries (3 attempts), and AbortController for cancellation. |
| Thinking Steps | Progressive rendering of reasoning_chain steps to show AI logic before the final answer. |
| Evidence Panel | Aggregates decisions, citations, and documents from all messages into a side panel. |
| Type Safety | Full TypeScript coverage for 43 MCP tools and their specific request/response shapes. |
Sources: lexwebapp/PHASE3_SUMMARY.md:70-95, lexwebapp/BUILD_SUMMARY.md:15-35, lexwebapp/src/components/ChatLayout.tsx:90-105
Summary
The Chat Interface & State system provides a robust, real-time environment for legal research. By leveraging Zustand for persistent local state and a dedicated service layer for MCP tool integration, the platform maintains a high degree of responsiveness and state consistency. The architecture supports both automated AI reasoning and explicit manual tool usage, all within a type-safe and modular frontend framework.