# LLM Summary Detail File

This file is a concatenation of all individual *llm.txt files found in the directory tree. Each section below corresponds to a specific directory's summary file.

================================================================================

## Section 1: frontend/frontend_llm.txt

**Source file:** `frontend/frontend_llm.txt`

# DEVELOPER GUIDE for frontend

## Quick Summary
The frontend directory contains a modern React + TypeScript + Vite application for an A2A (Agent-to-Agent) Chat interface. The architecture provides a comprehensive chat platform with AI agents, real-time task monitoring, file handling, authentication, and visualization components. The application uses React Context for global state management, Material-UI for components, and includes both development source code and production-ready static assets.

## Files and Subdirectories Overview

### Direct Files:
- **README.md** - Project documentation with React + TypeScript + Vite setup instructions
- **eslint.config.js** - ESLint configuration for TypeScript and React with hooks and refresh plugins
- **package-lock.json** - Dependency lock file ensuring consistent installations
- **package.json** - Project configuration with dependencies for React, Material-UI, charts, and development tools
- **postcss.config.js** - PostCSS configuration with Tailwind CSS and Autoprefixer
- **tsconfig.app.json** - TypeScript configuration for application source code
- **tsconfig.json** - Root TypeScript configuration with project references
- **tsconfig.node.json** - TypeScript configuration for Node.js tools (Vite)

### Subdirectories:
- **src/** - Main source code with React components, contexts, and application logic
- **static/** - Compiled production assets including JavaScript bundles for browser delivery

## Developer API Reference

### Direct Files

#### package.json
**Purpose:** Project configuration and dependency management
**Import:** Configuration file - not imported directly

**Scripts:**
- `dev` - Start development server with Vite
- `build` - Build production bundle with TypeScript compilation
- `lint` - Run ESLint on source code
- `preview` - Preview production build

**Key Dependencies:**
- React 19.0.0 with TypeScript support
- Material-UI for component library
- React Router for navigation
- Recharts for data visualization
- Mermaid for diagram rendering

#### eslint.config.js
**Purpose:** ESLint configuration for code quality and React best practices
**Import:** Configuration file - not imported directly

**Configuration:**
- TypeScript ESLint integration
- React Hooks rules enforcement
- React Refresh plugin for development
- Browser globals support

#### tsconfig.app.json
**Purpose:** TypeScript configuration for application source code
**Import:** Configuration file - not imported directly

**Settings:**
- ES2020 target with modern features
- React JSX support
- Strict type checking enabled
- Bundler module resolution

### Subdirectory APIs

#### src/
**Purpose:** Main source code with React components, contexts, and application logic for A2A chat interface
**Key Exports:** App, AuthProvider, ChatProvider, TaskMonitorProvider, ChatBox, AgentSelector, ArtifactPanel
**Import Examples:**
```typescript
import App from './src/App'
import { AuthProvider, useAuth } from './src/contexts/AuthProvider'
import { ChatProvider } from './src/contexts/ChatProvider'
import ChatBox from './src/components/ChatBox/ChatBox'
import AgentSelector from './src/components/AgentSelector'
```

#### static/
**Purpose:** Compiled production assets for browser delivery including React bundles and authentication handling
**Key Exports:** React runtime, JSX functions, ReactDOM methods, authentication callback handler
**Import Examples:**
```javascript
import { r as React, j as jsx, e as ReactDOM } from "./static/assets/client-y9YGnS5j.js"
// Authentication callback (auto-executing script)
<script src="./static/assets/auth-callback-BnT9Il8i.js"></script>
```

## Complete Usage Guide

### 1. Development Environment Setup

```bash
# Install dependencies
npm install

# Start development server
npm run dev

# Build for production
npm run build

# Preview production build
npm run preview

# Run linting
npm run lint
```

### 2. Complete A2A Chat Application

```typescript
// Main application entry point
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './src/App';
import './src/index.css';

// Initialize the application
createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// App.tsx - Full application with all providers
import React from 'react';
import { AuthProvider, useAuth } from './src/contexts/AuthProvider';
import { ChatProvider } from './src/contexts/ChatProvider';
import { TaskMonitorProvider } from './src/contexts/TaskMonitorContext';
import ConfigProvider from './src/components/ConfigProvider';
import ChatBox from './src/components/ChatBox/ChatBox';
import AgentSelector from './src/components/AgentSelector';
import ArtifactPanel from './src/components/ArtifactPanel';
import TaskMonitorPage from './src/components/TaskMonitorPage';

function App() {
  return (
    <ConfigProvider>
      <AuthProvider useAuthorization={true}>
        <ChatProvider>
          <TaskMonitorProvider>
            <MainInterface />
          </TaskMonitorProvider>
        </ChatProvider>
      </AuthProvider>
    </ConfigProvider>
  );
}

function MainInterface() {
  const { isAuthenticated, login, useAuthorization } = useAuth();
  
  if (useAuthorization && !isAuthenticated) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-900">
        <button
          onClick={login}
          className="px-6 py-3 text-lg font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-700"
        >
          Login to Chat
        </button>
      </div>
    );
  }

  return <ChatInterface />;
}
```

### 3. Chat Interface with Real-time Features

```typescript
import React, { useContext, useEffect, useState } from 'react';
import ChatContext from './src/contexts/ChatContext';
import { useTaskMonitor } from './src/contexts/TaskMonitorContext';
import ChatBox from './src/components/ChatBox/ChatBox';
import AgentSelector from './src/components/AgentSelector';
import ArtifactPanel from './src/components/ArtifactPanel';

function ChatInterface() {
  const {
    messages,
    userInput,
    setUserInput,
    handleSubmit,
    handleNewSession,
    isResponding,
    selectedAgentName,
    setSelectedAgentName,
    artifacts,
    isArtifactPanelOpen,
    toggleArtifactPanel,
    fetchArtifacts
  } = useContext(ChatContext)!;

  const {
    connectTaskMonitorStream,
    disconnectTaskMonitorStream,
    isTaskMonitorConnected,
    monitoredTasks
  } = useTaskMonitor();

  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);

  useEffect(() => {
    // Initialize connections
    connectTaskMonitorStream();
    fetchArtifacts();
    
    return () => {
      disconnectTaskMonitorStream();
    };
  }, []);

  const handleFilePreview = (file: any) => {
    console.log('Preview file:', file);
  };

  const handleFileRun = (file: any) => {
    console.log('Run file:', file);
  };

  return (
    <div className="h-screen flex flex-col bg-gray-900 text-white">
      {/* Header */}
      <div className="flex items-center justify-between p-4 bg-gray-800 border-b border-gray-700">
        <div className="flex items-center space-x-4">
          <AgentSelector
            selectedAgentName={selectedAgentName}
            onSelectAgent={setSelectedAgentName}
            disabled={isResponding}
          />
          <button
            onClick={handleNewSession}
            disabled={isResponding}
            className="px-4 py-2 bg-blue-600 rounded hover:bg-blue-700 disabled:opacity-50"
          >
            New Session
          </button>
        </div>
        
        <div className="flex items-center space-x-4">
          <span className="text-sm">
            Tasks: {Object.keys(monitoredTasks).length}
          </span>
          <div className={`w-3 h-3 rounded-full ${
            isTaskMonitorConnected ? 'bg-green-500' : 'bg-red-500'
          }`} />
          <button
            onClick={toggleArtifactPanel}
            className="px-4 py-2 bg-purple-600 rounded hover:bg-purple-700"
          >
            Artifacts ({artifacts.length})
          </button>
        </div>
      </div>

      {/* Main content */}
      <div className="flex-1 flex overflow-hidden">
        {/* Chat area */}
        <div className="flex-1">
          <ChatBox
            messages={messages}
            userInput={userInput}
            setUserInput={setUserInput}
            handleSubmit={handleSubmit}
            isResponding={isResponding}
            selectedFiles={selectedFiles}
            setSelectedFiles={setSelectedFiles}
            selectedAgentName={selectedAgentName}
            handlePreviewFile={handleFilePreview}
            handleRunFile={handleFileRun}
          />
        </div>

        {/* Artifact panel */}
        <ArtifactPanel
          isOpen={isArtifactPanelOpen}
          artifacts={artifacts}
          isLoading={false}
          onClose={() => toggleArtifactPanel()}
          onPreviewFile={handleFilePreview}
          onDownloadFile={(filename) => console.log('Download:', filename)}
          onCopyFile={(artifact) => console.log('Copy:', artifact)}
          onUploadFile={(file) => console.log('Upload:', file)}
          onDeleteArtifact={(artifact) => console.log('Delete:', artifact)}
          onDeleteSelected={() => console.log('Delete selected')}
        />
      </div>
    </div>
  );
}
```

### 4. Task Monitoring Dashboard

```typescript
import React, { useState } from 'react';
import { TaskMonitorProvider, useTaskMonitor } from './src/contexts/TaskMonitorContext';
import TaskMonitorPage from './src/components/TaskMonitorPage';
import FlowChartPanel from './src/components/TaskMonitor/FlowChart/FlowChartPanel';

function TaskMonitorDashboard() {
  return (
    <TaskMonitorProvider>
      <TaskMonitorInterface />
    </TaskMonitorProvider>
  );
}

function TaskMonitorInterface() {
  const {
    isTaskMonitorConnected,
    monitoredTasks,
    monitoredTaskOrder,
    highlightedStepId,
    setHighlightedStepId
  } = useTaskMonitor();

  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);

  return (
    <div className="h-screen flex bg-gray-900 text-white">
      {/* Task list */}
      <div className="w-1/3 border-r border-gray-700 overflow-y-auto">
        <div className="p-4 border-b border-gray-700">
          <h2 className="text-lg font-semibold">
            Active Tasks ({monitoredTaskOrder.length})
          </h2>
          <div className={`inline-block w-3 h-3 rounded-full ml-2 ${
            isTaskMonitorConnected ? 'bg-green-500' : 'bg-red-500'
          }`} />
        </div>
        
        {monitoredTaskOrder.map(taskId => {
          const task = monitoredTasks[taskId];
          return (
            <div
              key={taskId}
              className={`p-3 border-b border-gray-700 cursor-pointer hover:bg-gray-800 ${
                selectedTaskId === taskId ? 'bg-blue-900' : ''
              }`}
              onClick={() => setSelectedTaskId(taskId)}
            >
              <div className="font-medium truncate">
                {task.initialRequestText}
              </div>
              <div className="text-sm text-gray-400">
                Events: {task.events.length} | Status: {task.status}
              </div>
            </div>
          );
        })}
      </div>

      {/* Task details */}
      <div className="flex-1">
        {selectedTaskId ? (
          <div className="h-full flex flex-col">
            <div className="p-4 border-b border-gray-700">
              <h3 className="text-lg font-semibold">
                Task: {monitoredTasks[selectedTaskId]?.initialRequestText}
              </h3>
            </div>
            <div className="flex-1">
              <FlowChartPanel
                taskId={selectedTaskId}
                highlightedStepId={highlightedStepId}
                onStepClick={setHighlightedStepId}
              />
            </div>
          </div>
        ) : (
          <div className="flex items-center justify-center h-full text-gray-500">
            Select a task to view details
          </div>
        )}
      </div>
    </div>
  );
}
```

### 5. Production Deployment

```typescript
// Production build using static assets
import { r as React, j as jsx, e as ReactDOM } from "./static/assets/client-y9YGnS5j.js";

// Production-ready error boundary
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  
  componentDidCatch(error, errorInfo) {
    console.error('Application error:', error, errorInfo);
  }
  
  render() {
    if (this.state.hasError) {
      return jsx('div', {
        className: 'error-boundary p-8 text-center',
        children: [
          jsx('h2', { children: 'Something went wrong' }),
          jsx('button', {
            onClick: () => window.location.reload(),
            className: 'mt-4 px-4 py-2 bg-blue-600 text-white rounded',
            children: 'Reload Application'
          })
        ]
      });
    }
    
    return this.props.children;
  }
}

// Initialize production app
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(
  jsx(ErrorBoundary, {
    children: jsx(App, {})
  })
);
```

### 6. Authentication Setup

```html
<!-- OAuth callback page -->
<!DOCTYPE html>
<html>
<head>
    <title>Authentication Callback</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <div id="callback-status" class="p-8 text-center">
        <h2>Processing authentication...</h2>
        <div class="spinner"></div>
    </div>
    <!-- Auto-processes OAuth tokens and redirects -->
    <script src="./static/assets/auth-callback-BnT9Il8i.js"></script>
</body>
</html>
```

**Critical Requirements:**
1. **Development vs Production:** Use `src/` imports for development, `static/assets/` for production
2. **Context Hierarchy:** Maintain proper provider order: Config → Auth → Chat → TaskMonitor
3. **Authentication Flow:** OAuth callback automatically processes tokens and stores in localStorage
4. **Real-time Connections:** Task monitoring uses SSE connections that need proper cleanup
5. **File Handling:** Support for file uploads, previews, and artifact management
6. **Error Boundaries:** Implement error boundaries for production stability
7. **

================================================================================

## Section 2: frontend/src/components/AgentCommunicationFlow/AgentCommunicationFlow_llm.txt

**Source file:** `frontend/src/components/AgentCommunicationFlow/AgentCommunicationFlow_llm.txt`

# DEVELOPER GUIDE: AgentCommunicationFlow

## Quick Summary
A React-based component system for visualizing agent communication flows using React Flow. Provides interactive network diagrams showing how agents communicate with each other, with multiple layout options and real-time updates.

## Files Overview
- **AgentCommEdge.tsx** - Custom edge component for rendering communication connections between agents
- **AgentCommNode.tsx** - Custom node component for displaying individual agents in the flow diagram
- **AgentCommunicationFlowChart.tsx** - Main flow chart component that orchestrates the entire visualization
- **LayoutSelector.tsx** - UI component for switching between different layout algorithms

## Developer API Reference

### AgentCommEdge.tsx
**Purpose:** Renders custom edges (connections) between agent nodes in the communication flow
**Import:** `import AgentCommEdge from './components/AgentCommunicationFlow/AgentCommEdge'`

**Components:**
- `AgentCommEdge(props: EdgeProps)` - Custom edge component with green styling
  - Extends React Flow's EdgeProps interface
  - Renders bezier curve paths between nodes
  - Uses consistent green color scheme (#00c895)

**Usage Examples:**
```tsx
// Used internally by React Flow - register as edge type
const edgeTypes = {
  commEdge: AgentCommEdge,
};

// In ReactFlow component
<ReactFlow edgeTypes={edgeTypes} />
```

### AgentCommNode.tsx
**Purpose:** Renders individual agent nodes with connection handles and agent information
**Import:** `import AgentCommNode from './components/AgentCommunicationFlow/AgentCommNode'`

**Types:**
- `AgentNodeData` - Data structure for node content (imported from communicationAnalysis)

**Components:**
- `AgentCommNode(props: NodeProps<Node<AgentNodeData>>)` - Agent node component
  - Displays agent name and label
  - Provides connection handles on all four sides
  - Shows selection state and hover effects
  - Responsive design with dark mode support

**Usage Examples:**
```tsx
// Register as node type
const nodeTypes = {
  agentCommNode: AgentCommNode,
};

// In ReactFlow component
<ReactFlow nodeTypes={nodeTypes} />
```

### AgentCommunicationFlowChart.tsx
**Purpose:** Main component that creates and manages the complete agent communication flow visualization
**Import:** `import AgentCommunicationFlowChart from './components/AgentCommunicationFlow/AgentCommunicationFlowChart'`

**Types:**
- `AgentCommunicationFlowChartProps` - Props interface for the main component
  - `agents: AgentCard[]` - Array of agents to visualize
  - `currentLayout: LayoutType` - Current layout algorithm
  - `onLayoutChange: (layout: LayoutType) => void` - Layout change handler

**Components:**
- `AgentCommunicationFlowChart(props: AgentCommunicationFlowChartProps)` - Main flow chart component
  - Manages node and edge state
  - Handles agent selection and highlighting
  - Provides summary panel and controls
  - Auto-fits view and handles layout changes

**Features:**
- Interactive node selection with connection highlighting
- Summary panel showing communication statistics
- Refresh functionality for real-time updates
- Responsive layout with dark mode support

**Usage Examples:**
```tsx
import AgentCommunicationFlowChart from './components/AgentCommunicationFlow/AgentCommunicationFlowChart';
import { LayoutType } from './components/AgentCommunicationFlow/layoutEngine';
import { AgentCard } from './common_a2a/types';

