Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Interview Context Documentation

The `interview-context.tsx` file provides a centralized state management system for the interview experience. It handles real-time chat, audio recording (STT), media playback, and interview lifecycle management (start/end).

## Overview
This module uses React Context to expose interview-related state and actions to the component tree. It integrates with `@ai-sdk/react` for streaming chat responses and a custom `useInterviewMedia` hook for handling microphone input and audio output.

## Key Components

### `InterviewContextProvider`
The provider component that wraps the interview interface. It manages:
* **Chat State:** Uses `useChat` with a custom `DefaultChatTransport` to stream messages to the backend.
* **Interview Lifecycle:** Tracks status (`SETUP`, `IN_PROGRESS`, `COMPLETED`) and handles transitions.
* **Media Integration:** Manages microphone toggling, STT (Speech-to-Text) connection, and audio playback.
* **Auto-Submission:** Automatically sends the transcript to the AI if the user stops speaking for a defined idle period (`AUTO_SUBMIT_IDLE_MS`).

### `useInterview`
A custom hook used by child components to consume the `InterviewContext`. It throws an error if used outside of the `InterviewContextProvider`.

## Core Functionality

### 1. Chat Management
* **Streaming:** Messages are streamed via `/api/interview/chat/stream`.
* **Metadata:** Supports attaching `codeSnippet`, `language`, and `audioUrl` to messages via the `interviewMessageMetadataSchema`.
* **Message Normalization:** Includes utility functions (`toClientMessage`, `toUIMessage`) to bridge the gap between the AI SDK's `UIMessage` format and the application's internal `Message` type.

### 2. Interview Lifecycle
* **`startInterview`**: Initializes the interview session via an ORPC mutation and triggers the initial STT connection.
* **`endInterview`**: Stops all media, finalizes the session on the server, and redirects the user to the report page.

### 3. Media & STT
* **Auto-Connect:** Automatically attempts to connect to the STT service when the interview status changes to `IN_PROGRESS`.
* **Transcript Handling:** Manages both `transcript` (finalized text) and `interimTranscript` (real-time partial text).
* **Auto-Submit:** Monitors the transcript; if the user is silent for 2.2 seconds, the current transcript is automatically sent as a message to the AI.

## Usage Example

```tsx
"use client";

import { useInterview } from "./_context/interview-context";

const InterviewComponent = () => {
const { messages, sendMessage, isResponding, status } = useInterview();

return (
<div>
<p>Status: {status}</p>
{/* Render messages and input controls */}
<button
disabled={isResponding}
onClick={() => sendMessage("Hello!")}
>
Send
</button>
</div>
);
};
```

## Dependencies
* **`@ai-sdk/react`**: Handles the chat streaming logic.
* **`@tanstack/react-query`**: Manages server state for interview data and mutations.
* **`orpc`**: Used for type-safe API communication with the backend.
* **`useInterviewMedia`**: Custom hook for browser media APIs (Web Audio/MediaRecorder).
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# StepCompanyContext Component

The `StepCompanyContext` component is a UI form section used within the interview creation wizard. It allows users to provide specific company details and job descriptions, which are used to tailor the AI-driven interview experience.

## Purpose
This component provides a structured input interface for:
1. **Company Name**: Sets the context for the AI's persona and tone.
2. **Job Description**: Provides the source material for the AI to generate relevant, role-specific interview questions.

## Key Features
* **Real-time Character Counting**: Uses `react-hook-form`'s `useWatch` to track input length against predefined `FIELD_LIMITS`, providing immediate visual feedback to the user.
* **Validation Integration**: Fully integrated with `react-hook-form` and Zod schemas to ensure data integrity before submission.
* **Responsive UI**: Utilizes a card-based layout with clear iconography and descriptive text to guide the user through the input process.
* **Performance Optimized**: Uses `useWatch` to subscribe only to the specific fields required for character counting, preventing unnecessary re-renders of the entire form.

## Props

| Prop | Type | Description |
| :--- | :--- | :--- |
| `form` | `UseFormReturn<CreateInterviewInput>` | The form instance object provided by `useForm` from `react-hook-form`. |

## Dependencies
* **`react-hook-form`**: Manages form state and validation.
* **`@/lib/zodSchemas/createInterview`**: Provides the `createInterviewSchema` for type safety and `FIELD_LIMITS` for input constraints.
* **`@/components/ui`**: Uses standard UI components (Card, Form, Input, Textarea) for consistent styling.

