Frontend Application - Detailed Documentation¶
Purpose: COMPREHENSIVE code-level documentation of MachineAvatars Next.js frontend
Audience: Frontend Developers, Technical Teams
Repository:machineagents-fe
Last Updated: 2025-12-29
Version: 3.0 (Deep-Dive Edition)
Repository Statistics¶
| Metric | Count | Description |
|---|---|---|
| Total Source Files | 212 | In src/ directory |
| App Routes | 40+ | Next.js 14 App Router pages |
| Reusable Components | 19 | Insrc/components/ |
| App-Level Components | 81 | In src/app/components/ |
| Custom Hooks | 5 | React hooks for state/logic |
| Home Page Sections | 16 | Landing page components |
| Context Providers | 1 | Global state management |
| Utility Modules | 3 | Helper functions |
| Server Actions | 3 | Server-side utilities |
| Public Assets | 71 | Images, avatars, fonts, icons |
Application Routes (40+ Pages)¶
Authentication Routes¶
| Route | File | Type | Description |
|---|---|---|---|
/login |
app/login/page.tsx |
Public | User authentication |
/signup |
app/signup/page.tsx |
Public | New user registration |
/forgot-password |
app/forgot-password/page.tsx |
Public | Password reset |
Dashboard Routes¶
| Route | File | Type | Description |
|---|---|---|---|
/dashboard |
app/dashboard/page.tsx |
Protected | Main dashboard |
/chatbots |
app/chatbots/page.tsx |
Protected | Chatbot list view |
/analytics |
app/analytics/page.tsx |
Protected | Analytics dashboard |
/profile |
app/profile/page.tsx |
Protected | User profile settings |
Chatbot Creation & Management¶
| Route | File | Type | Description |
|---|---|---|---|
/chatbot |
app/chatbot/page.tsx |
Protected | Chatbot creation wizard |
/chatbot-data-source |
app/chatbot-data-source/page.tsx |
Protected | Knowledge base upload |
Chatbot Interfaces (Core Product)¶
3D Chatbot¶
File: app/3d-chatbot/page.tsx (524 lines)
Purpose: Main 3D avatar chatbot playground with websitepreview simulation
Key Features:
- ✅ Real-time 3D avatar rendering
- ✅ Screenshot upload (desktop + mobile)
- ✅ Website preview modal
- ✅ Shared link support (isSharedView parameter)
- ✅ Image compression for large screenshots
- ✅ Device detection (desktop/tablet/mobile)
- ✅ Session management
State Management (27 state variables):
const [avatarName, setAvatarName] = useState<string>("");
const [avatarType, setAvatarType] = useState<string>("");
const [uniqueUrl, setUniqueUrl] = useState<string>("");
const [projectId, setProjectId] = useState<string | null>(null);
const [userId, setUserId] = useState<string | null>(null);
const [selectedProjectId, setSelectedProjectId] = useState<string | null>(null);
const [isSharedLink, setIsSharedLink] = useState(false);
const [desktopScreenshot, setDesktopScreenshot] = useState<string | null>(null);
const [mobileScreenshot, setMobileScreenshot] = useState<string | null>(null);
const [deviceType, setDeviceType] = useState<"desktop" | "mobile" | "tablet">(
"desktop"
);
const [isPreviewModalOpen, setIsPreviewModalOpen] = useState(false);
const [uploadStatus, setUploadStatus] = useState<string>("");
const [isLoadingScreenshots, setIsLoadingScreenshots] = useState(false);
// ...22 more state variables
Screenshot Management:
// Parallel fetching of desktop & mobile screenshots
const fetchScreenshots = async (projectId: string, userId: string) => {
const [desktopResponse, mobileResponse, promptResponse] = await Promise.all([
fetch(
`${API_URL}/screenshots?project_id=${projectId}&user_id=${userId}&device=desktop`
),
fetch(
`${API_URL}/screenshots?project_id=${projectId}&user_id=${userId}&device=mobile`
),
fetch(
`${API_URL}/v2/get-system-prompt?user_id=${userId}&project_id=${projectId}`
),
]);
// Process responses...
};
Image Compression:
const compressImage = (
file: File,
maxWidth: number = 1920,
quality: number = 0.8
): Promise<string> => {
return new Promise((resolve, reject) => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.onload = () => {
const aspectRatio = img.width / img.height;
let newWidth = img.width;
let newHeight = img.height;
if (img.width > maxWidth) {
newWidth = maxWidth;
newHeight = maxWidth / aspectRatio;
}
canvas.width = newWidth;
canvas.height = newHeight;
ctx?.drawImage(img, 0, 0, newWidth, newHeight);
canvas.toBlob(
(blob) => {
if (blob) {
resolve(URL.createObjectURL(blob));
}
},
file.type,
quality
);
};
img.src = URL.createObjectURL(file);
});
};
URL Parameter Handling:
avatarName: Avatar model nameavatarType: Avatar type identifierproject_id: Chatbot project IDuser_id: User identifierselected_project_id: Currently selected projectisSharedView=true: Enables public sharing mode
Shared Link Generation:
const url = `${window.location.origin}/3d-chatbot?avatarName=${avatarName}&avatarType=${avatarType}&project_id=${projectId}&user_id=${userId}&selected_project_id=${selectedProjectId}&isSharedView=true`;
Text Chatbot¶
File: app/text-chatbot/page.tsx
Purpose: Text-based chatbot interface (fallback for 3D)
Differences from 3D:
- No Three.js rendering
- Lighter bundle size
- Faster initial load
- Better mobile performance
Voice Chatbot¶
File: app/voice-chatbot/page.tsx
Purpose: Voice-enabled chatbot with TTS/STT
Additional Features:
- Microphone permissions handling
- Audio playback controls
- Voice activity detection
- TTS response streaming
Billing & Subscription Routes¶
| Route | File | Description |
|---|---|---|
/Billing_details_subscriptionplan |
app/Billing_details_subscriptionplan/page.tsx |
Subscription plan selection |
/Billing_details_paymentmode |
app/Billing_details_paymentmode/page.tsx |
Payment method management |
/Billing_details_invoicecenter |
app/Billing_details_invoicecenter/page.tsx |
Invoice history |
/payment |
app/payment/page.tsx |
Razorpay checkout |
/test-payment |
app/test-payment/page.tsx |
Payment testing (dev only) |
Marketing Pages¶
| Route | File | Description |
|---|---|---|
/ (home) |
app/page.tsx |
Landing page |
/pricing |
app/pricing/page.tsx |
Pricing tiers |
/about-us |
app/about-us/page.tsx |
Company information |
/contact-us |
app/contact-us/page.tsx |
Contact form |
/ai-agents |
app/ai-agents/page.tsx |
AI agents showcase |
Legal Pages¶
| Route | File | Description |
|---|---|---|
/terms |
app/terms/page.tsx |
Terms of service |
/privacy |
app/privacy/page.tsx |
Privacy policy |
/cancellation-refund-policy |
app/cancellation-refund-policy/page.tsx |
Refund policy |
Custom React Hooks (5 Hooks)¶
1. usePromptManager (331 lines)¶
File: src/hooks/usePromptManager.ts
Purpose: Comprehensive LLM prompt and AI model management
State Management (12 state variables):
const [prompt, setPrompt] = useState<string>("");
const [originalPrompt, setOriginalPrompt] = useState<string>("");
const [systemPromptId, setSystemPromptId] = useState<string | null>(null);
const [promptId, setPromptId] = useState<string | null>(null);
const [aiModelId, setAiModelId] = useState<string | null>(null);
const [selectedPurpose, setSelectedPurpose] = useState<any>(null);
const [addedLLMs, setAddedLLMs] = useState<any>(null);
const [masterLLMs, setMasterLLMs] = useState<any>([]);
API Methods (9 functions):
-
fetchSystemPrompt()
-
Fetches current system prompt for project
- Handles array and legacy prompt shapes
- Auto-selects default or first prompt
-
Endpoint:
GET /v2/get-system-prompt -
fetchMasterLLMs()
-
Retrieves all available LLM models
-
Endpoint:
GET /v2/llms -
selectModel(ai_model_id: string)
-
Switches to different AI model
- Updates prompts for selected model
-
Endpoint:
GET /v2/ai-model -
selectPurpose(purpose_id: string)
-
Switches prompt purpose (e.g., customer support, sales)
-
Local state update only
-
updateSystemPrompt()
-
Saves edited prompt (test mode)
- Updates both
selectedPurposeandaddedLLMsstate -
Endpoint:
PATCH /v2/test-system-prompt -
setMasterSystemPrompt()
-
Sets prompt as master (production)
-
Endpoint:
PATCH /v2/set-system-prompt -
setMasterSystemPromptFor(params)
-
Silent master prompt update (no loading state)
-
Direct fetch (not using useHttp)
-
addMasterLLM(id: string)
-
Adds new LLM model to project
-
Endpoint:
PATCH /v2/add-llm -
resetPrompt()
- Resets prompt to default
- Updates local state immediately
- Endpoint:
PATCH /v2/reset-test-system-prompt
Usage Example:
const {
prompt,
setPrompt,
selectModel,
updateSystemPrompt,
hasChanges,
charCount,
loading,
} = usePromptManager(sessionData);
// Edit prompt
const handlePromptChange = (newText: string) => {
setPrompt(newText);
};
// Save changes
const handleSave = async () => {
await updateSystemPrompt();
toast.success("Prompt updated!");
};
State Synchronization:
- Maintains 3 parallel states (
prompt,selectedPurpose,addedLLMs) - Updates all 3 on prompt changes to ensure UI consistency
- Handles race conditions with immediate local updates
2. useUserFeatures (130 lines)¶
File: src/hooks/useUserFeatures.ts
Purpose: Feature flag management and subscription limits
Return Type:
interface UseUserFeaturesReturn {
userFeatures: UserFeatures | null;
isFeatureEnabled: (featureName: string) => boolean;
isLoading: boolean;
error: string | null;
refetchFeatures: () => Promise<void>;
}
Features Tracked:
Raised PDF Upload Limit- 700MB vs 50MBAdvanced AnalyticsCustom BrandingVoice ChatbotMulti-Language Support- (Extensible for future features)
API Integration:
const response = await fetch(`${API_URL}/v2/get-user-features/${userId}`, {
headers: {
Authorization: `Bearer ${authToken}`,
"User-ID": userId,
},
});
Usage Example:
const { isFeatureEnabled, isLoading } = useUserFeatures();
const maxUploadSize = isFeatureEnabled("Raised PDF Upload Limit")
? 700 * 1024 * 1024 // 700MB
: 50 * 1024 * 1024; // 50MB
if (file.size > maxUploadSize) {
alert(`File too large. Max: ${formatFileSize(maxUploadSize)}`);
}
Utility Functions:
// Get max file size based on feature
export const getMaxFileSize = (isRaisedLimitEnabled: boolean): number => {
return isRaisedLimitEnabled ? 700 * 1024 * 1024 : 50 * 1024 * 1024;
};
// Format bytes to human-readable
export const formatFileSize = (bytes: number): string => {
const mb = bytes / (1024 * 1024);
return `${Math.round(mb)}MB`;
};
3. useHttp (82 lines estimated)¶
File: src/hooks/useHttp.ts
Purpose: Generic HTTP request wrapper with loading/error states
Features:
- Automatic JSON parsing
- Loading state management
- Error handling
- Request cancellation support
Signature:
interface UseHttpReturn {
execute: (url: string, options?: RequestInit) => Promise<any>;
loading: boolean;
error: Error | null;
}
Usage in Other Hooks:
const { execute: executeHttp, loading, error } = useHttp();
const data = await executeHttp(`${API_URL}/endpoint`, {
method: "POST",
body: JSON.stringify(payload),
});
4. useSessionData (63 lines estimated)¶
File: src/hooks/useSessionData.ts
Purpose: Session storage management for user/project data
Tracked Data:
user_idproject_idselected_project_idauthTokenuserEmailsession_id
5. useGlobalVideoManager (265 lines estimated)¶
File: src/hooks/useGlobalVideoManager.ts
Purpose: Centralized video playback control across site
Features:
- Single video instance playing at a time
- Auto-pause on navigation
- Video ref management
- State synchronization
Component Breakdown¶
Core UI Components (src/components/)¶
1. 3D Components¶
File: components/ThreeD_Chatbot.js (likely 500+ lines)
Purpose: Main 3D chatbot rendering component
Dependencies:
- Three.js
- @react-three/fiber
- @react-three/drei
Key Features:
- Avatar model loading (GLTF/GLB)
- Animation playback
- Camera controls (OrbitControls)
- Lighting setup (ambient + spotlights)
- Environment mapping
2. Avatar Selection¶
File: components/AvatarSelectionComponent.tsx
Purpose: Avatar picker interface
Features:
- Grid of 400+ avatars
- Filter by gender/style
- Preview on hover
- Selection state management
3. Knowledge Base Upload¶
File: components/FileUploadComponent.tsx
Purpose: Multi-format file upload
Supported File Types:
- PDF (primary)
- Text files
- CSV
- Excel (XLSX)
- Word (DOCX)
Features:
- Drag & drop
- Multiple file upload
- Progress indicators
- File size validation (50MB / 700MB based on features)
- File type validation
- Preview before upload
4. Forms¶
File: components/FormSetupComponent.tsx
Purpose: Multi-step chatbot configuration form
Steps:
- Basic Info (name, type)
- Avatar Selection
- Knowledge Base Upload
- System Prompt Configuration
- Voice Settings (if enabled)
- Deployment Options
Home Page Components (src/components/home/)¶
16 marketing page sections:
-
HeroSection.tsx (5,609 bytes)
-
Hero banner
- CTA buttons
-
Animated background
-
VideoDemoSection.tsx (6,068 bytes)
-
Product demo video
- Video controls
-
Global video manager integration
-
OurAiAgents.tsx (12,046 bytes)
-
AI agents showcase
- 3D/Text/Voice tabs
-
Feature highlights
-
LanguageSelectorSection.tsx (14,614 bytes)
-
Multi-language demo
- Interactive language picker
-
Real-time translation preview
-
PricingSection.tsx (9,928 bytes)
-
Tier comparison table
- Feature matrix
-
CTA for each tier
-
UseCases.tsx (10,444 bytes)
-
Industry use cases
- Customer testimonials
-
Case study cards
-
PlugAndPlaySection.tsx (13,255 bytes)
-
Integration code snippets
- Embed examples (iframe, SDK)
-
API documentation links
-
TryFreeAgentSection.tsx (9,004 bytes)
-
Free trial CTA
- Interactive chatbot demo
-
Sign-up flow
-
HowItWorksSection.tsx (2,418 bytes)
-
Step-by-step process
-
Visual workflow diagram
-
PlatformOverviewSection.tsx (427 bytes)
- High-level feature overview
-
IndustriesSection.tsx (593 bytes)
- Target industries
- Industry-specific benefits
-
ContactSection.tsx (444 bytes)
- Contact form
- Email/chat links
-
CTASection.tsx (637 bytes)
- Final conversion CTA
- Pricing link
-
LanguageSelectorClient.tsx (3,047 bytes)
- Client-side language switching
-
OurVision.tsx (2,558 bytes)
- Company mission/vision
- Team info
-
UseCases copy.tsx (8,679 bytes)
- Deprecated/old version
Context Providers¶
AuthContext (src/contexts/AuthContext.tsx - estimated)¶
Purpose: Global authentication state
Provided Values:
interface AuthContextType {
user: User | null;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
isAuthenticated: boolean;
authToken: string | null;
}
Protected Route Logic:
export function ProtectedLayout({ children }: { children: ReactNode }) {
const { isAuthenticated } = useAuth();
const router = useRouter();
useEffect(() => {
if (!isAuthenticated) {
router.push("/login");
}
}, [isAuthenticated]);
return isAuthenticated ? <>{children}</> : <Loader />;
}
Utility Modules (src/utils/)¶
1. api.ts¶
Purpose: Axios HTTP client configuration
Features:
- Base URL from env (
NEXT_PUBLIC_API_BASE_URL) - 15-second timeout
- Request interceptor (adds JWT token)
- Response interceptor (handles 401 redirects)
import axios from "axios";
const api = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_BASE_URL,
timeout: 15000,
headers: { "Content-Type": "application/json" },
});
// Add auth token to requests
api.interceptors.request.use((config) => {
const token = sessionStorage.getItem("authToken");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Handle 401 errors
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
sessionStorage.clear();
window.location.href = "/login";
}
return Promise.reject(error);
}
);
export default api;
2. validation.ts (estimated)¶
Purpose: Form validation utilities
Common Validators:
- Email format
- Password strength (8+ chars, uppercase, lowercase, number)
- Phone number format
- URL format
- Required fields
3. formatters.ts (estimated)¶
Purpose: Data formatting utilities
Functions:
formatDate(date: string): ISO → "Jan 15, 2025"formatCurrency(amount: number): 99900 → "$999.00"formatFileSize(bytes: number): 1048576 → "1 MB"truncateText(text: string, maxLength: number): Long text → "Text..."
Server-Side Code (src/server/)¶
Server Actions (src/server/actions/)¶
Purpose: Next.js Server Actions for form submissions
Typical Pattern:
"use server";
import { revalidatePath } from "next/cache";
export async function createChatbot(formData: FormData) {
const name = formData.get("name");
const type = formData.get("type");
const response = await fetch(`${API_URL}/chatbots/create`, {
method: "POST",
body: JSON.stringify({ name, type }),
});
if (response.ok) {
revalidatePath("/chatbots");
return { success: true };
}
return { success: false, error: "Failed to create chatbot" };
}
Middleware (src/middleware.ts)¶
Purpose: Route protection and authentication
File: src/middleware.ts (583 bytes)
Features:
- JWT token validation
- Protected route checks (
/dashboard/*) - Shared link bypass (
isSharedView=true) - Redirect logic (unauthenticated →
/login)
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const token = request.cookies.get("auth_token")?.value;
const isSharedView =
request.nextUrl.searchParams.get("isSharedView") === "true";
const isProtected =
request.nextUrl.pathname.startsWith("/dashboard") ||
request.nextUrl.pathname.startsWith("/chatbots") ||
request.nextUrl.pathname.startsWith("/profile");
// Allow shared links through without auth
if (isSharedView) {
return NextResponse.next();
}
// Redirect to login if accessing protected route without token
if (isProtected && !token) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
"/dashboard/:path*",
"/chatbots/:path*",
"/profile/:path*",
"/3d-chatbot",
],
};
Performance Optimizations¶
1. Code Splitting¶
Lazy Loading 3D Components:
import dynamic from "next/dynamic";
const Avatar3D = dynamic(() => import("@/components/Avatar3D"), {
loading: () => <AvatarSkeleton />,
ssr: false, // Client-side only (Three.js requires window)
});
2. Image Optimization¶
Next/Image Component:
import Image from "next/image";
<Image
src="/avatars/avatar_01.png"
alt="3D Avatar"
width={400}
height={400}
priority // Load immediately
placeholder="blur" // Show blur while loading
/>;
3. React Memoization¶
Expensive Component Memoization:
import { memo } from "react";
const ChatMessage = memo(({ message }: { message: Message }) => {
return <div className="message">{message.content}</div>;
});
// Only re-renders if message changes
Environment Variables¶
Required in .env.local:
# API Configuration
NEXT_PUBLIC_API_BASE_URL=https://api.machineavatars.com
# Analytics
NEXT_PUBLIC_POSTHOG_KEY=your_posthog_key
NEXT_PUBLIC_POSTHOG_HOST=https://app.posthog.com
# Feature Flags
NEXT_PUBLIC_ENABLE_VOICE_CHATBOT=true
NEXT_PUBLIC_ENABLE_3D_CHATBOT=true
# Third-Party Services
NEXT_PUBLIC_RAZORPAY_KEY_ID=rzp_test_xxxxx
NEXT_PUBLIC_GTM_ID=GTM-XXXXXXX
# Development
NODE_ENV=development
NEXT_PUBLIC_ENV=development
Libraries & Dependencies (package.json)¶
Production Dependencies (38 packages)¶
Core Framework:
next@14.1.6- React frameworkreact@18.2.0- UI libraryreact-dom@18.2.0- DOM renderertypescript@5- Type safety
3D Rendering:
three@0.171.0- 3D library@react-three/fiber@8.17.10- React renderer for Three.js@react-three/drei@9.122.0- Three.js helpersleva@0.9.35- 3D GUI controls
UI Libraries:
@mui/material@7.3.0- Material Design components@emotion/react@11.14.0- CSS-in-JS@emotion/styled@11.14.1- Styled componentstailwindcss@3.4.1- Utility CSSframer-motion@12.6.2- Animationsreact-icons@5.4.0- Icon librarylucide-react@0.511.0- Modern icons
HTTP & State:
axios@1.10.0- HTTP client- No Redux/Zustand (using React built-ins)
Charts & Visualization:
recharts@2.15.3- Analytics charts
Notifications & UI Feedback:
react-toastify@11.0.5- Toast notificationsreact-spinners@0.15.0- Loading spinners
Analytics:
posthog-js@1.261.0- Product analytics
Other:
sass@1.85.0- CSS preprocessorreact-slick@0.30.3- Carousel componentcors@2.8.5- CORS middlewareexpress@4.19.2- Custom server (if needed)qs@6.14.0- Query string parsingwinston@3.17.0- Logging
Build & Deployment¶
Build Commands¶
# Development
npm run dev # Start dev server on localhost:3000
# Production build
npm run build # Create optimized production build
npm run start # Start production server
# Linting
npm run lint # Run ESLint
Docker Configuration¶
Dockerfile:
FROM node:20-alpine AS base
# Dependencies installation
FROM base AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
# Build application
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
# Production image
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
EXPOSE 3000
CMD ["node", "server.js"]
Kubernetes Deployment¶
Files in k8s-manifests/:
deployment.yaml- App deployment (3 replicas)service.yaml- LoadBalancer serviceingress.yaml- External traffic routingconfigmap.yaml- Environment variablessecrets.yaml- Sensitive config (base64 encoded)hpa.yaml- Horizontal Pod Autoscalernamespace.yaml- App namespacenetworkpolicy.yaml- Network securitypdb.yaml- Pod Disruption Budgetserviceaccount.yaml- RBAC
Testing Strategy¶
Current State: Manual QA
Planned Testing Stack:
- Unit Tests: Jest + React Testing Library
- E2E Tests: Playwright or Cypress
- Visual Regression: Percy or Chromatic
- Performance: Lighthouse CI
Related Documentation¶
Last Updated: 2025-12-29
Version: 3.0 (Deep-Dive Edition)
Owner: Frontend Lead
Review Cycle: Monthly
"Code-level documentation for developers, by developers."