function MyComponent() {
  const [agents, setAgents] = useState<AgentCard[]>([]);
  const [layout, setLayout] = useState<LayoutType>(LayoutType.AUTO);

  return (
    <div style={{ height: '600px', width: '100%' }}>
      <AgentCommunicationFlowChart
        agents={agents}
        currentLayout={layout}
        onLayoutChange={setLayout}
      />
    </div>
  );
}
```

### LayoutSelector.tsx
**Purpose:** UI component for selecting different layout algorithms for the flow chart
**Import:** `import LayoutSelector from './components/AgentCommunicationFlow/LayoutSelector'`

**Types:**
- `LayoutSelectorProps` - Props interface for layout selector
  - `currentLayout: LayoutType` - Currently selected layout
  - `onLayoutChange: (layout: LayoutType) => void` - Layout change callback
  - `className?: string` - Optional CSS classes

**Components:**
- `LayoutSelector(props: LayoutSelectorProps)` - Layout selection component
  - Provides buttons for AUTO, HIERARCHICAL, and GRID layouts
  - Shows icons and descriptions for each layout type
  - Highlights currently active layout

**Usage Examples:**
```tsx
import LayoutSelector from './components/AgentCommunicationFlow/LayoutSelector';
import { LayoutType } from './components/AgentCommunicationFlow/layoutEngine';

function MyComponent() {
  const [currentLayout, setCurrentLayout] = useState<LayoutType>(LayoutType.AUTO);

  return (
    <div className="flex items-center justify-between p-4">
      <h2>Agent Communication</h2>
      <LayoutSelector
        currentLayout={currentLayout}
        onLayoutChange={setCurrentLayout}
        className="ml-auto"
      />
    </div>
  );
}
```

**Constants:**
- `LayoutType.AUTO` - Automatically selects best layout
- `LayoutType.HIERARCHICAL` - Layer-based layout
- `LayoutType.GRID` - Grid-based layout

================================================================================

## Section 3: frontend/src/components/ChatBox/ChatBox_llm.txt

**Source file:** `frontend/src/components/ChatBox/ChatBox_llm.txt`

# DEVELOPER GUIDE: ChatBox

## Quick Summary
The ChatBox directory provides a complete React-based chat interface system for AI agent conversations. It handles real-time messaging, file attachments, auto-scrolling behavior, loading states, tool call visualization, and responsive layout management with preview and artifact panels.

## Files Overview
- **ChatBox.tsx** - Main chat container component with scroll management and layout control
- **ChatMessages.tsx** - Message list container that renders individual message bubbles
- **MessageBubble.tsx** - Individual message component with content rendering and file displays
- **LoadingIndicator.tsx** - Animated loading dots component for response states
- **ChatBox.types** - TypeScript type definitions for Message and FileAttachment interfaces

## Developer API Reference

### ChatBox.tsx
**Purpose:** Main chat interface container with auto-scroll management and responsive layout
**Import:** `import ChatBox from './components/ChatBox/ChatBox'`

**Classes:**
- `ChatBox(props: ChatBoxProps)` - Main chat interface component
  - Manages scroll behavior and user interaction detection
  - Handles responsive layout based on panel states
  - Provides fixed input area with dynamic positioning

**Props Interface:**
```typescript
interface ChatBoxProps {
  messages: Message[];
  userInput: string;
  setUserInput: React.Dispatch<React.SetStateAction<string>>;
  handleSubmit: (e: FormEvent, files?: File[] | null) => void;
  isResponding: boolean;
  selectedFiles: File[];
  setSelectedFiles: React.Dispatch<React.SetStateAction<File[]>>;
  selectedAgentName: string;
  handlePreviewFile: (file: FileAttachment, autoRun?: boolean) => void;
  handleRunFile: (file: FileAttachment) => void;
}
```

**Usage Examples:**
```typescript
import ChatBox from './components/ChatBox/ChatBox';
import { Message } from './components/ChatBox/ChatBox.types';

function ChatContainer() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [userInput, setUserInput] = useState("");
  const [isResponding, setIsResponding] = useState(false);
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);

  const handleSubmit = (e: FormEvent, files?: File[] | null) => {
    // Handle message submission
  };

  const handlePreviewFile = (file: FileAttachment) => {
    // Handle file preview
  };

  return (
    <ChatBox
      messages={messages}
      userInput={userInput}
      setUserInput={setUserInput}
      handleSubmit={handleSubmit}
      isResponding={isResponding}
      selectedFiles={selectedFiles}
      setSelectedFiles={setSelectedFiles}
      selectedAgentName="MyAgent"
      handlePreviewFile={handlePreviewFile}
      handleRunFile={handleRunFile}
    />
  );
}
```

### ChatMessages.tsx
**Purpose:** Container component that renders a list of message bubbles
**Import:** `import ChatMessages from './components/ChatBox/ChatMessages'`

**Classes:**
- `ChatMessages(props: ChatMessagesProps)` - Message list renderer
  - Maps over messages array to render MessageBubble components
  - Provides scroll target reference for auto-scrolling
  - Handles message key generation for React rendering

**Props Interface:**
```typescript
interface ChatMessagesProps {
  messages: Message[];
  messagesEndRef: React.RefObject<HTMLDivElement>;
  isResponding: boolean;
  onPreviewFile?: (file: FileAttachment) => void;
  onRunFile?: (file: FileAttachment) => void;
}
```

**Usage Examples:**
```typescript
import ChatMessages from './components/ChatBox/ChatMessages';
import { useRef } from 'react';

function ChatContainer() {
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const messages = [/* your messages */];

  return (
    <ChatMessages
      messages={messages}
      messagesEndRef={messagesEndRef}
      isResponding={false}
      onPreviewFile={(file) => console.log('Preview:', file)}
      onRunFile={(file) => console.log('Run:', file)}
    />
  );
}
```

### MessageBubble.tsx
**Purpose:** Individual message component with content rendering and file handling
**Import:** `import MessageBubble from './components/ChatBox/MessageBubble'`

**Classes:**
- `MessageBubble(props: MessageBubbleProps)` - Memoized message bubble component
  - Renders different message types (user, agent, status, error)
  - Displays file attachments and tool call results
  - Shows completion indicators and artifact notifications

**Props Interface:**
```typescript
interface MessageBubbleProps {
  msg: Message;
  idx: number;
  isResponding: boolean;
  onPreviewFile?: (file: FileAttachment) => void;
  onRunFile?: (file: FileAttachment) => void;
}
```

**Usage Examples:**
```typescript
import MessageBubble from './components/ChatBox/MessageBubble';
import { Message } from './components/ChatBox/ChatBox.types';

const message: Message = {
  text: "Hello, how can I help you?",
  isUser: false,
  isComplete: true,
  files: [{
    name: "example.txt",
    content: "File content",
    type: "text/plain"
  }]
};

function MessageList() {
  return (
    <MessageBubble
      msg={message}
      idx={0}
      isResponding={false}
      onPreviewFile={(file) => console.log('Preview:', file)}
      onRunFile={(file) => console.log('Run:', file)}
    />
  );
}
```

### LoadingIndicator.tsx
**Purpose:** Animated loading dots component for response states
**Import:** `import LoadingIndicator from './components/ChatBox/LoadingIndicator'`

**Classes:**
- `LoadingIndicator()` - Memoized loading animation component
  - Displays three animated dots with staggered timing
  - Uses CSS animations for smooth loading effect
  - Inherits text color from parent component

**Usage Examples:**
```typescript
import LoadingIndicator from './components/ChatBox/LoadingIndicator';

function StatusMessage() {
  return (
    <div>
      Agent is typing
      <LoadingIndicator />
    </div>
  );
}
```

### ChatBox.types
**Purpose:** TypeScript type definitions for chat system
**Import:** `import { Message, FileAttachment, ToolEvent } from './components/ChatBox/ChatBox.types'`

**Types:**
- `Message` - Complete message structure with all possible properties
- `FileAttachment` - File attachment structure for agent-generated files
- `ToolEvent` - Tool execution event structure

**Type Definitions:**
```typescript
interface Message {
  text?: string;
  isUser: boolean;
  isStatusBubble?: boolean;
  isComplete?: boolean;
  isError?: boolean;
  uploadedFiles?: File[];
  files?: FileAttachment[];
  toolEvents?: ToolEvent[];
  artifactNotification?: {
    name: string;
    version?: string;
  };
  metadata?: {
    sessionId?: string;
  };
}

interface FileAttachment {
  name: string;
  content?: string;
  url?: string;
  type?: string;
  size?: number;
}

interface ToolEvent {
  toolName: string;
  data: any;
}
```

**Usage Examples:**
```typescript
import { Message, FileAttachment, ToolEvent } from './components/ChatBox/ChatBox.types';

// Create a user message with file uploads
const userMessage: Message = {
  text: "Please analyze these files",
  isUser: true,
  uploadedFiles: [file1, file2],
  metadata: { sessionId: "session-123" }
};

// Create an agent response with generated files and tool calls
const agentMessage: Message = {
  text: "I've analyzed your files and created a report.",
  isUser: false,
  isComplete: true,
  files: [{
    name: "analysis_report.pdf",
    url: "/api/files/download/456",
    type: "application/pdf",
    size: 1024000
  }],
  toolEvents: [{
    toolName: "file_analyzer",
    data: { status: "complete", results: {...} }
  }],
  artifactNotification: {
    name: "Analysis Report",
    version: "1.0"
  }
};

// Create a status/loading message
const statusMessage: Message = {
  text: "Analyzing files",
  isUser: false,
  isStatusBubble: true
};

// Create an error message
const errorMessage: Message = {
  text: "Failed to process the request. Please try again.",
  isUser: false,
  isError: true,
  isComplete: true
};
```

================================================================================

## Section 4: frontend/src/components/PreviewFileContent/PreviewFileContent_llm.txt

**Source file:** `frontend/src/components/PreviewFileContent/PreviewFileContent_llm.txt`

# DEVELOPER GUIDE: PreviewFileContent

## Quick Summary
The PreviewFileContent directory provides a comprehensive file preview system for React applications. It consists of direct files that handle file type detection, content rendering coordination, and specialized preview components for CSV and data structures, plus a Renderers subdirectory containing specific renderer components for different file types (HTML, Mermaid, images, audio, etc.). The system supports both inline message previews and full-panel previews with features like resizing, version navigation, and content rendering/source code toggling.

## Files and Subdirectories Overview

### Direct Files:
- **ContentRenderer.tsx** - Central dispatcher that routes content to appropriate renderers based on type
- **CsvPreview.tsx** - Basic CSV table preview component for inline display
- **CsvPreviewMessage.tsx** - CSV preview optimized for chat message contexts
- **CsvPreviewPanel.tsx** - Full-featured CSV preview with scrolling and sticky headers
- **DataStructurePreviewPanel.tsx** - JSON/YAML viewer with structured and raw text toggle
- **JsonPreviewPanel.tsx** - Dedicated JSON viewer component
- **PreviewContent.tsx** - Inline file preview with action buttons (copy, download, preview, run)
- **PreviewHelpers.tsx** - Utility functions for file type detection and content decoding
- **PreviewPanel.tsx** - Full-screen resizable preview panel with version navigation

### Subdirectories:
- **Renderers/** - Specialized renderer components for specific file types (HTML, Mermaid, images, audio, SQLite, Markdown)

## Developer API Reference

### Direct Files

#### ContentRenderer.tsx
**Purpose:** Central content routing component that delegates rendering to appropriate specialized renderers
**Import:** `import { ContentRenderer, RendererType } from './components/PreviewFileContent/ContentRenderer'`

**Types:**
- `RendererType = 'html' | 'mermaid' | 'image' | 'markdown' | 'audio' | 'sqlite'`

**Components:**
- `ContentRenderer({ content, width, rendererType, mime_type }: ContentRendererProps)` - Routes content to appropriate renderer
  - `content: string` - File content (base64 for binary files, decoded for text)
  - `width: number` - Available width for rendering
  - `rendererType: RendererType` - Type of renderer to use
  - `mime_type?: string` - Optional MIME type for binary files

#### CsvPreview.tsx
**Purpose:** Basic CSV table component for inline previews
**Import:** `import CsvPreview from './components/PreviewFileContent/CsvPreview'`

**Components:**
- `CsvPreview({ content, isExpanded }: CsvPreviewProps)` - Renders CSV as HTML table
  - `content: string` - Decoded CSV content
  - `isExpanded: boolean` - Whether to show all rows or just first 4

**Functions:**
- `parseCsv(csvString: string) -> string[][]` - Simple CSV parser for comma-separated values

#### CsvPreviewMessage.tsx
**Purpose:** CSV preview component optimized for chat message contexts
**Import:** `import { CsvPreviewMessage } from './components/PreviewFileContent/CsvPreviewMessage'`

**Components:**
- `CsvPreviewMessage({ content, isExpanded }: CsvPreviewMessageProps)` - Chat-optimized CSV table
  - `content: string` - Decoded CSV content
  - `isExpanded: boolean` - Whether to show all rows or just first 4

#### CsvPreviewPanel.tsx
**Purpose:** Full-featured CSV preview with scrolling and sticky headers
**Import:** `import { CsvPreviewPanel } from './components/PreviewFileContent/CsvPreviewPanel'`

**Components:**
- `CsvPreviewPanel({ content, width }: CsvPreviewPanelProps)` - Full CSV table with sticky headers
  - `content: string` - Decoded CSV content
  - `width: number` - Available width for the panel

#### DataStructurePreviewPanel.tsx
**Purpose:** Interactive JSON/YAML viewer with structured and raw text views
**Import:** `import { DataStructurePreviewPanel } from './components/PreviewFileContent/DataStructurePreviewPanel'`

**Components:**
- `DataStructurePreviewPanel({ dataString, inputType, width }: DataStructurePreviewPanelProps)` - Interactive data structure viewer
  - `dataString: string` - Raw JSON or YAML content
  - `inputType: 'json' | 'yaml'` - Type of input data
  - `width: number` - Available width for the panel

#### JsonPreviewPanel.tsx
**Purpose:** Dedicated JSON viewer component
**Import:** `import { JsonPreviewPanel } from './components/PreviewFileContent/JsonPreviewPanel'`

**Components:**
- `JsonPreviewPanel({ jsonString, width }: JsonPreviewPanelProps)` - JSON-specific viewer
  - `jsonString: string` - Raw JSON content
  - `width: number` - Available width for the panel

#### PreviewContent.tsx
**Purpose:** Inline file preview component with action buttons
**Import:** `import PreviewContent from './components/PreviewFileContent/PreviewContent'`

**Components:**
- `PreviewContent({ file, className, onDownload, onPreview, onRun }: PreviewContentProps)` - Inline file preview with actions
  - `file: FileAttachment` - File object with content and metadata
  - `className?: string` - Additional CSS classes
  - `onDownload: () => void` - Download handler
  - `onPreview?: (file: FileAttachment) => void` - Preview panel opener
  - `onRun?: (file: FileAttachment) => void` - Render mode opener

#### PreviewHelpers.tsx
**Purpose:** Utility functions for file type detection and content processing
**Import:** `import { isHtmlFile, isMermaidFile, decodeBase64Content, ... } from './components/PreviewFileContent/PreviewHelpers'`

**Functions:**
- `isHtmlFile(fileName?: string) -> boolean` - Detects HTML files (.html, .htm)
- `isMermaidFile(fileName?: string) -> boolean` - Detects Mermaid files (.mermaid, .mmd)
- `isCsvFile(fileName?: string) -> boolean` - Detects CSV files (.csv)
- `isImageFile(fileName?: string) -> boolean` - Detects image files (png, jpg, gif, etc.)
- `isJsonFile(fileName?: string, mimeType?: string) -> boolean` - Detects JSON files
- `isYamlFile(fileName?: string, mimeType?: string) -> boolean` - Detects YAML files
- `isMarkdownFile(fileName?: string) -> boolean` - Detects Markdown files (.md, .markdown)
- `isAudioFile(fileName?: string, mimeType?: string) -> boolean` - Detects audio files
- `isSqliteFile(fileName?: string, mimeType?: string) -> boolean` - Detects SQLite files
- `decodeBase64Content(content: string) -> string` - Safely decodes base64 to UTF-8

#### PreviewPanel.tsx
**Purpose:** Full-screen resizable preview panel with advanced features
**Import:** `import PreviewPanel from './components/PreviewFileContent/PreviewPanel'`

**Components:**
- `PreviewPanel({ file, onClose, autoRun, currentVersionNumber, availableVersions, onNavigateVersion }: PreviewPanelProps)` - Full-featured preview panel
  - `file: FileAttachment | null` - File to preview
  - `onClose: () => void` - Panel close handler
  - `autoRun?: boolean` - Start in render mode for HTML/Mermaid
  - `currentVersionNumber: number | null` - Current file version
  - `availableVersions: number[] | null` - Available version numbers
  - `onNavigateVersion: (targetVersion: number) => void` - Version navigation handler

### Subdirectory APIs

#### Renderers/
**Purpose:** Specialized renderer components for different file types
**Key Exports:** AudioRenderer, HtmlRenderer, ImageRenderer, MarkdownRenderer, MermaidRenderer, SqliteRenderer
**Import Examples:**
```typescript
import { AudioRenderer } from './components/PreviewFileContent/Renderers/AudioRenderer'
import { HtmlRenderer } from './components/PreviewFileContent/Renderers/HTMLRenderer'
import { ImageRenderer } from './components/PreviewFileContent/Renderers/ImageRenderer'
```

## Complete Usage Guide

### 1. Basic File Type Detection
```typescript
import { 
  isHtmlFile, 
  isMermaidFile, 
  isCsvFile, 
  isImageFile, 
  decodeBase64Content 
} from './components/PreviewFileContent/PreviewHelpers';

