You are an expert AI assistant tasked with generating a single-page, fully functional SPA (Single Page Application) for a SaaS product called 'CodeCompanion'. This application allows developers to connect AI coding agents to their active Chrome browser sessions for debugging and analysis. The core technology used is React, with Tailwind CSS for styling.
**1. PROJECT OVERVIEW:**
CodeCompanion aims to revolutionize the debugging and development workflow for web professionals. By integrating directly with Chrome DevTools' Message Channel Protocol (MCP), it allows developers to seamlessly connect their AI coding agents to active browser sessions. This enables AI agents to:
- Reuse existing browser sessions (e.g., for logged-in states).
- Access active debugging sessions in DevTools (e.g., analyze failed network requests, inspect DOM elements).
- Facilitate a smooth transition between manual and AI-assisted debugging.
The primary value proposition is significant time savings, improved accuracy in bug detection, and enhanced developer productivity by leveraging AI directly within the context of a live browsing session. The application will serve as a central hub for managing these AI-assisted debugging workflows.
**2. TECH STACK:**
- **Framework:** React (using functional components and Hooks)
- **UI Library:** Tailwind CSS for rapid and utility-first styling.
- **State Management:** Zustand for efficient and simple global state management.
- **Routing:** React Router DOM for client-side routing.
- **API Communication:** Axios for making HTTP requests to a hypothetical backend or AI service.
- **Chrome Extension API:** To interact with Chrome's browser and DevTools functionalities (MCP).
- **Build Tool:** Vite (for fast development server and optimized builds).
- **TypeScript:** (Optional but recommended for larger projects, assume basic JS for this prompt unless specified).
**3. CORE FEATURES:**
a. **Extension - Session Connection:**
- **User Flow:** User installs the Chrome extension. Upon visiting a webpage, the extension detects an active Chrome session. A button/icon within the extension popup allows the user to initiate a connection. Upon clicking, the extension attempts to establish an MCP connection with the current tab's DevTools.
- **Functionality:** The extension background script will listen for tab updates and DevTools connection events. It will use `chrome.runtime.connect` and potentially `chrome.devtools.inspectedWindow.eval` to interact with the inspected window and DevTools.
b. **Extension - AI Agent Trigger:**
- **User Flow:** Once connected, the user can select a specific DevTools panel (e.g., Network, Elements, Console). Within the extension popup, the user can choose an AI agent type (e.g., 'General Debugger', 'Network Analyzer', 'Code Suggester') and provide a specific prompt or context (e.g., 'Investigate this failed network request', 'Find accessibility issues in this component'). Clicking 'Analyze' sends the context and request to the backend/AI service.
- **Functionality:** The extension will capture relevant data from the selected DevTools panel (e.g., selected network request details, DOM snapshot, console logs). This data, along with the user's prompt, will be bundled and sent via `axios` to the backend API.
c. **Main Application - Session Management & History:**
- **User Flow:** The main web application (SPA) serves as a dashboard. Users can view a list of their past debugging sessions initiated via the extension. Each session entry displays the URL, timestamp, AI agent used, and a summary of the findings. Users can click on a session to view detailed logs, AI responses, and captured data. Sessions can be saved, categorized with tags, and searched.
- **Functionality:** This SPA will fetch session history from a backend API. It will display this data in a sortable, filterable table. Users can interact with individual session details, potentially re-running analyses or exporting data.
d. **Main Application - AI Response Display:**
- **User Flow:** When viewing a detailed session, AI-generated code suggestions, explanations, and analysis reports are displayed in a clear, readable format. Code snippets should be syntax-highlighted and offer 'copy' functionality. Links to relevant DevTools elements or network requests should be navigable.
- **Functionality:** The SPA will render structured AI responses, including text, code blocks, and potentially JSON data. It will use a code highlighting library (like `react-syntax-highlighter`) and ensure interactive elements are properly implemented.
**4. UI/UX DESIGN:**
- **Layout:** A clean, two-column layout for the SPA dashboard. Left sidebar for navigation (Dashboard, History, Settings). Main content area displays the selected view (e.g., session list, session details). The Chrome extension popup will be simple, focusing on connection status, AI agent selection, and prompt input.
- **Color Palette:** Primary: `#4A90E2` (Calm Blue), Secondary: `#50E3C2` (Vibrant Teal), Accent: `#F5A623` (Energetic Orange). Background: `#F8F9FA` (Light Gray). Text: `#333333` (Dark Gray). Use sparingly for alerts/notifications: `#D0021B` (Red).
- **Typography:** Use a clean, modern sans-serif font like 'Inter' or 'Roboto'. Headings should be distinct but not overpowering. Body text should be highly readable.
- **Responsive Design:** The SPA must be fully responsive, adapting gracefully to desktop, tablet, and mobile screen sizes. The extension popup should be compact and functional on small screens.
- **Component Hierarchy (SPA):** `App -> Router -> Sidebar, Header, MainContent -> (DashboardView, HistoryView, SettingsView, SessionDetailView) -> Components (SessionTable, SessionListItem, SessionDetails, CodeViewer, LogDisplay, etc.)`
**5. DATA MODEL:**
- **Extension State:** `isConnected: boolean`, `currentTabId: string | null`, `devToolsStatus: 'connected' | 'disconnected' | 'pending'`, `selectedPanel: string | null`, `aiAgentType: string`, `userPrompt: string`.
- **Session Object (for History):**
```json
{
"id": "uuid-string",
"url": "https://example.com",
"timestamp": "ISO-8601-string",
"title": "Page Title",
"devToolsPanel": "Network",
"aiAgent": "Network Analyzer",
"userPrompt": "Investigate failed request",
"aiResponse": {
"summary": "Request failed due to 404 Not Found. Possible reasons: incorrect URL, missing resource.",
"details": "Detailed analysis...",
"codeSuggestion": "if (response.status === 404) { console.error('Resource not found!'); }",
"logEntries": ["Log entry 1", "Log entry 2"],
"networkData": { /* relevant request/response data */ }
},
"tags": ["bug", "404", "urgent"],
"isSaved": true
}
```
- **State Management (Zustand):** A central store managing `sessionHistory: Session[]`, `currentSession: Session | null`, `isLoading: boolean`, `error: string | null`.
- **Local Storage:** The extension might use local storage for basic settings or temporary state. The SPA will primarily rely on API calls.
**6. COMPONENT BREAKDOWN (Example - SPA):**
- **`App.jsx`:** Main application component, sets up routing and global layout.
- **`Sidebar.jsx`:** Navigation menu component. Props: `navItems: [{ name: string, path: string }]`, `activeItem: string`.
- **`Header.jsx`:** Application header, potentially with user info or global actions.
- **`DashboardView.jsx`:** Displays overview, recent activity, quick actions.
- **`HistoryView.jsx`:** Main component for displaying the session history table.
- **`SessionTable.jsx`:** Renders the table of past sessions. Props: `sessions: Session[]`, `onRowClick: function`.
- **`SessionListItem.jsx`:** Renders a single row in the history table. Props: `session: Session`, `onClick: function`, `onTagClick: function`.
- **`SessionDetailView.jsx`:** Displays the full details of a selected session.
- **`ResponseSummary.jsx`:** Displays the AI's summary. Props: `summary: string`.
- **`CodeViewer.jsx`:** Displays code snippets with syntax highlighting and copy button. Props: `code: string`, `language: string`.
- **`LogDisplay.jsx`:** Renders log entries or network data. Props: `logs: string[] | object`.
- **`ExtensionPopup.jsx` (Conceptual):** Component within the extension popup UI.
- **`ConnectionStatus.jsx`:** Shows connection state. Props: `status: 'connected' | 'disconnected' | 'pending'`.
- **`AgentSelector.jsx`:** Dropdown for selecting AI agent. Props: `agents: string[]`, `onSelect: function`.
- **`PromptInput.jsx`:** Text area for user prompt. Props: `onChange: function`.
- **`AnalyzeButton.jsx`:** Triggers the analysis. Props: `onClick: function`, `disabled: boolean`.
**7. ANIMATIONS & INTERACTIONS:**
- **Page Transitions:** Subtle fade-in/out transitions between SPA views using libraries like `Framer Motion` or CSS transitions.
- **Button Hovers:** Slight scale or background color change on interactive elements.
- **Loading States:** Use spinners or skeleton loaders (e.g., `react-content-loader`) when fetching data or waiting for AI responses. Indicate loading progress clearly.
- **Micro-interactions:** Smooth expansion/collapse of detail sections, subtle animations on adding/removing tags.
- **Extension Popup:** Smooth opening and closing animation.
**8. EDGE CASES:**
- **No Active Sessions:** The extension should gracefully inform the user if no compatible Chrome session is found or if DevTools is not open.
- **API Errors:** Implement robust error handling for API calls. Display user-friendly error messages (e.g., 'AI service unavailable. Please try again later.'). Use Zustand to manage and display errors globally.
- **Empty State:** The history view should display a clear message and potentially a call to action when no sessions have been recorded yet.
- **Invalid User Input:** Basic validation on prompt length or format if necessary.
- **Security:** Ensure secure communication between the extension and the backend (HTTPS, potentially API keys handled securely). Never expose sensitive user data unnecessarily.
- **Accessibility (a11y):** Use semantic HTML, ensure sufficient color contrast, support keyboard navigation, and use ARIA attributes where appropriate. Test with screen readers.
- **Chrome Updates:** Be mindful of potential breaking changes in Chrome APIs.
**9. SAMPLE DATA:**
- **`agentsListMock`:** `['General Debugger', 'Network Analyzer', 'Code Suggester', 'Accessibility Auditor']`
- **`sessionHistoryMock` (Array of Session Objects):**
```json
[
{
"id": "sess_12345",
"url": "https://react.dev/learn",
"timestamp": "2023-10-27T10:00:00Z",
"title": "React Docs - Learn",
"devToolsPanel": "Console",
"aiAgent": "Code Suggester",
"userPrompt": "Suggest improvements for the main navigation component's accessibility.",
"aiResponse": {
"summary": "Navigation component lacks ARIA labels for some links and has insufficient contrast on hover.",
"details": "The primary navigation menu items require ARIA roles and labels to improve screen reader compatibility. Additionally, the hover state color contrast falls below WCAG AA standards.",
"codeSuggestion": "// Add ARIA label to navigation links\n<nav aria-label=\"Main navigation\"><ul role=\"list\"><li role=\"listitem\"><a href=\"/docs\" aria-label=\"Documentation\">Docs</a></li>...</ul></nav>\n\n// Adjust CSS for hover state contrast (example)\n.nav-link:hover { color: #0056b3; /* Ensure contrast ratio > 4.5 */ }",
"logEntries": [],
"networkData": null
},
"tags": ["accessibility", "react", "frontend"],
"isSaved": true
},
{
"id": "sess_67890",
"url": "https://example-ecommerce.com/products/123",
"timestamp": "2023-10-27T09:30:00Z",
"title": "Product 123 - Example E-commerce",
"devToolsPanel": "Network",
"aiAgent": "Network Analyzer",
"userPrompt": "Investigate why the product image failed to load.",
"aiResponse": {
"summary": "Image failed to load due to a 404 error. The URL provided in the 'img' tag is incorrect.",
"details": "The network request for 'https://example-ecommerce.com/images/product-123-large.jpg' returned a 404 status. The correct URL appears to be '/images/products/123-main.jpg'.",
"codeSuggestion": "<img src=\"/images/products/123-main.jpg\" alt=\"Product Image\">
",
"logEntries": [],
"networkData": {
"request": {"url": "https://example-ecommerce.com/images/product-123-large.jpg", "method": "GET"},
"response": {"status": 404, "statusText": "Not Found"}
}
},
"tags": ["bug", "image", "404"],
"isSaved": false
}
// ... more session objects ...
]
```
**10. DEPLOYMENT NOTES:**
- **Build Command:** Use `npm run build` or `yarn build` (configured by Vite).
- **Environment Variables:** Use `.env` files for managing API endpoints (`VITE_API_URL`), API keys (`VITE_AI_API_KEY` - handle with care, ideally server-side), and other configurations.
- **SPA Hosting:** The React SPA can be hosted on services like Vercel, Netlify, AWS S3/CloudFront, or Firebase Hosting.
- **Chrome Extension:** The extension needs to be packaged and uploaded to the Chrome Web Store. Separate build configurations might be needed for the extension's background scripts and content scripts vs. the main SPA.
- **Performance Optimizations:** Code splitting (handled by Vite), lazy loading components, memoization (React.memo, useMemo, useCallback), image optimization, and minimizing bundle size are crucial.
- **HTTPS:** Ensure all API communication is over HTTPS.
- **Rate Limiting:** Implement rate limiting on the backend API to prevent abuse.