C4 Model - Level 3: Component Diagram
Overview
The Component diagram shows the internal structure of each container, detailing the major components and their interactions within the Sasha Studio system.
Frontend Components
C4Component
title Component Diagram - React SPA
Container_Boundary(spa, "Single-Page Application") {
Component(router, "Router", "React Router", "Handles client-side routing")
Component(auth, "Auth Context", "React Context", "Manages authentication state")
Component(chat, "Chat Interface", "React Component", "Main chat UI with message handling")
Component(sidebar, "Sidebar", "React Component", "Navigation and project selection")
Component(file_browser, "File Browser", "React Component", "File tree and operations")
Component(settings, "Settings Panel", "React Component", "User preferences and config")
Component(ws_client, "WebSocket Client", "WebSocket API", "Real-time communication")
Component(api_client, "API Client", "Axios", "REST API communication")
Component(markdown, "Markdown Renderer", "React Markdown", "Renders formatted content")
Component(editor, "Code Editor", "CodeMirror", "Syntax-highlighted editing")
}
Rel(router, auth, "Checks auth")
Rel(chat, ws_client, "Sends/receives messages")
Rel(chat, api_client, "Fetches history")
Rel(sidebar, api_client, "Gets projects")
Rel(file_browser, api_client, "File operations")
Rel(settings, api_client, "Saves preferences")
Rel(chat, markdown, "Renders messages")
Rel(file_browser, editor, "Edit files")
UpdateLayoutConfig($c4ShapeInRow="3", $c4BoundaryInRow="1")
Frontend Component Details
1. Router Component
File: src/App.jsx
- Manages application routes
- Protected route handling
- Session-based navigation
- Dynamic route parameters
2. Auth Context
File: src/contexts/AuthContext.jsx
- JWT token management
- Login/logout functionality
- Auth state persistence
- API request authentication
3. Chat Interface
File: src/components/ChatInterface.jsx
// Key responsibilities
- Message composition and sending
- Real-time message streaming
- File drag-and-drop
- Voice input integration
- Todo list management
- Tool execution display
4. Sidebar Component
File: src/components/Sidebar.jsx
- Project navigation
- Session history
- Quick actions
- Search functionality
- Mobile responsive
5. File Browser
File: src/components/FileTree.jsx
- Directory tree rendering
- File operations (CRUD)
- Drag-and-drop support
- Context menus
- File preview
6. WebSocket Client
File: src/utils/websocket.js
- Connection management
- Auto-reconnection
- Message queuing
- Event handling
- Authentication
Backend Components
C4Component
title Component Diagram - API Server
Container_Boundary(api, "API Server") {
Component(express_app, "Express App", "Express.js", "Main application server")
Component(auth_middleware, "Auth Middleware", "JWT", "Request authentication")
Component(route_auth, "Auth Routes", "Express Router", "Login/register endpoints")
Component(route_files, "File Routes", "Express Router", "File management endpoints")
Component(route_git, "Git Routes", "Express Router", "Git operations")
Component(ws_server, "WebSocket Server", "ws", "Real-time messaging")
Component(claude_manager, "Claude Manager", "Child Process", "Claude CLI orchestration")
Component(db_layer, "Database Layer", "better-sqlite3", "Data persistence")
Component(doc_processor, "Document Processor", "Custom", "File conversion")
Component(session_manager, "Session Manager", "In-memory", "Active session tracking")
}
Rel(express_app, auth_middleware, "Uses")
Rel(auth_middleware, route_auth, "Protects")
Rel(auth_middleware, route_files, "Protects")
Rel(route_auth, db_layer, "User ops")
Rel(route_files, doc_processor, "Process uploads")
Rel(ws_server, claude_manager, "Spawns Claude")
Rel(ws_server, session_manager, "Tracks sessions")
Rel(claude_manager, session_manager, "Updates status")
Rel(doc_processor, db_layer, "Stores documents")
UpdateLayoutConfig($c4ShapeInRow="3", $c4BoundaryInRow="1")
Backend Component Details
1. Express Application
File: server/index.js
// Core setup
- CORS configuration
- Body parsing
- Static file serving
- Route mounting
- Error handling
- Health checks
2. Authentication Middleware
File: server/middleware/auth.js
- JWT token validation
- Request authentication
- WebSocket authentication
- API key validation
- Session verification
3. Route Components
Auth Routes
File: server/routes/auth.js
- User registration
- Login/logout
- Token refresh
- Password reset
- Status checks
File Routes
File: server/routes/files.js
- File upload handling
- Document conversion
- File browsing
- Download serving
- Deletion operations
Git Routes
File: server/routes/git.js
- Repository status
- Commit operations
- Branch management
- Diff generation
- History retrieval
4. WebSocket Server
File: server/index.js (WebSocket section)
// Message types handled
- 'claude-request': New AI query
- 'abort-claude': Cancel operation
- 'get-messages': Fetch history
- 'clear-messages': Clear session
- 'update-tools-settings': Config update
5. Claude Manager
File: server/claude-cli.js
class ClaudeManager {
spawnClaude(command, options)
abortClaudeSession(sessionId)
handleOutputStream(data)
parseToolUsage(output)
manageTempFiles(images)
}
6. Database Layer
File: server/database/db.js
// Key operations
- User CRUD
- Session management
- Document storage
- Profile management
- Migration handling
7. Document Processor
File: server/services/document-processor.js
- PDF to Markdown
- DOCX to Markdown
- Text extraction
- Metadata parsing
- Content indexing
8. Session Manager
File: server/projects.js
// Session tracking
- Active sessions Map
- Session metadata
- Message history
- Status updates
- Cleanup routines
Data Flow Components
graph TB
subgraph "User Interaction Flow"
UI[User Input] --> Validate[Input Validation]
Validate --> Format[Message Formatting]
Format --> Context[Context Addition]
Context --> Send[Send to Claude]
end
subgraph "AI Processing Flow"
Receive[Receive Prompt] --> Parse[Parse Request]
Parse --> Spawn[Spawn Claude]
Spawn --> Stream[Stream Response]
Stream --> Tools[Handle Tools]
Tools --> Complete[Complete Response]
end
subgraph "Storage Flow"
Message[Message Data] --> Serialize[Serialize]
Serialize --> Store[Store in DB]
Store --> Index[Index for Search]
Index --> Cache[Update Cache]
end
Component Interactions
Message Processing Pipeline
sequenceDiagram
participant User
participant ChatUI
participant WebSocket
participant Server
participant Claude
participant Database
User->>ChatUI: Type message
ChatUI->>WebSocket: Send message
WebSocket->>Server: Forward request
Server->>Claude: Spawn with prompt
Claude-->>Server: Stream response
Server-->>WebSocket: Forward chunks
WebSocket-->>ChatUI: Update UI
Server->>Database: Save conversation
File Upload Pipeline
sequenceDiagram
participant User
participant FileUI
participant API
participant Processor
participant Storage
participant Database
User->>FileUI: Select file
FileUI->>API: Upload file
API->>Processor: Convert to MD
Processor->>Storage: Save file
Storage->>Database: Store metadata
Database-->>API: Confirm stored
API-->>FileUI: Upload complete
Component Configuration
Frontend Configuration
// src/config/appConfig.js
export default {
API_URL: process.env.VITE_API_URL,
WS_URL: process.env.VITE_WS_URL,
MAX_FILE_SIZE: 50 * 1024 * 1024,
SUPPORTED_FORMATS: ['pdf', 'docx', 'txt', 'md'],
AUTO_SAVE_INTERVAL: 30000,
MESSAGE_CACHE_SIZE: 50
}
Backend Configuration
// server/config.js
export const config = {
PORT: process.env.PORT || 3005,
JWT_SECRET: process.env.JWT_SECRET,
SESSION_SECRET: process.env.SESSION_SECRET,
DB_PATH: process.env.DB_PATH,
CLAUDE_TIMEOUT: 900000,
MAX_UPLOAD_SIZE: 52428800
}
Component Dependencies
Frontend Dependencies Graph
graph LR
App[App.jsx] --> Router[React Router]
App --> Auth[AuthContext]
App --> Theme[ThemeContext]
Chat[ChatInterface] --> WS[WebSocket]
Chat --> API[API Client]
Chat --> MD[Markdown]
File[FileTree] --> API
File --> Editor[CodeMirror]
Backend Dependencies Graph
graph LR
Server[index.js] --> Express[Express]
Server --> WS[WebSocket]
Server --> Auth[Auth Middleware]
Routes[Routes] --> DB[Database]
Routes --> Services[Services]
Claude[Claude Manager] --> CP[Child Process]
Claude --> PTY[node-pty]
Error Handling Components
Frontend Error Boundary
// src/components/ErrorBoundary.jsx
class ErrorBoundary extends Component {
componentDidCatch(error, errorInfo)
handleReset()
render() // Fallback UI
}
Backend Error Middleware
// server/middleware/error.js
function errorHandler(err, req, res, next) {
logError(err)
sanitizeError(err)
sendErrorResponse(res, err)
}
Performance Optimization Components
Frontend Optimizations
- React.memo for expensive components
- useMemo for computed values
- useCallback for stable references
- Virtual scrolling for long lists
- Code splitting with lazy loading
Backend Optimizations
- Database connection pooling
- Response compression
- Static file caching
- Request rate limiting
- Stream processing
Security Components
Frontend Security
- XSS prevention via React
- CSRF token handling
- Secure credential storage
- Input sanitization
- Content Security Policy
Backend Security
- JWT authentication
- Password hashing (bcrypt)
- SQL injection prevention
- Rate limiting
- CORS configuration
- Security headers
Testing Components
Frontend Testing
// Component tests
- Unit tests (Jest)
- Component tests (React Testing Library)
- Integration tests
- E2E tests (Cypress)
Backend Testing
// API tests
- Unit tests (Jest)
- API endpoint tests
- WebSocket tests
- Database tests
- Claude integration tests