// Detect file types
const fileName = "document.html";
const isHtml = isHtmlFile(fileName); // true
const isCsv = isCsvFile("data.csv"); // true
const isImage = isImageFile("photo.png"); // true

// Decode base64 content safely
const base64Content = "SGVsbG8gV29ybGQ=";
const decodedText = decodeBase64Content(base64Content); // "Hello World"
```

### 2. Inline File Preview with Actions
```typescript
import PreviewContent from './components/PreviewFileContent/PreviewContent';
import { FileAttachment } from '../ChatBox/ChatBox.types';

const MyComponent = () => {
  const file: FileAttachment = {
    name: "data.csv",
    content: "bmFtZSxhZ2UKSm9obiwyNQpKYW5lLDMw", // base64 encoded CSV
    mime_type: "text/csv"
  };

  const handleDownload = () => {
    // Download logic
  };

  const handlePreview = (file: FileAttachment) => {
    // Open preview panel
  };

  const handleRun = (file: FileAttachment) => {
    // Open in render mode
  };

  return (
    <PreviewContent
      file={file}
      onDownload={handleDownload}
      onPreview={handlePreview}
      onRun={handleRun}
      className="my-4"
    />
  );
};
```

### 3. Full Preview Panel with Version Navigation
```typescript
import PreviewPanel from './components/PreviewFileContent/PreviewPanel';

const MyApp = () => {
  const [selectedFile, setSelectedFile] = useState<FileAttachment | null>(null);
  const [currentVersion, setCurrentVersion] = useState<number>(1);
  const availableVersions = [1, 2, 3];

  return (
    <>
      {selectedFile && (
        <PreviewPanel
          file={selectedFile}
          onClose={() => setSelectedFile(null)}
          autoRun={true} // Start in render mode for HTML/Mermaid
          currentVersionNumber={currentVersion}
          availableVersions={availableVersions}
          onNavigateVersion={setCurrentVersion}
        />
      )}
    </>
  );
};
```

### 4. Direct Content Rendering
```typescript
import { ContentRenderer } from './components/PreviewFileContent/ContentRenderer';

// Render different content types
const RenderExamples = () => {
  return (
    <div>
      {/* Render HTML */}
      <ContentRenderer
        content="<h1>Hello World</h1>"
        width={800}
        rendererType="html"
      />

      {/* Render Mermaid diagram */}
      <ContentRenderer
        content="graph TD\n    A[Start] --> B[End]"
        width={600}
        rendererType="mermaid"
      />

      {/* Render image */}
      <ContentRenderer
        content="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
        width={400}
        rendererType="image"
        mime_type="image/png"
      />
    </div>
  );
};
```

### 5. Specialized Data Structure Viewing
```typescript
import { DataStructurePreviewPanel } from './components/PreviewFileContent/DataStructurePreviewPanel';
import { CsvPreviewPanel } from './components/PreviewFileContent/CsvPreviewPanel';

const DataViewers = () => {
  const jsonData = '{"name": "John", "age": 30}';
  const yamlData = 'name: John\nage: 30';
  const csvData = 'name,age\nJohn,30\nJane,25';

  return (
    <div>
      {/* JSON viewer with toggle between structured and raw */}
      <DataStructurePreviewPanel
        dataString={jsonData}
        inputType="json"
        width={800}
      />

      {/* YAML viewer */}
      <DataStructurePreviewPanel
        dataString={yamlData}
        inputType="yaml"
        width={800}
      />

      {/* CSV table with sticky headers */}
      <CsvPreviewPanel
        content={csvData}
        width={600}
      />
    </div>
  );
};
```

### 6. Working with File Attachments
```typescript
import { 
  isHtmlFile, 
  isMermaidFile, 
  decodeBase64Content 
} from './components/PreviewFileContent/PreviewHelpers';
import { ContentRenderer } from './components/PreviewFileContent/ContentRenderer';

const FileProcessor = ({ file }: { file: FileAttachment }) => {
  // Determine file type and appropriate renderer
  const isRenderable = isHtmlFile(file.name) || isMermaidFile(file.name);
  const isImage = isImageFile(file.name);
  
  // Decode content if it's text-based
  const content = isImage ? file.content : decodeBase64Content(file.content);
  
  // Choose appropriate renderer type
  let rendererType: RendererType;
  if (isHtmlFile(file.name)) rendererType = 'html';
  else if (isMermaidFile(file.name)) rendererType = 'mermaid';
  else if (isImage) rendererType = 'image';
  else if (isMarkdownFile(file.name)) rendererType = 'markdown';
  else if (isAudioFile(file.name, file.mime_type)) rendererType = 'audio';
  else if (isSqliteFile(file.name, file.mime_type)) rendererType = 'sqlite';
  else return <div>Unsupported file type</div>;

  return (
    <ContentRenderer
      content={content}
      width={800}
      rendererType={rendererType}
      mime_type={file.mime_type}
    />
  );
};
```

This system provides a complete file preview solution with support for multiple file types, interactive features, and both inline and full-panel viewing modes. The modular architecture allows for easy extension with new file types and renderers.

================================================================================

## Section 5: frontend/src/components/PreviewFileContent/Renderers/Renderers_llm.txt

**Source file:** `frontend/src/components/PreviewFileContent/Renderers/Renderers_llm.txt`

# DEVELOPER GUIDE: Renderers

## Quick Summary
The Renderers directory contains React components for rendering different file types in a preview interface. Each renderer handles specific MIME types and provides appropriate visualization for audio, HTML, images, Markdown, Mermaid diagrams, and SQLite databases.

## Files Overview
- **AudioRenderer.tsx** - Renders audio files with HTML5 audio controls
- **HTMLRenderer.tsx** - Renders HTML content in a sandboxed iframe
- **ImageRenderer.tsx** - Displays images from base64 encoded content
- **MarkdownRenderer.tsx** - Renders Markdown content using a custom component
- **MermaidRenderer.tsx** - Renders Mermaid diagrams with pan/zoom functionality
- **SqliteRenderer.tsx** - Shows placeholder UI for SQLite database files
- **types.ts** - Contains shared TypeScript interfaces (referenced but not provided)

## Developer API Reference

### AudioRenderer.tsx
**Purpose:** Renders audio files with HTML5 audio player controls
**Import:** `import { AudioRenderer } from './components/PreviewFileContent/Renderers/AudioRenderer'`

**Components:**
- `AudioRenderer({ content, width, mime_type }: AudioRendererProps)` - React component for audio playback
  - `content: string` - Base64 encoded audio data
  - `width: number` - Maximum width for the container
  - `mime_type?: string` - Audio MIME type (defaults to 'audio/mpeg')

**Usage Examples:**
```tsx
import { AudioRenderer } from './components/PreviewFileContent/Renderers/AudioRenderer';

// Basic audio rendering
<AudioRenderer 
  content="UklGRnoGAABXQVZFZm10IBAAAAABAAEA..." 
  width={800} 
  mime_type="audio/mp3" 
/>
```

### HTMLRenderer.tsx
**Purpose:** Renders HTML content in a secure sandboxed iframe
**Import:** `import { HtmlRenderer } from './components/PreviewFileContent/Renderers/HTMLRenderer'`

**Components:**
- `HtmlRenderer({ content, width }: BaseRendererProps)` - React component for HTML preview
  - `content: string` - Raw HTML content
  - `width: number` - Maximum width for the container

**Usage Examples:**
```tsx
import { HtmlRenderer } from './components/PreviewFileContent/Renderers/HTMLRenderer';

// Render HTML content
<HtmlRenderer 
  content="<html><body><h1>Hello World</h1></body></html>" 
  width={1000} 
/>
```

### ImageRenderer.tsx
**Purpose:** Displays images from base64 encoded content
**Import:** `import { ImageRenderer } from './components/PreviewFileContent/Renderers/ImageRenderer'`

**Components:**
- `ImageRenderer({ content, width, mime_type }: ImageRendererProps)` - React component for image display
  - `content: string` - Base64 encoded image data
  - `width: number` - Maximum width for the container
  - `mime_type?: string` - Image MIME type (defaults to 'image/png')

**Usage Examples:**
```tsx
import { ImageRenderer } from './components/PreviewFileContent/Renderers/ImageRenderer';

// Display an image
<ImageRenderer 
  content="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" 
  width={600} 
  mime_type="image/png" 
/>
```

### MarkdownRenderer.tsx
**Purpose:** Renders Markdown content using a custom Markdown component
**Import:** `import { MarkdownRenderer } from './components/PreviewFileContent/Renderers/MarkdownRenderer'`

**Components:**
- `MarkdownRenderer({ content, width }: BaseRendererProps)` - React component for Markdown rendering
  - `content: string` - Raw Markdown text
  - `width: number` - Maximum width for the container

**Usage Examples:**
```tsx
import { MarkdownRenderer } from './components/PreviewFileContent/Renderers/MarkdownRenderer';

// Render Markdown content
<MarkdownRenderer 
  content="# Hello World\n\nThis is **bold** text." 
  width={800} 
/>
```

### MermaidRenderer.tsx
**Purpose:** Renders Mermaid diagrams with interactive pan and zoom functionality
**Import:** `import { MermaidRenderer } from './components/PreviewFileContent/Renderers/MermaidRenderer'`

**Components:**
- `MermaidRenderer({ content, width }: BaseRendererProps)` - React component for Mermaid diagram rendering
  - `content: string` - Mermaid diagram syntax
  - `width: number` - Maximum width for the container

**Usage Examples:**
```tsx
import { MermaidRenderer } from './components/PreviewFileContent/Renderers/MermaidRenderer';

// Render a Mermaid flowchart
<MermaidRenderer 
  content="graph TD\n    A[Start] --> B{Decision}\n    B -->|Yes| C[End]\n    B -->|No| D[Continue]" 
  width={900} 
/>
```

### SqliteRenderer.tsx
**Purpose:** Shows a placeholder UI for SQLite database files that cannot be previewed
**Import:** `import { SqliteRenderer } from './components/PreviewFileContent/Renderers/SqliteRenderer'`

**Components:**
- `SqliteRenderer({ width, filename, filesize }: SqliteRendererProps)` - React component for SQLite file placeholder
  - `width: number` - Maximum width for the container
  - `filename?: string` - Optional filename to display
  - `filesize?: number` - Optional file size in bytes

**Functions:**
- `formatBytes(bytes: number, decimals?: number) -> string` - Helper function to format file sizes

**Usage Examples:**
```tsx
import { SqliteRenderer } from './components/PreviewFileContent/Renderers/SqliteRenderer';

// Show SQLite file info
<SqliteRenderer 
  width={600} 
  filename="database.sqlite" 
  filesize={1048576} 
/>

// Format file size
const sizeString = formatBytes(1024); // Returns "1 KB"
```

================================================================================

## Section 6: frontend/src/components/TaskMonitor/FlowChart/FlowChart_llm.txt

**Source file:** `frontend/src/components/TaskMonitor/FlowChart/FlowChart_llm.txt`

# DEVELOPER GUIDE: FlowChart

## Quick Summary
The FlowChart directory provides a comprehensive React Flow-based visualization system for AI agent workflows and task monitoring. It combines a main panel component with custom nodes and edges to create interactive flowcharts that can display agent interactions, tool executions, and data flow with real-time animation. The architecture separates the main flow panel logic from reusable custom node/edge components.

## Files and Subdirectories Overview
- **Direct files:**
  - `FlowChartPanel.tsx` - Main React Flow panel component with task monitoring integration
- **Subdirectories:**
  - `customEdges/` - Custom edge components with animation support for data flow visualization
  - `customNodes/` - Collection of specialized node components for different entity types (agents, tools, users, LLM)

## Developer API Reference

### Direct Files

#### FlowChartPanel.tsx
**Purpose:** Main React Flow panel component that orchestrates the entire flowchart visualization
**Import:** `import FlowChartPanel from 'frontend/src/components/TaskMonitor/FlowChart/FlowChartPanel'`

**Interfaces:**
- `FlowChartPanelProps` - Main component props interface
  - `processedSteps: VisualizerStep[]` - Array of workflow steps to visualize
  - `isFullScreen: boolean` - Whether the panel is in fullscreen mode
  - `onToggleFullScreen: () => void` - Callback to toggle fullscreen state

**Components:**
- `FlowChartPanel: React.FC<FlowChartPanelProps>` - Main exported component wrapped with ReactFlowProvider
- `FlowRenderer: React.FC<FlowChartPanelProps>` - Internal component containing React Flow logic

**Key Features:**
- Integration with TaskMonitorContext for state management
- Custom node and edge type registration
- Automatic layout using timeline flow transformation
- Interactive node highlighting and selection
- Fullscreen mode support with automatic view fitting

### Subdirectory APIs

#### customEdges/
**Purpose:** Provides custom edge components with animation capabilities for visualizing data flow
**Key Exports:** GenericFlowEdge component and AnimatedEdgeData interface
**Import Examples:**
```typescript
import GenericFlowEdge, { AnimatedEdgeData } from 'frontend/src/components/TaskMonitor/FlowChart/customEdges/GenericFlowEdge'
```

#### customNodes/
**Purpose:** Collection of specialized node components for different entity types in AI workflows
**Key Exports:** GenericAgentNode, UserNode, LLMNode, OrchestratorAgentNode, GenericToolNode
**Import Examples:**
```typescript
import GenericAgentNode, { GenericNodeData } from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/GenericAgentNode'
import UserNode, { UserNodeType, UserNodeData } from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/UserNode'
import LLMNode, { LLMNodeType } from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/LLMNode'
```

## Complete Usage Guide

### 1. Basic FlowChart Setup

```typescript
import React, { useState } from 'react';
import FlowChartPanel from 'frontend/src/components/TaskMonitor/FlowChart/FlowChartPanel';
import { VisualizerStep } from '../TaskVisualizer.types';

const MyFlowChart: React.FC = () => {
  const [isFullScreen, setIsFullScreen] = useState(false);
  const [processedSteps, setProcessedSteps] = useState<VisualizerStep[]>([]);

  const handleToggleFullScreen = () => {
    setIsFullScreen(!isFullScreen);
  };

  return (
    <div className={isFullScreen ? 'fixed inset-0 z-50' : 'h-96'}>
      <FlowChartPanel
        processedSteps={processedSteps}
        isFullScreen={isFullScreen}
        onToggleFullScreen={handleToggleFullScreen}
      />
    </div>
  );
};
```

### 2. Creating Custom Node Types

```typescript
import { Node } from '@xyflow/react';
import { GenericNodeData } from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/GenericAgentNode';
import { UserNodeData } from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/UserNode';

// Create different node types
const agentNode: Node<GenericNodeData> = {
  id: 'agent-1',
  type: 'genericAgentNode',
  position: { x: 100, y: 100 },
  data: {
    label: 'Processing Agent',
    description: 'Handles data processing',
    status: 'in-progress'
  }
};

const userNode: Node<UserNodeData> = {
  id: 'user-1',
  type: 'userNode',
  position: { x: 100, y: 0 },
  data: {
    label: 'User Input',
    isTopNode: true,
    status: 'completed'
  }
};

const toolNode: Node<GenericNodeData> = {
  id: 'tool-1',
  type: 'genericToolNode',
  position: { x: 300, y: 100 },
  data: {
    label: 'File Reader',
    status: 'started'
  }
};
```

### 3. Creating Custom Edges with Animation

```typescript
import { Edge } from '@xyflow/react';
import { AnimatedEdgeData } from 'frontend/src/components/TaskMonitor/FlowChart/customEdges/GenericFlowEdge';

// Create animated edges
const requestEdge: Edge = {
  id: 'edge-1',
  source: 'agent-1',
  target: 'tool-1',
  type: 'defaultFlowEdge',
  data: {
    visualizerStepId: 'step-123',
    isAnimated: true,
    animationType: 'request'
  } as AnimatedEdgeData
};