## Usage Example

```tsx
import { useForm } from "react-hook-form";
import { StepCompanyContext } from "./StepCompanyContext";

const CreateInterviewForm = () => {
const form = useForm<CreateInterviewInput>({
// ... configuration
});

return (
<form>
<StepCompanyContext form={form} />
</form>
);
};
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Create Interview Page

The `CreateInterviewPage` component provides a multi-step wizard interface for users to configure and initialize a new AI-powered interview session. It handles form state, resume parsing, and billing validation before creating an interview record.

## Functionality
- **Multi-step Wizard**: Guides users through four distinct configuration steps:
1. **Interview Type**: Select between Technical, System Design, or Behavioral interviews.
2. **Role Details**: Define the target job title, tech stack, and experience level.
3. **Company Context**: Provide specific company details and job descriptions.
4. **Resume Context**: Upload or select a resume to provide the AI with personalized background information.
- **Resume Parsing**: Automatically extracts text from uploaded resumes using the `orpc` client to provide context for the AI interviewer.
- **Billing Integration**: Checks user subscription status via `orpc` before allowing the creation of a new interview, triggering an `UpgradePlanDialog` if limits are reached.
- **Form Validation**: Uses `zod` and `react-hook-form` to ensure data integrity across all steps.

## Key Components
- **`FormStepper`**: Visual indicator of the current progress through the 4-step process.
- **`ResumeUploader`**: Handles file uploads and triggers the parsing mutation.
- **`StepCompanyContext`**: A modular component for handling company-specific inputs.
- **`UpgradePlanDialog`**: A modal that prompts users to upgrade their subscription when they exceed their interview quota.

## State Management
- **`currentStep`**: Tracks the active step in the wizard.
- **`react-hook-form`**: Manages the complex form state, including conditional fields based on the selected interview type.
- **`@tanstack/react-query`**:
- `createInterview`: Mutation to persist the interview configuration to the backend.
- `parseResume`: Mutation to process uploaded resume files.
- `billing.getState`: Query to fetch current user usage limits.

## Usage
This page is accessed via the `/dashboard/interview/create` route. It relies on the `orpc` client for type-safe communication with the backend and expects the user to be authenticated.

### Key Methods
- `canProceedFromStep(step)`: Validates the current form state before allowing the user to advance to the next step.
- `onResumeUpload`: Callback triggered when a file is uploaded, initiating the parsing process.
- `onSubmit`: Finalizes the configuration and triggers the `createInterview` mutation.

## Dependencies
- **`react-hook-form` & `zod`**: For form handling and schema validation.
- **`@tanstack/react-query`**: For server state and API mutations.
- **`orpc`**: For type-safe API calls.
- **`lucide-react`**: For UI iconography.
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# ArenaCanvas Component

The `ArenaCanvas` component is the core interactive workspace for system design challenges. It provides a visual graph editor where users can drag and drop components, connect them, and submit their architecture for AI-driven evaluation.

## Overview

The component is built using `@xyflow/react` and is designed to handle complex state management for system architecture diagrams. It features automatic persistence, real-time feedback, and a context-aware inspector for modifying node and edge properties.

## Key Components

### 1. `ArenaCanvas` (Wrapper)
The entry point component. It ensures client-side mounting compatibility by wrapping the inner logic in a `ReactFlowProvider` and providing a loading state during initialization.

### 2. `ArenaInner` (Logic Layer)
The primary functional component that orchestrates the design environment:
* **State Management**: Tracks nodes and edges using `useNodesState` and `useEdgesState`.
* **Persistence**: Implements a debounced autosave mechanism (1.4s) that syncs the canvas state to the backend via `orpc`.
* **Interaction**:
* **Drag-and-Drop**: Supports dragging components from the `NodeSidebar` onto the canvas.
* **Selection**: Uses `useOnSelectionChange` to track active elements for the `NodeInspector`.
* **Keyboard Shortcuts**: Handles deletion of selected elements via `Backspace` or `Delete`.
* **Evaluation**: Integrates with the `evaluateArchitecture` mutation to send the current graph structure to an AI service for feedback.

## Key Internal Methods

| Method | Description |
| :--- | :--- |
| `onDrop` | Handles dropping new nodes from the sidebar onto the canvas. |
| `onConnect` | Creates a new edge between nodes with default `SYNC` flow type. |
| `saveCanvas` | Manually triggers a save request to the backend. |
| `handleEvaluate` | Validates the current canvas and triggers the AI evaluation mutation. |
| `updateNode` / `updateEdge` | Efficiently updates element data using XYFlow's internal Map-based lookup. |

## Features

* **Autosave**: Automatically persists changes to the backend after a 1.4-second debounce period.
* **Node Inspection**: Works in tandem with `NodeInspector` to allow users to modify properties of selected nodes or edges.
* **Evaluation Feedback**: Displays results via `EvaluationResultsSheet` once the AI evaluation is complete.
* **Optimized Updates**: Uses `updateNodeData` and `updateEdgeData` for efficient state updates instead of full array re-renders.

## Dependencies

* **`@xyflow/react`**: Powers the interactive graph canvas.
* **`@tanstack/react-query`**: Manages server state (fetching attempts, submitting evaluations).
* **`orpc`**: The RPC client used for API communication.
* **`zod`**: Used for schema validation of the architecture JSON.

## Usage Example

The component is designed to be used within a dashboard route, requiring a `problemId` to fetch the specific design challenge:

```tsx
<ArenaCanvas problemId="system-design-123" />
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# NodeSidebar Component

