Skip to content

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 name
  • avatarType: Avatar type identifier
  • project_id: Chatbot project ID
  • user_id: User identifier
  • selected_project_id: Currently selected project
  • isSharedView=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

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):

  1. fetchSystemPrompt()

  2. Fetches current system prompt for project

  3. Handles array and legacy prompt shapes
  4. Auto-selects default or first prompt
  5. Endpoint: GET /v2/get-system-prompt

  6. fetchMasterLLMs()

  7. Retrieves all available LLM models

  8. Endpoint: GET /v2/llms

  9. selectModel(ai_model_id: string)

  10. Switches to different AI model

  11. Updates prompts for selected model
  12. Endpoint: GET /v2/ai-model

  13. selectPurpose(purpose_id: string)

  14. Switches prompt purpose (e.g., customer support, sales)

  15. Local state update only

  16. updateSystemPrompt()

  17. Saves edited prompt (test mode)

  18. Updates both selectedPurpose and addedLLMs state
  19. Endpoint: PATCH /v2/test-system-prompt

  20. setMasterSystemPrompt()

  21. Sets prompt as master (production)

  22. Endpoint: PATCH /v2/set-system-prompt

  23. setMasterSystemPromptFor(params)

  24. Silent master prompt update (no loading state)

  25. Direct fetch (not using useHttp)

  26. addMasterLLM(id: string)

  27. Adds new LLM model to project

  28. Endpoint: PATCH /v2/add-llm

  29. resetPrompt()

  30. Resets prompt to default
  31. Updates local state immediately
  32. 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 50MB
  • Advanced Analytics
  • Custom Branding
  • Voice Chatbot
  • Multi-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_id
  • project_id
  • selected_project_id
  • authToken
  • userEmail
  • session_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:

  1. Basic Info (name, type)
  2. Avatar Selection
  3. Knowledge Base Upload
  4. System Prompt Configuration
  5. Voice Settings (if enabled)
  6. Deployment Options

Home Page Components (src/components/home/)

16 marketing page sections:

  1. HeroSection.tsx (5,609 bytes)

  2. Hero banner

  3. CTA buttons
  4. Animated background

  5. VideoDemoSection.tsx (6,068 bytes)

  6. Product demo video

  7. Video controls
  8. Global video manager integration

  9. OurAiAgents.tsx (12,046 bytes)

  10. AI agents showcase

  11. 3D/Text/Voice tabs
  12. Feature highlights

  13. LanguageSelectorSection.tsx (14,614 bytes)

  14. Multi-language demo

  15. Interactive language picker
  16. Real-time translation preview

  17. PricingSection.tsx (9,928 bytes)

  18. Tier comparison table

  19. Feature matrix
  20. CTA for each tier

  21. UseCases.tsx (10,444 bytes)

  22. Industry use cases

  23. Customer testimonials
  24. Case study cards

  25. PlugAndPlaySection.tsx (13,255 bytes)

  26. Integration code snippets

  27. Embed examples (iframe, SDK)
  28. API documentation links

  29. TryFreeAgentSection.tsx (9,004 bytes)

  30. Free trial CTA

  31. Interactive chatbot demo
  32. Sign-up flow

  33. HowItWorksSection.tsx (2,418 bytes)

  34. Step-by-step process

  35. Visual workflow diagram

  36. PlatformOverviewSection.tsx (427 bytes)

    • High-level feature overview
  37. IndustriesSection.tsx (593 bytes)

    • Target industries
    • Industry-specific benefits
  38. ContactSection.tsx (444 bytes)

    • Contact form
    • Email/chat links
  39. CTASection.tsx (637 bytes)

    • Final conversion CTA
    • Pricing link
  40. LanguageSelectorClient.tsx (3,047 bytes)

    • Client-side language switching
  41. OurVision.tsx (2,558 bytes)

    • Company mission/vision
    • Team info
  42. 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 framework
  • react@18.2.0 - UI library
  • react-dom@18.2.0 - DOM renderer
  • typescript@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 helpers
  • leva@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 components
  • tailwindcss@3.4.1 - Utility CSS
  • framer-motion@12.6.2 - Animations
  • react-icons@5.4.0 - Icon library
  • lucide-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 notifications
  • react-spinners@0.15.0 - Loading spinners

Analytics:

  • posthog-js@1.261.0 - Product analytics

Other:

  • sass@1.85.0 - CSS preprocessor
  • react-slick@0.30.3 - Carousel component
  • cors@2.8.5 - CORS middleware
  • express@4.19.2 - Custom server (if needed)
  • qs@6.14.0 - Query string parsing
  • winston@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/:

  1. deployment.yaml - App deployment (3 replicas)
  2. service.yaml - LoadBalancer service
  3. ingress.yaml - External traffic routing
  4. configmap.yaml - Environment variables
  5. secrets.yaml - Sensitive config (base64 encoded)
  6. hpa.yaml - Horizontal Pod Autoscaler
  7. namespace.yaml - App namespace
  8. networkpolicy.yaml - Network security
  9. pdb.yaml - Pod Disruption Budget
  10. serviceaccount.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


Last Updated: 2025-12-29
Version: 3.0 (Deep-Dive Edition)
Owner: Frontend Lead
Review Cycle: Monthly


"Code-level documentation for developers, by developers."