const responseEdge: Edge = {
  id: 'edge-2',
  source: 'tool-1',
  target: 'agent-1',
  type: 'defaultFlowEdge',
  data: {
    visualizerStepId: 'step-124',
    isAnimated: false,
    animationType: 'response'
  } as AnimatedEdgeData
};
```

### 4. Integration with TaskMonitorContext

```typescript
import React from 'react';
import { useTaskMonitor } from 'frontend/src/contexts/TaskMonitorContext';
import FlowChartPanel from 'frontend/src/components/TaskMonitor/FlowChart/FlowChartPanel';

const TaskFlowVisualization: React.FC = () => {
  const {
    processedSteps,
    highlightedStepId,
    setHighlightedStepId
  } = useTaskMonitor();
  
  const [isFullScreen, setIsFullScreen] = useState(false);

  // The FlowChartPanel automatically integrates with TaskMonitorContext
  // for step highlighting
  return (
    <FlowChartPanel
      processedSteps={processedSteps}
      isFullScreen={isFullScreen}
      onToggleFullScreen={() => setIsFullScreen(!isFullScreen)}
    />
  );
};
```

### 5. Custom Node Registration and Usage

```typescript
import React from 'react';
import { ReactFlow, ReactFlowProvider } from '@xyflow/react';
import GenericAgentNode from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/GenericAgentNode';
import UserNode from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/UserNode';
import LLMNode from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/LLMNode';
import OrchestratorAgentNode from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/OrchestratorAgentNode';
import GenericToolNode from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/GenericToolNode';
import GenericFlowEdge from 'frontend/src/components/TaskMonitor/FlowChart/customEdges/GenericFlowEdge';

// Register all custom node and edge types
const nodeTypes = {
  genericAgentNode: GenericAgentNode,
  userNode: UserNode,
  llmNode: LLMNode,
  orchestratorNode: OrchestratorAgentNode,
  genericToolNode: GenericToolNode,
};

const edgeTypes = {
  defaultFlowEdge: GenericFlowEdge,
};

const CustomFlowChart: React.FC = () => {
  return (
    <ReactFlowProvider>
      <ReactFlow
        nodeTypes={nodeTypes}
        edgeTypes={edgeTypes}
        // ... other props
      />
    </ReactFlowProvider>
  );
};
```

### 6. Working with Different Node States

```typescript
// Different status states supported by nodes
const nodeStatuses = [
  'completed',    // Green indicator
  'in-progress',  // Yellow/orange indicator  
  'error',        // Red indicator
  'started',      // Blue indicator
  'idle'          // Gray indicator
];

// Example of updating node status
const updateNodeStatus = (nodeId: string, status: string) => {
  setNodes(currentNodes => 
    currentNodes.map(node => 
      node.id === nodeId 
        ? { ...node, data: { ...node.data, status } }
        : node
    )
  );
};
```

This comprehensive guide shows how the FlowChart directory components work together to create rich, interactive workflow visualizations with real-time updates and animations. The modular design allows for easy customization and extension of both node types and edge behaviors.

================================================================================

## Section 7: frontend/src/components/TaskMonitor/FlowChart/customEdges/customEdges_llm.txt

**Source file:** `frontend/src/components/TaskMonitor/FlowChart/customEdges/customEdges_llm.txt`

# DEVELOPER GUIDE: customEdges

## Quick Summary
The `customEdges` directory contains custom edge components for React Flow charts in the TaskMonitor. It provides specialized edge rendering with animation support for visualizing data flow between nodes in flowcharts.

## Files Overview
- `GenericFlowEdge.tsx` - A customizable React Flow edge component with animation support for request/response visualization

## Developer API Reference

### GenericFlowEdge.tsx
**Purpose:** Renders custom edges in React Flow charts with animation capabilities for visualizing data flow
**Import:** `import GenericFlowEdge, { AnimatedEdgeData } from 'frontend/src/components/TaskMonitor/FlowChart/customEdges/GenericFlowEdge'`

**Interfaces:**
- `AnimatedEdgeData` - Configuration interface for edge animation and visualization
  - `visualizerStepId: string` - Unique identifier for the visualizer step
  - `isAnimated?: boolean` - Whether the edge should display as animated/active
  - `animationType?: 'request' | 'response' | 'static'` - Type of animation to display

**Components:**
- `GenericFlowEdge(props: EdgeProps) -> JSX.Element` - React component that renders a customizable Bezier curve edge
  - Accepts standard React Flow EdgeProps
  - Applies custom styling based on animation state
  - Renders blue stroke for animated edges, gray for static edges

**Usage Examples:**
```tsx
// Import the edge component and interface
import GenericFlowEdge, { AnimatedEdgeData } from 'frontend/src/components/TaskMonitor/FlowChart/customEdges/GenericFlowEdge';
import { Edge } from '@xyflow/react';

// Define edge data with animation
const edgeData: AnimatedEdgeData = {
  visualizerStepId: 'step-123',
  isAnimated: true,
  animationType: 'request'
};

// Create an edge with custom data
const customEdge: Edge = {
  id: 'edge-1',
  source: 'node-1',
  target: 'node-2',
  type: 'generic', // Register this edge type in React Flow
  data: edgeData
};

// Register the edge type in React Flow
const edgeTypes = {
  generic: GenericFlowEdge
};

// Use in React Flow component
<ReactFlow
  edges={[customEdge]}
  edgeTypes={edgeTypes}
  // ... other props
/>
```

================================================================================

## Section 8: frontend/src/components/TaskMonitor/FlowChart/customNodes/customNodes_llm.txt

**Source file:** `frontend/src/components/TaskMonitor/FlowChart/customNodes/customNodes_llm.txt`

# DEVELOPER GUIDE: customNodes

## Quick Summary
This directory contains React components for custom node types used in a flow chart visualization system. These nodes represent different entities in an AI agent workflow including users, orchestrator agents, generic agents, tools, and LLM interactions. All nodes are built using the @xyflow/react library and share a common data structure.

## Files Overview
- **GenericAgentNode.tsx** - Base agent node component with standard connection handles
- **GenericToolNode.tsx** - Tool node component with status indicators and left-side connections
- **LLMNode.tsx** - Large Language Model node component with teal styling and status tracking
- **OrchestratorAgentNode.tsx** - Special agent node with enhanced styling for orchestrator roles
- **UserNode.tsx** - User interaction node with position-aware handle placement

## Developer API Reference

### GenericAgentNode.tsx
**Purpose:** Base component for agent nodes in the flow chart with standard connection points
**Import:** `import GenericAgentNode, { GenericNodeData } from './customNodes/GenericAgentNode'`

**Interfaces:**
- `GenericNodeData extends Record<string, unknown>` - Base data structure for all nodes
  - `label: string` - Display text for the node
  - `description?: string` - Optional description text
  - `icon?: string` - Optional icon identifier
  - `subflow?: boolean` - Whether this node represents a subflow
  - `isInitial?: boolean` - Whether this is the first user node
  - `isFinal?: boolean` - Whether this is the last user node

**Components:**
- `GenericAgentNode: React.FC<NodeProps<Node<GenericNodeData>>>` - Main agent node component with blue styling and multiple connection handles

**Usage Examples:**
```typescript
import GenericAgentNode, { GenericNodeData } from './customNodes/GenericAgentNode';
import { Node } from '@xyflow/react';

const nodeData: GenericNodeData = {
  label: "Processing Agent",
  description: "Handles data processing tasks",
  subflow: false
};

const agentNode: Node<GenericNodeData> = {
  id: 'agent-1',
  type: 'genericAgent',
  position: { x: 100, y: 100 },
  data: nodeData
};
```

### GenericToolNode.tsx
**Purpose:** Component for tool nodes that connect to agents and show execution status
**Import:** `import GenericToolNode, { GenericToolNodeType } from './customNodes/GenericToolNode'`

**Types:**
- `GenericToolNodeType = Node<GenericNodeData>` - Type alias for tool nodes

**Components:**
- `GenericToolNode: React.FC<NodeProps<GenericToolNodeType>>` - Tool node with cyan styling and status indicator
  - Supports status values: 'completed', 'in-progress', 'error', 'started', 'idle'
  - Has left-side input/output handles for agent connections

**Usage Examples:**
```typescript
import GenericToolNode, { GenericToolNodeType } from './customNodes/GenericToolNode';

const toolNode: GenericToolNodeType = {
  id: 'tool-1',
  type: 'genericTool',
  position: { x: 300, y: 100 },
  data: {
    label: "File Reader",
    status: 'in-progress'
  }
};
```

### LLMNode.tsx
**Purpose:** Component for Large Language Model nodes with specialized styling and status tracking
**Import:** `import LLMNode, { LLMNodeType } from './customNodes/LLMNode'`

**Types:**
- `LLMNodeType = Node<GenericNodeData>` - Type alias for LLM nodes

**Components:**
- `LLMNode: React.FC<NodeProps<LLMNodeType>>` - LLM node with teal styling and status indicator
  - Supports same status values as GenericToolNode
  - Has left-side input/output handles for agent connections

**Usage Examples:**
```typescript
import LLMNode, { LLMNodeType } from './customNodes/LLMNode';

const llmNode: LLMNodeType = {
  id: 'llm-1',
  type: 'llm',
  position: { x: 300, y: 200 },
  data: {
    label: "GPT-4",
    status: 'started'
  }
};
```

### OrchestratorAgentNode.tsx
**Purpose:** Enhanced agent node component for orchestrator roles with premium styling
**Import:** `import OrchestratorAgentNode, { OrchestratorAgentNodeType } from './customNodes/OrchestratorAgentNode'`

**Types:**
- `OrchestratorAgentNodeType = Node<GenericNodeData>` - Type alias for orchestrator nodes

**Components:**
- `OrchestratorAgentNode: React.FC<NodeProps<OrchestratorAgentNodeType>>` - Orchestrator node with gradient styling and indigo theme
  - Has multiple connection handles (top, bottom, left, right)
  - Enhanced visual styling with gradient background and shadow effects

**Usage Examples:**
```typescript
import OrchestratorAgentNode, { OrchestratorAgentNodeType } from './customNodes/OrchestratorAgentNode';

const orchestratorNode: OrchestratorAgentNodeType = {
  id: 'orch-1',
  type: 'orchestrator',
  position: { x: 100, y: 200 },
  data: {
    label: "Main Orchestrator",
    description: "Coordinates all agent activities"
  }
};
```

### UserNode.tsx
**Purpose:** Component for user interaction nodes with position-aware handle placement
**Import:** `import UserNode, { UserNodeType, UserNodeData } from './customNodes/UserNode'`

**Interfaces:**
- `UserNodeData extends GenericNodeData` - Extended data structure for user nodes
  - `isTopNode?: boolean` - True if this is the top node in the flow
  - `isBottomNode?: boolean` - True if this is the bottom node in the flow

**Types:**
- `UserNodeType = Node<UserNodeData>` - Type alias for user nodes

**Components:**
- `UserNode: React.FC<NodeProps<UserNodeType>>` - User node with purple styling and dynamic handle placement
  - Handle placement depends on position flags (top, bottom, or middle)
  - Supports status indicators with user-specific color scheme

**Usage Examples:**
```typescript
import UserNode, { UserNodeType, UserNodeData } from './customNodes/UserNode';

const topUserNode: UserNodeType = {
  id: 'user-1',
  type: 'user',
  position: { x: 100, y: 0 },
  data: {
    label: "User",
    isTopNode: true,
    status: 'completed'
  }
};

const bottomUserNode: UserNodeType = {
  id: 'user-2',
  type: 'user',
  position: { x: 100, y: 400 },
  data: {
    label: "User Response",
    isBottomNode: true,
    status: 'idle'
  }
};
```

================================================================================

## Section 9: frontend/src/components/TaskMonitor/TaskMonitor_llm.txt

**Source file:** `frontend/src/components/TaskMonitor/TaskMonitor_llm.txt`

# DEVELOPER GUIDE: TaskMonitor

## Quick Summary
The TaskMonitor directory provides a comprehensive React-based system for monitoring and visualizing AI agent task execution in real-time. It combines event tracking, task visualization, performance analysis, and interactive flowcharts to create a complete monitoring dashboard. The architecture includes direct UI components for displaying events and tasks, plus a FlowChart subdirectory for advanced workflow visualization with React Flow.

## Files and Subdirectories Overview
- **Direct files:**
  - `EventCard.tsx` - Individual event display component with expandable payload details
  - `EventDetailsPanel.tsx` - Panel for displaying all events related to a selected task
  - `LinearStepViewPanel.tsx` - Linear timeline view of processed workflow steps
  - `PerformanceModal.tsx` - Modal dialog for detailed performance metrics and charts
  - `TaskListPanel.tsx` - Hierarchical task list with expandable sub-tasks
  - `TaskTimingSummaryPanel.tsx` - Collapsible performance summary with timing aggregations
  - `VisualizerStepCard.tsx` - Individual step card component for workflow visualization
- **Subdirectories:**
  - `FlowChart/` - React Flow-based interactive flowchart visualization system with custom nodes and edges

## Developer API Reference

### Direct Files

#### EventCard.tsx
**Purpose:** Displays individual A2A events with expandable JSON payload and message content rendering
**Import:** `import EventCard from 'frontend/src/components/TaskMonitor/EventCard'`

**Interfaces:**
- `EventCardProps` - Component props interface
  - `event: A2AEventSSEPayload` - The event data to display

**Components:**
- `EventCard: React.FC<EventCardProps>` - Main event card component with click-to-expand functionality

#### EventDetailsPanel.tsx
**Purpose:** Container panel that displays all events for a selected task using EventCard components
**Import:** `import EventDetailsPanel from 'frontend/src/components/TaskMonitor/EventDetailsPanel'`

**Interfaces:**
- `EventDetailsPanelProps` - Component props interface
  - `selectedTask: MonitoredTask | null` - The currently selected task

**Components:**
- `EventDetailsPanel: React.FC<EventDetailsPanelProps>` - Panel component that renders event list

#### LinearStepViewPanel.tsx
**Purpose:** Displays workflow steps in a linear timeline format with step highlighting
**Import:** `import LinearStepViewPanel from 'frontend/src/components/TaskMonitor/LinearStepViewPanel'`

**Interfaces:**
- `LinearStepViewPanelProps` - Component props interface
  - `steps: VisualizerStep[]` - Array of workflow steps to display

**Components:**
- `LinearStepViewPanel: React.FC<LinearStepViewPanelProps>` - Main panel component with TaskMonitorContext integration

#### PerformanceModal.tsx
**Purpose:** Modal dialog displaying comprehensive performance metrics with interactive charts and agent breakdowns
**Import:** `import PerformanceModal from 'frontend/src/components/TaskMonitor/PerformanceModal'`

**Interfaces:**
- `PerformanceModalProps` - Component props interface
  - `isOpen: boolean` - Modal visibility state
  - `onClose: () => void` - Callback to close modal
  - `task: VisualizedTask | null` - Task to analyze

**Components:**
- `PerformanceModal: React.FC<PerformanceModalProps>` - Modal component with charts and expandable agent details

#### TaskListPanel.tsx
**Purpose:** Hierarchical task list with expandable sub-tasks and selection management
**Import:** `import TaskListPanel, { HierarchicalTaskItem } from 'frontend/src/components/TaskMonitor/TaskListPanel'`

**Interfaces:**
- `HierarchicalTaskItem` - Extended task interface with hierarchy support
  - `children: HierarchicalTaskItem[]` - Child tasks for hierarchy
  - `nestingLevel: number` - Indentation level for display
- `TaskListPanelProps` - Component props interface
  - `hierarchicalTasks: HierarchicalTaskItem[]` - Hierarchical task structure
  - `selectedTaskId: string | null` - Currently selected task ID
  - `onSelectTask: (taskId: string) => void` - Task selection callback
  - `isLoading: boolean` - Loading state
  - `expandedTaskIds: Set<string>` - Set of expanded task IDs
  - `onToggleExpand: (taskId: string) => void` - Expand/collapse callback

**Components:**
- `TaskListPanel: React.FC<TaskListPanelProps>` - Main task list component with recursive rendering

#### TaskTimingSummaryPanel.tsx
**Purpose:** Collapsible panel showing aggregated performance timing data for LLM and tool calls
**Import:** `import TaskTimingSummaryPanel from 'frontend/src/components/TaskMonitor/TaskTimingSummaryPanel'`

**Interfaces:**
- `TaskTimingSummaryPanelProps` - Component props interface
  - `steps: VisualizerStep[]` - Array of workflow steps to analyze

**Components:**
- `TaskTimingSummaryPanel: React.FC<TaskTimingSummaryPanelProps>` - Expandable summary panel

#### VisualizerStepCard.tsx
**Purpose:** Individual step card component for displaying workflow steps with rich content rendering
**Import:** `import VisualizerStepCard from 'frontend/src/components/TaskMonitor/VisualizerStepCard'`

**Interfaces:**
- `VisualizerStepCardProps` - Component props interface
  - `step: VisualizerStep` - The workflow step to display
  - `isHighlighted?: boolean` - Whether the step is highlighted
  - `onClick?: () => void` - Click handler for step selection

**Components:**
- `VisualizerStepCard: React.FC<VisualizerStepCardProps>` - Step card with type-specific rendering and delegation info

### Subdirectory APIs

#### FlowChart/
**Purpose:** Provides React Flow-based interactive flowchart visualization with custom nodes and edges for AI workflows
**Key Exports:** FlowChartPanel, GenericAgentNode, UserNode, LLMNode, GenericFlowEdge
**Import Examples:**
```typescript
import FlowChartPanel from 'frontend/src/components/TaskMonitor/FlowChart/FlowChartPanel'
import GenericAgentNode from 'frontend/src/components/TaskMonitor/FlowChart/customNodes/GenericAgentNode'
import GenericFlowEdge from 'frontend/src/components/TaskMonitor/FlowChart/customEdges/GenericFlowEdge'
```

## Complete Usage Guide

### 1. Basic Task Monitoring Setup

```typescript
import React, { useState } from 'react';
import TaskListPanel, { HierarchicalTaskItem } from 'frontend/src/components/TaskMonitor/TaskListPanel';
import EventDetailsPanel from 'frontend/src/components/TaskMonitor/EventDetailsPanel';
import { MonitoredTask } from './TaskMonitor.types';