The `NodeSidebar` component is a specialized UI panel used within the architecture design arena. It provides a searchable, categorized library of system components that users can drag and drop onto the `ReactFlow` canvas.

## Purpose
This component serves as the primary interface for users to discover and add architectural nodes (e.g., databases, load balancers, services) to their design. It handles the drag-and-drop data transfer protocol required by the canvas to instantiate new nodes.

## Key Features
* **Drag-and-Drop Integration:** Implements `onDragStart` to pass node metadata (`type`, `label`, `details`) to the canvas via the `dataTransfer` API.
* **Categorized Library:** Groups components by category (e.g., Compute, Storage, Networking) using `NODE_CATEGORIES` and `DESIGN_NODES`.
* **Search Functionality:** Real-time filtering of components based on label, type, or details.
* **Collapsible Sections:** Users can toggle the visibility of specific categories to manage screen real estate.
* **Optimized Rendering:** Uses `useMemo` to group nodes efficiently, ensuring high performance even with large component libraries.

## Component Structure

### State Management
* `search`: Tracks the current user input for filtering nodes.
* `collapsed`: A dictionary mapping category IDs to their visibility state.

### Data Flow
1. **Filtering:** The `filteredNodes` variable computes the subset of nodes matching the search query.
2. **Grouping:** The `groupedNodes` memoized object organizes the filtered list into categories for rendering.
3. **Interaction:**
* **Toggle:** Clicking a category header updates the `collapsed` state.
* **Drag:** The `onDragStart` function attaches the necessary `application/reactflow/*` data types to the event, which the `ArenaCanvas` consumes during the `onDrop` event.

## Usage
The `NodeSidebar` is intended to be used as a sidebar component within the `ArenaCanvas` layout:

```tsx
import { NodeSidebar } from "./node-sidebar";

export function ArenaLayout() {
return (
<div className="flex h-screen">
<NodeSidebar />
<div className="flex-1">
{/* ReactFlow Canvas */}
</div>
</div>
);
}
```

## Dependencies
* **`@/lib/design-nodes`**: Provides the source data for `DESIGN_NODES` and `NODE_CATEGORIES`.
* **`lucide-react`**: Provides UI icons for categories and search.
* **`@/components/ui/scroll-area`**: Used for handling overflow in the sidebar.
* **`@xyflow/react`**: The underlying framework for the canvas that consumes the drag-and-drop data.
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# AnimatedMockup Component

The `AnimatedMockup` component is a marketing UI element designed to simulate an interactive AI interview session. It provides a visual demonstration of the platform's capabilities, including session setup, AI-user interaction, real-time analysis, and feedback generation.

## Purpose
This component serves as a high-fidelity visual aid for landing pages or marketing materials, showcasing the "RoundZero" interview experience without requiring actual backend integration. It uses `framer-motion` to create smooth transitions between different stages of an interview.

## Key Features

