Skip to main content

Key Component Specification

🧩 Frontend Key Component Specification Last Updated: June 29, 2025

This document describes the roles and structures of key React components, Contexts, and custom Hooks in the comfy-surfai-frontend-next project.


1. Global Context & Hooks​

These are core elements that manage application-wide state and logic.

A. AuthContext.tsx​

  • Location: src/contexts/AuthContext.tsx
  • Role: "Authentication and User State Manager" that globally manages user authentication status (login status, user information, coin balance) and provides related functions (login, logout, profile update).
  • Key Provided Values (value):
    • user: User | null: Information object of the currently logged-in user. null if not logged in.
    • isLoading: boolean: Becomes true while checking authentication status during app startup or login/logout.
    • login(credentials): Function to handle standard email/password login.
    • logout(): Function to log out the user and delete related cookies.
    • fetchUserProfile(): Function to refresh the user state by requesting profile information from the server.
    • setUser(): Function to directly update the user object on the client side (e.g., optimistic updates).

B. useComfyWebSocket.ts​

  • Location: src/hooks/useComfyWebSocket.ts
  • Role: "Real-time Communication Manager" that communicates in real-time with the backend WebSocket server, receiving all events occurring during AI generation and managing related states.
  • Key Return Values:
    • isWsConnected: boolean: WebSocket connection status.
    • executionStatus: string | null: Current task status text, such as "Generating...", "Final results received!".
    • progressValue: { value, max } | null: Progress of nodes like KSampler.
    • sessionOutputs: HistoryItemData[]: List of generated results during the current session on the Generate page. (Maintains up to 20 items)

C. apiClient.ts​

  • Location: src/lib/apiClient.ts
  • Role: "Central Communication Gateway" responsible for all HTTP communication with the backend API.
  • Key Features:
    • Automatic Token Reissue: If an Access Token expires and a 401 error is received during an API request, it automatically reissues a new token using the Refresh Token and retries the original failed request.
    • Automatic CSRF Header Addition: When making state-changing requests (e.g., POST, PUT, DELETE), it automatically reads the XSRF-TOKEN cookie value and adds the X-XSRF-TOKEN header to defend against CSRF attacks.
    • Automatic Cookie Transmission: Through the credentials: 'include' option, all requests automatically include authentication-related HttpOnly cookies stored by the browser.

2. Page Components​

Located in the src/app/ directory, these are "smart" components that serve as entry points for each route.

A. generate/page.tsx​

  • Role: Main page for AI image/video generation.
  • Key Logic:
    • Fetches user information (including coin balance) via the useAuth hook and displays it.
    • Manages real-time status using the useComfyWebSocket hook.
    • Loads workflow template list via API and passes it to TemplateForm.
    • First calls the coin deduction API (POST /api/coin/deduct) with parameters received from TemplateForm, and only if successful, calls the image generation API (POST /api/generate).
    • Temporarily checks current session results via SessionGallery.
    • Manages the open/close state of ImageLightbox.

B. history/page.tsx​

  • Role: "My Album" page that permanently displays all results generated by the user.
  • Key Logic:
    • Calls the backend's /my-outputs API to retrieve the user's generation history list.
    • Implements pagination (infinite scroll) functionality via a "Load More" button.
    • Reuses HistoryGallery and GeneratedItem components to display results.
    • Manages the open/close state of ImageLightbox.

C. admin/workflows/new/page.tsx and admin/workflows/[id]/edit/page.tsx​

  • Role: Admin page for creating and editing workflow templates.
  • Key Logic:
    • Includes access control logic that checks the user's role via useAuth upon page access and immediately redirects if not admin.
    • Reuses the ParameterMappingForm component to render the parameter setting UI.
    • Creation Page: Manages a 2-step flow (basic info input -> parameter mapping) and calls the appropriate APIs (POST /workflow-templates, PUT /.../parameter-map) for each step.
    • Edit Page: Loads existing template data upon page load to populate all forms, and calls the PATCH /workflow-templates/:id API upon 'Save' to update all changes at once.

3. Reusable Components​

Located in the src/components/ directory, these are "dumb" components responsible for specific UI fragments or functionalities.

A. TemplateForm.tsx​

  • Location: src/components/template/TemplateForm.tsx
  • Role: Provides a form UI for selecting workflow templates and entering parameters. Displays user coin balance and includes an image generation button.
  • Key Features:
    • Template selection dropdown.
    • Dynamically renders parameter input fields based on the parameter_map of the selected template.
    • Displays coin balance received via user prop next to the image generation button.
    • Disables button and changes text based on isSubmitting state.

B. ParameterMappingForm.tsx​

  • Location: src/components/admin/ParameterMappingForm.tsx
  • Role: "Parameter Mapping Specialist Component" responsible for the entire complex and dynamic form UI used to create and modify workflow template parameter_map.
  • Reusability:
    • Creation Page (new/page.tsx): Used in the 2nd step screen. Receives onSave and onBack functions to perform its own save/cancel logic via internal buttons.
    • Edit Page (edit/page.tsx): Included as part of the page. Renders without onSave and onBack, only handling data display and modification. Final saving is handled by the main 'Save' button on the edit page.
  • Key Features:
    • Category-based Logic: Calls API based on the category prop to load related parameter preset lists.
    • Automatic Required Parameter Addition: When in new page mode, automatically adds required parameters corresponding to the category to the list.
    • Intelligent UI:
      • Displays detailed information (inputs, class_type) of a selected node.
      • Allows one-click auto-completion of input_name.
      • Parameters added as presets have their key and type locked to prevent errors.
      • Required parameters are disabled to prevent deletion.
      • Already added presets are disabled in the 'Add Parameter' dropdown.
    • State Management: Directly receives parameterMap state and setParameterMap function as props, directly controlling the parent component's (page) state.

C. GeneratedItem.tsx​

  • Location: src/components/admin/GeneratedItem.tsx
  • Role: Renders a single generated result card displayed in the gallery. Reused in both SessionGallery and HistoryGallery.
  • Key Features:
    • Draws UI based on item data (HistoryItemData) received as a prop.
    • Conditionally renders image (<img>) or video (<video>) based on item.mimeType.
    • Calculates and displays video playback time by analyzing item.usedParameters.
    • Determines file expiration based on item.createdAt and displays alternative UI if expired.
    • Includes enlarge/download/delete buttons, calling handler functions (onImageClick, onDelete) received from the parent upon click.

D. ImageLightbox.tsx​

  • Location: src/components/admin/ImageLightbox.tsx
  • Role: A modal that covers the entire screen, displaying an enlarged image and detailed metadata when the user clicks an image in the gallery.
  • Key Features:
    • Renders based on the item object (HistoryItemData | null) received as a prop. Hidden if item is null.
    • Displays media (image/video) largely on the left using item.viewUrl.
    • Displays detailed metadata such as item.usedParameters, item.createdAt in a scrollable area on the right.
    • Calls the onClose handler when the outer background or 'X' button is clicked to close.

E. ChatModal.tsx​

  • Location: src/components/common/ChatModal.tsx
  • Role: A reusable modal component that provides AI chat functionality. Used on the /surf page.
  • Key Features:
    • Features a popup UI based on the Dialog component.
    • Includes an Input for user prompts and a 'Send' Button.
    • Manages internal states like isLoading, error, and response to display the API request status.
    • Calls the backend's /langchain/chat endpoint via apiClient when the 'Send' button is clicked.
    • Displays the AI's response in a scrollable area.