const TaskMonitorDashboard: React.FC = () => {
  const [hierarchicalTasks, setHierarchicalTasks] = useState<HierarchicalTaskItem[]>([]);
  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);
  const [expandedTaskIds, setExpandedTaskIds] = useState<Set<string>>(new Set());
  const [isLoading, setIsLoading] = useState(false);

  const selectedTask = hierarchicalTasks
    .flatMap(task => [task, ...task.children])
    .find(task => task.taskId === selectedTaskId) || null;

  const handleSelectTask = (taskId: string) => {
    setSelectedTaskId(taskId);
  };

  const handleToggleExpand = (taskId: string) => {
    setExpandedTaskIds(prev => {
      const newSet = new Set(prev);
      if (newSet.has(taskId)) {
        newSet.delete(taskId);
      } else {
        newSet.add(taskId);
      }
      return newSet;
    });
  };

  return (
    <div className="flex h-screen">
      <div className="w-1/3 border-r">
        <TaskListPanel
          hierarchicalTasks={hierarchicalTasks}
          selectedTaskId={selectedTaskId}
          onSelectTask={handleSelectTask}
          isLoading={isLoading}
          expandedTaskIds={expandedTaskIds}
          onToggleExpand={handleToggleExpand}
        />
      </div>
      <div className="flex-1 p-4">
        <EventDetailsPanel selectedTask={selectedTask} />
      </div>
    </div>
  );
};
```

### 2. Workflow Step Visualization

```typescript
import React, { useState } from 'react';
import LinearStepViewPanel from 'frontend/src/components/TaskMonitor/LinearStepViewPanel';
import FlowChartPanel from 'frontend/src/components/TaskMonitor/FlowChart/FlowChartPanel';
import TaskTimingSummaryPanel from 'frontend/src/components/TaskMonitor/TaskTimingSummaryPanel';
import { VisualizerStep } from './TaskVisualizer.types';

const WorkflowVisualization: React.FC = () => {
  const [processedSteps, setProcessedSteps] = useState<VisualizerStep[]>([]);
  const [viewMode, setViewMode] = useState<'linear' | 'flowchart'>('linear');
  const [isFullScreen, setIsFullScreen] = useState(false);

  return (
    <div className="h-screen flex flex-col">
      {/* View Mode Toggle */}
      <div className="p-4 border-b">
        <button
          onClick={() => setViewMode('linear')}
          className={`mr-2 px-4 py-2 rounded ${viewMode === 'linear' ? 'bg-blue-500 text-white' : 'bg-gray-200'}`}
        >
          Linear View
        </button>
        <button
          onClick={() => setViewMode('flowchart')}
          className={`px-4 py-2 rounded ${viewMode === 'flowchart' ? 'bg-blue-500 text-white' : 'bg-gray-200'}`}
        >
          Flow Chart
        </button>
      </div>

      {/* Performance Summary */}
      <div className="p-4 border-b">
        <TaskTimingSummaryPanel steps={processedSteps} />
      </div>

      {/* Main Visualization Area */}
      <div className="flex-1 p-4">
        {viewMode === 'linear' ? (
          <LinearStepViewPanel steps={processedSteps} />
        ) : (
          <FlowChartPanel
            processedSteps={processedSteps}
            isFullScreen={isFullScreen}
            onToggleFullScreen={() => setIsFullScreen(!isFullScreen)}
          />
        )}
      </div>
    </div>
  );
};
```

### 3. Performance Analysis Integration

```typescript
import React, { useState } from 'react';
import PerformanceModal from 'frontend/src/components/TaskMonitor/PerformanceModal';
import { VisualizedTask } from './TaskVisualizer.types';

const TaskPerformanceAnalysis: React.FC = () => {
  const [selectedTask, setSelectedTask] = useState<VisualizedTask | null>(null);
  const [isPerformanceModalOpen, setIsPerformanceModalOpen] = useState(false);

  const handleShowPerformance = (task: VisualizedTask) => {
    setSelectedTask(task);
    setIsPerformanceModalOpen(true);
  };

  const handleClosePerformance = () => {
    setIsPerformanceModalOpen(false);
    setSelectedTask(null);
  };

  return (
    <div>
      {/* Task list with performance buttons */}
      <div className="space-y-2">
        {/* Your task list here */}
        <button
          onClick={() => handleShowPerformance(selectedTask)}
          className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
          disabled={!selectedTask}
        >
          Show Performance Insights
        </button>
      </div>

      {/* Performance Modal */}
      <PerformanceModal
        isOpen={isPerformanceModalOpen}
        onClose={handleClosePerformance}
        task={selectedTask}
      />
    </div>
  );
};
```

### 4. Event Card Usage with Custom Rendering

```typescript
import React from 'react';
import EventCard from 'frontend/src/components/TaskMonitor/EventCard';
import { A2AEventSSEPayload } from './TaskMonitor.types';

const EventDisplay: React.FC = () => {
  const sampleEvent: A2AEventSSEPayload = {
    timestamp: new Date().toISOString(),
    direction: 'request',
    source_entity: 'UserAgent',
    target_entity: 'ProcessingAgent',
    solace_topic: 'a2a/agents/processing/tasks',
    message_id: 'msg-123',
    task_id: 'task-456',
    payload_summary: {
      method: 'tasks/process_document',
      params_preview: 'document.pdf, extract_text=true'
    },
    full_payload: {
      method: 'tasks/process_document',
      params: {
        message: {
          parts: [
            {
              type: 'text',
              text: 'Please process this document and extract the key information.'
            }
          ]
        }
      }
    }
  };

  return (
    <div className="p-4">
      <h2 className="text-lg font-semibold mb-4">Event Details</h2>
      <EventCard event={sampleEvent} />
    </div>
  );
};
```

### 5. Step Card with Delegation Information

```typescript
import React from 'react';
import VisualizerStepCard from 'frontend/src/components/TaskMonitor/VisualizerStepCard';
import { VisualizerStep } from './TaskVisualizer.types';

const StepVisualization: React.FC = () => {
  const [highlightedStepId, setHighlightedStepId] = useState<string | null>(null);

  const sampleStep: VisualizerStep = {
    id: 'step-123',
    timestamp: new Date().toISOString(),
    type: 'AGENT_TOOL_INVOCATION_START',
    title: 'Delegating to File Processing Agent',
    source: 'OrchestratorAgent',
    nestingLevel: 0,
    durationMs: 1500,
    delegationInfo: [
      {
        functionCallId: 'call-456',
        peerAgentName: 'FileProcessingAgent',
        subTaskId: 'subtask-789'
      }
    ],
    data: {
      toolInvocationStart: {
        toolName: 'process_file',
        toolArguments: { file_path: '/documents/report.pdf' },
        isPeerInvocation: true
      }
    }
  };

  const handleStepClick = (stepId: string) => {
    setHighlightedStepId(highlightedStepId === stepId ? null : stepId);
  };

  return (
    <div className="p-4">
      <VisualizerStepCard
        step={sampleStep}
        isHighlighted={highlightedStepId === sampleStep.id}
        onClick={() => handleStepClick(sampleStep.id)}
      />
    </div>
  );
};
```

### 6. Complete TaskMonitor Integration

```typescript
import React, { useState, useEffect } from 'react';
import { useTaskMonitor } from 'frontend/src

================================================================================

## Section 10: frontend/src/components/components_llm.txt

**Source file:** `frontend/src/components/components_llm.txt`

## Quick Summary
The components directory contains the main React UI components for the A2A Chat application. It includes both direct component files for core functionality (chat interface, agent management, file handling, etc.) and specialized subdirectories for complex features like agent communication visualization, chat messaging, file preview, and task monitoring. The architecture follows a modular design with reusable components, custom hooks integration, and comprehensive TypeScript typing.

## Files and Subdirectories Overview

### Direct Files:
- **AgentDisplayCard.tsx** - 3D flip card component for displaying agent information with front/back views
- **AgentSelector.tsx** - Dropdown component for selecting active agents with auto-selection logic
- **AgentsPage.tsx** - Main page component for browsing and managing discovered agents
- **ArtifactCard.tsx** - Card component for displaying file artifacts with preview/download actions
- **ArtifactList.tsx** - List container for artifact cards with selection and edit modes
- **ArtifactPanel.tsx** - Side panel for managing session artifacts with drag-drop upload
- **ArtifactToggleButton.tsx** - Button to show/hide the artifact panel
- **ChatInput.tsx** - Chat input component with file attachment and auto-resize functionality
- **ChatPage.tsx** - Main chat interface page with drag-drop, preview panels, and modals
- **ConfigProvider.tsx** - React context provider for application configuration and authentication
- **CustomMarkdown.tsx** - Markdown renderer component with sanitization and link handling
- **DarkModeToggle.tsx** - Toggle button component for switching between light/dark themes
- **FileCapsule.tsx** - Small file preview component with remove functionality for selected files
- **FileDisplay.tsx** - Component for displaying file attachments in messages with type-specific rendering
- **FilePreview.tsx** - Generic file preview component with icon and remove button
- **FileRow.tsx** - Simple file row component with download functionality
- **FlowChartModal.tsx** - Modal wrapper for displaying flow charts and network diagrams
- **Modal.tsx** - Generic modal dialog component with confirm/cancel actions
- **Notifications.tsx** - Toast notification system with animations and auto-dismiss
- **PageContainer.tsx** - Main application container with header, navigation, and page routing
- **TaskMonitorPage.tsx** - Task monitoring dashboard with real-time event streaming
- **ToolCallCapsule.tsx** - Component for displaying tool execution results in expandable format

### Subdirectories:
- **AgentCommunicationFlow/** - Interactive network visualization for agent communication patterns
- **ChatBox/** - Complete chat interface system with messages, bubbles, and file handling
- **PreviewFileContent/** - Comprehensive file preview system with multiple renderer types
- **TaskMonitor/** - Real-time task monitoring and visualization components with flowcharts

## Developer API Reference

### Direct Files

#### AgentDisplayCard.tsx
**Purpose:** 3D flip card component for displaying comprehensive agent information
**Import:** `import AgentDisplayCard from './components/AgentDisplayCard'`

**Interfaces:**
- `AgentDisplayCardProps` - Component props interface
  - `agent: AgentCard` - Agent data to display
  - `isExpanded: boolean` - Whether card is flipped to back view
  - `onToggleExpand: () => void` - Callback to toggle card state

**Components:**
- `AgentDisplayCard: React.FC<AgentDisplayCardProps>` - 3D flip card with front summary and detailed back view

#### AgentSelector.tsx
**Purpose:** Dropdown component for selecting active agents with auto-selection logic
**Import:** `import AgentSelector from './components/AgentSelector'`

**Interfaces:**
- `AgentSelectorProps` - Component props interface
  - `selectedAgentName: string` - Currently selected agent name
  - `onSelectAgent: (agentName: string) => void` - Agent selection callback
  - `disabled?: boolean` - Optional disabled state

**Components:**
- `AgentSelector: React.FC<AgentSelectorProps>` - Dropdown with agent list, auto-selection, and keyboard navigation

#### ChatInput.tsx
**Purpose:** Chat input component with file attachments and auto-resize functionality
**Import:** `import ChatInput from './components/ChatInput'`

**Interfaces:**
- `ChatInputProps` - Component props interface
  - `userInput: string` - Current input text
  - `setUserInput: React.Dispatch<React.SetStateAction<string>>` - Input setter
  - `handleSubmit: (e: FormEvent, files?: File[] | null) => void` - Submit handler
  - `isResponding: boolean` - Whether AI is currently responding
  - `selectedFiles: File[]` - Currently selected files
  - `setSelectedFiles: React.Dispatch<React.SetStateAction<File[]>>` - File setter

**Components:**
- `ChatInput: React.FC<ChatInputProps>` - Multi-line input with file attachments, paste support, and auto-resize

#### ConfigProvider.tsx
**Purpose:** React context provider for application configuration and authentication
**Import:** `import ConfigProvider, { useConfig } from './components/ConfigProvider'`

**Interfaces:**
- `AppConfig` - Configuration object structure
  - `configServerUrl: string` - Backend server URL
  - `configUseAuthorization: boolean` - Whether auth is enabled
  - `configWelcomeMessage: string` - Welcome message text
  - `configBotName: string` - Application name

**Components:**
- `ConfigProvider: React.FC<{ children: ReactNode }>` - Context provider component
- `useConfig: () => AppConfig` - Hook to access configuration

**Functions:**
- `getCsrfToken: (retries?: number, delayMs?: number) => Promise<string | null>` - CSRF token retrieval

#### CustomMarkdown.tsx
**Purpose:** Markdown renderer with sanitization and custom link handling
**Import:** `import CustomMarkdown from './components/CustomMarkdown'`

**Interfaces:**
- `CustomMarkdownProps` - Component props interface
  - `children: string` - Markdown content to render
  - `className?: string` - Optional CSS classes

**Components:**
- `CustomMarkdown: React.FC<CustomMarkdownProps>` - Sanitized markdown renderer with external link handling

#### PageContainer.tsx
**Purpose:** Main application container with navigation and page routing
**Import:** `import PageContainer from './components/PageContainer'`

**Components:**
- `PageContainer: React.FC` - Main app container with header, navigation, and page switching

### Subdirectory APIs

#### AgentCommunicationFlow/
**Purpose:** Interactive network visualization for agent communication patterns using React Flow
**Key Exports:** AgentCommunicationFlowChart, LayoutSelector, AgentCommNode, AgentCommEdge
**Import Examples:**
```typescript
import AgentCommunicationFlowChart from './components/AgentCommunicationFlow/AgentCommunicationFlowChart'
import LayoutSelector from './components/AgentCommunicationFlow/LayoutSelector'
import { LayoutType } from './components/AgentCommunicationFlow/layoutEngine'
```

#### ChatBox/
**Purpose:** Complete chat interface system with messages, file handling, and loading states
**Key Exports:** ChatBox, ChatMessages, MessageBubble, LoadingIndicator
**Import Examples:**
```typescript
import ChatBox from './components/ChatBox/ChatBox'
import { Message, FileAttachment } from './components/ChatBox/ChatBox.types'
```

#### PreviewFileContent/
**Purpose:** Comprehensive file preview system supporting multiple file types and rendering modes
**Key Exports:** PreviewPanel, PreviewContent, ContentRenderer, various preview components
**Import Examples:**
```typescript
import PreviewPanel from './components/PreviewFileContent/PreviewPanel'
import PreviewContent from './components/PreviewFileContent/PreviewContent'
import { isHtmlFile, isMermaidFile } from './components/PreviewFileContent/PreviewHelpers'
```

#### TaskMonitor/
**Purpose:** Real-time task monitoring and visualization with flowcharts and performance analysis
**Key Exports:** TaskListPanel, EventDetailsPanel, LinearStepViewPanel, PerformanceModal, FlowChartPanel
**Import Examples:**
```typescript
import TaskListPanel from './components/TaskMonitor/TaskListPanel'
import EventDetailsPanel from './components/TaskMonitor/EventDetailsPanel'
import FlowChartPanel from './components/TaskMonitor/FlowChart/FlowChartPanel'
```

## Complete Usage Guide

### 1. Basic Application Setup with Configuration

```typescript
import React from 'react';
import ConfigProvider, { useConfig } from './components/ConfigProvider';
import PageContainer from './components/PageContainer';

// Main App Component
function App() {
  return (
    <ConfigProvider>
      <PageContainer />
    </ConfigProvider>
  );
}

// Using configuration in components
function MyComponent() {
  const { configServerUrl, configBotName, configUseAuthorization } = useConfig();
  
  return (
    <div>
      <h1>{configBotName}</h1>
      <p>Server: {configServerUrl}</p>
      <p>Auth: {configUseAuthorization ? 'Enabled' : 'Disabled'}</p>
    </div>
  );
}
```

### 2. Chat Interface with File Handling

```typescript
import React, { useState } from 'react';
import ChatBox from './components/ChatBox/ChatBox';
import { Message, FileAttachment } from './components/ChatBox/ChatBox.types';
import PreviewPanel from './components/PreviewFileContent/PreviewPanel';

function ChatInterface() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [userInput, setUserInput] = useState("");
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [isResponding, setIsResponding] = useState(false);
  const [previewFile, setPreviewFile] = useState<FileAttachment | null>(null);

  const handleSubmit = (e: React.FormEvent, files?: File[] | null) => {
    e.preventDefault();
    if (!userInput.trim() && (!files || files.length === 0)) return;

    // Add user message
    const userMessage: Message = {
      text: userInput,
      isUser: true,
      uploadedFiles: files || undefined,
      metadata: { sessionId: 'session-123' }
    };
    
    setMessages(prev => [...prev, userMessage]);
    setUserInput("");
    setSelectedFiles([]);
    
    // Simulate AI response
    setIsResponding(true);
    setTimeout(() => {
      const aiMessage: Message = {
        text: "I've processed your request.",
        isUser: false,
        isComplete: true,
        files: [{
          name: "response.txt",
          content: "UmVzcG9uc2UgY29udGVudA==", // base64 encoded
          mime_type: "text/plain"
        }]
      };
      setMessages(prev => [...prev, aiMessage]);
      setIsResponding(false);
    }, 2000);
  };

  const handlePreviewFile = (file: FileAttachment) => {
    setPreviewFile(file);
  };

  return (
    <div className="h-screen flex flex-col">
      <ChatBox
        messages={messages}
        userInput={userInput}
        setUserInput={setUserInput}
        handleSubmit={handleSubmit}
        isResponding={isResponding}
        selectedFiles={selectedFiles}
        setSelectedFiles={setSelectedFiles}
        selectedAgentName="MyAgent"
        handlePreviewFile={handlePreviewFile}
        handleRunFile={handlePreviewFile}
      />
      
      {previewFile && (
        <PreviewPanel
          file={previewFile}
          onClose={() => setPreviewFile(null)}
          autoRun={false}
          currentVersionNumber={1}
          availableVersions={[1]}
          onNavigateVersion={() => {}}
        />
      )}
    </div>
  );
}
```

### 3. Agent Management and Selection

```typescript
import React, { useState } from 'react';
import AgentsPage from './components/AgentsPage';
import AgentSelector from './components/AgentSelector';
import AgentDisplayCard from './components/AgentDisplayCard';
import { AgentCard } from './common_a2a/types';

function AgentManagement() {
  const [selectedAgentName, setSelectedAgentName] = useState("");
  const [expandedAgent, setExpandedAgent] = useState<string | null>(null);
  
  const agents: AgentCard[] = [
    {
      name: "OrchestratorAgent",
      display_name: "Orchestrator",
      description: "Main coordination agent",
      version: "1.0.0",
      url: "http://localhost:8000/agents/orchestrator",
      capabilities: {
        file_processing: true,
        task_delegation: true
      }
    }
  ];

  return (
    <div className="p-4">
      {/* Agent Selection */}
      <div className="mb-6">
        <AgentSelector
          selectedAgentName={selectedAgentName}
          onSelectAgent={setSelectedAgentName}
          disabled={false}
        />
      </div>

      {/* Agent Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {agents.map(agent => (
          <AgentDisplayCard
            key={agent.name}
            agent={agent}
            isExpanded={expandedAgent === agent.name}
            onToggleExpand={() => setExpandedAgent(
              expandedAgent === agent.name ? null : agent.name
            )}
          />
        ))}
      </div>

      {/* Full Agents Page */}
      <div className="mt-8">
        <AgentsPage />
      </div>
    </div>
  );
}
```

### 4. Artifact Management with Preview

```typescript
import React, { useState } from 'react';
import ArtifactPanel from './components/ArtifactPanel';
import ArtifactToggleButton from './components/ArtifactToggleButton';
import { ArtifactInfo } from './common_a2a/types';