* **Simulated Lifecycle:** Automatically cycles through five distinct stages:
1. **Setup:** Displays the configuration phase with a typing effect for the target role.
2. **AI Speaking:** Simulates the AI interviewer asking a question with a visual voice waveform.
3. **User Speaking:** Simulates a candidate's response, featuring dynamic keyword highlighting for technical terms.
4. **Analyzing:** Displays a progress bar and status updates while the AI "processes" the response.
5. **Scorecard:** Presents a final feedback summary with metrics and actionable insights.
* **Dynamic Visuals:**
* **Typing Effects:** Simulates human-like text entry for roles and responses.
* **Voice Waveforms:** Uses `framer-motion` to animate bars, mimicking audio input/output.
* **Keyword Highlighting:** The `highlightKeywords` helper function automatically styles technical jargon (e.g., "Redis", "120ms") to emphasize technical depth.
* **Responsive Design:** Built with a grid-based layout that adapts from a sidebar-focused desktop view to a streamlined mobile-friendly interface.

## Technical Implementation

### State Management
The component uses a local `stage` state to control the animation loop. An `useEffect` hook manages an asynchronous sequence that updates text content and progress percentages, ensuring the simulation runs continuously.

### Helper Functions
* **`highlightKeywords(text: string)`**: A utility that parses text and wraps specific technical terms in styled `<span>` elements. It applies distinct colors (e.g., emerald for performance metrics) to highlight key technical achievements.

### Dependencies
* **`framer-motion`**: Used for entrance/exit animations and the continuous waveform pulse effects.
* **`lucide-react`**: Provides the iconography for the UI (e.g., `Mic`, `Brain`, `Terminal`).

## Usage
The component is self-contained and can be dropped into any page within the `(marketing)` route:

```tsx
import { AnimatedMockup } from "@/app/(marketing)/_components/animated-mockup";

export default function LandingPage() {
return (
<section>
<AnimatedMockup />
</section>
);
}
```

*Note: This component is intended for demonstration purposes and does not connect to the actual `InterviewContext` or backend services.*
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# AudioSamples Component

The `AudioSamples` component is a marketing section designed to showcase the platform's AI-driven interview capabilities through interactive audio previews. It provides users with a visual and auditory demonstration of different interview scenarios, such as behavioral rounds, technical deep-dives, and AI feedback sessions.

## Overview

This component features a grid of interactive cards, each representing a specific type of interview session. Users can toggle playback for each sample, which triggers a simulated "live" waveform animation.

### Key Features
* **Interactive Playback:** Users can play/pause audio samples. Playback is currently simulated with a 5-second auto-stop timer.
* **Dynamic Waveform Visualization:** The `AudioWaveform` sub-component uses `framer-motion` to animate bars, simulating real-time audio activity when a sample is playing.
* **Responsive Design:** Built with a grid layout that adapts from a single column on mobile to three columns on desktop.
* **Visual Feedback:** Includes hover effects, pulse animations for active playback, and subtle background gradients to enhance user engagement.

## Components

### `AudioSamples` (Main Export)
The primary container for the section. It manages the state of the currently playing audio sample using the `playing` state variable.

* **`samples`**: A static array defining the metadata for each audio demo (title, description, duration, and styling).
* **`togglePlay(id)`**: A handler that manages the playback state. If a user clicks a different sample, it switches the active state; clicking the same sample pauses it.

### `AudioWaveform`
A visual representation of audio activity.
* **Props**:
* `isPlaying` (boolean): Determines whether the animation should be active.
* `gradient` (string): Used for styling the waveform bars.
* **Functionality**: Uses `useEffect` to update the height of 24 bars at 100ms intervals when `isPlaying` is true, creating a randomized "bouncing" effect.

## Usage

This component is intended for use on marketing or landing pages. It requires no external props and can be dropped directly into a page:

```tsx
import { AudioSamples } from "@/app/(marketing)/_components/audio-samples";

export default function LandingPage() {
return (
<main>
<AudioSamples />
</main>
);
}
```

## Dependencies
* **`framer-motion`**: Used for smooth entrance animations and the dynamic waveform bar transitions.
* **`lucide-react`**: Provides the UI icons (`Headphones`, `Play`, `Pause`, `Volume2`).
* **`@/components/ui/badge`**: Used for the section header label.
Loading