You are an AI assistant tasked with generating a single-page React Single Page Application (SPA) for a coding agent tool. This application should leverage modern web technologies to provide an intuitive interface for developers to interact with AI-powered coding assistance. The goal is to create a tool that enhances developer productivity by understanding code context, generating code snippets, explaining existing code, and assisting in debugging.
## 1. PROJECT OVERVIEW
**Project Name:** CodeCompanion AI
**Purpose:** To provide developers with an intelligent, context-aware coding assistant that streamlines various development tasks, from code generation and completion to explanation and debugging. It aims to bridge the gap between raw LLM capabilities and practical, real-world coding workflows by incorporating context management, tool understanding, and memory.
**Problem Solved:** Developers often struggle with repetitive coding tasks, understanding large or unfamiliar codebases, and debugging complex issues. Existing tools might lack deep project context or advanced reasoning capabilities. CodeCompanion AI addresses this by offering a unified interface that integrates these advanced LLM features into the developer's workflow.
**Value Proposition:** Boost developer productivity, improve code quality, reduce time spent on repetitive tasks, and facilitate faster learning and understanding of codebases. It acts as an intelligent pair programmer, available 24/7.
## 2. TECH STACK
* **Frontend Framework:** React.js (using Create React App or Vite for project setup)
* **Styling:** Tailwind CSS for rapid UI development and utility-first styling.
* **State Management:** Zustand or React Context API for efficient state management.
* **Routing (if needed for future expansion, though SPA focus):** React Router DOM (optional for a single page)
* **API Interaction:** Axios or Fetch API for communicating with a hypothetical backend AI service.
* **Syntax Highlighting:** `react-syntax-highlighter` or similar.
* **IDE-like Editor Component:** `react-codemirror2` or `monaco-editor` (via a React wrapper) for code input/output.
## 3. CORE FEATURES (MVP)
### 3.1. Intelligent Code Completion
* **User Flow:** The user types code in the editor. As they type, suggestions appear based on the current file's context, project structure, and potentially imported libraries. The user can accept a suggestion using Tab or Enter.
* **Functionality:** Intercepts user input, sends relevant context (current file content, cursor position, surrounding code) to the AI backend, and displays ranked suggestions.
### 3.2. Code Generation
* **User Flow:** The user provides a natural language prompt (e.g., "Create a function to calculate the factorial of a number") or specifies a task in a dedicated input field. The AI generates the code, which is then displayed in the editor or a separate output pane.
* **Functionality:** Takes a text prompt, sends it to the AI backend, and renders the returned code.
### 3.3. Code Explanation & Documentation
* **User Flow:** The user selects a block of code in the editor. They then trigger the "Explain Code" or "Generate Docs" action. The explanation or documentation draft is displayed in a separate panel.
* **Functionality:** Takes selected code, sends it to the AI backend for analysis, and displays the textual explanation or Markdown documentation.
### 3.4. Debugging Assistance
* **User Flow:** The user pastes or writes code containing a potential error. They trigger the "Debug Code" action. The AI analyzes the code, identifies potential errors, and suggests fixes or explanations for the errors.
* **Functionality:** Sends code snippet and potentially error messages (if provided) to the AI backend, returns identified issues and suggested solutions.
### 3.5. Context Management (Simulated)
* **User Flow:** The application implicitly maintains context. When performing actions like code completion or generation, the system considers the currently active file and potentially a representation of the project's file structure (simulated for MVP).
* **Functionality:** For MVP, this will involve passing the content of the currently viewed file to the AI. Future iterations would involve more sophisticated project parsing.
## 4. UI/UX DESIGN
* **Layout:** A three-panel layout is recommended:
1. **Left Panel:** (Optional for MVP, can be added later) File explorer/Project structure simulation.
2. **Center Panel:** Main code editor (`react-codemirror2` or `monaco-editor`). This is where code is written, viewed, and generated.
3. **Right Panel:** Contextual Information/Output Panel. This panel displays AI responses: code completions, generated code, explanations, documentation, and debugging suggestions. It should also contain input fields for code generation prompts and action buttons.
* **Color Palette:** A dark theme suitable for coding environments. Primary colors: Dark charcoal/deep blue background (`#1E1E1E`, `#252526`), accent colors: Electric blue (`#007ACC`), vibrant green (`#6B8E23`), or a warm orange (`#D48000`) for interactive elements, buttons, and highlights. Text color: Light gray/off-white (`#D4D4D4`).
* **Typography:** Monospaced font for the code editor (e.g., 'Fira Code', 'Source Code Pro'). Sans-serif font for UI elements and explanations (e.g., 'Inter', 'Roboto').
* **Responsive Design:** The layout should be responsive. On smaller screens, panels might stack vertically or become collapsible sidebars. The code editor should always be usable and readable.
* **Interactivity:** Clear buttons for actions (Generate, Explain, Debug). Hover effects on buttons and interactive elements. Loading indicators when AI is processing.
## 5. DATA MODEL
* **State Structure (using Zustand example):
```javascript
interface AICodingAgentState {
currentCode: string;
generatedCode: string;
codeExplanation: string;
debugInfo: string;
completionSuggestions: string[];
isLoading: boolean;
error: string | null;
// Methods for actions
generateCode: (prompt: string) => Promise<void>;
explainCode: (code: string) => Promise<void>;
debugCode: (code: string) => Promise<void>;
fetchCompletions: (code: string, cursorPosition: number) => Promise<void>;
setCode: (code: string) => void;
}
```
* **Mock Data Formats:**
* **Code Completion Response:** `{
suggestions: ["function greet(name) {", "console.log(", "const result = "]
}`
* **Code Generation Response:** `{
generatedCode: "function factorial(n) {\n if (n === 0) return 1;\n return n * factorial(n - 1);\n}"
}`
* **Explanation Response:** `{
explanation: "This function calculates the factorial of a non-negative integer using recursion."
}`
* **Debugging Response:** `{
issues: [{"line": 5, "message": "Potential infinite loop detected if n is negative.", "suggestion": "Add validation for negative input."}]
}`
## 6. COMPONENT BREAKDOWN
* **`App.js` / `main.jsx`:** Root component, sets up state management provider and main layout.
* **`Layout.jsx`:** Main application layout component. Manages the three-panel structure (or two if file explorer is omitted for MVP). Handles responsive adjustments.
* Props: `children`
* **`CodeEditor.jsx`:** Wrapper component for the code editor library (e.g., `react-codemirror2`). Manages editor state, syntax highlighting, and event handling.
* Props: `value` (string), `onChange` (function), `language` (string, e.g., 'javascript'), `options` (object)
* **`OutputPanel.jsx`:** Container for AI-generated content. Switches between different views (Generated Code, Explanation, Debug Info).
* Props: `activeTab` (string), `content` (object, containing generatedCode, explanation, debugInfo etc.)
* **`PromptInput.jsx`:** Input field for users to enter prompts for code generation.
* Props: `onSubmit` (function), `placeholder` (string)
* **`ActionButton.jsx`:** Reusable button component for triggering AI actions (Generate, Explain, Debug).
* Props: `onClick` (function), `children` (string/ReactNode), `variant` (string, e.g., 'primary', 'secondary'), `isLoading` (boolean)
* **`SuggestionsDropdown.jsx`:** (For Code Completion) Displays the list of code completion suggestions.
* Props: `suggestions` (array of strings), `onSelect` (function), `highlightedIndex` (number)
* **`FileExplorer.jsx` (Optional MVP):** Simulates a file explorer. Allows selecting files to view/edit.
* Props: `files` (array of objects), `onFileSelect` (function), `activeFile` (string)
## 7. ANIMATIONS & INTERACTIONS
* **Loading States:** Use subtle spinners or pulsing animations within buttons and the output panel when AI requests are processing. Example: Tailwind CSS animations for spinners.
* **Transitions:** Smooth transitions for panel resizing or showing/hiding elements. Fade-in/fade-out for content changes in the output panel.
* **Hover Effects:** Subtle background color changes or slight scaling on buttons and interactive elements.
* **Code Completion:** Appear smoothly near the cursor. Highlight the currently selected suggestion. Accept suggestion with a clear visual confirmation.
* **Code Block Rendering:** Syntax highlighted code blocks should render cleanly. Use `react-syntax-highlighter` with appropriate themes.
## 8. EDGE CASES
* **Empty State:** When no code is present or no AI response is available, the output panel should display informative messages (e.g., "Enter a prompt to generate code", "Select code to explain").
* **Error Handling:** Implement robust error handling for API calls. Display user-friendly error messages if the AI service is unavailable or returns an error. Provide options to retry.
* **Validation:** Validate user inputs (e.g., prompt length, ensuring code is selected before explanation).
* **Accessibility (a11y):** Ensure proper ARIA attributes are used, keyboard navigation is functional (especially for suggestions and buttons), and color contrast meets accessibility standards.
* **Large Code Output:** Handle potentially very large code outputs gracefully, possibly using pagination or lazy loading within the output panel.
## 9. SAMPLE DATA
* **`mockFiles.json` (for FileExplorer)
```json
[
{"id": "file1", "name": "main.js", "content": "function hello() {\n console.log('Hello World!');\n}"},
{"id": "file2", "name": "utils.js", "content": "export const add = (a, b) => a + b;"},
{"id": "file3", "name": "styles.css", "content": ".container { margin: 10px; }"}
]
```
* **`mockCompletionResponse.json`**
```json
{
"suggestions": [
"function calculateSum(a, b) {",
"const PI = 3.14159;",
"if (input === null || input === undefined) {"
]
}
```
* **`mockGenerationResponse.json`**
```json
{
"generatedCode": "/**\n * Fetches data from a given URL.\n * @param {string} url - The URL to fetch data from.\n * @returns {Promise<object>} - A promise that resolves with the JSON data.\n */\nasync function fetchData(url) {\n try {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n const data = await response.json();\n return data;\n } catch (error) {\n console.error('Error fetching data:', error);\n throw error;\n }\n}"
}
```
* **`mockExplanationResponse.json`**
```json
{
"explanation": "This is an asynchronous JavaScript function named `fetchData` that takes a URL as input. It uses the `fetch` API to make a network request. If the response is not successful (e.g., 404, 500), it throws an error. Otherwise, it parses the response body as JSON and returns the data. It includes basic error handling for network issues."
}
```
* **`mockDebugResponse.json`**
```json
{
"issues": [
{"line": 10, "message": "Potentially unsafe use of `eval()`. Consider safer alternatives if possible.", "severity": "warning", "suggestion": "Avoid `eval()` for parsing JSON; use `JSON.parse()` instead."}
]
}
```
## 10. DEPLOYMENT NOTES
* **Build Process:** Use the standard build command for your chosen tool (e.g., `npm run build` for CRA or Vite). This generates optimized static assets.
* **Environment Variables:** Use environment variables for API endpoints (e.g., `REACT_APP_AI_API_URL` or `VITE_AI_API_URL`). Ensure these are configured correctly during the build process.
* **Performance Optimizations:**
* Code Splitting: Implement code splitting for different sections of the application if it grows beyond a single page.
* Lazy Loading: Lazy load components that are not immediately visible.
* Memoization: Use `React.memo`, `useMemo`, and `useCallback` where appropriate to prevent unnecessary re-renders.
* Image Optimization: If any images are used, ensure they are optimized.
* **Hosting:** Deployable on static hosting platforms like Netlify, Vercel, AWS S3/CloudFront, or GitHub Pages.