function ArtifactManagement() {
  const [isArtifactPanelOpen, setIsArtifactPanelOpen] = useState(false);
  const [artifacts, setArtifacts] = useState<ArtifactInfo[]>([]);
  const [isEditMode, setIsEditMode] = useState(false);
  const [selectedArtifacts, setSelectedArtifacts] = useState<Set<string>>(new Set());

  const handlePreviewFile = async (artifact: ArtifactInfo, autoRun = false) => {
    console.log('Previewing:', artifact.filename, 'autoRun:', autoRun);
    // Implement preview logic
  };

  const handleDownloadFile = (filename: string) => {
    console.log('Downloading:', filename);
    // Implement download logic
  };

  const handleCopyFile = async (artifact: ArtifactInfo) => {
    console.log('Copying:', artifact.filename);
    // Implement copy logic
  };

  const handleUploadFile = async (file: File) => {
    console.log('Uploading:', file.name);
    // Implement upload logic
  };

  const handleDeleteArtifact = (artifact: ArtifactInfo) => {
    console.log('Deleting:', artifact.filename);
    // Implement delete logic
  };

  const handleDeleteSelected = () => {
    console.log('Deleting selected:', Array.from(selectedArtifacts));
    // Implement batch delete logic
  };

  return (
    <div className="relative h-screen">
      <ArtifactToggleButton
        isOpen={isArtifactPanelOpen}
        onClick={() => setIsArtifactPanelOpen(!isArtifactPanelOpen)}
      />
      
      <ArtifactPanel
        isOpen={isArtifactPanelOpen}
        artifacts={artifacts}
        isLoading={false}
        onClose={() => setIsArtifactPanelOpen(false)}
        onPreviewFile={

================================================================================

## Section 11: frontend/src/contexts/contexts_llm.txt

**Source file:** `frontend/src/contexts/contexts_llm.txt`

# DEVELOPER GUIDE: contexts

## Quick Summary
The contexts directory provides React Context providers for managing global application state including authentication, chat functionality, and task monitoring. These contexts handle user authentication, chat sessions with AI agents, artifact management, and real-time task monitoring via Server-Sent Events (SSE).

## Files Overview
- **AuthProvider.tsx** - Authentication context with login state and authorization controls
- **ChatContext.tsx** - Type definitions and interfaces for chat state and actions
- **ChatProvider.tsx** - Main chat functionality provider with SSE handling and artifact management
- **TaskMonitorContext.tsx** - Task monitoring context with real-time event streaming

## Developer API Reference

### AuthProvider.tsx
**Purpose:** Manages user authentication state and provides login functionality
**Import:** `import { AuthProvider, useAuth } from '../contexts/AuthProvider'`

**Components:**
- `AuthProvider({ children: ReactNode, useAuthorization: boolean })` - Authentication context provider
  - Wraps app components to provide auth state
  - Handles token validation and storage events

**Hooks:**
- `useAuth() -> AuthContextType` - Access authentication context

**Types:**
- `AuthContextType` - Authentication context interface
  - `isAuthenticated: boolean` - Current authentication status
  - `login: () => void` - Redirect to login endpoint
  - `useAuthorization: boolean` - Whether authorization is enabled

**Usage Examples:**
```tsx
import { AuthProvider, useAuth } from '../contexts/AuthProvider';

// Wrap your app
function App() {
  return (
    <AuthProvider useAuthorization={true}>
      <MyComponent />
    </AuthProvider>
  );
}

// Use in components
function MyComponent() {
  const { isAuthenticated, login, useAuthorization } = useAuth();
  
  if (!isAuthenticated && useAuthorization) {
    return <button onClick={login}>Login</button>;
  }
  
  return <div>Authenticated content</div>;
}
```

### ChatContext.tsx
**Purpose:** Type definitions and context creation for chat functionality
**Import:** `import ChatContext, { ChatContextValue, Notification } from '../contexts/ChatContext'`

**Types:**
- `Notification` - Notification object structure
  - `id: string` - Unique notification identifier
  - `message: string` - Notification text content

- `ChatState` - Chat state interface
  - `sessionId: string` - Current chat session ID
  - `messages: Message[]` - Array of chat messages
  - `userInput: string` - Current user input text
  - `isResponding: boolean` - Whether AI is currently responding
  - `currentTaskId: string | null` - Active task identifier
  - `selectedAgentName: string` - Currently selected AI agent
  - `notifications: Notification[]` - Active notifications
  - `darkMode: boolean` - Dark mode preference
  - `isCancelling: boolean` - Whether task cancellation is in progress
  - `artifacts: ArtifactInfo[]` - Available artifacts
  - `isArtifactPanelOpen: boolean` - Artifact panel visibility
  - `isLoadingArtifacts: boolean` - Artifact loading state

- `ChatActions` - Chat action interface
  - `setMessages: React.Dispatch<React.SetStateAction<Message[]>>` - Update messages
  - `setUserInput: React.Dispatch<React.SetStateAction<string>>` - Update user input
  - `handleNewSession: () => void` - Start new chat session
  - `handleSubmit: (event: FormEvent, files?: File[] | null) => Promise<void>` - Submit message
  - `handleCancel: () => void` - Cancel current task
  - `addNotification: (message: string) => void` - Add notification
  - `toggleArtifactPanel: () => void` - Toggle artifact panel
  - `fetchArtifacts: () => Promise<void>` - Refresh artifacts list

- `ChatContextValue` - Combined state and actions type

**Usage Examples:**
```tsx
import ChatContext, { ChatContextValue } from '../contexts/ChatContext';
import { useContext } from 'react';

function ChatComponent() {
  const context = useContext(ChatContext);
  if (!context) {
    throw new Error('Must be used within ChatProvider');
  }
  
  const { messages, userInput, setUserInput, handleSubmit } = context;
  // Use chat functionality
}
```

### ChatProvider.tsx
**Purpose:** Implements chat functionality with SSE handling, artifact management, and task coordination
**Import:** `import { ChatProvider } from '../contexts/ChatProvider'`

**Components:**
- `ChatProvider({ children: ReactNode })` - Chat context provider
  - Manages chat state, SSE connections, and artifact operations
  - Handles real-time communication with AI agents
  - Provides artifact upload, download, and versioning

**Usage Examples:**
```tsx
import { ChatProvider } from '../contexts/ChatProvider';
import { useContext } from 'react';
import ChatContext from '../contexts/ChatContext';

// Wrap your chat interface
function App() {
  return (
    <ChatProvider>
      <ChatInterface />
    </ChatProvider>
  );
}

// Use in components
function ChatInterface() {
  const {
    messages,
    userInput,
    setUserInput,
    handleSubmit,
    handleNewSession,
    isResponding,
    artifacts,
    toggleArtifactPanel,
    addNotification
  } = useContext(ChatContext)!;

  const onSubmit = async (e: React.FormEvent) => {
    await handleSubmit(e);
  };

  return (
    <div>
      <div>{messages.map(msg => <div key={msg.id}>{msg.text}</div>)}</div>
      <form onSubmit={onSubmit}>
        <input 
          value={userInput} 
          onChange={(e) => setUserInput(e.target.value)}
          disabled={isResponding}
        />
        <button type="submit" disabled={isResponding}>Send</button>
      </form>
      <button onClick={handleNewSession}>New Session</button>
      <button onClick={toggleArtifactPanel}>
        Artifacts ({artifacts.length})
      </button>
    </div>
  );
}
```

### TaskMonitorContext.tsx
**Purpose:** Provides real-time task monitoring with SSE event streaming
**Import:** `import { TaskMonitorProvider, useTaskMonitor } from '../contexts/TaskMonitorContext'`

**Components:**
- `TaskMonitorProvider({ children: ReactNode })` - Task monitoring context provider
  - Manages SSE connections for real-time task events
  - Tracks multiple concurrent tasks and their progress

**Hooks:**
- `useTaskMonitor() -> TaskMonitorContextValue` - Access task monitoring context

**Types:**
- `TaskMonitorState` - Task monitor state
  - `isTaskMonitorConnecting: boolean` - Connection establishment status
  - `isTaskMonitorConnected: boolean` - Current connection status
  - `taskMonitorSseError: string | null` - Connection error message
  - `monitoredTasks: Record<string, MonitoredTask>` - Active tasks by ID
  - `monitoredTaskOrder: string[]` - Task display order
  - `highlightedStepId: string | null` - Currently highlighted step

- `TaskMonitorActions` - Task monitor actions
  - `connectTaskMonitorStream: () => Promise<void>` - Establish SSE connection
  - `disconnectTaskMonitorStream: () => Promise<void>` - Close SSE connection
  - `setHighlightedStepId: (stepId: string | null) => void` - Highlight specific step

**Usage Examples:**
```tsx
import { TaskMonitorProvider, useTaskMonitor } from '../contexts/TaskMonitorContext';

// Wrap your app
function App() {
  return (
    <TaskMonitorProvider>
      <TaskMonitorComponent />
    </TaskMonitorProvider>
  );
}

// Use in components
function TaskMonitorComponent() {
  const {
    isTaskMonitorConnected,
    monitoredTasks,
    monitoredTaskOrder,
    connectTaskMonitorStream,
    disconnectTaskMonitorStream,
    taskMonitorSseError
  } = useTaskMonitor();

  useEffect(() => {
    connectTaskMonitorStream();
    return () => {
      disconnectTaskMonitorStream();
    };
  }, []);

  if (taskMonitorSseError) {
    return <div>Error: {taskMonitorSseError}</div>;
  }

  return (
    <div>
      <div>Status: {isTaskMonitorConnected ? 'Connected' : 'Disconnected'}</div>
      <div>Active Tasks: {monitoredTaskOrder.length}</div>
      {monitoredTaskOrder.map(taskId => (
        <div key={taskId}>
          Task: {monitoredTasks[taskId]?.initialRequestText}
          Events: {monitoredTasks[taskId]?.events.length}
        </div>
      ))}
    </div>
  );
}
```

================================================================================

## Section 12: frontend/src/src_llm.txt

**Source file:** `frontend/src/src_llm.txt`

# DEVELOPER GUIDE: src

## Quick Summary
The src directory is the main source code directory for a React-based A2A (Agent-to-Agent) Chat application frontend. It provides a comprehensive chat interface with AI agents, real-time task monitoring, file handling, and authentication. The architecture consists of the main App component with context providers for global state management, a rich component library for UI elements, and specialized contexts for authentication, chat functionality, and task monitoring.

## Files and Subdirectories Overview

### Direct Files:
- **App.tsx** - Main application component with context providers and authentication flow
- **auth-callback-loader.tsx** - Entry point for OAuth callback page rendering
- **auth-callback.tsx** - OAuth callback handler for token processing and redirection
- **main.tsx** - Application entry point with React root rendering

### Subdirectories:
- **components/** - Complete UI component library with chat interface, agent management, file handling, and specialized visualization components
- **contexts/** - React Context providers for authentication, chat functionality, and task monitoring with real-time SSE connections

## Developer API Reference

### Direct Files

#### App.tsx
**Purpose:** Main application component orchestrating authentication flow and context providers
**Import:** `import App from './App'`

**Components:**
- `App: React.FC` - Root application component with ConfigProvider wrapper
- `AppWithAuth: React.FC` - Authentication-aware app wrapper
- `AppContent: React.FC` - Conditional content based on auth status
- `AuthenticatedApp: React.FC` - Main app for authenticated users

**Architecture:**
```
App (ConfigProvider)
└── AppWithAuth (reads config)
    └── AuthProvider
        └── AppContent (auth check)
            └── AuthenticatedApp
                └── ChatProvider
                    └── TaskMonitorProvider
                        └── PageContainer
```

#### auth-callback.tsx
**Purpose:** OAuth callback handler for processing authentication tokens
**Import:** `import AuthCallback from './auth-callback'`

**Components:**
- `AuthCallback: React.FC` - Processes OAuth tokens from URL hash and redirects to main app

**Token Processing:**
- Extracts `access_token` and `refresh_token` from URL hash
- Stores tokens in localStorage
- Redirects to main application

#### main.tsx
**Purpose:** Application entry point with React root rendering
**Import:** Entry point file - not typically imported

**Setup:**
- Creates React root on `#root` element
- Renders App component in StrictMode
- Imports global CSS styles

### Subdirectory APIs

#### components/
**Purpose:** Complete UI component library for chat interface, agent management, file handling, and visualization
**Key Exports:** ChatBox, AgentSelector, ArtifactPanel, TaskMonitorPage, PreviewPanel, AgentCommunicationFlowChart
**Import Examples:**
```typescript
import ChatBox from './components/ChatBox/ChatBox'
import AgentSelector from './components/AgentSelector'
import ArtifactPanel from './components/ArtifactPanel'
import TaskMonitorPage from './components/TaskMonitorPage'
import PreviewPanel from './components/PreviewFileContent/PreviewPanel'
import AgentCommunicationFlowChart from './components/AgentCommunicationFlow/AgentCommunicationFlowChart'
```

#### contexts/
**Purpose:** React Context providers for global state management including authentication, chat, and task monitoring
**Key Exports:** AuthProvider, ChatProvider, TaskMonitorProvider, useAuth, useTaskMonitor
**Import Examples:**
```typescript
import { AuthProvider, useAuth } from './contexts/AuthProvider'
import { ChatProvider } from './contexts/ChatProvider'
import { TaskMonitorProvider, useTaskMonitor } from './contexts/TaskMonitorContext'
import ChatContext from './contexts/ChatContext'
```

## Complete Usage Guide

### 1. Basic Application Setup

```typescript
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import './index.css';

// Main entry point (main.tsx pattern)
createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// App component provides full context hierarchy
function MyApp() {
  return <App />; // Includes all necessary providers
}
```

### 2. Complete Chat Application with All Features

```typescript
import React, { useContext, useEffect } from 'react';
import { AuthProvider, useAuth } from './contexts/AuthProvider';
import { ChatProvider } from './contexts/ChatProvider';
import { TaskMonitorProvider, useTaskMonitor } from './contexts/TaskMonitorContext';
import ConfigProvider, { useConfig } from './components/ConfigProvider';
import ChatBox from './components/ChatBox/ChatBox';
import TaskMonitorPage from './components/TaskMonitorPage';
import AgentSelector from './components/AgentSelector';
import ArtifactPanel from './components/ArtifactPanel';
import ChatContext from './contexts/ChatContext';

// Full application with all features
function FullChatApplication() {
  return (
    <ConfigProvider>
      <AuthProvider useAuthorization={true}>
        <ChatProvider>
          <TaskMonitorProvider>
            <MainInterface />
          </TaskMonitorProvider>
        </ChatProvider>
      </AuthProvider>
    </ConfigProvider>
  );
}

function MainInterface() {
  const { isAuthenticated, login, useAuthorization } = useAuth();
  const { configBotName } = useConfig();
  
  // Show login if auth required and not authenticated
  if (useAuthorization && !isAuthenticated) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-900">
        <button
          onClick={login}
          className="px-6 py-3 text-lg font-semibold text-white bg-solace-blue rounded-md hover:bg-solace-blue-dark transition-colors"
        >
          Login to {configBotName}
        </button>
      </div>
    );
  }

  return <AuthenticatedInterface />;
}

function AuthenticatedInterface() {
  const {
    messages,
    userInput,
    setUserInput,
    handleSubmit,
    handleNewSession,
    isResponding,
    selectedAgentName,
    setSelectedAgentName,
    artifacts,
    isArtifactPanelOpen,
    toggleArtifactPanel,
    fetchArtifacts
  } = useContext(ChatContext)!;

  const {
    connectTaskMonitorStream,
    disconnectTaskMonitorStream,
    isTaskMonitorConnected,
    monitoredTasks
  } = useTaskMonitor();

  useEffect(() => {
    // Connect to task monitoring on mount
    connectTaskMonitorStream();
    fetchArtifacts();
    
    return () => {
      disconnectTaskMonitorStream();
    };
  }, []);

  return (
    <div className="h-screen flex flex-col">
      {/* Header with agent selection and controls */}
      <div className="flex items-center justify-between p-4 bg-gray-800 text-white">
        <div className="flex items-center space-x-4">
          <AgentSelector
            selectedAgentName={selectedAgentName}
            onSelectAgent={setSelectedAgentName}
            disabled={isResponding}
          />
          <button
            onClick={handleNewSession}
            className="px-4 py-2 bg-blue-600 rounded hover:bg-blue-700"
          >
            New Session
          </button>
        </div>
        
        <div className="flex items-center space-x-4">
          <span>Tasks: {Object.keys(monitoredTasks).length}</span>
          <span className={`w-3 h-3 rounded-full ${isTaskMonitorConnected ? 'bg-green-500' : 'bg-red-500'}`} />
          <button
            onClick={toggleArtifactPanel}
            className="px-4 py-2 bg-purple-600 rounded hover:bg-purple-700"
          >
            Artifacts ({artifacts.length})
          </button>
        </div>
      </div>

      {/* Main content area */}
      <div className="flex-1 flex">
        {/* Chat interface */}
        <div className="flex-1">
          <ChatBox
            messages={messages}
            userInput={userInput}
            setUserInput={setUserInput}
            handleSubmit={handleSubmit}
            isResponding={isResponding}
            selectedFiles={[]}
            setSelectedFiles={() => {}}
            selectedAgentName={selectedAgentName}
            handlePreviewFile={(file) => console.log('Preview:', file)}
            handleRunFile={(file) => console.log('Run:', file)}
          />
        </div>

        {/* Artifact panel */}
        <ArtifactPanel
          isOpen={isArtifactPanelOpen}
          artifacts={artifacts}
          isLoading={false}
          onClose={() => toggleArtifactPanel()}
          onPreviewFile={(artifact) => console.log('Preview artifact:', artifact)}
          onDownloadFile={(filename) => console.log('Download:', filename)}
          onCopyFile={(artifact) => console.log('Copy:', artifact)}
          onUploadFile={(file) => console.log('Upload:', file)}
          onDeleteArtifact={(artifact) => console.log('Delete:', artifact)}
          onDeleteSelected={() => console.log('Delete selected')}
        />
      </div>
    </div>
  );
}
```

### 3. OAuth Authentication Setup

```typescript
import React from 'react';
import AuthCallback from './auth-callback';

