Pika's frontend is a production-ready SvelteKit application that provides a complete chat interface, authentication integration, and admin capabilities. This page explains the frontend architecture and design decisions.
Technology Stack
Section titled “Technology Stack”SvelteKit
Section titled “SvelteKit”Why SvelteKit:
- Fast and lightweight: Minimal JavaScript bundle size
- Server-side rendering: Better SEO and initial load performance
- Built-in routing: File-based routing system
- Type-safe: Full TypeScript support
- Developer experience: Hot module replacement, intuitive API
Trade-offs:
- Less widespread than React (smaller ecosystem)
- Newer framework (less mature tooling)
- We accept this for performance and developer experience benefits
TypeScript
Section titled “TypeScript”All frontend code is written in TypeScript for:
- Type safety across frontend and backend
- Better IDE support
- Catching errors at compile time
- Shared types with backend (via
pika-sharedpackage)
Tailwind CSS
Section titled “Tailwind CSS”Styling uses Tailwind CSS for:
- Utility-first approach
- Consistent design system
- Small production bundle (unused styles purged)
- Responsive design patterns
Other Key Libraries
Section titled “Other Key Libraries”- @auth/sveltekit: Authentication framework integration
- marked: Markdown parsing for agent responses
- DOMPurify: XSS protection for HTML content
- highlight.js: Code syntax highlighting in responses
Application Structure
Section titled “Application Structure”Directory Layout
Section titled “Directory Layout”apps/pika-chat/├── src/│ ├── lib/│ │ ├── client/ # Client-side code│ │ │ ├── features/│ │ │ │ └── chat/│ │ │ │ ├── components/ # Chat UI components│ │ │ │ ├── markdown-message-renderer/│ │ │ │ │ └── custom-markdown-tag-components/ # Your custom components│ │ │ │ └── stores/ # State management│ │ │ └── utils/ # Client utilities│ │ └── server/ # Server-side code│ │ ├── auth-provider/ # Authentication (pluggable)│ │ └── api/ # Backend API integration│ ├── routes/ # SvelteKit routes│ │ ├── +page.svelte # Home page│ │ ├── chat/│ │ │ └── [chatAppId]/│ │ │ └── [sessionId]/+page.svelte # Chat page│ │ ├── admin/ # Admin interface│ │ └── api/ # API endpoints│ └── app.html # HTML template├── static/ # Static assets└── svelte.config.js # SvelteKit configurationCore Components
Section titled “Core Components”1. Authentication Layer
Section titled “1. Authentication Layer”Location: src/lib/server/auth-provider/
Purpose: Pluggable authentication that integrates with your enterprise systems
Key Files:
// auth-provider.ts - Your implementationexport async function handleSignIn(/* ... */) { // Integrate with your SSO, SAML, OAuth, etc. return { userId: '...', email: '...', userType: 'internal' | 'external', customData: { accountId: '...', // ... entity and custom data } };}What You Customize:
- Sign-in flow
- Sign-out flow
- Session validation
- User profile retrieval
- Entity/organization mapping
What Pika Provides:
- JWT generation and validation
- Session management
- Cookie handling
- CSRF protection
2. Chat Interface
Section titled “2. Chat Interface”Location: src/lib/client/features/chat/
Key Components:
ChatSession
Section titled “ChatSession”<!-- Main chat container --><script> import MessageList from './MessageList.svelte'; import MessageInput from './MessageInput.svelte'; import SessionSidebar from './SessionSidebar.svelte';</script>
<div class="chat-container"> <SessionSidebar /> <div class="chat-main"> <MessageList {messages} /> <MessageInput on:send={handleSend} /> </div></div>MessageList
Section titled “MessageList”- Renders conversation history
- Handles streaming message updates
- Manages scroll position (auto-scroll to bottom)
- Loading states and error handling
MessageInput
Section titled “MessageInput”- Multi-line text input with auto-resize
- File upload support (if enabled)
- Keyboard shortcuts (Enter to send, Shift+Enter for newline)
- Character count and limits
MessageRenderer
Section titled “MessageRenderer”- Parses markdown from agent responses
- Renders custom XML tags via web components
- Syntax highlighting for code blocks
- Link handling and sanitization
3. Markdown and Custom Components
Section titled “3. Markdown and Custom Components”Location: src/lib/client/features/chat/markdown-message-renderer/
How It Works:
- Agent returns message with markdown and XML:
Here's the weather data:
<weather-card city="San Francisco" temp="65" condition="sunny" />
You can also check the forecast for the week.Markdown renderer processes content:
- Markdown → HTML (via
marked) - Custom XML tags → Custom Svelte components
- Code blocks → Syntax highlighted
- Markdown → HTML (via
Custom components render:
<script> export let city; export let temp; export let condition;</script>
<div class="weather-card"> <h3>{city}</h3> <div class="temp">{temp}°F</div> <div class="condition">{condition}</div></div>Your Customization Point: Add custom Svelte components in custom-markdown-tag-components/ to handle domain-specific XML tags from your agents.
4. Session Management
Section titled “4. Session Management”Location: src/lib/client/features/chat/stores/
State Management:
- Svelte stores for reactive state
- Session list and current session
- Message history
- Streaming state
Key Stores:
export const sessions = writable<Session[]>([]);export const currentSession = writable<Session | null>(null);
// messages.tsexport const messages = writable<Message[]>([]);export const streamingMessage = writable<string>('');
// ui.tsexport const sidebarOpen = writable<boolean>(true);export const uploading = writable<boolean>(false);5. API Integration
Section titled “5. API Integration”Location: src/lib/server/api/
Backend Communication:
REST API Calls
Section titled “REST API Calls”export async function createSession(chatAppId: string) { const response = await fetch('/api/sessions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ chatAppId }) }); return response.json();}
export async function getMessages(sessionId: string) { const response = await fetch(`/api/sessions/${sessionId}/messages`); return response.json();}Streaming Agent Responses
Section titled “Streaming Agent Responses”export async function streamAgentResponse( sessionId: string, message: string) { const eventSource = new EventSource( `/api/stream?sessionId=${sessionId}&message=${encodeURIComponent(message)}` );
eventSource.onmessage = (event) => { const token = event.data; streamingMessage.update(current => current + token); };
eventSource.onerror = () => { eventSource.close(); };}6. Admin Interface
Section titled “6. Admin Interface”Location: src/routes/admin/
Capabilities:
- Chat app management (enable/disable, configure)
- User access control
- Session review and search
- Insights and feedback review
- Platform configuration
Key Admin Pages:
/admin/chatapps- Manage chat applications/admin/users- User management/admin/sessions- Session search and review/admin/insights- Feedback and insights/admin/config- Platform configuration
Key Features
Section titled “Key Features”1. Responsive Design
Section titled “1. Responsive Design”Works across desktop, tablet, and mobile:
- Desktop: Full sidebar, multi-column layout
- Tablet: Collapsible sidebar
- Mobile: Bottom sheet navigation, full-screen chat
Tailwind breakpoints:
<div class="hidden md:block lg:w-64"> <!-- Sidebar: hidden on mobile, visible on desktop --></div>2. Real-Time Streaming
Section titled “2. Real-Time Streaming”Agent responses stream token-by-token:
- Server-Sent Events (SSE) for streaming
- Optimistic UI updates
- Graceful handling of connection issues
- Automatic reconnection on failure
3. File Upload
Section titled “3. File Upload”Supports file attachments (if enabled):
- Presigned URL upload to S3
- Progress indication
- File type and size validation
- Drag-and-drop support
4. Session Features
Section titled “4. Session Features”- History: Browse past conversations
- Pinning: Bookmark important sessions
- Sharing: Generate secure share links
- Titles: Auto-generated session titles
- Suggestions: LLM-generated follow-up questions
5. Accessibility
Section titled “5. Accessibility”Built with accessibility in mind:
- Semantic HTML
- ARIA labels and roles
- Keyboard navigation
- Screen reader support
- Focus management
6. Security Features
Section titled “6. Security Features”- XSS Protection: DOMPurify sanitizes HTML
- CSRF Protection: Built into SvelteKit
- Secure Cookies: HTTP-only, secure, SameSite
- JWT Validation: Server-side auth checks
- Rate Limiting: Protection against abuse
Deployment Options
Section titled “Deployment Options”Option 1: AWS Amplify
Section titled “Option 1: AWS Amplify”Pros:
- Automatic CI/CD from Git
- Built-in CDN and SSL
- Environment variable management
- Serverless SSR support
Setup:
amplify initamplify add hostingamplify publishOption 2: Vercel
Section titled “Option 2: Vercel”Pros:
- Excellent SvelteKit support
- Fast global CDN
- Automatic preview deployments
- Easy domain configuration
Setup:
vercel deployOption 3: S3 + CloudFront
Section titled “Option 3: S3 + CloudFront”Pros:
- Full AWS integration
- Custom CDK stack
- Complete control
Setup:
- Build static site:
npm run build - Upload to S3
- Configure CloudFront distribution
Option 4: Standalone Node Server
Section titled “Option 4: Standalone Node Server”Pros:
- Complete control
- Custom middleware
- Works with any hosting
Setup:
pnpm run buildnode build/index.jsConfiguration and Customization
Section titled “Configuration and Customization”Environment Variables
Section titled “Environment Variables”# Backend APIPUBLIC_API_URL=https://api.example.com
# AuthenticationAUTH_SECRET=...AUTH_CALLBACK_URL=...
# Feature flagsPUBLIC_FILE_UPLOAD_ENABLED=truePUBLIC_SELF_CORRECTION_ENABLED=trueTheme Customization
Section titled “Theme Customization”Modify tailwind.config.ts:
export default { theme: { extend: { colors: { primary: '#your-brand-color', // ... other colors } } }}Feature Overrides
Section titled “Feature Overrides”Per-chat-app feature overrides:
// Load from backend APIconst chatApp = await getChatApp(chatAppId);const features = { ...siteDefaults, ...chatApp.featureOverrides};Performance Optimization
Section titled “Performance Optimization”Code Splitting
Section titled “Code Splitting”SvelteKit automatically splits code by route:
- Only load code for current page
- Preload links on hover
- Dynamic imports for heavy components
Bundle Size
Section titled “Bundle Size”Optimizations:
- Tree shaking removes unused code
- Tailwind purges unused styles
- Svelte compiles to vanilla JS (no runtime)
Typical bundle sizes:
- Initial load: ~50KB gzipped
- Per-route: ~10-20KB gzipped
Caching
Section titled “Caching”- Static assets: Long-term caching (immutable)
- API responses: Short-term caching
- Agent responses: No caching (real-time)
Development Workflow
Section titled “Development Workflow”Local Development
Section titled “Local Development”# Install dependenciespnpm install
# Start dev serverpnpm dev
# Open browser# http://localhost:5173Building for Production
Section titled “Building for Production”# Build static sitepnpm build
# Preview production buildpnpm previewTesting
Section titled “Testing”// Component tests with Vitestimport { render } from '@testing-library/svelte';import MessageInput from './MessageInput.svelte';
test('sends message on Enter key', () => { const { getByRole } = render(MessageInput); const input = getByRole('textbox'); // ... test interactions});Integration Points
Section titled “Integration Points”Backend APIs
Section titled “Backend APIs”Frontend calls these backend endpoints:
/api/sessions- Session CRUD/api/sessions/{id}/messages- Message history/api/stream- Streaming agent responses/api/admin/*- Admin operations
Authentication Provider
Section titled “Authentication Provider”Your custom auth provider integrates with:
- Sign-in page
- Session validation middleware
- User profile endpoints
Custom Web Components
Section titled “Custom Web Components”Your Svelte components in custom-markdown-tag-components/:
- Automatically registered by name
- Props passed from XML attributes
- Full Svelte reactivity
Related Documentation
Section titled “Related Documentation”- System Architecture - Overall architecture
- Customize the UI - UI customization guide
- Build Custom Web Components - Component development
- Authentication Integration - Auth setup