// OAuth callback page (separate entry point)
function AuthCallbackPage() {
  return <AuthCallback />;
}

// Custom auth handling
function CustomAuthFlow() {
  const handleLogin = () => {
    // Redirect to OAuth provider
    window.location.href = '/api/auth/login';
  };

  const handleLogout = () => {
    // Clear tokens and redirect
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    window.location.href = '/';
  };

  return (
    <div>
      <button onClick={handleLogin}>Login</button>
      <button onClick={handleLogout}>Logout</button>
    </div>
  );
}
```

### 4. Task Monitoring Integration

```typescript
import React, { useEffect, useState } from 'react';
import { TaskMonitorProvider, useTaskMonitor } from './contexts/TaskMonitorContext';
import TaskMonitorPage from './components/TaskMonitorPage';
import FlowChartPanel from './components/TaskMonitor/FlowChart/FlowChartPanel';

function TaskMonitoringApp() {
  return (
    <TaskMonitorProvider>
      <TaskMonitorInterface />
    </TaskMonitorProvider>
  );
}

function TaskMonitorInterface() {
  const {
    isTaskMonitorConnected,
    monitoredTasks,
    monitoredTaskOrder,
    connectTaskMonitorStream,
    disconnectTaskMonitorStream,
    highlightedStepId,
    setHighlightedStepId
  } = useTaskMonitor();

  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);

  useEffect(() => {
    connectTaskMonitorStream();
    return () => disconnectTaskMonitorStream();
  }, []);

  return (
    <div className="h-screen flex">
      {/* Task list sidebar */}
      <div className="w-1/3 border-r">
        <div className="p-4">
          <h2>Active Tasks ({monitoredTaskOrder.length})</h2>
          <div className={`w-3 h-3 rounded-full inline-block ml-2 ${
            isTaskMonitorConnected ? 'bg-green-500' : 'bg-red-500'
          }`} />
        </div>
        
        {monitoredTaskOrder.map(taskId => {
          const task = monitoredTasks[taskId];
          return (
            <div
              key={taskId}
              className={`p-3 border-b cursor-pointer hover:bg-gray-100 ${
                selectedTaskId === taskId ? 'bg-blue-100' : ''
              }`}
              onClick={() => setSelectedTaskId(taskId)}
            >
              <div className="font-medium">{task.initialRequestText}</div>
              <div className="text-sm text-gray-600">
                Events: {task.events.length} | Status: {task.status}
              </div>
            </div>
          );
        })}
      </div>

      {/* Task details and flowchart */}
      <div className="flex-1">
        {selectedTaskId ? (
          <div className="h-full flex flex-col">
            <div className="p-4 border-b">
              <h3>Task: {monitoredTasks[selectedTaskId]?.initialRequestText}</h3>
            </div>
            <div className="flex-1">
              <FlowChartPanel
                taskId={selectedTaskId}
                highlightedStepId={highlightedStepId}
                onStepClick={setHighlightedStepId}
              />
            </div>
          </div>
        ) : (
          <div className="flex items-center justify-center h-full text-gray-500">
            Select a task to view details
          </div>
        )}
      </div>
    </div>
  );
}
```

### 5. Component Integration Patterns

```typescript
import React, { useState } from 'react';
import AgentSelector from './components/AgentSelector';
import AgentDisplayCard from './components/AgentDisplayCard';
import PreviewPanel from './components/PreviewFileContent/PreviewPanel';
import Modal from './components/Modal';
import { AgentCard, FileAttachment } from './common_a2a/types';

function IntegratedComponentExample() {
  const [selectedAgent, setSelectedAgent] = useState("");
  const [previewFile, setPreviewFile] = useState<FileAttachment | null>(null);
  const [showModal, setShowModal] = useState(false);

  const agents: AgentCard[] = [
    {
      name: "orchestrator",
      display_name: "Orchestrator Agent",
      description: "Main coordination agent",
      version: "1.0.0",
      url: "http://localhost:8000",
      capabilities: { file_processing: true }
    }
  ];

  const handleFilePreview = (file: FileAttachment) => {
    setPreviewFile(file);
  };

  const handleAgentAction = () => {
    setShowModal(true);
  };

  return (
    <div className="p-6">
      {/* Agent selection and display */}
      <div className="mb-6">
        <AgentSelector
          selectedAgentName={selectedAgent}
          onSelectAgent={setSelectedAgent}
        />
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
        {agents.map(agent => (
          <AgentDisplayCard
            key={agent.name}
            agent={agent}
            isExpanded={false}
            onToggleExpand={handleAgentAction}
          />
        ))}
      </div>

      {/* File preview panel */}
      {previewFile && (
        <PreviewPanel
          file={previewFile}
          onClose={() => setPreviewFile(null)}
          autoRun={false}
          currentVersionNumber={1}
          availableVersions={[1]}
          onNavigateVersion={() => {}}
        />
      )}

      {/* Modal dialog */}
      <Modal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onConfirm={() => {
          console.log('Confirmed action for agent:', selectedAgent);
          setShowModal(false);
        }}
        title="Agent Action"
        message={`Perform action on ${selectedAgent}?`}
        confirmText="Execute"

================================================================================

## Section 13: frontend/static/assets/assets_llm.txt

**Source file:** `frontend/static/assets/assets_llm.txt`

# DEVELOPER GUIDE for assets

## Quick Summary
This directory contains compiled JavaScript assets for a React application, including the main client bundle, authentication callback handler, and React runtime dependencies. These are production-ready, minified JavaScript files that handle the frontend functionality.

## Files Overview
- `auth-callback-BnT9Il8i.js` - Handles OAuth authentication callback processing
- `client-y9YGnS5j.js` - Main React client bundle with core React functionality and components

## Developer API Reference

### auth-callback-BnT9Il8i.js
**Purpose:** Processes OAuth authentication callbacks by extracting tokens from URL hash and storing them in localStorage
**Import:** This is a standalone script that auto-executes, no manual import needed

**Functions:**
- `c()` - Main callback component that processes authentication tokens
  - Extracts `access_token` and `refresh_token` from URL hash
  - Stores tokens in localStorage
  - Redirects to home page on success
  - Logs error if no access token found

**Usage Examples:**
```javascript
// This script runs automatically when loaded
// It processes URLs like: /callback#access_token=abc123&refresh_token=def456
// Tokens are automatically stored in localStorage and user is redirected
```

### client-y9YGnS5j.js
**Purpose:** Main React client bundle containing React runtime, hooks, components, and DOM manipulation utilities
**Import:** 
```javascript
import { r as React, j as jsx, e as ReactDOM } from "./client-y9YGnS5j.js"
```

**Key Exports:**
- `r` (React) - Main React object with hooks and utilities
- `j` (jsx) - JSX runtime for creating React elements  
- `e` (ReactDOM) - React DOM methods for rendering
- `a` (ReactDOMClient) - React 18+ client rendering methods
- `b` (ReactDOMServer) - Server-side rendering utilities
- `c` (ReactCore) - Core React functionality
- `d` (ReactShared) - Shared React utilities
- `g` (ReactUtils) - General React utility functions

**React Hooks Available:**
- `r.useState(initialState)` - State management hook
- `r.useEffect(effect, deps)` - Side effect hook
- `r.useContext(context)` - Context consumption hook
- `r.useReducer(reducer, initialState)` - Complex state management
- `r.useMemo(factory, deps)` - Memoization hook
- `r.useCallback(callback, deps)` - Callback memoization
- `r.useRef(initialValue)` - Ref creation hook

**ReactDOM Methods:**
- `e.createRoot(container)` - Create React 18 root
- `e.hydrateRoot(container, element)` - Hydrate server-rendered content

**Usage Examples:**
```javascript
// Import the main React functionality
import { r as React, j as jsx, e as ReactDOM } from "./client-y9YGnS5j.js";

// Create a simple component
function MyComponent() {
  const [count, setCount] = React.useState(0);
  
  React.useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);
  
  return jsx('div', {
    children: [
      jsx('p', { children: `Count: ${count}` }),
      jsx('button', { 
        onClick: () => setCount(count + 1),
        children: 'Increment'
      })
    ]
  });
}

// Render the component
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(jsx(MyComponent, {}));
```

**Critical Requirements:**
1. These are minified production builds - use exact import paths
2. The auth callback script runs automatically when loaded
3. React hooks must be used within React components
4. Always use the jsx function for creating elements in this build
5. Ensure proper error boundaries when using these compiled assets

================================================================================

## Section 14: frontend/static/static_llm.txt

**Source file:** `frontend/static/static_llm.txt`

# DEVELOPER GUIDE for static

## Quick Summary
The `static` directory serves as the frontend asset distribution layer for a React-based web application. It contains compiled, production-ready JavaScript bundles that handle client-side functionality including React components, authentication flows, and DOM manipulation. The architecture is designed for efficient browser delivery with minified assets that provide complete frontend functionality through a modular import system.

## Files and Subdirectories Overview
- **Direct files:** None - all functionality is organized in subdirectories
- **Subdirectories:** 
  - **assets/** - Contains compiled JavaScript bundles for React application and authentication handling

## Developer API Reference

### Direct Files
No direct files in this directory.

### Subdirectory APIs

#### assets/
**Purpose:** Provides compiled JavaScript assets for React application frontend and OAuth authentication
**Key Exports:** React runtime, JSX functions, ReactDOM methods, and authentication callback handler
**Import Examples:**
```javascript
// Main React functionality
import { r as React, j as jsx, e as ReactDOM } from "./static/assets/client-y9YGnS5j.js"

// Authentication callback (auto-executing script)
<script src="./static/assets/auth-callback-BnT9Il8i.js"></script>
```

## Complete Usage Guide

### 1. Setting Up React Application

```javascript
// Import core React functionality
import { r as React, j as jsx, e as ReactDOM } from "./static/assets/client-y9YGnS5j.js";

// Create a basic React component with hooks
function App() {
  const [user, setUser] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  
  React.useEffect(() => {
    // Check for stored authentication tokens
    const token = localStorage.getItem('access_token');
    if (token) {
      setUser({ authenticated: true });
    }
    setLoading(false);
  }, []);
  
  if (loading) {
    return jsx('div', { children: 'Loading...' });
  }
  
  return jsx('div', {
    className: 'app',
    children: [
      jsx('h1', { children: 'My Application' }),
      user ? 
        jsx('p', { children: 'Welcome back!' }) :
        jsx('button', { 
          onClick: () => window.location.href = '/auth',
          children: 'Login'
        })
    ]
  });
}

// Initialize the React application
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(jsx(App, {}));
```

### 2. Authentication Integration

```html
<!-- Include authentication callback handler in your callback page -->
<!DOCTYPE html>
<html>
<head>
    <title>Authentication Callback</title>
</head>
<body>
    <div id="callback-status">Processing authentication...</div>
    <!-- This script automatically processes OAuth tokens and redirects -->
    <script src="./static/assets/auth-callback-BnT9Il8i.js"></script>
</body>
</html>
```

### 3. Advanced React Patterns

```javascript
import { r as React, j as jsx } from "./static/assets/client-y9YGnS5j.js";

// Context for authentication state
const AuthContext = React.createContext();

// Custom hook for authentication
function useAuth() {
  const context = React.useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within AuthProvider');
  }
  return context;
}

// Authentication provider component
function AuthProvider({ children }) {
  const [token, setToken] = React.useState(
    localStorage.getItem('access_token')
  );
  
  const login = React.useCallback((newToken) => {
    localStorage.setItem('access_token', newToken);
    setToken(newToken);
  }, []);
  
  const logout = React.useCallback(() => {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    setToken(null);
  }, []);
  
  const value = React.useMemo(() => ({
    token,
    isAuthenticated: !!token,
    login,
    logout
  }), [token, login, logout]);
  
  return jsx(AuthContext.Provider, {
    value,
    children
  });
}

// Protected route component
function ProtectedRoute({ children }) {
  const { isAuthenticated } = useAuth();
  
  if (!isAuthenticated) {
    return jsx('div', {
      children: jsx('button', {
        onClick: () => window.location.href = '/auth',
        children: 'Please login to continue'
      })
    });
  }
  
  return children;
}
```

### 4. Complete Application Setup

```javascript
import { r as React, j as jsx, e as ReactDOM } from "./static/assets/client-y9YGnS5j.js";

// Main application with routing and authentication
function MainApp() {
  const [currentPage, setCurrentPage] = React.useState('home');
  
  React.useEffect(() => {
    // Listen for authentication completion
    const handleStorageChange = (e) => {
      if (e.key === 'access_token' && e.newValue) {
        setCurrentPage('dashboard');
      }
    };
    
    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);
  
  const renderPage = () => {
    switch (currentPage) {
      case 'home':
        return jsx(HomePage, {});
      case 'dashboard':
        return jsx(ProtectedRoute, {
          children: jsx(Dashboard, {})
        });
      default:
        return jsx('div', { children: 'Page not found' });
    }
  };
  
  return jsx(AuthProvider, {
    children: jsx('div', {
      className: 'main-app',
      children: [
        jsx(Navigation, { setCurrentPage }),
        jsx('main', { children: renderPage() })
      ]
    })
  });
}

// Initialize the complete application
document.addEventListener('DOMContentLoaded', () => {
  const container = document.getElementById('app');
  const root = ReactDOM.createRoot(container);
  root.render(jsx(MainApp, {}));
});
```

### 5. Error Handling and Production Considerations

```javascript
import { r as React, j as jsx } from "./static/assets/client-y9YGnS5j.js";

// Error boundary for production
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }
  
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  
  componentDidCatch(error, errorInfo) {
    console.error('Application error:', error, errorInfo);
  }
  
  render() {
    if (this.state.hasError) {
      return jsx('div', {
        className: 'error-boundary',
        children: [
          jsx('h2', { children: 'Something went wrong' }),
          jsx('button', {
            onClick: () => window.location.reload(),
            children: 'Reload page'
          })
        ]
      });
    }
    
    return this.props.children;
  }
}

// Wrap your app with error boundary
const root = ReactDOM.createRoot(document.getElementById('app'));
root.render(
  jsx(ErrorBoundary, {
    children: jsx(MainApp, {})
  })
);
```

**Critical Requirements:**
1. **Exact Import Paths:** Always use the exact file paths from `./static/assets/` directory
2. **Authentication Flow:** The auth callback script automatically processes OAuth tokens and stores them in localStorage
3. **React Hooks Rules:** All hooks must be used within React components and follow React's rules of hooks
4. **JSX Usage:** Use the `jsx` function for all element creation in this compiled environment
5. **Error Boundaries:** Implement error boundaries for production stability
6. **Token Management:** Authentication tokens are managed through localStorage by the callback script
7. **Production Ready:** These are minified, production builds - handle errors gracefully and provide fallbacks

================================================================================

## Section 15: llm.txt

**Source file:** `llm.txt`

# DEVELOPER GUIDE for webui

## Quick Summary
The webui directory provides a complete web-based user interface for an A2A (Agent-to-Agent) Chat system. It contains a modern React + TypeScript + Vite frontend application with comprehensive chat capabilities, real-time task monitoring, file handling, authentication, and visualization components. The architecture uses React Context for global state management, Material-UI for components, and includes both development source code and production-ready static assets for deployment.

## Files and Subdirectories Overview

### Direct Files:
*No direct files in this directory*

### Subdirectories:
- **frontend/** - Complete React + TypeScript + Vite application for A2A Chat interface with real-time features

## Developer API Reference

### Subdirectory APIs

#### frontend/
**Purpose:** Modern React + TypeScript + Vite application for A2A Chat interface with AI agents, real-time task monitoring, file handling, authentication, and visualization
**Key Exports:** App, AuthProvider, ChatProvider, TaskMonitorProvider, ChatBox, AgentSelector, ArtifactPanel, React runtime components
**Import Examples:**
```typescript
// Development imports
import App from './webui/frontend/src/App'
import { AuthProvider, useAuth } from './webui/frontend/src/contexts/AuthProvider'
import { ChatProvider } from './webui/frontend/src/contexts/ChatProvider'
import ChatBox from './webui/frontend/src/components/ChatBox/ChatBox'
import AgentSelector from './webui/frontend/src/components/AgentSelector'

// Production imports
import { r as React, j as jsx, e as ReactDOM } from "./webui/frontend/static/assets/client-y9YGnS5j.js"
```

## Complete Usage Guide

### 1. Development Environment Setup

```bash
# Navigate to frontend directory
cd webui/frontend

# Install dependencies
npm install

# Start development server
npm run dev

# Build for production
npm run build

# Preview production build
npm run preview

# Run linting
npm run lint
```

### 2. Complete A2A Chat Application Integration

```typescript
// Main application entry point
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './webui/frontend/src/App';
import './webui/frontend/src/index.css';

// Initialize the complete A2A chat application
createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// Full application with all providers and features
import React from 'react';
import { AuthProvider, useAuth } from './webui/frontend/src/contexts/AuthProvider';
import { ChatProvider } from './webui/frontend/src/contexts/ChatProvider';
import { TaskMonitorProvider } from './webui/frontend/src/contexts/TaskMonitorContext';
import ConfigProvider from './webui/frontend/src/components/ConfigProvider';
import ChatBox from './webui/frontend/src/components/ChatBox/ChatBox';
import AgentSelector from './webui/frontend/src/components/AgentSelector';
import ArtifactPanel from './webui/frontend/src/components/ArtifactPanel';

function A2AChatApplication() {
  return (
    <ConfigProvider>
      <AuthProvider useAuthorization={true}>
        <ChatProvider>
          <TaskMonitorProvider>
            <MainChatInterface />
          </TaskMonitorProvider>
        </ChatProvider>
      </AuthProvider>
    </ConfigProvider>
  );
}

function MainChatInterface() {
  const { isAuthenticated, login, useAuthorization } = useAuth();
  
  if (useAuthorization && !isAuthenticated) {
    return (
      <div className="flex items-center justify-center h-screen bg-gray-900">
        <button
          onClick={login}
          className="px-6 py-3 text-lg font-semibold text-white bg-blue-600 rounded-md hover:bg-blue-700"
        >
          Login to A2A Chat
        </button>
      </div>
    );
  }

  return <ChatInterface />;
}
```

### 3. Real-time Chat Interface with Agent Communication

```typescript
import React, { useContext, useEffect, useState } from 'react';
import ChatContext from './webui/frontend/src/contexts/ChatContext';
import { useTaskMonitor } from './webui/frontend/src/contexts/TaskMonitorContext';
import ChatBox from './webui/frontend/src/components/ChatBox/ChatBox';
import AgentSelector from './webui/frontend/src/components/AgentSelector';
import ArtifactPanel from './webui/frontend/src/components/ArtifactPanel';

function ChatInterface() {
  const {
    messages,
    userInput,
    setUserInput,
    handleSubmit,
    handleNewSession,
    isResponding,
    selectedAgentName,
    setSelectedAgentName,
    artifacts,
    isArtifactPanelOpen,
    toggleArtifactPanel,
    fetchArtifacts
  } = useContext(ChatContext)!;

  const {
    connectTaskMonitorStream,
    disconnectTaskMonitorStream,
    isTaskMonitorConnected,
    monitoredTasks
  } = useTaskMonitor();

  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);

  useEffect(() => {
    // Initialize real-time connections
    connectTaskMonitorStream();
    fetchArtifacts();
    
    return () => {
      disconnectTaskMonitorStream();
    };
  }, []);

  const handleAgentCommunication = async (message: string, files: File[]) => {
    try {
      await handleSubmit(new Event('submit') as any);
    } catch (error) {
      console.error('Agent communication error:', error);
    }
  };

  return (
    <div className="h-screen flex flex-col bg-gray-900 text-white">
      {/* Header with agent selection and controls */}
      <div className="flex items-center justify-between p-4 bg-gray-800 border-b border-gray-700">
        <div className="flex items-center space-x-4">
          <AgentSelector
            selectedAgentName={selectedAgentName}
            onSelectAgent={setSelectedAgentName}
            disabled={isResponding}
          />
          <button
            onClick={handleNewSession}
            disabled={isResponding}
            className="px-4 py-2 bg-blue-600 rounded hover:bg-blue-700 disabled:opacity-50"
          >
            New A2A Session
          </button>
        </div>
        
        <div className="flex items-center space-x-4">
          <span className="text-sm">
            Active Tasks: {Object.keys(monitoredTasks).length}
          </span>
          <div className={`w-3 h-3 rounded-full ${
            isTaskMonitorConnected ? 'bg-green-500' : 'bg-red-500'
          }`} title={isTaskMonitorConnected ? 'Connected' : 'Disconnected'} />
          <button
            onClick={toggleArtifactPanel}
            className="px-4 py-2 bg-purple-600 rounded hover:bg-purple-700"
          >
            Artifacts ({artifacts.length})
          </button>
        </div>
      </div>

      {/* Main chat interface */}
      <div className="flex-1 flex overflow-hidden">
        <div className="flex-1">
          <ChatBox
            messages={messages}
            userInput={userInput}
            setUserInput={setUserInput}
            handleSubmit={handleAgentCommunication}
            isResponding={isResponding}
            selectedFiles={selectedFiles}
            setSelectedFiles={setSelectedFiles}
            selectedAgentName={selectedAgentName}
            handlePreviewFile={(file) => console.log('Preview:', file)}
            handleRunFile={(file) => console.log('Execute:', file)}
          />
        </div>

        {/* Artifact management panel */}
        <ArtifactPanel
          isOpen={isArtifactPanelOpen}
          artifacts={artifacts}
          isLoading={false}
          onClose={() => toggleArtifactPanel()}
          onPreviewFile={(file) => console.log('Preview artifact:', file)}
          onDownloadFile={(filename) => console.log('Download:', filename)}
          onCopyFile={(artifact) => navigator.clipboard.writeText(artifact.content)}
          onUploadFile={(file) => console.log('Upload artifact:', file)}
          onDeleteArtifact={(artifact) => console.log('Delete:', artifact)}
          onDeleteSelected={() => console.log('Delete selected artifacts')}
        />
      </div>
    </div>
  );
}
```

### 4. Task Monitoring and Visualization Dashboard

```typescript
import React, { useState } from 'react';
import { TaskMonitorProvider, useTaskMonitor } from './webui/frontend/src/contexts/TaskMonitorContext';
import TaskMonitorPage from './webui/frontend/src/components/TaskMonitorPage';
import FlowChartPanel from './webui/frontend/src/components/TaskMonitor/FlowChart/FlowChartPanel';

function TaskMonitorDashboard() {
  return (
    <TaskMonitorProvider>
      <TaskMonitorInterface />
    </TaskMonitorProvider>
  );
}

function TaskMonitorInterface() {
  const {
    isTaskMonitorConnected,
    monitoredTasks,
    monitoredTaskOrder,
    highlightedStepId,
    setHighlightedStepId,
    connectTaskMonitorStream,
    disconnectTaskMonitorStream
  } = useTaskMonitor();

  const [selectedTaskId, setSelectedTaskId] = useState<string | null>(null);

  React.useEffect(() => {
    connectTaskMonitorStream();
    return () => disconnectTaskMonitorStream();
  }, []);

  return (
    <div className="h-screen flex bg-gray-900 text-white">
      {/* Task list sidebar */}
      <div className="w-1/3 border-r border-gray-700 overflow-y-auto">
        <div className="p-4 border-b border-gray-700">
          <h2 className="text-lg font-semibold">
            A2A Tasks ({monitoredTaskOrder.length})
          </h2>
          <div className={`inline-block w-3 h-3 rounded-full ml-2 ${
            isTaskMonitorConnected ? 'bg-green-500' : 'bg-red-500'
          }`} />
        </div>
        
        {monitoredTaskOrder.map(taskId => {
          const task = monitoredTasks[taskId];
          return (
            <div
              key={taskId}
              className={`p-3 border-b border-gray-700 cursor-pointer hover:bg-gray-800 ${
                selectedTaskId === taskId ? 'bg-blue-900' : ''
              }`}
              onClick={() => setSelectedTaskId(taskId)}
            >
              <div className="font-medium truncate">
                {task.initialRequestText}
              </div>
              <div className="text-sm text-gray-400">
                Events: {task.events.length} | Status: {task.status}
              </div>
              <div className="text-xs text-gray-500">
                Agent: {task.agentName || 'Unknown'}
              </div>
            </div>
          );
        })}
      </div>

      {/* Task visualization */}
      <div className="flex-1">
        {selectedTaskId ? (
          <div className="h-full flex flex-col">
            <div className="p-4 border-b border-gray-700">
              <h3 className="text-lg font-semibold">
                Task Flow: {monitoredTasks[selectedTaskId]?.initialRequestText}
              </h3>
            </div>
            <div className="flex-1">
              <FlowChartPanel
                taskId={selectedTaskId}
                highlightedStepId={highlightedStepId}
                onStepClick={setHighlightedStepId}
              />
            </div>
          </div>
        ) : (
          <div className="flex items-center justify-center h-full text-gray-500">
            <div className="text-center">
              <h3 className="text-xl mb-2">A2A Task Monitor</h3>
              <p>Select a task to view its execution flow</p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
```

### 5. Production Deployment Setup

```typescript
// Production build using static assets
import { r as React, j as jsx, e as ReactDOM } from "./webui/frontend/static/assets/client-y9YGnS5j.js";

// Production-ready error boundary for A2A chat
class A2AErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorInfo: null };
  }
  
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  
  componentDidCatch(error, errorInfo) {
    console.error('A2A Chat Application Error:', error, errorInfo);
    this.setState({ errorInfo });
  }
  
  render() {
    if (this.state.hasError) {
      return jsx('div', {
        className: 'error-boundary p-8 text-center bg-gray-900 text-white min-h-screen',
        children: [
          jsx('h2', { 
            className: 'text-2xl mb-4',
            children: 'A2A Chat System Error' 
          }),
          jsx('p', {
            className: 'mb-4 text-gray-300',
            children: 'The chat application encountered an unexpected error.'
          }),
          jsx('button', {
            onClick: () => window.location.reload(),
            className: 'px-6 py-3 bg-blue-600 text-white rounded hover:bg-blue-700',
            children: 'Restart Application'
          })
        ]
      });
    }
    
    return this.props.children;
  }
}

// Initialize production A2A chat app
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(
  jsx(A2AErrorBoundary, {
    children: jsx(A2AChatApplication, {})
  })
);
```

### 6. Authentication and OAuth Integration

```html
<!-- OAuth callback page for A2A chat authentication -->
<!DOCTYPE html>
<html>
<head>
    <title>A2A Chat - Authentication</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { 
            font-family: system-ui, -apple-system, sans-serif;
            background: #111827;
            color: white;
            margin: 0;
        }
        .auth-container {
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            text-align: center;
        }
        .spinner {
            border: 3px solid #374151;
            border-top: 3px solid #3b82f6;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 20px auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="auth-container">

================================================================================

