# 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 comprehensive React-based web UI for the Solace Agent Mesh (SAM) platform. It provides a modern chat interface for interacting with AI agents, real-time agent communication flow visualization, and agent discovery capabilities. The architecture is built around reusable components, custom hooks, context providers, and a modular library structure under `src/lib/`. The application supports OAuth authentication, real-time updates via Server-Sent Events, file handling, and includes an enterprise-only Activities page for task management.

## Files and Subdirectories Overview
- **Direct files:**
  - `README.md` - Project documentation and setup instructions
  - `components.json` - shadcn/ui configuration for component styling and aliases
  - `eslint.config.js` - ESLint configuration for code quality and React best practices
  - `package-lock.json` - Locked dependency versions for reproducible builds
  - `package.json` - Project metadata, dependencies, and build scripts
  - `tailwind.config.js` - Tailwind CSS configuration
  - `tsconfig.app.json` - TypeScript configuration for application code
  - `tsconfig.json` - Root TypeScript configuration with path aliases
  - `tsconfig.lib.json` - TypeScript configuration for library builds
  - `tsconfig.node.json` - TypeScript configuration for Node.js tools

- **Subdirectories:**
  - `src/` - Main source code with React components, providers, hooks, and application logic
  - `static/` - Compiled JavaScript bundles and static assets for production

## Developer API Reference

### Direct Files

#### README.md
**Purpose:** Comprehensive project documentation covering features, setup, architecture, and contribution guidelines
**Import:** Documentation file - not imported in code

**Key Information:**
- Features: Chat interface, agent discovery, activities page (enterprise), file handling, real-time updates
- Tech stack: React 19, TypeScript, Vite, Tailwind CSS, shadcn/ui, ESLint
- Architecture: Modular library structure under `src/lib/`
- Development commands: `npm run dev`, `npm run lint`

#### components.json
**Purpose:** Configuration file for shadcn/ui component library setup
**Import:** Configuration file - used by shadcn CLI tools

**Configuration:**
- Style: "new-york" theme
- TypeScript: enabled
- Tailwind: configured with CSS variables and neutral base color
- Path aliases: `@/components`, `@/utils`, `@/ui`, `@/lib`, `@/hooks`
- Icon library: lucide

#### eslint.config.js
**Purpose:** ESLint configuration for maintaining code quality and React best practices
**Import:** Configuration file - used by ESLint

**Rules:**
- Extends recommended JavaScript and TypeScript configurations
- React hooks rules for proper hook usage
- React refresh rules for development hot reloading
- Ignores: `dist`, `lib-package` directories

#### package.json
**Purpose:** Project metadata, dependencies, and build scripts configuration
**Import:** Configuration file - used by npm/yarn

**Key Scripts:**
- `npm run dev` - Start development server
- `npm run build` - Build for production
- `npm run build-lib` - Build as library
- `npm run lint` - Run ESLint

**Key Dependencies:**
- React 19, TypeScript, Vite for core framework
- Radix UI components for accessible primitives
- Tailwind CSS for styling
- @xyflow/react for flowcharts
- Various utility libraries (clsx, marked, js-yaml, etc.)

#### tailwind.config.js
**Purpose:** Tailwind CSS configuration for styling system
**Import:** Configuration file - used by Tailwind CSS

**Configuration:**
- Content: Scans `./src/**/*.{js,ts,jsx,tsx}` for classes
- Theme: Extended with custom properties
- Plugins: Empty array (can be extended)
- Safelist: Empty array (can be extended)

#### TypeScript Configuration Files
**Purpose:** TypeScript compiler configurations for different build targets

**tsconfig.json:**
- Root configuration with path aliases
- References to app and node configurations

**tsconfig.app.json:**
- Application code configuration
- ES2020 target, React JSX, strict mode
- Path aliases: `@/*` → `./src/*`

**tsconfig.lib.json:**
- Library build configuration
- Declaration file generation
- Includes only `src/lib/**/*`

**tsconfig.node.json:**
- Node.js tools configuration
- ES2022 target for build tools

### Subdirectory APIs

#### src/
**Purpose:** Main source code containing React application components, providers, hooks, and core library
**Key Exports:** App component, authentication handling, complete component library, state management
**Import Examples:**
```tsx
import App from "./src/App"
import AuthCallback from "./src/auth/authCallback"
import { ChatPage, AgentMeshPage, NavigationSidebar } from "./src/lib/components"
import { AuthProvider, ChatProvider, ThemeProvider } from "./src/lib/providers"
import { useAuthContext, useBeforeUnload } from "./src/lib/hooks"
```

#### static/
**Purpose:** Compiled JavaScript bundles and static assets for production deployment
**Key Exports:** Production-ready React bundles, authentication callback scripts
**Import Examples:**
```html
<script src="/static/assets/client-bp6u3qVZ.js"></script>
<script src="/static/assets/authCallback-DvlO62me.js"></script>
```

## Complete Usage Guide

### 1. Setting Up the Development Environment

```bash
# Install dependencies
cd frontend
npm install

# Start development server
npm run dev

# Run linting
npm run lint

# Build for production
npm run build

# Build as library package
npm run build-package
```

### 2. Basic Application Setup

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

// Basic setup - renders complete application with all providers
createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
```

### 3. Using Individual Components

```tsx
import React from 'react';
import { 
  ChatPage, 
  AgentMeshPage, 
  NavigationSidebar,
  Button,
  Card,
  Dialog,
  ToastContainer 
} from './src/lib/components';
import { 
  AuthProvider, 
  ChatProvider, 
  ConfigProvider,
  ThemeProvider 
} from './src/lib/providers';
import { useAuthContext, useBeforeUnload } from './src/lib/hooks';

// Custom application with selective components
function CustomApp() {
  const [activeView, setActiveView] = React.useState('chat');
  
  return (
    <ThemeProvider>
      <ConfigProvider>
        <AuthProvider>
          <ChatProvider>
            <div className="flex h-screen">
              <NavigationSidebar
                items={[
                  { id: 'chat', label: 'Chat', icon: 'chat' },
                  { id: 'agents', label: 'Agents', icon: 'agents' }
                ]}
                activeItem={activeView}
                onItemChange={setActiveView}
              />
              <main className="flex-1">
                {activeView === 'chat' ? <ChatPage /> : <AgentMeshPage />}
              </main>
            </div>
            <ToastContainer />
          </ChatProvider>
        </AuthProvider>
      </ConfigProvider>
    </ThemeProvider>
  );
}
```

### 4. OAuth Authentication Integration

```tsx
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import App from './src/App';
import AuthCallback from './src/auth/authCallback';

// Setup with OAuth callback handling
function AppWithAuth() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/auth/callback" element={<AuthCallback />} />
        <Route path="/*" element={<App />} />
      </Routes>
    </BrowserRouter>
  );
}

// Using authentication context
import { useAuthContext } from './src/lib/hooks';

function AuthenticatedComponent() {
  const { isAuthenticated, login, logout, user } = useAuthContext();
  
  if (!isAuthenticated) {
    return <Button onClick={login}>Login</Button>;
  }
  
  return (
    <div>
      <p>Welcome, {user?.name}!</p>
      <Button onClick={logout}>Logout</Button>
    </div>
  );
}
```

### 5. Building Custom Chat Interface

```tsx
import React from 'react';
import { 
  ChatMessageList, 
  ChatInputArea, 
  FlowChartPanel,
  Card,
  ResizablePanelGroup,
  ResizablePanel,
  ResizableHandle 
} from './src/lib/components';
import { ChatProvider, useChatContext } from './src/lib/providers';

function CustomChatInterface() {
  return (
    <ChatProvider>
      <div className="h-screen flex flex-col">
        <ResizablePanelGroup direction="horizontal">
          <ResizablePanel defaultSize={60}>
            <div className="flex flex-col h-full">
              <div className="flex-1 overflow-auto">
                <ChatMessageList />
              </div>
              <div className="border-t">
                <ChatInputArea />
              </div>
            </div>
          </ResizablePanel>
          
          <ResizableHandle />
          
          <ResizablePanel defaultSize={40}>
            <Card className="h-full">
              <FlowChartPanel />
            </Card>
          </ResizablePanel>
        </ResizablePanelGroup>
      </div>
    </ChatProvider>
  );
}
```

### 6. Using UI Components

```tsx
import React from 'react';
import { 
  Button, 
  Card, 
  CardContent, 
  CardHeader, 
  CardTitle,
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
  Input,
  Label,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger
} from './src/lib/components/ui';

function UIShowcase() {
  return (
    <div className="p-6 space-y-6">
      {/* Cards */}
      <Card>
        <CardHeader>
          <CardTitle>Agent Status</CardTitle>
        </CardHeader>
        <CardContent>
          <p>All agents are running normally.</p>
        </CardContent>
      </Card>

      {/* Buttons */}
      <div className="space-x-2">
        <Button>Primary</Button>
        <Button variant="secondary">Secondary</Button>
        <Button variant="outline">Outline</Button>
        <Button variant="ghost">Ghost</Button>
      </div>

      {/* Dialog */}
      <Dialog>
        <DialogTrigger asChild>
          <Button>Open Dialog</Button>
        </DialogTrigger>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Settings</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label htmlFor="name">Name</Label>
              <Input id="name" placeholder="Enter name" />
            </div>
            <div>
              <Label htmlFor="role">Role</Label>
              <Select>
                <SelectTrigger>
                  <SelectValue placeholder="Select role" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="admin">Admin</SelectItem>
                  <SelectItem value="user">User</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Tabs */}
      <Tabs defaultValue="overview">
        <TabsList>
          <TabsTrigger value="overview">Overview</TabsTrigger>
          <TabsTrigger value="details">Details</TabsTrigger>
          <TabsTrigger value="settings">Settings</TabsTrigger>
        </TabsList>
        <TabsContent value="overview">
          <p>Overview content</p>
        </TabsContent>
        <TabsContent value="details">
          <p>Details content</p>
        </TabsContent>
        <TabsContent value="settings">
          <p>Settings content</p>
        </TabsContent>
      </Tabs>
    </div>
  );
}
```

### 7. Customizing Themes and Styling

```tsx
// tailwind.config.js customization
export default {
  content: ["./src/**/*.{js,ts,jsx,tsx}"],
  theme: {
    extend: {
      colors: {
        primary: {
          50: '#eff6ff',
          500: '#3b82f6',
          900: '#1e3a8a',
        },
        secondary: {
          50: '#f8fafc',
          500: '#64748b',
          900: '#0f172a',
        }
      },
      fontFamily: {
        sans: ['Inter', 'sans-serif'],
      }
    }
  },
  plugins: []
}

// Using custom theme in components
import { ThemeProvider } from './src/lib/providers';

function ThemedApp() {
  return (
    <ThemeProvider defaultTheme="dark" storageKey="app-theme">
      <div className="min-h-screen bg-background text-foreground">
        <YourAppContent />
      </div>
    </ThemeProvider>
  );
}
```

### 8. Production Deployment

```bash
# Build for production
npm run build

# The dist/ directory contains:
# - index.html (main entry point)
# - assets/ (CSS and JS bundles)
# - static/ (additional static assets)

# Deploy to web server
cp -r dist/* /var/www/html/

# Or use with Docker
FROM nginx:alpine
COPY dist/ /usr/share/nginx/html/
EXPOSE 80
```

### 9. Library Usage (Building Packages)

```bash
# Build as reusable library
npm run build-package

# This creates:
# - dist/index.js (ES module)
# - dist/index.cjs (CommonJS)
# - dist/index.d.ts (TypeScript definitions)
# - dist/solace-agent-mesh-ui.css (Styles)
```

```tsx
// Using as external library
import { 
  ChatPage, 
  AgentMeshPage, 
  AuthProvider 
} from 'solace-agent-mesh-ui';
import 'solace-agent-mesh-ui/dist/solace-agent-mesh-ui.css';

function MyApp() {
  return (
    <AuthProvider>
      <ChatPage />
    </AuthProvider>
  );
}
```

This comprehensive guide demonstrates how to use the frontend directory to build modern React applications with chat interfaces, agent management, authentication, and real-time communication features. The modular architecture allows for both complete application deployment and selective component usage in custom applications.

# content_hash: 31a7a395e0338e80c1d1b2bfaab3489511ca93fdd68e688bf9047ae8c69a3051

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

## Section 2: frontend/src/auth/auth_llm.txt

**Source file:** `frontend/src/auth/auth_llm.txt`

# DEVELOPER GUIDE: auth

## Quick Summary
The auth directory contains React components for handling OAuth authentication callbacks. It processes authentication tokens from URL fragments and stores them in localStorage for session management.

## Files Overview
- `authCallback.tsx` - React component that extracts and stores OAuth tokens from URL hash parameters
- `authCallbackLoader.tsx` - Entry point that renders the AuthCallback component to the DOM

## Developer API Reference

### authCallback.tsx
**Purpose:** Handles OAuth callback processing by extracting access and refresh tokens from URL hash and storing them in localStorage
**Import:** `import AuthCallback from "./auth/authCallback"`

**Components:**
- `AuthCallback()` - React functional component that processes OAuth callback
  - Automatically extracts `access_token` and `refresh_token` from URL hash on mount
  - Stores tokens in localStorage
  - Redirects to "/" on success or logs error on failure
  - Returns loading UI while processing

**Usage Examples:**
```tsx
import AuthCallback from "./auth/authCallback";

// Use as a route component for OAuth callback endpoint
function App() {
  return (
    <Routes>
      <Route path="/auth/callback" element={<AuthCallback />} />
    </Routes>
  );
}

// Or render directly
function CallbackPage() {
  return <AuthCallback />;
}
```

### authCallbackLoader.tsx
**Purpose:** Standalone entry point that renders AuthCallback component to the DOM root
**Import:** This file is typically used as a separate entry point, not imported

**Functions:**
- Creates React root and renders `AuthCallback` component
- Expects DOM element with id "root" to exist

**Usage Examples:**
```tsx
// This file is typically used as a webpack entry point
// webpack.config.js
module.exports = {
  entry: {
    authCallback: './src/auth/authCallbackLoader.tsx'
  }
};

// Or include as script in HTML for OAuth callback page
// <script src="/dist/authCallbackLoader.js"></script>
```

**Expected URL Format:**
```
https://yourapp.com/auth/callback#access_token=abc123&refresh_token=def456
```

**localStorage Keys Set:**
- `access_token: string` - OAuth access token for API authentication
- `refresh_token: string` - OAuth refresh token for token renewal (optional)

# content_hash: 7e137a80ac9265260bf5a0fb6f93d874ead97441e07df645c6f9cf85640ca7df

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

## Section 3: frontend/src/lib/components/activities/FlowChart/FlowChart_llm.txt

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

# DEVELOPER GUIDE: FlowChart

## Quick Summary
The FlowChart directory provides a comprehensive React Flow-based visualization system for agent-based workflows. It consists of custom node components representing different entities (agents, tools, LLMs, orchestrators, users) and custom edge components with enhanced visual features. The architecture separates node types into the `customNodes` subdirectory and edge functionality into the `customEdges` subdirectory, creating a modular system for building interactive flow diagrams with status indicators, animations, and error handling.

## Files and Subdirectories Overview
- **Direct files:** None
- **Subdirectories:** 
  - `customEdges/` - Custom edge components with animations, hover states, and error visualization
  - `customNodes/` - Custom node components for agents, tools, LLMs, orchestrators, and user interactions

## Developer API Reference

### Subdirectory APIs

#### customEdges/
**Purpose:** Provides enhanced edge components for React Flow with animation, selection, and error state support
**Key Exports:** GenericFlowEdge component and AnimatedEdgeData interface
**Import Examples:**
```typescript
import GenericFlowEdge, { type AnimatedEdgeData } from './FlowChart/customEdges/GenericFlowEdge'
```

#### customNodes/
**Purpose:** Provides specialized node components for different workflow entities with status indicators and connection handles
**Key Exports:** GenericAgentNode, GenericToolNode, LLMNode, OrchestratorAgentNode, UserNode components and their associated data types
**Import Examples:**
```typescript
import GenericAgentNode, { GenericNodeData } from './FlowChart/customNodes/GenericAgentNode'
import GenericToolNode, { GenericToolNodeType } from './FlowChart/customNodes/GenericToolNode'
import LLMNode, { LLMNodeType } from './FlowChart/customNodes/LLMNode'
import OrchestratorAgentNode, { OrchestratorAgentNodeType } from './FlowChart/customNodes/OrchestratorAgentNode'
import UserNode, { UserNodeData, UserNodeType } from './FlowChart/customNodes/UserNode'
```

## Complete Usage Guide

### 1. Setting Up a Complete Flow Chart

```typescript
import React from 'react';
import { ReactFlow, Node, Edge, NodeTypes, EdgeTypes } from '@xyflow/react';

// Import all custom nodes
import GenericAgentNode, { GenericNodeData } from './FlowChart/customNodes/GenericAgentNode';
import GenericToolNode, { GenericToolNodeType } from './FlowChart/customNodes/GenericToolNode';
import LLMNode, { LLMNodeType } from './FlowChart/customNodes/LLMNode';
import OrchestratorAgentNode, { OrchestratorAgentNodeType } from './FlowChart/customNodes/OrchestratorAgentNode';
import UserNode, { UserNodeData, UserNodeType } from './FlowChart/customNodes/UserNode';

// Import custom edge
import GenericFlowEdge, { type AnimatedEdgeData } from './FlowChart/customEdges/GenericFlowEdge';

// Register custom node and edge types
const nodeTypes: NodeTypes = {
  genericAgent: GenericAgentNode,
  genericTool: GenericToolNode,
  llm: LLMNode,
  orchestrator: OrchestratorAgentNode,
  user: UserNode,
};

const edgeTypes: EdgeTypes = {
  generic: GenericFlowEdge,
};
```

### 2. Creating Nodes with Different Types

```typescript
// Create a user input node (top of flow)
const userInputNode: UserNodeType = {
  id: 'user-input',
  type: 'user',
  position: { x: 250, y: 0 },
  data: {
    label: 'User Request',
    isTopNode: true,
    status: 'completed'
  }
};

// Create an orchestrator node
const orchestratorNode: OrchestratorAgentNodeType = {
  id: 'orchestrator-1',
  type: 'orchestrator',
  position: { x: 200, y: 100 },
  data: {
    label: 'Main Orchestrator',
    description: 'Coordinates workflow execution',
    isInitial: true,
    status: 'in-progress'
  }
};

// Create agent nodes
const agentNode: Node<GenericNodeData> = {
  id: 'agent-1',
  type: 'genericAgent',
  position: { x: 100, y: 200 },
  data: {
    label: 'Processing Agent',
    description: 'Handles data processing',
    status: 'completed'
  }
};

// Create tool nodes
const toolNode: GenericToolNodeType = {
  id: 'tool-1',
  type: 'genericTool',
  position: { x: 300, y: 200 },
  data: {
    label: 'Data Parser',
    status: 'in-progress'
  }
};

// Create LLM node
const llmNode: LLMNodeType = {
  id: 'llm-1',
  type: 'llm',
  position: { x: 200, y: 300 },
  data: {
    label: 'GPT-4',
    status: 'idle'
  }
};

// Create user output node (bottom of flow)
const userOutputNode: UserNodeType = {
  id: 'user-output',
  type: 'user',
  position: { x: 250, y: 400 },
  data: {
    label: 'User Response',
    isBottomNode: true,
    status: 'idle'
  }
};
```

### 3. Creating Enhanced Edges with Animations and States

```typescript
// Create animated edges with different states
const edges: Edge[] = [
  {
    id: 'edge-1',
    source: 'user-input',
    target: 'orchestrator-1',
    type: 'generic',
    data: {
      visualizerStepId: 'step-1',
      isAnimated: true,
      animationType: 'request',
      isSelected: false,
      isError: false
    } as AnimatedEdgeData
  },
  {
    id: 'edge-2',
    source: 'orchestrator-1',
    target: 'agent-1',
    type: 'generic',
    data: {
      visualizerStepId: 'step-2',
      isAnimated: true,
      animationType: 'request',
      isSelected: true, // This edge is currently selected
      isError: false
    } as AnimatedEdgeData
  },
  {
    id: 'edge-3',
    source: 'agent-1',
    target: 'tool-1',
    type: 'generic',
    data: {
      visualizerStepId: 'step-3',
      isAnimated: false,
      isError: true, // This edge shows an error state
      errorMessage: 'Connection timeout'
    } as AnimatedEdgeData
  },
  {
    id: 'edge-4',
    source: 'tool-1',
    target: 'llm-1',
    type: 'generic',
    data: {
      visualizerStepId: 'step-4',
      isAnimated: true,
      animationType: 'response'
    } as AnimatedEdgeData
  }
];
```

### 4. Complete Flow Chart Component

```typescript
const FlowChartComponent: React.FC = () => {
  const nodes = [
    userInputNode,
    orchestratorNode,
    agentNode,
    toolNode,
    llmNode,
    userOutputNode
  ];

  return (
    <div style={{ width: '100%', height: '600px' }}>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        nodeTypes={nodeTypes}
        edgeTypes={edgeTypes}
        fitView
        attributionPosition="top-right"
      />
    </div>
  );
};
```

### 5. Dynamic Status Updates

```typescript
// Function to update node status dynamically
const updateNodeStatus = (nodeId: string, newStatus: string, nodes: Node[]) => {
  return nodes.map(node => {
    if (node.id === nodeId) {
      return {
        ...node,
        data: {
          ...node.data,
          status: newStatus
        }
      };
    }
    return node;
  });
};

// Function to update edge animation state
const updateEdgeAnimation = (edgeId: string, isAnimated: boolean, edges: Edge[]) => {
  return edges.map(edge => {
    if (edge.id === edgeId) {
      return {
        ...edge,
        data: {
          ...edge.data,
          isAnimated
        } as AnimatedEdgeData
      };
    }
    return edge;
  });
};
```

### 6. Common Usage Patterns

```typescript
// Pattern 1: Creating a workflow with user interaction points
const createUserWorkflow = () => {
  const topUserNode: UserNodeType = {
    id: 'user-start',
    type: 'user',
    position: { x: 200, y: 0 },
    data: { label: 'Start', isTopNode: true, status: 'completed' }
  };

  const bottomUserNode: UserNodeType = {
    id: 'user-end',
    type: 'user',
    position: { x: 200, y: 500 },
    data: { label: 'End', isBottomNode: true, status: 'idle' }
  };

  return [topUserNode, bottomUserNode];
};

// Pattern 2: Creating an orchestrated agent workflow
const createAgentWorkflow = () => {
  const orchestrator: OrchestratorAgentNodeType = {
    id: 'main-orch',
    type: 'orchestrator',
    position: { x: 200, y: 100 },
    data: { label: 'Main Controller', isInitial: true }
  };

  const agents = ['agent-1', 'agent-2'].map((id, index) => ({
    id,
    type: 'genericAgent' as const,
    position: { x: 100 + index * 200, y: 200 },
    data: { label: `Agent ${index + 1}` }
  }));

  return [orchestrator, ...agents];
};

// Pattern 3: Error handling in edges
const createErrorEdge = (source: string, target: string, errorMsg: string): Edge => ({
  id: `${source}-${target}-error`,
  source,
  target,
  type: 'generic',
  data: {
    visualizerStepId: `error-${source}-${target}`,
    isError: true,
    errorMessage: errorMsg,
    isAnimated: false
  } as AnimatedEdgeData
});
```

This comprehensive system allows developers to create rich, interactive flow diagrams with proper typing, status management, and visual feedback for agent-based workflows.

# content_hash: 30d44c5adde8eaa07621ed12af37f7b82cc1a6477a8045fcdab5ea8b47b35a1e

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

## Section 4: frontend/src/lib/components/activities/FlowChart/customEdges/customEdges_llm.txt

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

# DEVELOPER GUIDE: customEdges

## Quick Summary
The `customEdges` directory contains custom edge components for React Flow charts. It provides enhanced edge functionality with animations, hover states, selection indicators, and error visualization for flow diagrams.

## Files Overview
- `GenericFlowEdge.tsx` - A customizable React Flow edge component with animation, selection, error states, and hover interactions

## Developer API Reference

### GenericFlowEdge.tsx
**Purpose:** Provides a feature-rich custom edge component for React Flow with support for animations, selections, errors, and interactive hover states

**Import:** 
```typescript
import GenericFlowEdge, { type AnimatedEdgeData } from 'path/to/customEdges/GenericFlowEdge'
```

**Interfaces:**
- `AnimatedEdgeData` - Configuration interface for edge data properties
  - `visualizerStepId: string` - Unique identifier for the visualizer step
  - `isAnimated?: boolean` - Whether the edge should display animation styling
  - `animationType?: "request" | "response" | "static"` - Type of animation (currently for categorization)
  - `isSelected?: boolean` - Whether the edge is currently selected
  - `isError?: boolean` - Whether the edge represents an error state
  - `errorMessage?: string` - Optional error message for error states

**Components:**
- `GenericFlowEdge(props: EdgeProps) -> React.FC` - Main edge component that renders customizable flow edges
  - Accepts standard React Flow `EdgeProps` with enhanced `data` property of type `AnimatedEdgeData`
  - Automatically handles hover states, selection highlighting, error visualization, and animation styling
  - Renders both an invisible interaction path for easier clicking and a visible styled path

**Usage Examples:**
```typescript
// Import the component and interface
import GenericFlowEdge, { type AnimatedEdgeData } from 'path/to/customEdges/GenericFlowEdge'
import { Edge } from '@xyflow/react'

// Define edge data with custom properties
const edgeData: AnimatedEdgeData = {
  visualizerStepId: "step-1",
  isAnimated: true,
  animationType: "request",
  isSelected: false,
  isError: false
}

// Create an edge with custom data
const customEdge: Edge = {
  id: 'edge-1',
  source: 'node-1',
  target: 'node-2',
  type: 'generic', // Register GenericFlowEdge as 'generic' type
  data: edgeData
}

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

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

// Example with error state
const errorEdgeData: AnimatedEdgeData = {
  visualizerStepId: "step-error",
  isError: true,
  errorMessage: "Connection failed"
}

// Example with selected state
const selectedEdgeData: AnimatedEdgeData = {
  visualizerStepId: "step-selected",
  isSelected: true,
  isAnimated: true
}
```

# content_hash: 61facac9b5c26018ca57fe89a4f410016e3b8b2638b99badcafacb0d4a3e4523

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

## Section 5: frontend/src/lib/components/activities/FlowChart/customNodes/customNodes_llm.txt

**Source file:** `frontend/src/lib/components/activities/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. Each node represents different entities in an agent-based workflow system, including agents, tools, LLMs, orchestrators, and user interactions. All nodes are built using the @xyflow/react library and share common styling patterns with status indicators and connection handles.

## Files Overview
- `GenericAgentNode.tsx` - Base agent node component with multiple 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 display
- `OrchestratorAgentNode.tsx` - Special agent node with gradient styling for orchestration roles
- `UserNode.tsx` - User interaction node with conditional handle positioning based on node type

## Developer API Reference

### GenericAgentNode.tsx
**Purpose:** Renders a generic agent node with multiple connection points for workflow integration
**Import:** `import GenericAgentNode, { GenericNodeData } from './customNodes/GenericAgentNode'`

**Interfaces:**
- `GenericNodeData extends Record<string, unknown>` - Base data structure for all node types
  - `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 a starting node
  - `isFinal?: boolean` - Whether this is an ending node

**Components:**
- `GenericAgentNode: React.FC<NodeProps<Node<GenericNodeData>>>` - Main agent node component

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

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

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

### GenericToolNode.tsx
**Purpose:** Renders a tool node with status indicators and left-side connection handles
**Import:** `import GenericToolNode, { GenericToolNodeType } from './customNodes/GenericToolNode'`

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

**Components:**
- `GenericToolNode: React.FC<NodeProps<GenericToolNodeType>>` - Tool node component with status colors

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

const toolNodeData = {
  label: "Data Parser",
  status: "completed" // "completed" | "in-progress" | "error" | "started" | "idle"
};

const toolNode: GenericToolNodeType = {
  id: 'tool-1',
  type: 'genericTool',
  position: { x: 200, y: 150 },
  data: toolNodeData
};
```

### LLMNode.tsx
**Purpose:** Renders a Large Language Model node with teal styling and status indicators
**Import:** `import LLMNode, { LLMNodeType } from './customNodes/LLMNode'`

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

**Components:**
- `LLMNode: React.FC<NodeProps<LLMNodeType>>` - LLM node component with teal color scheme

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

const llmNodeData = {
  label: "GPT-4",
  status: "in-progress"
};

const llmNode: LLMNodeType = {
  id: 'llm-1',
  type: 'llm',
  position: { x: 300, y: 200 },
  data: llmNodeData
};
```

### OrchestratorAgentNode.tsx
**Purpose:** Renders an orchestrator agent node with special gradient styling and enhanced visual prominence
**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 indigo gradient styling

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

const orchestratorData = {
  label: "Main Orchestrator",
  description: "Coordinates all agents"
};

const orchestratorNode: OrchestratorAgentNodeType = {
  id: 'orch-1',
  type: 'orchestrator',
  position: { x: 150, y: 50 },
  data: orchestratorData
};
```

### UserNode.tsx
**Purpose:** Renders user interaction nodes with conditional handle positioning based on node type
**Import:** `import UserNode, { UserNodeData, UserNodeType } from './customNodes/UserNode'`

**Interfaces:**
- `UserNodeData extends GenericNodeData` - Extended data structure for user nodes
  - `isTopNode?: boolean` - True if created by handleUserRequest (shows bottom handle)
  - `isBottomNode?: boolean` - True if created at bottom (shows top handle)

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

**Components:**
- `UserNode: React.FC<NodeProps<UserNodeType>>` - User node with conditional handle rendering

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

const topUserData: UserNodeData = {
  label: "User Input",
  isTopNode: true,
  status: "completed"
};

const bottomUserData: UserNodeData = {
  label: "User Response",
  isBottomNode: true,
  status: "idle"
};

const topUserNode: UserNodeType = {
  id: 'user-top',
  type: 'user',
  position: { x: 100, y: 0 },
  data: topUserData
};

const bottomUserNode: UserNodeType = {
  id: 'user-bottom',
  type: 'user',
  position: { x: 100, y: 400 },
  data: bottomUserData
};
```

# content_hash: aee202fe2cd9fcc4aed3b78a36e25c58149f68d4f0a0da9f4487b6027d5a3b90

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

## Section 6: frontend/src/lib/components/activities/activities_llm.txt

**Source file:** `frontend/src/lib/components/activities/activities_llm.txt`

# DEVELOPER GUIDE: activities

## Quick Summary
The activities directory provides a comprehensive React-based visualization system for agent workflow activities. It combines flow chart visualization with detailed step tracking, offering both high-level flow diagrams and granular step-by-step analysis. The architecture consists of direct files for main components (FlowChartDetails, FlowChartPanel, VisualizerStepCard) and a FlowChart subdirectory containing specialized React Flow components for creating interactive workflow diagrams with custom nodes and edges.

## Files and Subdirectories Overview
- **Direct files:**
  - `FlowChartDetails.tsx` - Component displaying task status and user request information
  - `FlowChartPanel.tsx` - Main flow chart visualization panel with React Flow integration
  - `VisualizerStepCard.tsx` - Individual step card component for detailed step information
- **Subdirectories:**
  - `FlowChart/` - Custom React Flow components including specialized nodes and edges for workflow visualization

## Developer API Reference

### Direct Files

#### FlowChartDetails.tsx
**Purpose:** Displays task overview information including user request and current status
**Import:** `import { FlowChartDetails } from '@/lib/components/activities/FlowChartDetails'`

**Components:**
- `FlowChartDetails: React.FC<{ task: VisualizedTask }>` - Main component displaying task details with status badges and loading states

#### FlowChartPanel.tsx
**Purpose:** Main flow chart visualization component with React Flow integration, animations, and interactive features
**Import:** `import { FlowChartPanel } from '@/lib/components/activities/FlowChartPanel'`

**Components:**
- `FlowChartPanel: React.FC<FlowChartPanelProps>` - Main flow chart panel with React Flow provider
- `FlowRenderer: React.FC<FlowChartPanelProps>` - Internal component handling React Flow logic

**Interfaces:**
- `FlowChartPanelProps` - Props interface with processedSteps, isRightPanelVisible, and isSidePanelTransitioning

#### VisualizerStepCard.tsx
**Purpose:** Individual step card component for displaying detailed step information with expandable content
**Import:** `import { VisualizerStepCard } from '@/lib/components/activities/VisualizerStepCard'`

**Components:**
- `VisualizerStepCard: React.FC<VisualizerStepCardProps>` - Step card with icons, timestamps, and detailed data display

**Interfaces:**
- `VisualizerStepCardProps` - Props interface with step, isHighlighted, onClick, and variant options

### Subdirectory APIs

#### FlowChart/
**Purpose:** Provides specialized React Flow components for workflow visualization with custom nodes and edges
**Key Exports:** Custom node components (GenericAgentNode, LLMNode, OrchestratorAgentNode, UserNode, GenericToolNode) and custom edge components (GenericFlowEdge)
**Import Examples:**
```typescript
import GenericAgentNode from '@/lib/components/activities/FlowChart/customNodes/GenericAgentNode'
import GenericFlowEdge from '@/lib/components/activities/FlowChart/customEdges/GenericFlowEdge'
```

## Complete Usage Guide

### 1. Basic Flow Chart Setup

```typescript
import React from 'react';
import { FlowChartPanel } from '@/lib/components/activities/FlowChartPanel';
import { FlowChartDetails } from '@/lib/components/activities/FlowChartDetails';
import type { VisualizerStep, VisualizedTask } from '@/lib/types';

// Basic usage with processed steps
const ActivityVisualization: React.FC = () => {
  const processedSteps: VisualizerStep[] = [
    {
      id: 'step-1',
      type: 'USER_REQUEST',
      timestamp: new Date().toISOString(),
      title: 'User Request',
      data: { text: 'Process this document' },
      nestingLevel: 0
    },
    {
      id: 'step-2',
      type: 'AGENT_LLM_CALL',
      timestamp: new Date().toISOString(),
      title: 'LLM Processing',
      data: {
        llmCall: {
          model_name: 'gpt-4',
          prompt_preview: 'Analyze the following document...'
        }
      },
      nestingLevel: 1
    }
  ];

  const task: VisualizedTask = {
    id: 'task-1',
    status: 'working',
    initialRequestText: 'Process this document'
  };

  return (
    <div className="h-screen flex flex-col">
      {/* Task details header */}
      <FlowChartDetails task={task} />
      
      {/* Main flow chart */}
      <div className="flex-1">
        <FlowChartPanel 
          processedSteps={processedSteps}
          isRightPanelVisible={false}
          isSidePanelTransitioning={false}
        />
      </div>
    </div>
  );
};
```

### 2. Step Card Usage with Different Variants

```typescript
import React from 'react';
import { VisualizerStepCard } from '@/lib/components/activities/VisualizerStepCard';
import type { VisualizerStep } from '@/lib/types';

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

  const steps: VisualizerStep[] = [
    {
      id: 'step-1',
      type: 'USER_REQUEST',
      timestamp: new Date().toISOString(),
      title: 'Initial Request',
      data: { text: 'Analyze this data set' },
      nestingLevel: 0
    },
    {
      id: 'step-2',
      type: 'AGENT_LLM_RESPONSE_TOOL_DECISION',
      timestamp: new Date().toISOString(),
      title: 'Tool Decision',
      data: {
        toolDecision: {
          is_parallel: false,
          decisions: [{
            function_call_id: 'call-1',
            tool_name: 'data_analyzer',
            is_peer_delegation: false
          }]
        }
      },
      nestingLevel: 1,
      delegationInfo: [{
        function_call_id: 'call-1',
        peer_agent_name: 'DataAnalyzer',
        sub_task_id: 'subtask-123'
      }]
    },
    {
      id: 'step-3',
      type: 'TASK_COMPLETED',
      timestamp: new Date().toISOString(),
      title: 'Task Completed',
      data: { finalMessage: 'Analysis complete with 95% confidence' },
      nestingLevel: 0
    }
  ];

  return (
    <div className="space-y-4">
      {/* List variant with highlighting */}
      <div className="space-y-2">
        <h3>Step Timeline (List View)</h3>
        {steps.map(step => (
          <VisualizerStepCard
            key={step.id}
            step={step}
            variant="list"
            isHighlighted={highlightedStepId === step.id}
            onClick={() => setHighlightedStepId(step.id)}
          />
        ))}
      </div>

      {/* Popover variant for detailed view */}
      {highlightedStepId && (
        <div className="border rounded-lg p-4">
          <h3>Detailed View (Popover Style)</h3>
          <VisualizerStepCard
            step={steps.find(s => s.id === highlightedStepId)!}
            variant="popover"
          />
        </div>
      )}
    </div>
  );
};
```

### 3. Complete Activity Dashboard

```typescript
import React from 'react';
import { FlowChartPanel } from '@/lib/components/activities/FlowChartPanel';
import { FlowChartDetails } from '@/lib/components/activities/FlowChartDetails';
import { VisualizerStepCard } from '@/lib/components/activities/VisualizerStepCard';
import { useTaskContext, useChatContext } from '@/lib/hooks';
import type { VisualizerStep, VisualizedTask } from '@/lib/types';

const ActivityDashboard: React.FC = () => {
  const { highlightedStepId, setHighlightedStepId } = useTaskContext();
  const { taskIdInSidePanel } = useChatContext();
  const [isRightPanelVisible, setIsRightPanelVisible] = React.useState(true);
  const [isSidePanelTransitioning, setIsSidePanelTransitioning] = React.useState(false);

  // Mock data - replace with actual data from your context/API
  const processedSteps: VisualizerStep[] = [
    {
      id: 'step-1',
      type: 'USER_REQUEST',
      timestamp: new Date(Date.now() - 5000).toISOString(),
      title: 'User Request',
      data: { text: 'Create a comprehensive report on market trends' },
      nestingLevel: 0
    },
    {
      id: 'step-2',
      type: 'AGENT_LLM_CALL',
      timestamp: new Date(Date.now() - 4000).toISOString(),
      title: 'Planning Analysis',
      data: {
        llmCall: {
          model_name: 'gpt-4-turbo',
          prompt_preview: 'Plan the market analysis approach...'
        }
      },
      nestingLevel: 1
    },
    {
      id: 'step-3',
      type: 'AGENT_TOOL_INVOCATION_START',
      timestamp: new Date(Date.now() - 3000).toISOString(),
      title: 'Data Collection',
      data: {
        toolInvocationStart: {
          tool_name: 'market_data_collector',
          tool_args: { timeframe: '1year', sectors: ['tech', 'finance'] },
          is_peer_invocation: false
        }
      },
      nestingLevel: 2
    },
    {
      id: 'step-4',
      type: 'AGENT_TOOL_EXECUTION_RESULT',
      timestamp: new Date(Date.now() - 2000).toISOString(),
      title: 'Data Retrieved',
      data: {
        toolResult: {
          tool_name: 'market_data_collector',
          result_data: { records: 1250, sectors_analyzed: 2 }
        }
      },
      nestingLevel: 2
    },
    {
      id: 'step-5',
      type: 'TASK_COMPLETED',
      timestamp: new Date().toISOString(),
      title: 'Report Generated',
      data: { finalMessage: 'Market analysis report has been generated successfully' },
      nestingLevel: 0
    }
  ];

  const currentTask: VisualizedTask = {
    id: taskIdInSidePanel || 'current-task',
    status: 'completed',
    initialRequestText: 'Create a comprehensive report on market trends'
  };

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

  const toggleRightPanel = () => {
    setIsSidePanelTransitioning(true);
    setIsRightPanelVisible(!isRightPanelVisible);
    
    // Simulate transition completion
    setTimeout(() => {
      setIsSidePanelTransitioning(false);
    }, 300);
  };

  return (
    <div className="h-screen flex flex-col bg-gray-50 dark:bg-gray-900">
      {/* Header with task details */}
      <div className="border-b bg-white dark:bg-gray-800">
        <FlowChartDetails task={currentTask} />
      </div>

      {/* Main content area */}
      <div className="flex-1 flex overflow-hidden">
        {/* Flow chart panel */}
        <div className={`transition-all duration-300 ${isRightPanelVisible ? 'flex-1' : 'w-full'}`}>
          <FlowChartPanel
            processedSteps={processedSteps}
            isRightPanelVisible={isRightPanelVisible}
            isSidePanelTransitioning={isSidePanelTransitioning}
          />
        </div>

        {/* Right panel with step details */}
        {isRightPanelVisible && (
          <div className="w-96 border-l bg-white dark:bg-gray-800 overflow-y-auto">
            <div className="p-4">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold">Step Details</h3>
                <button
                  onClick={toggleRightPanel}
                  className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
                >
                  ✕
                </button>
              </div>
              
              <div className="space-y-2">
                {processedSteps.map(step => (
                  <VisualizerStepCard
                    key={step.id}
                    step={step}
                    variant="list"
                    isHighlighted={highlightedStepId === step.id}
                    onClick={() => handleStepClick(step.id)}
                  />
                ))}
              </div>
            </div>
          </div>
        )}

        {/* Toggle button when panel is hidden */}
        {!isRightPanelVisible && (
          <button
            onClick={toggleRightPanel}
            className="absolute top-4 right-4 bg-white dark:bg-gray-800 border rounded-lg p-2 shadow-lg hover:shadow-xl transition-shadow"
          >
            📋
          </button>
        )}
      </div>
    </div>
  );
};

export default ActivityDashboard;
```

### 4. Integration with Custom Flow Chart Components

```typescript
import React from 'react';
import { ReactFlow, ReactFlowProvider } from '@xyflow/react';
import { FlowChartPanel } from '@/lib/components/activities/FlowChartPanel';

// Import custom nodes and edges from FlowChart subdirectory
import GenericAgentNode from '@/lib/components/activities/FlowChart/customNodes/GenericAgentNode';
import LLMNode from '@/lib/components/activities/FlowChart/customNodes/LLMNode';
import GenericFlowEdge from '@/lib/components/activities/FlowChart/customEdges/GenericFlowEdge';

const CustomFlowIntegration: React.FC = () => {
  // Custom node types for specialized workflows
  const customNodeTypes = {
    genericAgentNode: GenericAgentNode,
    llmNode: LLMNode,
    // Add other custom nodes as needed
  };

  const customEdgeTypes = {
    defaultFlowEdge: GenericFlowEdge,
  };

  const processedSteps = [
    // Your processed steps data
  ];

  return (
    <ReactFlowProvider>
      <div className="h-screen">
        <FlowChartPanel
          processedSteps={processedSteps}
          isRightPanelVisible={true}

# content_hash: 8471669377ff9f87e4816f24c5c863fefeb4df36e12dabca7428eb79baffdbfd

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

## Section 7: frontend/src/lib/components/agents/agents_llm.txt

**Source file:** `frontend/src/lib/components/agents/agents_llm.txt`

# DEVELOPER GUIDE: agents

## Quick Summary
The `agents` directory contains React components for displaying and managing agent information in a card-based interface. It provides components for individual agent display cards, a mesh layout for multiple agents, and layout selection functionality.

## Files Overview
- `AgentDisplayCard.tsx` - Displays detailed information about a single agent in a flippable card format
- `AgentMeshCards.tsx` - Renders a collection of agent cards with search functionality
- `LayoutSelector.tsx` - Provides UI for switching between different layout options

## Developer API Reference

### AgentDisplayCard.tsx
**Purpose:** Renders a single agent's information in an interactive card that flips to show detailed information
**Import:** `import { AgentDisplayCard } from "@/lib/components/agents/AgentDisplayCard"`

**Components:**
- `AgentDisplayCard(agent: AgentCard, isExpanded: boolean, onToggleExpand: () => void)` - Main agent card component with flip animation
  - Shows agent summary on front, detailed information on back
  - Handles click interactions to toggle between views
  - Displays capabilities, tools, authentication, and other agent metadata

**Internal Components:**
- `DetailItem(label: string, value?: string | null | ReactNode, icon?: ReactNode, fullWidthValue?: boolean)` - Renders individual detail rows with optional icons

**Usage Examples:**
```tsx
import { AgentDisplayCard } from "@/lib/components/agents/AgentDisplayCard";
import type { AgentCard } from "@/lib/types";

const MyComponent = () => {
  const [expandedAgent, setExpandedAgent] = useState<string | null>(null);
  
  const agent: AgentCard = {
    name: "my-agent",
    display_name: "My Agent",
    description: "A helpful AI agent",
    version: "1.0.0",
    // ... other agent properties
  };

  return (
    <AgentDisplayCard
      agent={agent}
      isExpanded={expandedAgent === agent.name}
      onToggleExpand={() => setExpandedAgent(
        expandedAgent === agent.name ? null : agent.name
      )}
    />
  );
};
```

### AgentMeshCards.tsx
**Purpose:** Displays a collection of agent cards in a grid layout with search functionality
**Import:** `import { AgentMeshCards } from "@/lib/components/agents/AgentMeshCards"`

**Components:**
- `AgentMeshCards(agents: AgentCard[])` - Container component for multiple agent cards
  - Provides search input to filter agents by name/display name
  - Manages expanded state for individual cards
  - Shows empty states when no agents or no search results

**Usage Examples:**
```tsx
import { AgentMeshCards } from "@/lib/components/agents/AgentMeshCards";
import type { AgentCard } from "@/lib/types";

const AgentsPage = () => {
  const agents: AgentCard[] = [
    {
      name: "agent-1",
      display_name: "Agent One",
      description: "First agent",
      // ... other properties
    },
    // ... more agents
  ];

  return (
    <div>
      <h1>Available Agents</h1>
      <AgentMeshCards agents={agents} />
    </div>
  );
};
```

### LayoutSelector.tsx
**Purpose:** Provides a UI component for selecting different layout options from the plugin registry
**Import:** `import { LayoutSelector } from "@/lib/components/agents/LayoutSelector"`

**Components:**
- `LayoutSelector(currentLayout: string, onLayoutChange: (layout: string) => void, className?: string)` - Layout selection buttons
  - Fetches available layouts from plugin registry
  - Only renders if multiple layouts are available
  - Highlights currently active layout

**Usage Examples:**
```tsx
import { LayoutSelector } from "@/lib/components/agents/LayoutSelector";

const LayoutControls = () => {
  const [currentLayout, setCurrentLayout] = useState("mesh");

  return (
    <div className="toolbar">
      <LayoutSelector
        currentLayout={currentLayout}
        onLayoutChange={setCurrentLayout}
        className="ml-auto"
      />
    </div>
  );
};
```

**Dependencies:**
- Requires `@/lib/types` for `AgentCard` and `AgentTool` types
- Requires `@/lib/components/ui` for `Button` component
- Requires `@/lib/plugins` for plugin registry access
- Requires `@/lib/utils/format` for timestamp formatting
- Uses Lucide React icons for UI elements

# content_hash: 389c8b8aa05ca46d23d0ed55d89bb7b3f801d30f5c0844992ea7118d14c78953

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

## Section 8: frontend/src/lib/components/chat/artifact/artifact_llm.txt

**Source file:** `frontend/src/lib/components/chat/artifact/artifact_llm.txt`

# DEVELOPER GUIDE: artifact

## Quick Summary
The artifact directory contains React components for managing and displaying file artifacts in a chat interface. It provides functionality for viewing, downloading, deleting, sorting, and previewing various file types with version control support.

## Files Overview
- `ArtifactCard.tsx` - Main card component displaying artifact information with expand/collapse functionality
- `ArtifactDeleteAllDialog.tsx` - Modal dialog for batch deletion of all artifacts
- `ArtifactDeleteDialog.tsx` - Modal dialog for deleting individual artifacts
- `ArtifactDetails.tsx` - Component showing artifact metadata and action buttons
- `ArtifactMorePopover.tsx` - Popover menu with additional artifact actions (refresh, delete all)
- `ArtifactPanel.tsx` - Main panel container managing artifact list and preview views
- `ArtifactPreviewContent.tsx` - Component for rendering artifact content previews
- `ArtifactPreviewDownload.tsx` - Fallback component when preview is not available
- `ArtifactSortPopover.tsx` - Popover menu for sorting artifacts by name or date
- `ArtifactVersionNavigation.tsx` - Component for navigating between artifact versions

## Developer API Reference

### ArtifactCard.tsx
**Purpose:** Displays individual artifact information in a card format with expandable details
**Import:** `import { ArtifactCard } from "@/lib/components/chat/artifact/ArtifactCard"`

**Components:**
- `ArtifactCard(artifact: ArtifactInfo, isPreview?: boolean)` - Main artifact card component
  - Renders artifact icon, name, and metadata
  - Supports expand/collapse for detailed view
  - Shows schema information for structured data
  - Handles click events to open preview

**Usage Examples:**
```tsx
import { ArtifactCard } from "@/lib/components/chat/artifact/ArtifactCard";

// Basic usage
<ArtifactCard artifact={artifactInfo} />

// Preview mode
<ArtifactCard artifact={artifactInfo} isPreview={true} />
```

### ArtifactDeleteAllDialog.tsx
**Purpose:** Modal dialog for confirming batch deletion of all artifacts
**Import:** `import { ArtifactDeleteAllDialog } from "@/lib/components/chat/artifact/ArtifactDeleteAllDialog"`

**Components:**
- `ArtifactDeleteAllDialog()` - Batch delete confirmation dialog
  - Automatically selects all artifacts for deletion
  - Shows count of files to be deleted
  - Integrates with chat context for state management

**Usage Examples:**
```tsx
import { ArtifactDeleteAllDialog } from "@/lib/components/chat/artifact/ArtifactDeleteAllDialog";

// Include in your component tree
<ArtifactDeleteAllDialog />
```

### ArtifactDeleteDialog.tsx
**Purpose:** Modal dialog for confirming deletion of individual artifacts
**Import:** `import { ArtifactDeleteDialog } from "@/lib/components/chat/artifact/ArtifactDeleteDialog"`

**Components:**
- `ArtifactDeleteDialog()` - Single artifact delete confirmation dialog
  - Shows filename of artifact to be deleted
  - Provides cancel and confirm actions
  - Integrates with chat context state

**Usage Examples:**
```tsx
import { ArtifactDeleteDialog } from "@/lib/components/chat/artifact/ArtifactDeleteDialog";

// Include in your component tree
<ArtifactDeleteDialog />
```

### ArtifactDetails.tsx
**Purpose:** Displays artifact metadata and action buttons (download, delete, expand)
**Import:** `import { ArtifactDetails } from "@/lib/components/chat/artifact/ArtifactDetails"`

**Components:**
- `ArtifactDetails(artifactInfo: ArtifactInfo, isPreview?: boolean, isExpanded?: boolean, onDelete?: (artifact: ArtifactInfo) => void, onDownload?: (artifact: ArtifactInfo) => void, setIsExpanded?: (expanded: boolean) => void)` - Artifact details and actions component
  - Shows filename and last modified time
  - Provides version navigation for multi-version artifacts
  - Renders action buttons with hover effects

**Usage Examples:**
```tsx
import { ArtifactDetails } from "@/lib/components/chat/artifact/ArtifactDetails";

<ArtifactDetails 
  artifactInfo={artifact}
  isExpanded={expanded}
  onDelete={handleDelete}
  onDownload={handleDownload}
  setIsExpanded={setExpanded}
/>
```

### ArtifactMorePopover.tsx
**Purpose:** Popover menu with additional artifact management actions
**Import:** `import { MorePopover } from "@/lib/components/chat/artifact/ArtifactMorePopover"`

**Components:**
- `MorePopover(children: React.ReactNode)` - Popover with refresh and delete all actions
  - Provides refresh functionality for artifact list
  - Opens batch delete modal
  - Uses trigger children for activation

**Usage Examples:**
```tsx
import { MorePopover } from "@/lib/components/chat/artifact/ArtifactMorePopover";

<MorePopover>
  <Button variant="ghost">
    <Ellipsis className="h-5 w-5" />
  </Button>
</MorePopover>
```

### ArtifactPanel.tsx
**Purpose:** Main container component managing artifact list view and preview mode
**Import:** `import { ArtifactPanel } from "@/lib/components/chat/artifact/ArtifactPanel"`

**Components:**
- `ArtifactPanel()` - Main artifact management panel
  - Handles sorting and filtering of artifacts
  - Manages preview mode switching
  - Renders artifact list or preview content
  - Includes all dialog components

**Constants/Variables:**
- `sortFunctions: Record<SortOptionType, (a1: ArtifactInfo, a2: ArtifactInfo) => number>` - Sorting functions for different criteria

**Usage Examples:**
```tsx
import { ArtifactPanel } from "@/lib/components/chat/artifact/ArtifactPanel";

// Use as main artifact interface
<ArtifactPanel />
```

### ArtifactPreviewContent.tsx
**Purpose:** Renders preview content for artifacts or shows download option
**Import:** `import { ArtifactPreviewContent } from "@/lib/components/chat/artifact/ArtifactPreviewContent"`

**Components:**
- `ArtifactPreviewContent(artifact: ArtifactInfo)` - Preview content renderer
  - Determines if artifact can be previewed
  - Fetches and displays content using ContentRenderer
  - Shows loading states and error handling
  - Falls back to download option when preview unavailable

**Usage Examples:**
```tsx
import { ArtifactPreviewContent } from "@/lib/components/chat/artifact/ArtifactPreviewContent";

<ArtifactPreviewContent artifact={selectedArtifact} />
```

### ArtifactPreviewDownload.tsx
**Purpose:** Fallback component when artifact preview is not available
**Import:** `import { ArtifactPreviewDownload } from "@/lib/components/chat/artifact/ArtifactPreviewDownload"`

**Components:**
- `ArtifactPreviewDownload(artifact: ArtifactInfo, message: string)` - Download fallback component
  - Shows informational message about preview availability
  - Provides download button for the artifact
  - Used when file type cannot be previewed

**Usage Examples:**
```tsx
import { ArtifactPreviewDownload } from "@/lib/components/chat/artifact/ArtifactPreviewDownload";

<ArtifactPreviewDownload 
  artifact={artifact} 
  message="Preview not available for this file type" 
/>
```

### ArtifactSortPopover.tsx
**Purpose:** Popover menu for sorting artifacts by different criteria
**Import:** `import { SortPopover, SortOption, type SortOptionType } from "@/lib/components/chat/artifact/ArtifactSortPopover"`

**Components:**
- `SortPopover(currentSortOption: SortOptionType, onSortChange: (option: SortOptionType) => void, children: React.ReactNode)` - Sort options popover
  - Provides name and date sorting options
  - Shows current selection with checkmark
  - Triggers callback on option change

**Constants/Variables:**
- `SortOption: { NameAsc: "name_asc", NameDesc: "name_desc", DateAsc: "date_asc", DateDesc: "date_desc" }` - Available sort options
- `SortOptionType` - Type definition for sort options

**Functions:**
- `getSortOptionLabel(option: SortOptionType) -> string` - Returns human-readable label for sort option

**Usage Examples:**
```tsx
import { SortPopover, SortOption, type SortOptionType } from "@/lib/components/chat/artifact/ArtifactSortPopover";

const [sortOption, setSortOption] = useState<SortOptionType>(SortOption.DateDesc);

<SortPopover 
  currentSortOption={sortOption} 
  onSortChange={setSortOption}
>
  <Button variant="ghost">Sort By</Button>
</SortPopover>
```

### ArtifactVersionNavigation.tsx
**Purpose:** Component for navigating between different versions of an artifact
**Import:** `import { ArtifactVersionNavigation } from "@/lib/components/chat/artifact/ArtifactVersionNavigation"`

**Components:**
- `ArtifactVersionNavigation(artifactInfo: ArtifactInfo)` - Version navigation dropdown
  - Shows version selector when multiple versions exist
  - Integrates with chat context for version management
  - Renders nothing when only one version available

**Usage Examples:**
```tsx
import { ArtifactVersionNavigation } from "@/lib/components/chat/artifact/ArtifactVersionNavigation";

<ArtifactVersionNavigation artifactInfo={artifact} />
```

# content_hash: f5d67954c848ecd6fdebe5c7ab5ca2cd5f40c69043ee56df1af97178e198299b

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

## Section 9: frontend/src/lib/components/chat/chat_llm.txt

**Source file:** `frontend/src/lib/components/chat/chat_llm.txt`

# DEVELOPER GUIDE: chat

## Quick Summary
The chat directory provides a comprehensive React-based chat interface system with support for real-time messaging, file attachments, workflow visualization, and artifact management. The architecture consists of core chat components for input/output, session management, side panels for artifacts and workflows, and specialized subdirectories for file handling, content preview, and artifact management. Components integrate through React context for state management and provide a complete chat experience with drag-and-drop file support, content rendering, and workflow monitoring.

## Files and Subdirectories Overview
- **Direct files:**
  - `ChatInputArea.tsx` - Input component with file upload, agent selection, and message submission
  - `ChatMessage.tsx` - Message display component with content rendering and workflow integration
  - `ChatSessionDialog.tsx` - Modal dialog for creating new chat sessions
  - `ChatSessions.tsx` - Session list component (placeholder for multi-session support)
  - `ChatSidePanel.tsx` - Right side panel with files and workflow tabs
  - `LoadingMessageRow.tsx` - Loading indicator component for pending messages
  - `SessionSidePanel.tsx` - Left side panel for session management

- **Subdirectories:**
  - `artifact/` - Artifact management components for file viewing and organization
  - `file/` - File attachment display and utility components
  - `preview/` - Content rendering system for various file types and formats

## Developer API Reference

### Direct Files

#### ChatInputArea.tsx
**Purpose:** Main chat input component with file upload, agent selection, and message submission
**Import:** `import { ChatInputArea } from "@/lib/components/chat/ChatInputArea"`

**Components:**
- `ChatInputArea({ agents, scrollToBottom })` - Complete chat input interface
  - Handles text input with debouncing
  - Supports file drag-and-drop and paste
  - Provides agent selection dropdown
  - Manages submit/cancel states

#### ChatMessage.tsx
**Purpose:** Renders individual chat messages with content, files, and tool events
**Import:** `import { ChatMessage } from "@/lib/components/chat/ChatMessage"`

**Components:**
- `ChatMessage({ message, isLastWithTaskId })` - Complete message renderer
  - Displays text content with markdown support
  - Shows file attachments and uploads
  - Renders tool events and workflow buttons
  - Handles error states and embedded content

#### ChatSessionDialog.tsx
**Purpose:** Modal dialog for confirming new chat session creation
**Import:** `import { ChatSessionDialog } from "@/lib/components/chat/ChatSessionDialog"`

**Components:**
- `ChatSessionDialog({ isOpen, onClose })` - New session confirmation dialog
  - Warns about clearing current chat history
  - Integrates with chat context for session management

#### ChatSessions.tsx
**Purpose:** Displays current session with placeholder for future multi-session support
**Import:** `import { ChatSessions } from "@/lib/components/chat/ChatSessions"`

**Components:**
- `ChatSessions()` - Session list component
  - Shows current session preview
  - Placeholder for future multi-session functionality

#### ChatSidePanel.tsx
**Purpose:** Right side panel with tabs for files and workflow visualization
**Import:** `import { ChatSidePanel } from "@/lib/components/chat/ChatSidePanel"`

**Components:**
- `ChatSidePanel({ onCollapsedToggle, isSidePanelCollapsed, setIsSidePanelCollapsed, isSidePanelTransitioning })` - Tabbed side panel
  - Files tab with artifact management
  - Workflow tab with task visualization
  - Collapsible with icon-only mode

#### LoadingMessageRow.tsx
**Purpose:** Loading indicator for pending chat messages
**Import:** `import { LoadingMessageRow } from "@/lib/components/chat/LoadingMessageRow"`

**Components:**
- `LoadingMessageRow({ statusText, onViewWorkflow })` - Loading message display
  - Shows animated loading indicator
  - Optional status text display
  - Optional workflow button

#### SessionSidePanel.tsx
**Purpose:** Left side panel for session management and navigation
**Import:** `import { SessionSidePanel } from "@/lib/components/chat/SessionSidePanel"`

**Components:**
- `SessionSidePanel({ onToggle })` - Session management panel
  - New chat session button
  - Session list display
  - Collapsible panel functionality

### Subdirectory APIs

#### artifact/
**Purpose:** Comprehensive artifact management system for file viewing, organization, and version control
**Key Exports:** ArtifactPanel, ArtifactCard, ArtifactPreviewContent, ArtifactDeleteDialog, ArtifactSortPopover
**Import Examples:**
```tsx
import { ArtifactPanel } from "@/lib/components/chat/artifact/ArtifactPanel"
import { ArtifactCard } from "@/lib/components/chat/artifact/ArtifactCard"
```

#### file/
**Purpose:** File attachment display components and file type utilities
**Key Exports:** FileBadge, FileMessage, FileAttachmentMessage, getFileIcon
**Import Examples:**
```tsx
import { FileBadge, FileMessage } from "@/lib/components/chat/file/FileMessage"
import { getFileIcon } from "@/lib/components/chat/file/fileUtils"
```

#### preview/
**Purpose:** Content rendering system supporting multiple formats (markdown, HTML, images, CSV, etc.)
**Key Exports:** ContentRenderer, various specialized renderers
**Import Examples:**
```tsx
import { ContentRenderer } from "@/lib/components/chat/preview/ContentRenderer"
import { MarkdownRenderer, CsvRenderer } from "@/lib/components/chat/preview/Renderers"
```

## Complete Usage Guide

### 1. Basic Chat Interface Setup

```tsx
import React, { useState } from 'react';
import { 
  ChatInputArea, 
  ChatMessage, 
  ChatSidePanel, 
  SessionSidePanel 
} from '@/lib/components/chat';
import { useChatContext } from '@/lib/hooks';

function ChatInterface() {
  const { messages, agents } = useChatContext();
  const [isSidePanelCollapsed, setIsSidePanelCollapsed] = useState(false);
  const [isSessionPanelVisible, setIsSessionPanelVisible] = useState(true);

  const scrollToBottom = () => {
    // Implement scroll logic
  };

  return (
    <div className="flex h-screen">
      {/* Session Panel */}
      {isSessionPanelVisible && (
        <SessionSidePanel onToggle={() => setIsSessionPanelVisible(false)} />
      )}
      
      {/* Main Chat Area */}
      <div className="flex-1 flex flex-col">
        {/* Messages */}
        <div className="flex-1 overflow-y-auto p-4">
          {messages.map((message, index) => (
            <ChatMessage 
              key={message.metadata?.messageId || index}
              message={message}
              isLastWithTaskId={/* logic to determine */}
            />
          ))}
        </div>
        
        {/* Input Area */}
        <div className="p-4">
          <ChatInputArea 
            agents={agents}
            scrollToBottom={scrollToBottom}
          />
        </div>
      </div>
      
      {/* Side Panel */}
      <ChatSidePanel
        isSidePanelCollapsed={isSidePanelCollapsed}
        setIsSidePanelCollapsed={setIsSidePanelCollapsed}
        onCollapsedToggle={setIsSidePanelCollapsed}
        isSidePanelTransitioning={false}
      />
    </div>
  );
}
```

### 2. File Upload and Management

```tsx
import React from 'react';
import { ChatInputArea } from '@/lib/components/chat/ChatInputArea';
import { FileBadge } from '@/lib/components/chat/file/FileMessage';
import { ArtifactPanel } from '@/lib/components/chat/artifact/ArtifactPanel';

function FileManagementExample() {
  const agents = [
    { name: 'assistant', display_name: 'AI Assistant' }
  ];

  return (
    <div className="space-y-4">
      {/* File upload via chat input */}
      <ChatInputArea agents={agents} />
      
      {/* File badges for selected files */}
      <div className="flex gap-2">
        <FileBadge 
          fileName="document.pdf" 
          onRemove={() => console.log('Remove file')}
        />
        <FileBadge fileName="image.jpg" />
      </div>
      
      {/* Artifact management panel */}
      <div className="h-96 border rounded">
        <ArtifactPanel />
      </div>
    </div>
  );
}
```

### 3. Content Preview and Rendering

```tsx
import React, { useState } from 'react';
import { ChatMessage } from '@/lib/components/chat/ChatMessage';
import { ContentRenderer } from '@/lib/components/chat/preview/ContentRenderer';
import type { MessageFE } from '@/lib/types';

function ContentPreviewExample() {
  const [renderError, setRenderError] = useState<string | null>(null);

  const sampleMessage: MessageFE = {
    isUser: false,
    isError: false,
    isComplete: true,
    isStatusBubble: false,
    parts: [
      {
        kind: 'text',
        text: '# Analysis Results\n\nHere are the findings:\n\n```csv\nname,score\nAlice,95\nBob,87\n```'
      }
    ],
    metadata: { messageId: '1' }
  };

  return (
    <div className="space-y-4">
      {/* Message with embedded content */}
      <ChatMessage message={sampleMessage} />
      
      {/* Direct content rendering */}
      <div className="border p-4 rounded">
        <h3>CSV Data Preview</h3>
        <ContentRenderer
          content="name,score,grade\nAlice,95,A\nBob,87,B"
          rendererType="csv"
          setRenderError={setRenderError}
        />
        {renderError && <div className="text-red-500">{renderError}</div>}
      </div>
    </div>
  );
}
```

### 4. Session Management

```tsx
import React, { useState } from 'react';
import { 
  ChatSessions, 
  ChatSessionDialog, 
  SessionSidePanel 
} from '@/lib/components/chat';
import { useChatContext } from '@/lib/hooks';

function SessionManagementExample() {
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isPanelVisible, setIsPanelVisible] = useState(true);
  const { handleNewSession } = useChatContext();

  return (
    <div className="flex h-screen">
      {/* Session side panel */}
      {isPanelVisible && (
        <SessionSidePanel onToggle={() => setIsPanelVisible(false)} />
      )}
      
      {/* Main content */}
      <div className="flex-1 p-4">
        <button 
          onClick={() => setIsDialogOpen(true)}
          className="mb-4 px-4 py-2 bg-blue-500 text-white rounded"
        >
          New Session
        </button>
        
        {/* Current sessions */}
        <ChatSessions />
      </div>
      
      {/* New session dialog */}
      <ChatSessionDialog
        isOpen={isDialogOpen}
        onClose={() => setIsDialogOpen(false)}
      />
    </div>
  );
}
```

### 5. Workflow Integration

```tsx
import React from 'react';
import { ChatSidePanel, LoadingMessageRow } from '@/lib/components/chat';
import { useChatContext, useTaskContext } from '@/lib/hooks';

function WorkflowIntegrationExample() {
  const { setTaskIdInSidePanel, openSidePanelTab } = useChatContext();
  const { monitoredTasks } = useTaskContext();
  const [isSidePanelCollapsed, setIsSidePanelCollapsed] = useState(false);

  const handleViewWorkflow = (taskId: string) => {
    setTaskIdInSidePanel(taskId);
    openSidePanelTab('workflow');
  };

  return (
    <div className="flex h-screen">
      {/* Main chat area */}
      <div className="flex-1 p-4">
        {/* Loading message with workflow button */}
        <LoadingMessageRow
          statusText="Processing your request..."
          onViewWorkflow={() => handleViewWorkflow('task-123')}
        />
        
        {/* Task status */}
        <div className="mt-4">
          <h3>Active Tasks:</h3>
          {Object.entries(monitoredTasks).map(([taskId, task]) => (
            <div key={taskId} className="p-2 border rounded mb-2">
              <span>Task: {taskId}</span>
              <button 
                onClick={() => handleViewWorkflow(taskId)}
                className="ml-2 text-blue-500"
              >
                View Workflow
              </button>
            </div>
          ))}
        </div>
      </div>
      
      {/* Side panel with workflow visualization */}
      <ChatSidePanel
        isSidePanelCollapsed={isSidePanelCollapsed}
        setIsSidePanelCollapsed={setIsSidePanelCollapsed}
        onCollapsedToggle={setIsSidePanelCollapsed}
        isSidePanelTransitioning={false}
      />
    </div>
  );
}
```

### 6. Complete Chat Application

```tsx
import React, { useState, useRef, useEffect } from 'react';
import {
  ChatInputArea,
  ChatMessage,
  ChatSidePanel,
  SessionSidePanel,
  LoadingMessageRow
} from '@/lib/components/chat';
import { useChatContext, useTaskContext } from '@/lib/hooks';

function CompleteChatApp() {
  const {
    messages,
    agents,
    isResponding,
    activeSidePanelTab,
    setActiveSidePanelTab
  } = useChatContext();
  
  const { monitoredTasks } = useTaskContext();
  
  const [isSidePanelCollapsed, setIsSidePanelCollapsed] = useState(false);
  const [isSessionPanelVisible, setIsSessionPanelVisible] = useState(true);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  return (
    <div className="flex h-screen bg-gray-50">
      {/* Session Management Panel */}
      {isSessionPanelVisible && (
        <div className="w-80 border-r bg-white">
          <SessionSidePanel 
            onToggle={() => setIsSessionPanelVisible(false)} 
          />
        </div>
      )}

      {/* Main Chat Interface */}
      <div className="flex-1 flex flex-col min-w-0">
        {/* Chat Header */}
        <div className="border-b bg-white p-4">
          <div className="flex items-center justify-between">
            <h1 className="text-xl font-semibold">Chat Assistant</h1>
            <div className="flex gap-2">
              <button
                onClick={() => setActiveSidePanelTab('files')}
                className={`px-3 py-1 rounded ${
                  activeSidePanelTab === 'files' ? 'bg-blue-100' : 'bg-gray

# content_hash: 73d2ebe86c557acec59484f1152df17adc166e235abba69778fa369531b27943

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

## Section 10: frontend/src/lib/components/chat/file/file_llm.txt

**Source file:** `frontend/src/lib/components/chat/file/file_llm.txt`

# DEVELOPER GUIDE: file

## Quick Summary
This directory contains React components for displaying and managing file attachments in a chat interface. It provides UI components for file badges, file messages with preview/download functionality, and utilities for determining appropriate file icons based on file types.

## Files Overview
- **FileBadge.tsx** - Removable badge component for displaying file names with optional delete functionality
- **FileMessage.tsx** - Message component for displaying file attachments with preview and download actions
- **fileUtils.tsx** - Utility functions for determining appropriate file icons based on file type and MIME type

## Developer API Reference

### FileBadge.tsx
**Purpose:** Renders a badge component displaying a file name with an optional remove button
**Import:** `import { FileBadge } from "@/lib/components/chat/file/FileBadge"`

**Components:**
- `FileBadge({ fileName, onRemove })` - A badge component that displays a file name with optional removal functionality
  - `fileName: string` - The name of the file to display
  - `onRemove?: () => void` - Optional callback function called when the remove button is clicked

**Usage Examples:**
```tsx
import { FileBadge } from "@/lib/components/chat/file/FileBadge";

// Basic file badge without remove functionality
<FileBadge fileName="document.pdf" />

// File badge with remove functionality
<FileBadge 
  fileName="image.jpg" 
  onRemove={() => console.log("File removed")} 
/>
```

### FileMessage.tsx
**Purpose:** Renders file attachment messages with preview and download capabilities
**Import:** `import { FileAttachmentMessage, FileMessage } from "@/lib/components/chat/file/FileMessage"`

**Components:**
- `FileAttachmentMessage({ fileAttachment })` - Component for displaying file attachment messages
  - `fileAttachment: FileAttachment` - The file attachment object to display

- `FileMessage({ filename, className, onDownload })` - Generic file message component with preview and download actions
  - `filename: string` - The name of the file to display
  - `className?: string` - Optional CSS class name for styling
  - `onDownload?: () => void` - Optional callback function for download action

**Usage Examples:**
```tsx
import { FileAttachmentMessage, FileMessage } from "@/lib/components/chat/file/FileMessage";

// File attachment message
<FileAttachmentMessage fileAttachment={myFileAttachment} />

// Generic file message with download
<FileMessage 
  filename="report.pdf"
  className="my-custom-class"
  onDownload={() => handleDownload()}
/>

// Simple file message without download
<FileMessage filename="data.csv" />
```

### fileUtils.tsx
**Purpose:** Provides utility functions for determining appropriate file icons based on file types
**Import:** `import { getFileIcon } from "@/lib/components/chat/file/fileUtils"`

**Functions:**
- `getFileIcon(artifact: ArtifactInfo | undefined, className?: string) -> JSX.Element` - Returns the appropriate file icon component based on the artifact's file type and MIME type
  - `artifact: ArtifactInfo | undefined` - The artifact information containing filename and MIME type
  - `className?: string` - Optional CSS class for the icon (defaults to "h-4 w-4")

**Usage Examples:**
```tsx
import { getFileIcon } from "@/lib/components/chat/file/fileUtils";

// Get icon for an artifact
const icon = getFileIcon(myArtifact);

// Get icon with custom styling
const styledIcon = getFileIcon(myArtifact, "h-6 w-6 text-blue-500");

// Handle undefined artifact (returns generic file icon)
const defaultIcon = getFileIcon(undefined);

// Use in a component
function MyFileComponent({ artifact }) {
  const FileIcon = getFileIcon(artifact);
  return (
    <div>
      {FileIcon}
      <span>{artifact?.filename}</span>
    </div>
  );
}
```

# content_hash: 50df4f2d4916ea3ab442d73988664933c5b1cf4938b6ca84bca672f9ed741ee9

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

## Section 11: frontend/src/lib/components/chat/preview/Renderers/Renderers_llm.txt

**Source file:** `frontend/src/lib/components/chat/preview/Renderers/Renderers_llm.txt`

# DEVELOPER GUIDE: Renderers

## Quick Summary
The Renderers directory contains React components for rendering different types of content in a chat preview interface. Each renderer handles a specific content type (audio, images, CSV, HTML, etc.) and provides appropriate display and interaction capabilities.

## Files Overview
- **AudioRenderer.tsx** - Renders audio content with playback controls
- **CsvRenderer.tsx** - Parses and displays CSV data in a table format
- **HTMLRenderer.tsx** - Renders HTML content in a sandboxed iframe
- **ImageRenderer.tsx** - Displays images from base64 data
- **MarkdownRenderer.tsx** - Renders Markdown content with copy functionality
- **MermaidRenderer.tsx** - Renders Mermaid diagrams with pan/zoom controls
- **StructuredDataRenderer.tsx** - Displays JSON/YAML data with structured and raw views
- **TextRenderer.tsx** - Displays plain text with copy functionality

## Developer API Reference

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

**Components:**
- `AudioRenderer(props: BaseRendererProps)` - Audio player component
  - Accepts base64 audio content and MIME type
  - Provides standard audio controls (play, pause, seek, volume)
  - Handles loading and error states

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

<AudioRenderer 
  content="base64AudioData" 
  mime_type="audio/mpeg" 
  setRenderError={setError} 
/>
```

### CsvRenderer.tsx
**Purpose:** Parses CSV content and displays it in a responsive table
**Import:** `import { CsvRenderer } from './Renderers/CsvRenderer'`

**Components:**
- `CsvRenderer(props: BaseRendererProps)` - CSV table component
  - Parses CSV with support for quoted fields and line breaks
  - Creates responsive table with sticky headers
  - Handles empty cells and malformed data

**Functions:**
- `parseCsv(csvString: string) -> string[][]` - Internal CSV parser function

**Usage Examples:**
```tsx
import { CsvRenderer } from './Renderers/CsvRenderer';

<CsvRenderer 
  content="name,age,city\nJohn,30,NYC\nJane,25,LA" 
  setRenderError={setError} 
/>
```

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

**Components:**
- `HtmlRenderer(props: BaseRendererProps)` - HTML preview component
  - Wraps JavaScript in IIFEs for error handling
  - Uses iframe sandbox for security
  - Supports interactive HTML content

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

<HtmlRenderer 
  content="<html><body><h1>Hello World</h1></body></html>" 
  setRenderError={setError} 
/>
```

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

**Components:**
- `ImageRenderer(props: BaseRendererProps)` - Image display component
  - Converts base64 data to data URLs
  - Responsive image sizing with object-contain
  - Handles image loading errors

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

<ImageRenderer 
  content="base64ImageData" 
  mime_type="image/png" 
  setRenderError={setError} 
/>
```

### MarkdownRenderer.tsx
**Purpose:** Renders Markdown content with copy functionality
**Import:** `import { MarkdownRenderer } from './Renderers/MarkdownRenderer'`

**Components:**
- `MarkdownRenderer(props: BaseRendererProps)` - Markdown display component
  - Uses MarkdownHTMLConverter for rendering
  - Includes keyboard copy functionality via useCopy hook
  - Supports text selection

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

<MarkdownRenderer 
  content="# Hello\n\nThis is **markdown** content." 
  setRenderError={setError} 
/>
```

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

**Components:**
- `MermaidRenderer(props: BaseRendererProps)` - Interactive diagram component
  - Sanitizes Mermaid content for security
  - Provides pan and zoom functionality
  - Includes reset view controls
  - Loads Mermaid.js from CDN in iframe

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

<MermaidRenderer 
  content="graph TD; A-->B; A-->C; B-->D; C-->D;" 
  setRenderError={setError} 
/>
```

### StructuredDataRenderer.tsx
**Purpose:** Displays JSON/YAML data with structured and raw text views
**Import:** `import { StructuredDataRenderer } from './Renderers/StructuredDataRenderer'`

**Components:**
- `StructuredDataRenderer(props: StructuredDataRendererProps)` - Dual-view data component
  - `rendererType: "json" | "yaml"` - Specifies data format
  - Toggle between structured JSONViewer and raw text
  - Handles parsing errors gracefully
  - Uses js-yaml library for YAML parsing

**Usage Examples:**
```tsx
import { StructuredDataRenderer } from './Renderers/StructuredDataRenderer';

<StructuredDataRenderer 
  content='{"name": "John", "age": 30}' 
  rendererType="json"
  setRenderError={setError} 
/>

<StructuredDataRenderer 
  content="name: John\nage: 30" 
  rendererType="yaml"
  setRenderError={setError} 
/>
```

### TextRenderer.tsx
**Purpose:** Displays plain text with copy functionality and custom styling
**Import:** `import { TextRenderer } from './Renderers/TextRenderer'`

**Components:**
- `TextRenderer(props: TextRendererProps)` - Plain text display component
  - `className?: string` - Optional CSS classes
  - Preserves whitespace and line breaks
  - Includes keyboard copy functionality
  - Supports text selection

**Usage Examples:**
```tsx
import { TextRenderer } from './Renderers/TextRenderer';

<TextRenderer 
  content="Plain text content with\nline breaks preserved" 
  setRenderError={setError}
  className="custom-text-styles" 
/>
```

### Common Types
**BaseRendererProps Interface:**
```typescript
interface BaseRendererProps {
  content: string;
  mime_type?: string;
  setRenderError: (error: string | null) => void;
}
```

All renderers accept these base properties for consistent error handling and content display.

# content_hash: dd9ff3dcaccc3990cca21e622b81463c15a4bf56d371ec6f49465dd51b48428a

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

## Section 12: frontend/src/lib/components/chat/preview/preview_llm.txt

**Source file:** `frontend/src/lib/components/chat/preview/preview_llm.txt`

# DEVELOPER GUIDE: preview

## Quick Summary
The preview directory provides a comprehensive content rendering system for chat interfaces. It consists of a main `ContentRenderer` component that acts as a router, delegating to specialized renderer components in the `Renderers` subdirectory based on content type. The architecture supports multiple content formats including text, markdown, HTML, images, audio, CSV, JSON/YAML, and Mermaid diagrams.

## Files and Subdirectories Overview
- **Direct files:**
  - `ContentRenderer.tsx` - Main routing component that selects appropriate renderer based on content type
- **Subdirectories:**
  - `Renderers/` - Collection of specialized renderer components for different content types

## Developer API Reference

### Direct Files

#### ContentRenderer.tsx
**Purpose:** Central routing component that selects and renders appropriate content renderer based on type
**Import:** `import { ContentRenderer } from 'frontend/src/lib/components/chat/preview/ContentRenderer'`

**Components:**
- `ContentRenderer(props: ContentRendererProps)` - Main content routing component
  - Routes content to appropriate specialized renderer
  - Supports csv, mermaid, html, json, yaml, image, markdown, audio, and text content
  - Falls back to TextRenderer for unknown types

**Interfaces:**
- `ContentRendererProps` - Props interface for ContentRenderer
  - `content: string` - The content to render
  - `rendererType: string` - Type of renderer to use
  - `mime_type?: string` - Optional MIME type for binary content
  - `setRenderError: (error: string | null) => void` - Error callback

### Subdirectory APIs

#### Renderers/
**Purpose:** Provides specialized renderer components for different content types
**Key Exports:** AudioRenderer, CsvRenderer, HtmlRenderer, ImageRenderer, MarkdownRenderer, MermaidRenderer, StructuredDataRenderer, TextRenderer
**Import Examples:**
```tsx
import { AudioRenderer, ImageRenderer, MarkdownRenderer } from 'frontend/src/lib/components/chat/preview/Renderers'
import { CsvRenderer } from 'frontend/src/lib/components/chat/preview/Renderers/CsvRenderer'
```

**Main Components:**
- `AudioRenderer` - HTML5 audio player with controls
- `CsvRenderer` - Table display for CSV data
- `HtmlRenderer` - Sandboxed HTML content display
- `ImageRenderer` - Base64 image display
- `MarkdownRenderer` - Markdown content with copy functionality
- `MermaidRenderer` - Interactive diagram rendering
- `StructuredDataRenderer` - JSON/YAML data viewer
- `TextRenderer` - Plain text with copy functionality

## Complete Usage Guide

### 1. Basic Content Rendering
The most common usage is through the main ContentRenderer component:

```tsx
import React, { useState } from 'react';
import { ContentRenderer } from 'frontend/src/lib/components/chat/preview/ContentRenderer';

function ChatMessage() {
  const [renderError, setRenderError] = useState<string | null>(null);
  
  return (
    <div>
      <ContentRenderer
        content="# Hello World\n\nThis is **markdown** content."
        rendererType="markdown"
        setRenderError={setRenderError}
      />
      {renderError && <div className="error">{renderError}</div>}
    </div>
  );
}
```

### 2. Direct Renderer Usage
You can also use individual renderers directly:

```tsx
import React, { useState } from 'react';
import { 
  MarkdownRenderer, 
  CsvRenderer, 
  ImageRenderer 
} from 'frontend/src/lib/components/chat/preview/Renderers';

function DirectRendererExample() {
  const [renderError, setRenderError] = useState<string | null>(null);
  
  return (
    <div>
      {/* Markdown content */}
      <MarkdownRenderer
        content="## Data Analysis\n\nResults show significant improvement."
        setRenderError={setRenderError}
      />
      
      {/* CSV data */}
      <CsvRenderer
        content="name,score,grade\nAlice,95,A\nBob,87,B\nCharlie,92,A"
        setRenderError={setRenderError}
      />
      
      {/* Image content */}
      <ImageRenderer
        content="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
        mime_type="image/png"
        setRenderError={setRenderError}
      />
    </div>
  );
}
```

### 3. Working with Different Content Types

```tsx
import React, { useState } from 'react';
import { ContentRenderer } from 'frontend/src/lib/components/chat/preview/ContentRenderer';

function MultiContentExample() {
  const [renderError, setRenderError] = useState<string | null>(null);
  
  const examples = [
    {
      type: 'json',
      content: '{"users": [{"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}]}'
    },
    {
      type: 'mermaid',
      content: 'graph TD; A[Start] --> B{Decision}; B -->|Yes| C[Action 1]; B -->|No| D[Action 2];'
    },
    {
      type: 'html',
      content: '<div style="padding: 20px; background: #f0f0f0;"><h2>Interactive HTML</h2><button onclick="alert(\'Hello!\')">Click me</button></div>'
    },
    {
      type: 'csv',
      content: 'Product,Price,Stock\n"Laptop",999.99,15\n"Mouse",29.99,50\n"Keyboard",79.99,30'
    }
  ];
  
  return (
    <div>
      {examples.map((example, index) => (
        <div key={index} style={{ marginBottom: '20px', border: '1px solid #ccc', padding: '10px' }}>
          <h3>Content Type: {example.type}</h3>
          <ContentRenderer
            content={example.content}
            rendererType={example.type}
            setRenderError={setRenderError}
          />
        </div>
      ))}
      {renderError && <div className="error">Render Error: {renderError}</div>}
    </div>
  );
}
```

### 4. Binary Content Handling

```tsx
import React, { useState } from 'react';
import { ContentRenderer } from 'frontend/src/lib/components/chat/preview/ContentRenderer';

function BinaryContentExample() {
  const [renderError, setRenderError] = useState<string | null>(null);
  
  return (
    <div>
      {/* Audio content */}
      <ContentRenderer
        content="base64AudioDataHere"
        rendererType="audio"
        mime_type="audio/mpeg"
        setRenderError={setRenderError}
      />
      
      {/* Image content */}
      <ContentRenderer
        content="base64ImageDataHere"
        rendererType="image"
        mime_type="image/jpeg"
        setRenderError={setRenderError}
      />
    </div>
  );
}
```

### 5. Error Handling Pattern

```tsx
import React, { useState, useCallback } from 'react';
import { ContentRenderer } from 'frontend/src/lib/components/chat/preview/ContentRenderer';

function ErrorHandlingExample() {
  const [renderError, setRenderError] = useState<string | null>(null);
  
  const handleRenderError = useCallback((error: string | null) => {
    setRenderError(error);
    if (error) {
      console.error('Content rendering failed:', error);
      // Could also send to error tracking service
    }
  }, []);
  
  const clearError = () => setRenderError(null);
  
  return (
    <div>
      {renderError && (
        <div className="error-banner" style={{ background: '#fee', padding: '10px', marginBottom: '10px' }}>
          <strong>Rendering Error:</strong> {renderError}
          <button onClick={clearError} style={{ marginLeft: '10px' }}>Dismiss</button>
        </div>
      )}
      
      <ContentRenderer
        content="invalid json content {"
        rendererType="json"
        setRenderError={handleRenderError}
      />
    </div>
  );
}
```

### 6. Custom Styling with TextRenderer

```tsx
import React, { useState } from 'react';
import { TextRenderer } from 'frontend/src/lib/components/chat/preview/Renderers/TextRenderer';

function StyledTextExample() {
  const [renderError, setRenderError] = useState<string | null>(null);
  
  return (
    <div>
      <TextRenderer
        content="This is custom styled text content\nwith preserved line breaks"
        setRenderError={setRenderError}
        className="custom-text-renderer"
      />
      
      <style jsx>{`
        .custom-text-renderer {
          font-family: 'Courier New', monospace;
          background-color: #f8f8f8;
          border: 1px solid #ddd;
          border-radius: 4px;
          padding: 12px;
        }
      `}</style>
    </div>
  );
}
```

This preview system provides a flexible, extensible architecture for rendering various content types in chat interfaces, with proper error handling and consistent APIs across all renderer components.

# content_hash: 5741db4c1ab64b8191f838a52d66ada58e744b5b60ab1ccf0e3f3409de821b6d

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

## Section 13: frontend/src/lib/components/common/common_llm.txt

**Source file:** `frontend/src/lib/components/common/common_llm.txt`

# DEVELOPER GUIDE: common

## Quick Summary
The `common` directory contains reusable UI components that provide core functionality across the application. It includes a markdown-to-HTML converter with sanitization and a flexible message banner component for displaying alerts and notifications.

## Files Overview
- `MarkdownHTMLConverter.tsx` - Converts markdown text to sanitized HTML React elements with theme styling
- `MessageBanner.tsx` - Displays styled alert messages with icons and optional dismiss functionality

## Developer API Reference

### MarkdownHTMLConverter.tsx
**Purpose:** Converts markdown strings to sanitized HTML React elements with proper theme styling and security measures
**Import:** `import { MarkdownHTMLConverter } from "@/lib/components/common/MarkdownHTMLConverter"`

**Components:**
- `MarkdownHTMLConverter({ children, className }: MarkdownHTMLConverterProps)` - React component that renders markdown as HTML
  - `children?: string` - The markdown string to convert and render
  - `className?: string` - Additional CSS classes to apply to the wrapper div

**Usage Examples:**
```tsx
import { MarkdownHTMLConverter } from "@/lib/components/common/MarkdownHTMLConverter";

// Basic markdown rendering
<MarkdownHTMLConverter>
  {`# Hello World\n\nThis is **bold** text with a [link](https://example.com)`}
</MarkdownHTMLConverter>

// With custom styling
<MarkdownHTMLConverter className="my-custom-class">
  {markdownContent}
</MarkdownHTMLConverter>

// Handles empty/null content gracefully
<MarkdownHTMLConverter>
  {null} {/* Returns null, no error */}
</MarkdownHTMLConverter>
```

### MessageBanner.tsx
**Purpose:** Displays styled alert messages with variant-based theming, icons, and optional dismiss functionality
**Import:** `import { MessageBanner } from "@/lib/components/common/MessageBanner"`

**Components:**
- `MessageBanner({ variant, message, dismissible, onDismiss, className, ...props }: MessageBannerProps)` - Alert banner component
  - `variant?: "error" | "warning" | "info" | "success"` - Visual style variant (default: "error")
  - `message: string` - The message text to display
  - `dismissible?: boolean` - Whether to show dismiss button (default: false)
  - `onDismiss?: () => void` - Callback function when dismiss button is clicked
  - `className?: string` - Additional CSS classes
  - `...props` - Standard HTML div attributes

**Types:**
- `MessageBannerProps` - Interface extending React.HTMLAttributes<HTMLDivElement> with banner-specific props

**Usage Examples:**
```tsx
import { MessageBanner } from "@/lib/components/common/MessageBanner";

// Basic error message
<MessageBanner message="Something went wrong!" />

// Success message with dismiss
<MessageBanner 
  variant="success" 
  message="Operation completed successfully!" 
  dismissible 
  onDismiss={() => console.log('Dismissed')} 
/>

// Warning message
<MessageBanner 
  variant="warning" 
  message="Please check your input" 
/>

// Info message with custom styling
<MessageBanner 
  variant="info" 
  message="New features available" 
  className="mb-4"
/>
```

# content_hash: 0f5040312fe2c71a23b3b1d44e0be23bbd8b1255b603e87d294611730215830d

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

## Section 14: frontend/src/lib/components/components_llm.txt

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

# DEVELOPER GUIDE: components

## Quick Summary
The components directory provides a comprehensive React component library for building modern web applications. It combines specialized feature components (activities, agents, chat, pages) with a complete UI design system. The architecture follows a modular approach with direct files for core functionality and subdirectories for specialized domains. Components integrate through React context for state management and provide features like workflow visualization, agent management, real-time chat, and a complete design system built on Radix UI primitives.

## Files and Subdirectories Overview
- **Direct files:** None - all functionality is organized in subdirectories
- **Subdirectories:**
  - `activities/` - React-based workflow visualization with flow charts and step tracking
  - `agents/` - Agent management components with card-based interfaces
  - `chat/` - Complete chat interface with real-time messaging and file attachments
  - `common/` - Reusable utilities like markdown converter and message banners
  - `header/` - Navigation header components with tabs and actions
  - `jsonViewer/` - JSON data visualization with theme support
  - `navigation/` - Sidebar navigation system with theme toggle
  - `pages/` - Top-level page components for major application sections
  - `toast/` - Toast notification system
  - `ui/` - Comprehensive design system and UI component library

## Developer API Reference

### Subdirectory APIs

#### activities/
**Purpose:** React-based visualization system for agent workflow activities with flow charts and step tracking
**Key Exports:** FlowChartPanel, FlowChartDetails, VisualizerStepCard, custom React Flow nodes and edges
**Import Examples:**
```typescript
import { FlowChartPanel } from '@/lib/components/activities/FlowChartPanel'
import { VisualizerStepCard } from '@/lib/components/activities/VisualizerStepCard'
import GenericAgentNode from '@/lib/components/activities/FlowChart/customNodes/GenericAgentNode'
```

#### agents/
**Purpose:** Agent management components for displaying and managing agent information in card-based interfaces
**Key Exports:** AgentDisplayCard, AgentMeshCards, LayoutSelector
**Import Examples:**
```tsx
import { AgentDisplayCard } from "@/lib/components/agents/AgentDisplayCard"
import { AgentMeshCards } from "@/lib/components/agents/AgentMeshCards"
import { LayoutSelector } from "@/lib/components/agents/LayoutSelector"
```

#### chat/
**Purpose:** Comprehensive chat interface system with real-time messaging, file attachments, and workflow visualization
**Key Exports:** ChatInputArea, ChatMessage, ChatSidePanel, SessionSidePanel, artifact management, file handling, content preview
**Import Examples:**
```tsx
import { ChatInputArea, ChatMessage, ChatSidePanel } from '@/lib/components/chat'
import { ArtifactPanel } from "@/lib/components/chat/artifact/ArtifactPanel"
import { ContentRenderer } from "@/lib/components/chat/preview/ContentRenderer"
```

#### common/
**Purpose:** Reusable utility components including markdown converter and message banners
**Key Exports:** MarkdownHTMLConverter, MessageBanner
**Import Examples:**
```tsx
import { MarkdownHTMLConverter } from "@/lib/components/common/MarkdownHTMLConverter"
import { MessageBanner } from "@/lib/components/common/MessageBanner"
```

#### header/
**Purpose:** Navigation header components with tab navigation and action buttons
**Key Exports:** Header component with tab and action support
**Import Examples:**
```tsx
import { Header, Tab } from "lib/components/header/Header"
```

#### jsonViewer/
**Purpose:** JSON data visualization with theme-aware styling and collapsible tree structure
**Key Exports:** JSONViewer component
**Import Examples:**
```tsx
import { JSONViewer } from "@/lib/components/jsonViewer/JSONViewer"
```

#### navigation/
**Purpose:** Complete sidebar navigation system with header, navigation buttons, and theme toggle
**Key Exports:** NavigationSidebar, NavigationButton, NavigationHeader, ToggleThemeButton
**Import Examples:**
```tsx
import { NavigationSidebar } from "@/lib/components/navigation"
import { NavigationButton } from "@/lib/components/navigation"
```

#### pages/
**Purpose:** Top-level page components that serve as main application views
**Key Exports:** AgentMeshPage, ChatPage
**Import Examples:**
```tsx
import { AgentMeshPage } from "@/lib/components/pages/AgentMeshPage"
import { ChatPage } from "@/lib/components/pages/ChatPage"
```

#### toast/
**Purpose:** Toast notification system for displaying temporary messages
**Key Exports:** Toast component with type-based styling
**Import Examples:**
```tsx
import { Toast } from "path/to/toast/Toast"
```

#### ui/
**Purpose:** Comprehensive design system and UI component library built on Radix UI primitives
**Key Exports:** Complete set of UI components including buttons, cards, dialogs, forms, navigation, and specialized chat components
**Import Examples:**
```tsx
import { Button } from "@/lib/components/ui/button"
import { Card, CardHeader, CardContent } from "@/lib/components/ui/card"
import { Dialog, DialogContent, DialogHeader } from "@/lib/components/ui/dialog"
import { ChatBubble } from "@/lib/components/ui/chat/chat-bubble"
```

## Complete Usage Guide

### 1. Building a Complete Application Layout

```tsx
import React, { useState } from 'react';
import { NavigationSidebar } from '@/lib/components/navigation';
import { Header } from '@/lib/components/header/Header';
import { ChatPage } from '@/lib/components/pages/ChatPage';
import { AgentMeshPage } from '@/lib/components/pages/AgentMeshPage';
import { Home, MessageSquare, Users, Settings } from 'lucide-react';

function App() {
  const [activeItem, setActiveItem] = useState('chat');

  const navigationItems = [
    { id: 'home', label: 'Home', icon: Home },
    { id: 'chat', label: 'Chat', icon: MessageSquare },
    { id: 'agents', label: 'Agents', icon: Users },
    { id: 'settings', label: 'Settings', icon: Settings }
  ];

  const bottomItems = [
    { id: 'theme-toggle', label: 'Toggle Theme', icon: Settings }
  ];

  const renderContent = () => {
    switch (activeItem) {
      case 'chat':
        return <ChatPage />;
      case 'agents':
        return <AgentMeshPage />;
      default:
        return <div className="p-8">Page content for {activeItem}</div>;
    }
  };

  return (
    <div className="flex h-screen bg-gray-50 dark:bg-gray-900">
      {/* Navigation Sidebar */}
      <NavigationSidebar
        items={navigationItems}
        bottomItems={bottomItems}
        activeItem={activeItem}
        onItemChange={setActiveItem}
        onHeaderClick={() => setActiveItem('home')}
      />

      {/* Main Content */}
      <div className="flex-1 flex flex-col min-w-0">
        <Header
          title={navigationItems.find(item => item.id === activeItem)?.label || 'Application'}
          buttons={[
            <Button key="action" variant="outline">Action</Button>
          ]}
        />
        
        <main className="flex-1 overflow-hidden">
          {renderContent()}
        </main>
      </div>
    </div>
  );
}
```

### 2. Chat Interface with Workflow Visualization

```tsx
import React, { useState } from 'react';
import { 
  ChatInputArea, 
  ChatMessage, 
  ChatSidePanel 
} from '@/lib/components/chat';
import { FlowChartPanel } from '@/lib/components/activities/FlowChartPanel';
import { MessageBanner } from '@/lib/components/common/MessageBanner';
import { useChatContext, useTaskContext } from '@/lib/hooks';

function ChatWithWorkflow() {
  const { messages, agents, isResponding } = useChatContext();
  const { processedSteps } = useTaskContext();
  const [showWorkflow, setShowWorkflow] = useState(false);
  const [error, setError] = useState<string | null>(null);

  return (
    <div className="h-screen flex flex-col">
      {/* Error Banner */}
      {error && (
        <MessageBanner
          variant="error"
          message={error}
          dismissible
          onDismiss={() => setError(null)}
        />
      )}

      <div className="flex-1 flex overflow-hidden">
        {/* Chat Area */}
        <div className="flex-1 flex flex-col">
          {/* Messages */}
          <div className="flex-1 overflow-y-auto p-4 space-y-4">
            {messages.map((message, index) => (
              <ChatMessage
                key={message.metadata?.messageId || index}
                message={message}
                isLastWithTaskId={false}
              />
            ))}
          </div>

          {/* Input */}
          <div className="p-4 border-t">
            <ChatInputArea agents={agents} />
          </div>
        </div>

        {/* Workflow Panel */}
        {showWorkflow && (
          <div className="w-1/2 border-l">
            <div className="h-full flex flex-col">
              <div className="p-4 border-b">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-semibold">Workflow</h3>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setShowWorkflow(false)}
                  >
                    ✕
                  </Button>
                </div>
              </div>
              <div className="flex-1">
                <FlowChartPanel
                  processedSteps={processedSteps}
                  isRightPanelVisible={true}
                  isSidePanelTransitioning={false}
                />
              </div>
            </div>
          </div>
        )}

        {/* Side Panel */}
        <ChatSidePanel
          isSidePanelCollapsed={false}
          setIsSidePanelCollapsed={() => {}}
          onCollapsedToggle={() => {}}
          isSidePanelTransitioning={false}
        />
      </div>

      {/* Workflow Toggle */}
      {!showWorkflow && (
        <Button
          className="fixed bottom-4 right-4"
          onClick={() => setShowWorkflow(true)}
        >
          View Workflow
        </Button>
      )}
    </div>
  );
}
```

### 3. Agent Management Dashboard

```tsx
import React, { useState } from 'react';
import { AgentMeshCards, LayoutSelector } from '@/lib/components/agents';
import { Header } from '@/lib/components/header/Header';
import { JSONViewer } from '@/lib/components/jsonViewer/JSONViewer';
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle 
} from '@/lib/components/ui/dialog';
import type { AgentCard } from '@/lib/types';

function AgentDashboard() {
  const [selectedAgent, setSelectedAgent] = useState<AgentCard | null>(null);
  const [layout, setLayout] = useState('mesh');
  const [agents, setAgents] = useState<AgentCard[]>([]);

  const tabs = [
    { id: 'overview', label: 'Overview', isActive: true, onClick: () => {} },
    { id: 'details', label: 'Details', isActive: false, onClick: () => {} }
  ];

  return (
    <div className="h-screen flex flex-col">
      <Header
        title="Agent Management"
        tabs={tabs}
        buttons={[
          <LayoutSelector
            key="layout"
            currentLayout={layout}
            onLayoutChange={setLayout}
          />,
          <Button key="add" variant="default">
            Add Agent
          </Button>
        ]}
      />

      <main className="flex-1 overflow-hidden p-6">
        <AgentMeshCards agents={agents} />
      </main>

      {/* Agent Details Dialog */}
      <Dialog open={!!selectedAgent} onOpenChange={() => setSelectedAgent(null)}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{selectedAgent?.display_name || selectedAgent?.name}</DialogTitle>
          </DialogHeader>
          
          {selectedAgent && (
            <div className="space-y-4">
              <div>
                <h4 className="font-medium mb-2">Configuration</h4>
                <JSONViewer data={selectedAgent} maxDepth={2} />
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
```

### 4. Data Visualization with Content Rendering

```tsx
import React, { useState } from 'react';
import { ContentRenderer } from '@/lib/components/chat/preview/ContentRenderer';
import { JSONViewer } from '@/lib/components/jsonViewer/JSONViewer';
import { MarkdownHTMLConverter } from '@/lib/components/common/MarkdownHTMLConverter';
import { 
  Tabs, 
  TabsList, 
  TabsTrigger, 
  TabsContent 
} from '@/lib/components/ui/tabs';
import { Card, CardContent } from '@/lib/components/ui/card';

function DataVisualization() {
  const [renderError, setRenderError] = useState<string | null>(null);

  const sampleData = {
    csv: "name,score,grade\nAlice,95,A\nBob,87,B\nCharlie,92,A-",
    json: { users: [{ name: "Alice", score: 95 }, { name: "Bob", score: 87 }] },
    markdown: "# Report\n\n## Summary\n\nAnalysis **complete** with high confidence.\n\n- ✅ Data validated\n- ✅ Results verified"
  };

  return (
    <div className="p-6 space-y-6">
      <h1 className="text-2xl font-bold">Data Visualization</h1>

      <Tabs defaultValue="csv" className="w-full">
        <TabsList>
          <TabsTrigger value="csv">CSV Data</TabsTrigger>
          <TabsTrigger value="json">JSON Data</TabsTrigger>
          <TabsTrigger value="markdown">Markdown</TabsTrigger>
        </TabsList>

        <TabsContent value="csv">
          <Card>
            <CardContent className="p-6">
              <h3 className="text-lg font-semibold mb-4">CSV Table</h3>
              <ContentRenderer
                content={sampleData.csv}
                rendererType="csv"
                setRenderError={setRenderError}
              />
              {renderError && (
                <div className="mt-2 text-red-500 text-sm">{renderError}</div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="json">
          <Card>
            <CardContent className="p-6">
              <h3 className="text-lg font-semibold mb-4">JSON Viewer</h3>
              <JSONViewer data={sampleData.json} maxDepth={3} />
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="markdown">
          <Card>

# content_hash: fba4c1fe43f4fa9f9629043ae48e0c93e235f4979a27b71bb39e8280ef5ae604

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

## Section 15: frontend/src/lib/components/header/header_llm.txt

**Source file:** `frontend/src/lib/components/header/header_llm.txt`

# DEVELOPER GUIDE: header

## Quick Summary
The header directory contains a reusable React header component that provides a consistent navigation bar with title, tabs, action buttons, and optional leading actions for the application interface.

## Files Overview
- `Header.tsx` - Main header component with tab navigation, title display, and action button support

## Developer API Reference

### Header.tsx
**Purpose:** Provides a flexible header component with navigation tabs, title, and action buttons
**Import:** `import { Header, HeaderProps, Tab } from "lib/components/header/Header"`

**Interfaces:**
- `Tab` - Configuration object for navigation tabs
  - `id: string` - Unique identifier for the tab
  - `label: string` - Display text for the tab
  - `isActive: boolean` - Whether this tab is currently selected
  - `onClick: () => void` - Callback function when tab is clicked

- `HeaderProps` - Props interface for the Header component
  - `title: string` - Main title text to display
  - `tabs?: Tab[]` - Optional array of navigation tabs
  - `buttons?: React.ReactNode[]` - Optional array of action buttons/elements
  - `leadingAction?: React.ReactNode` - Optional leading element (e.g., back button)

**Components:**
- `Header: React.FC<HeaderProps>` - Main header component that renders a navigation bar with consistent styling and layout

**Usage Examples:**
```tsx
import React from "react";
import { Header, Tab } from "lib/components/header/Header";

// Basic header with just title
<Header title="Dashboard" />

// Header with tabs
const tabs: Tab[] = [
  { id: "overview", label: "Overview", isActive: true, onClick: () => setActiveTab("overview") },
  { id: "settings", label: "Settings", isActive: false, onClick: () => setActiveTab("settings") }
];

<Header 
  title="Project Management" 
  tabs={tabs}
/>

// Full header with all features
<Header
  title="User Profile"
  leadingAction={<BackButton onClick={() => navigate(-1)} />}
  tabs={tabs}
  buttons={[
    <Button variant="primary">Save</Button>,
    <Button variant="secondary">Cancel</Button>
  ]}
/>

// Header with action buttons only
<Header
  title="Reports"
  buttons={[
    <Button>Export</Button>,
    <IconButton icon="settings" />
  ]}
/>
```

# content_hash: 52ae81bce480f3e268cef8fdd5e41c30128ea1702f278053073dfc8904e4bb72

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

## Section 16: frontend/src/lib/components/jsonViewer/jsonViewer_llm.txt

**Source file:** `frontend/src/lib/components/jsonViewer/jsonViewer_llm.txt`

# DEVELOPER GUIDE: jsonViewer

## Quick Summary
A React component directory that provides a customizable JSON viewer with theme support. The main component renders JSON data in a read-only, collapsible tree view that automatically adapts to the application's light/dark theme using CSS variables.

## Files Overview
- `JSONViewer.tsx` - Main React component for displaying JSON data with theme-aware styling and configurable expansion depth

## Developer API Reference

### JSONViewer.tsx
**Purpose:** Provides a themed, read-only JSON viewer component with collapsible tree structure
**Import:** `import { JSONViewer } from "@/lib/components/jsonViewer/JSONViewer"`

**Types:**
- `JSONValue` - Union type representing any valid JSON value: `string | number | boolean | null | JSONObject | JSONArray`
- `JSONObject` - Object type: `{ [key: string]: JSONValue }`
- `JSONArray` - Array type: `JSONValue[]`
- `JSONViewerProps` - Component props interface

**Components:**
- `JSONViewer(props: JSONViewerProps)` - Main JSON viewer component
  - `data: JSONValue` - The JSON data to display (required)
  - `maxDepth?: number` - Maximum expansion depth (default: 2, set to negative for fully expanded)
  - `className?: string` - Additional CSS classes to apply to container

**Functions:**
- `createJsonEditorTheme(isDark: boolean) -> JerTheme` - Creates theme object using CSS variables for consistent styling

**Usage Examples:**
```tsx
import { JSONViewer } from "@/lib/components/jsonViewer/JSONViewer";

// Basic usage with object data
const MyComponent = () => {
  const jsonData = { 
    name: "John", 
    age: 30, 
    active: true,
    metadata: { created: "2024-01-01", tags: ["user", "premium"] }
  };
  
  return <JSONViewer data={jsonData} />;
};

// With custom expansion depth
const DeepViewer = () => {
  return (
    <JSONViewer 
      data={complexData} 
      maxDepth={3} 
      className="max-h-96 p-4" 
    />
  );
};

// Handling primitive values
const PrimitiveViewer = () => {
  return <JSONViewer data="Hello World" />; // Automatically wrapped in {value: "Hello World"}
};

// Fully expanded view
const ExpandedViewer = () => {
  return <JSONViewer data={data} maxDepth={-1} />;
};

// Handling undefined/no data
const EmptyViewer = () => {
  return <JSONViewer data={undefined} />; // Shows "No JSON data"
};
```

# content_hash: 554bb259037f829218111d9330b626aa208a069856a74e49fe3b24e65f30de2d

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

## Section 17: frontend/src/lib/components/navigation/navigation_llm.txt

**Source file:** `frontend/src/lib/components/navigation/navigation_llm.txt`

# DEVELOPER GUIDE: navigation

## Quick Summary
The navigation directory provides a complete sidebar navigation system for React applications. It includes a main sidebar component with header, navigation buttons, theme toggle, and support for both main and bottom navigation items with tooltips and accessibility features.

## Files Overview
- `NavigationButton.tsx` - Individual navigation button component with tooltip and accessibility
- `NavigationHeader.tsx` - Header component with logo/branding for the navigation sidebar
- `NavigationList.tsx` - Container for organizing navigation items and bottom items
- `NavigationSidebar.tsx` - Main sidebar component that combines all navigation elements
- `ToggleThemeButton.tsx` - Theme toggle button with sun/moon icon

## Developer API Reference

### NavigationButton.tsx
**Purpose:** Renders individual navigation buttons with icons, labels, tooltips, and click handling
**Import:** `import { NavigationButton } from "@/lib/components/navigation"`

**Interfaces:**
- `NavigationItemProps` - Props for the NavigationButton component
  - `item: NavigationItem` - Navigation item data with id, label, icon, and disabled state
  - `isActive: boolean` - Whether this button represents the currently active page/section
  - `onItemClick?: (itemId: string) => void` - Optional callback when button is clicked

**Components:**
- `NavigationButton: React.FC<NavigationItemProps>` - Navigation button with tooltip and accessibility features
  - Handles click and keyboard events (Enter/Space)
  - Shows active state with visual indicators
  - Includes tooltip on hover
  - Supports disabled state

**Usage Examples:**
```tsx
import { NavigationButton } from "@/lib/components/navigation";
import { Home } from "lucide-react";

const navigationItem = {
  id: "home",
  label: "Home",
  icon: Home,
  disabled: false
};

<NavigationButton 
  item={navigationItem}
  isActive={true}
  onItemClick={(itemId) => console.log(`Clicked: ${itemId}`)}
/>
```

### NavigationHeader.tsx
**Purpose:** Displays the header/logo section at the top of the navigation sidebar
**Import:** `import { NavigationHeader } from "@/lib/components/navigation"`

**Interfaces:**
- `NavigationHeaderProps` - Props for the NavigationHeader component
  - `onClick?: () => void` - Optional callback when header is clicked

**Components:**
- `NavigationHeader: React.FC<NavigationHeaderProps>` - Header component with logo SVG
  - Fixed height of 80px
  - Clickable with optional callback
  - Contains branded logo SVG

**Constants/Variables:**
- `HEADER_ICON: JSX.Element` - SVG logo element with brand styling

**Usage Examples:**
```tsx
import { NavigationHeader } from "@/lib/components/navigation";

<NavigationHeader onClick={() => console.log("Header clicked")} />
```

### NavigationList.tsx
**Purpose:** Organizes and renders lists of navigation items with support for main and bottom sections
**Import:** `import { NavigationList } from "@/lib/components/navigation"`

**Interfaces:**
- `NavigationListProps` - Props for the NavigationList component
  - `items: NavigationItem[]` - Main navigation items
  - `bottomItems?: NavigationItem[]` - Optional bottom navigation items
  - `activeItem: string | null` - ID of currently active item
  - `onItemClick: (itemId: string) => void` - Callback when any item is clicked

**Components:**
- `NavigationList: React.FC<NavigationListProps>` - Navigation list container
  - Renders main navigation items at top
  - Renders bottom items at bottom with spacer
  - Handles special "theme-toggle" item with ToggleThemeButton
  - Supports dividers between items

**Usage Examples:**
```tsx
import { NavigationList } from "@/lib/components/navigation";
import { Home, Settings } from "lucide-react";

const mainItems = [
  { id: "home", label: "Home", icon: Home },
  { id: "settings", label: "Settings", icon: Settings, showDividerAfter: true }
];

const bottomItems = [
  { id: "theme-toggle", label: "Toggle Theme", icon: SunMoon }
];

<NavigationList 
  items={mainItems}
  bottomItems={bottomItems}
  activeItem="home"
  onItemClick={(itemId) => console.log(`Clicked: ${itemId}`)}
/>
```

### NavigationSidebar.tsx
**Purpose:** Main sidebar component that combines header, navigation list, and provides the complete navigation experience
**Import:** `import { NavigationSidebar } from "@/lib/components/navigation"`

**Interfaces:**
- `NavigationSidebarProps` - Props for the NavigationSidebar component
  - `items: NavigationItem[]` - Main navigation items
  - `bottomItems?: NavigationItem[]` - Optional bottom navigation items
  - `activeItem: string` - ID of currently active item
  - `onItemChange: (itemId: string) => void` - Callback when active item changes
  - `onHeaderClick?: () => void` - Optional callback when header is clicked

**Components:**
- `NavigationSidebar: React.FC<NavigationSidebarProps>` - Complete sidebar navigation
  - Fixed width of 100px
  - Full height (h-screen)
  - Combines NavigationHeader and NavigationList
  - Handles item change events

**Usage Examples:**
```tsx
import { NavigationSidebar } from "@/lib/components/navigation";
import { Home, Settings, User } from "lucide-react";

const mainItems = [
  { id: "home", label: "Home", icon: Home },
  { id: "profile", label: "Profile", icon: User },
  { id: "settings", label: "Settings", icon: Settings }
];

const bottomItems = [
  { id: "theme-toggle", label: "Toggle Theme", icon: SunMoon }
];

<NavigationSidebar 
  items={mainItems}
  bottomItems={bottomItems}
  activeItem="home"
  onItemChange={(itemId) => setActiveItem(itemId)}
  onHeaderClick={() => console.log("Header clicked")}
/>
```

### ToggleThemeButton.tsx
**Purpose:** Specialized button for toggling between light and dark themes
**Import:** `import { ToggleThemeButton } from "@/lib/components/navigation"`

**Components:**
- `ToggleThemeButton: React.FC` - Theme toggle button component
  - Uses `useThemeContext` hook for theme management
  - Shows current theme in tooltip and aria-label
  - Uses SunMoon icon from lucide-react
  - Includes tooltip with current theme state

**Usage Examples:**
```tsx
import { ToggleThemeButton } from "@/lib/components/navigation";

// Used automatically in NavigationList when item.id === "theme-toggle"
// Or can be used standalone:
<ToggleThemeButton />
```

# content_hash: dcd0575fc59316e750a5c6319045413ed2d26be93343c1593d4d2fb25201d1f3

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

## Section 18: frontend/src/lib/components/pages/pages_llm.txt

**Source file:** `frontend/src/lib/components/pages/pages_llm.txt`

# DEVELOPER GUIDE: pages

## Quick Summary
The `pages` directory contains React page components that serve as top-level views in the application. These components orchestrate the layout and functionality for major application sections including agent management and chat interfaces.

## Files Overview
- `AgentMeshPage.tsx` - Main page component for displaying and managing agents in various layout formats
- `ChatPage.tsx` - Complex chat interface page with resizable panels, session management, and real-time messaging

## Developer API Reference

### AgentMeshPage.tsx
**Purpose:** Renders the main agents page with layout switching capabilities and plugin support
**Import:** `import { AgentMeshPage } from "@/lib/components/pages/AgentMeshPage"`

**Components:**
- `AgentMeshPage()` - Main page component for agent management interface
  - Handles loading and error states for agent data
  - Provides layout switching between cards view and plugin-based layouts
  - Integrates with plugin registry for extensible layout options

**Usage Examples:**
```tsx
import { AgentMeshPage } from "@/lib/components/pages/AgentMeshPage";

// Use as a route component
function App() {
  return (
    <Routes>
      <Route path="/agents" element={<AgentMeshPage />} />
    </Routes>
  );
}
```

### ChatPage.tsx
**Purpose:** Comprehensive chat interface with resizable panels, session management, and real-time task monitoring
**Import:** `import { ChatPage } from "@/lib/components/pages/ChatPage"`

**Components:**
- `ChatPage()` - Main chat page component with advanced panel management
  - Manages resizable chat and side panels with smooth transitions
  - Handles session management with collapsible session panel
  - Integrates real-time task monitoring and progress tracking
  - Automatically selects default agent and displays welcome message
  - Supports window focus reconnection for task monitoring

**Constants:**
- `COLLAPSED_SIZE: number` - Size (4) for collapsed side panel in icon-only mode
- `PANEL_SIZES_CLOSED: object` - Panel size configurations when session panel is closed
- `PANEL_SIZES_OPEN: object` - Panel size configurations when session panel is open

**Usage Examples:**
```tsx
import { ChatPage } from "@/lib/components/pages/ChatPage";

// Use as a route component
function App() {
  return (
    <Routes>
      <Route path="/chat" element={<ChatPage />} />
    </Routes>
  );
}

// The component automatically handles:
// - Agent selection and welcome messages
// - Panel resizing and state management
// - Task monitoring reconnection
// - Session management
```

**Key Features:**
- **Panel Management:** Resizable chat and side panels with smooth animations
- **Session Management:** Collapsible session panel with toggle controls
- **Task Monitoring:** Real-time task progress tracking with auto-reconnection
- **Agent Integration:** Automatic agent selection and welcome message display
- **Responsive Layout:** Adaptive panel sizing based on session panel state

# content_hash: 341a5659229183fbafcdddfcaf543d13a53f145bdd85ce202576cb7226f8c335

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

## Section 19: frontend/src/lib/components/toast/toast_llm.txt

**Source file:** `frontend/src/lib/components/toast/toast_llm.txt`

# DEVELOPER GUIDE: toast

## Quick Summary
The toast directory provides a React component system for displaying temporary notification messages to users. It includes a customizable Toast component that supports different message types (info, success, warning, error) with visual indicators and styling.

## Files Overview
- `Toast.tsx` - Main toast notification component with type-based styling and icon support

## Developer API Reference

### Toast.tsx
**Purpose:** Renders a toast notification message with optional type-based styling and icons
**Import:** `import { Toast, ToastProps } from "path/to/toast/Toast"`

**Interfaces:**
- `ToastProps` - Configuration interface for toast notifications
  - `id: string` - Unique identifier for the toast
  - `message: string` - Text content to display in the toast
  - `type?: "info" | "success" | "warning" | "error"` - Visual style variant (optional)
  - `duration?: number` - How long to display the toast in milliseconds (optional)

**Components:**
- `Toast({ message, type }: ToastProps)` - React component that renders a toast notification
  - Displays an alert with the provided message
  - Shows an error icon for error type toasts
  - Applies transition animations and responsive styling
  - Truncates long messages to fit within max width

**Usage Examples:**
```tsx
import { Toast } from "path/to/toast/Toast";

// Basic toast with just a message
<Toast id="toast-1" message="Operation completed successfully" />

// Error toast with icon
<Toast 
  id="toast-2" 
  message="Failed to save changes" 
  type="error" 
/>

// Toast with custom duration
<Toast 
  id="toast-3" 
  message="Settings updated" 
  type="success" 
  duration={3000} 
/>

// Warning toast
<Toast 
  id="toast-4" 
  message="This action cannot be undone" 
  type="warning" 
/>
```

**Dependencies:**
- Requires `lucide-react` for icons
- Requires `Alert` and `AlertTitle` components from `../ui/alert`
- Uses CSS custom properties for error color (`--color-error-wMain`)

# content_hash: 4245b7468417b17dcdd9e8832d67d82ed101fe7f35b24acd5e7dc9d567f32d2e

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

## Section 20: frontend/src/lib/components/ui/chat/chat_llm.txt

**Source file:** `frontend/src/lib/components/ui/chat/chat_llm.txt`

# DEVELOPER GUIDE: chat

## Quick Summary
The chat directory provides a comprehensive set of React components and hooks for building chat interfaces. It includes visual components for chat bubbles, messages, input fields, and message lists, along with utility hooks for managing auto-scrolling behavior. The architecture separates presentation components (direct files) from behavioral logic (hooks subdirectory), enabling flexible and reusable chat UI implementations.

## Files and Subdirectories Overview
- **Direct files:**
  - `chat-bubble.tsx` - Complete chat bubble component system with avatar, message, timestamp, and actions
  - `chat-input.tsx` - Styled textarea component for chat message input
  - `chat-message-list.tsx` - Scrollable container for chat messages with auto-scroll functionality
  - `message-loading.tsx` - Loading spinner component for pending messages

- **Subdirectories:**
  - `hooks/` - Custom React hooks for chat functionality, primarily auto-scrolling behavior

## Developer API Reference

### Direct Files

#### chat-bubble.tsx
**Purpose:** Provides a complete chat bubble system with avatar, message content, timestamps, and action buttons
**Import:** `import { ChatBubble, ChatBubbleAvatar, ChatBubbleMessage, ChatBubbleTimestamp, ChatBubbleAction, ChatBubbleActionWrapper } from "@/lib/components/ui/chat/chat-bubble"`

**Components:**
- `ChatBubble` - Main container component with variant support for sent/received messages
  - Props: `variant?: "sent" | "received"`, `layout?: "default" | "ai"`
- `ChatBubbleAvatar` - Avatar component for message sender
  - Props: `src?: string`, `fallback?: string`, `className?: string`
- `ChatBubbleMessage` - Message content container with styling variants
  - Props: `variant?: "sent" | "received"`, `layout?: "default" | "ai"`, `isComplete?: boolean`
- `ChatBubbleTimestamp` - Timestamp display component
  - Props: `timestamp: string`
- `ChatBubbleAction` - Action button component for message interactions
  - Props: `icon: React.ReactNode`, extends Button props
- `ChatBubbleActionWrapper` - Container for action buttons with hover effects
  - Props: `variant?: "sent" | "received"`

#### chat-input.tsx
**Purpose:** Styled textarea component specifically designed for chat message input
**Import:** `import { ChatInput } from "@/lib/components/ui/chat/chat-input"`

**Components:**
- `ChatInput` - Enhanced textarea with chat-specific styling and behavior
  - Props: Extends `React.TextareaHTMLAttributes<HTMLTextAreaElement>`

#### chat-message-list.tsx
**Purpose:** Scrollable container for chat messages with auto-scroll and scroll-to-bottom functionality
**Import:** `import { ChatMessageList, type ChatMessageListRef } from "@/lib/components/ui/chat/chat-message-list"`

**Components:**
- `ChatMessageList` - Scrollable message container with auto-scroll behavior
  - Props: `smooth?: boolean`, extends `React.HTMLAttributes<HTMLDivElement>`
  - Ref: `ChatMessageListRef` with `scrollToBottom(): void` method

#### message-loading.tsx
**Purpose:** Loading indicator for pending chat messages
**Import:** `import MessageLoading from "@/lib/components/ui/chat/message-loading"`

**Components:**
- `MessageLoading` - Spinner component for loading states
  - Props: `className?: string`

### Subdirectory APIs

#### hooks/
**Purpose:** Provides custom React hooks for chat functionality, primarily auto-scrolling behavior
**Key Exports:** `useAutoScroll` hook for managing automatic scrolling in chat interfaces
**Import Examples:**
```typescript
import { useAutoScroll } from "@/lib/components/ui/chat/hooks/useAutoScroll"
```

## Complete Usage Guide

### 1. Basic Chat Message Display

```tsx
import { 
  ChatBubble, 
  ChatBubbleAvatar, 
  ChatBubbleMessage, 
  ChatBubbleTimestamp 
} from "@/lib/components/ui/chat/chat-bubble";

function BasicMessage({ message, isUser }) {
  return (
    <ChatBubble variant={isUser ? "sent" : "received"}>
      <ChatBubbleAvatar 
        src={message.avatar} 
        fallback={message.name[0]} 
      />
      <ChatBubbleMessage variant={isUser ? "sent" : "received"}>
        {message.content}
        <ChatBubbleTimestamp timestamp={message.timestamp} />
      </ChatBubbleMessage>
    </ChatBubble>
  );
}
```

### 2. Interactive Chat Messages with Actions

```tsx
import { 
  ChatBubble, 
  ChatBubbleMessage, 
  ChatBubbleAction, 
  ChatBubbleActionWrapper 
} from "@/lib/components/ui/chat/chat-bubble";
import { Copy, ThumbsUp } from "lucide-react";

function InteractiveMessage({ message, onCopy, onLike }) {
  return (
    <ChatBubble variant="received">
      <ChatBubbleMessage variant="received">
        {message.content}
        <ChatBubbleActionWrapper variant="received">
          <ChatBubbleAction 
            icon={<Copy />} 
            onClick={() => onCopy(message.content)}
          />
          <ChatBubbleAction 
            icon={<ThumbsUp />} 
            onClick={() => onLike(message.id)}
          />
        </ChatBubbleActionWrapper>
      </ChatBubbleMessage>
    </ChatBubble>
  );
}
```

### 3. Complete Chat Interface

```tsx
import { useState, useRef } from "react";
import { ChatMessageList, type ChatMessageListRef } from "@/lib/components/ui/chat/chat-message-list";
import { ChatInput } from "@/lib/components/ui/chat/chat-input";
import { ChatBubble, ChatBubbleMessage } from "@/lib/components/ui/chat/chat-bubble";
import MessageLoading from "@/lib/components/ui/chat/message-loading";
import { useAutoScroll } from "@/lib/components/ui/chat/hooks/useAutoScroll";

function ChatInterface() {
  const [messages, setMessages] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [inputValue, setInputValue] = useState("");
  const messageListRef = useRef<ChatMessageListRef>(null);

  const handleSendMessage = async () => {
    if (!inputValue.trim()) return;
    
    const newMessage = {
      id: Date.now(),
      content: inputValue,
      isUser: true,
      timestamp: new Date().toLocaleTimeString()
    };
    
    setMessages(prev => [...prev, newMessage]);
    setInputValue("");
    setIsLoading(true);
    
    // Simulate AI response
    setTimeout(() => {
      setMessages(prev => [...prev, {
        id: Date.now(),
        content: "AI response here",
        isUser: false,
        timestamp: new Date().toLocaleTimeString()
      }]);
      setIsLoading(false);
    }, 1000);
  };

  return (
    <div className="flex flex-col h-96 border rounded-lg">
      <ChatMessageList ref={messageListRef}>
        {messages.map(message => (
          <ChatBubble key={message.id} variant={message.isUser ? "sent" : "received"}>
            <ChatBubbleMessage variant={message.isUser ? "sent" : "received"}>
              {message.content}
            </ChatBubbleMessage>
          </ChatBubble>
        ))}
        {isLoading && (
          <ChatBubble variant="received">
            <ChatBubbleMessage variant="received">
              <MessageLoading />
            </ChatBubbleMessage>
          </ChatBubble>
        )}
      </ChatMessageList>
      
      <div className="p-4 border-t">
        <div className="flex gap-2">
          <ChatInput
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder="Type your message..."
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleSendMessage();
              }
            }}
          />
          <button onClick={handleSendMessage}>Send</button>
        </div>
      </div>
    </div>
  );
}
```

### 4. AI Chat Layout

```tsx
import { ChatBubble, ChatBubbleMessage } from "@/lib/components/ui/chat/chat-bubble";

function AIMessage({ message }) {
  return (
    <ChatBubble variant="received" layout="ai">
      <ChatBubbleMessage variant="received" layout="ai">
        {message.content}
      </ChatBubbleMessage>
    </ChatBubble>
  );
}
```

### 5. Custom Auto-Scroll Implementation

```tsx
import { useAutoScroll } from "@/lib/components/ui/chat/hooks/useAutoScroll";

function CustomChatList({ messages }) {
  const { 
    scrollRef, 
    isAtBottom, 
    scrollToBottom, 
    disableAutoScroll,
    userHasScrolled 
  } = useAutoScroll({
    content: messages,
    smooth: true,
    offset: 50
  });

  return (
    <div className="relative h-96">
      <div 
        ref={scrollRef}
        className="h-full overflow-y-auto p-4"
        onWheel={disableAutoScroll}
        onTouchMove={disableAutoScroll}
      >
        {messages.map(message => (
          <div key={message.id}>{message.content}</div>
        ))}
      </div>
      
      {!isAtBottom && userHasScrolled && (
        <button 
          onClick={scrollToBottom}
          className="absolute bottom-4 right-4 bg-blue-500 text-white p-2 rounded-full"
        >
          ↓
        </button>
      )}
    </div>
  );
}
```

This chat system provides a complete foundation for building modern chat interfaces with proper message styling, auto-scrolling behavior, loading states, and interactive elements. The modular design allows you to use individual components or combine them for full chat functionality.

# content_hash: 4ebf6e5472fe9ac1f8f4916bd17181aaed0431f963ac60ddc2dfe0136f9a808a

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

## Section 21: frontend/src/lib/components/ui/chat/hooks/hooks_llm.txt

**Source file:** `frontend/src/lib/components/ui/chat/hooks/hooks_llm.txt`

# DEVELOPER GUIDE: hooks

## Quick Summary
This directory contains React custom hooks for UI components, specifically providing auto-scrolling functionality for chat interfaces and other scrollable content areas.

## Files Overview
- `useAutoScroll.tsx` - Custom React hook for managing automatic scrolling behavior in chat-like interfaces

## Developer API Reference

### useAutoScroll.tsx
**Purpose:** Provides automatic scrolling functionality for chat interfaces, maintaining scroll position at bottom for new content while allowing users to scroll up to view history.

**Import:** `import { useAutoScroll } from 'lib/components/ui/chat/hooks/useAutoScroll'`

**Interfaces:**
- `ScrollState` - Internal state interface
  - `isAtBottom: boolean` - Whether scroll is at bottom
  - `autoScrollEnabled: boolean` - Whether auto-scroll is active

- `UseAutoScrollOptions` - Configuration options
  - `offset?: number` - Distance from bottom to consider "at bottom" (default: 20)
  - `smooth?: boolean` - Use smooth scrolling animation (default: false)
  - `content?: React.ReactNode` - Content to monitor for changes
  - `autoScrollOnNewContent?: boolean` - Force scroll on new content (default: false)

**Functions:**
- `useAutoScroll(options?: UseAutoScrollOptions) -> AutoScrollReturn` - Main hook for auto-scroll functionality

**Return Object Properties:**
- `scrollRef: React.RefObject<HTMLDivElement>` - Ref to attach to scrollable container
- `isAtBottom: boolean` - Current scroll position state
- `autoScrollEnabled: boolean` - Whether auto-scroll is currently enabled
- `scrollToBottom: () => void` - Manually scroll to bottom
- `disableAutoScroll: () => void` - Disable auto-scroll when user scrolls up
- `userHasScrolled: boolean` - Whether user has manually scrolled

**Usage Examples:**
```tsx
import { useAutoScroll } from 'lib/components/ui/chat/hooks/useAutoScroll';

// Basic usage
function ChatContainer({ messages }) {
  const { scrollRef, isAtBottom, scrollToBottom } = useAutoScroll({
    content: messages,
    smooth: true,
    offset: 50
  });

  return (
    <div>
      <div ref={scrollRef} className="chat-messages">
        {messages.map(msg => <div key={msg.id}>{msg.text}</div>)}
      </div>
      {!isAtBottom && (
        <button onClick={scrollToBottom}>
          Scroll to bottom
        </button>
      )}
    </div>
  );
}

// Advanced usage with auto-scroll control
function AdvancedChat({ messages }) {
  const { 
    scrollRef, 
    isAtBottom, 
    autoScrollEnabled, 
    scrollToBottom, 
    disableAutoScroll 
  } = useAutoScroll({
    content: messages,
    autoScrollOnNewContent: true,
    smooth: true
  });

  return (
    <div>
      <div 
        ref={scrollRef} 
        className="overflow-y-auto h-96"
        onWheel={disableAutoScroll} // Disable on manual scroll
      >
        {messages.map(msg => <div key={msg.id}>{msg.text}</div>)}
      </div>
      
      <div className="flex justify-between">
        <span>Auto-scroll: {autoScrollEnabled ? 'ON' : 'OFF'}</span>
        <button onClick={scrollToBottom}>↓ Bottom</button>
      </div>
    </div>
  );
}
```

# content_hash: f318b3f9e5773c3a1c5098af04bfec2ce1968224e666f89395e19f4f1726f8e9

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

## Section 22: frontend/src/lib/components/ui/ui_llm.txt

**Source file:** `frontend/src/lib/components/ui/ui_llm.txt`

# DEVELOPER GUIDE: ui

## Quick Summary
The ui directory provides a comprehensive design system and component library for building modern React applications. It combines a complete set of reusable UI components (direct files) with specialized chat functionality (chat subdirectory). The architecture follows a modular approach with consistent styling, accessibility features, and TypeScript support. Components are built on top of Radix UI primitives and styled with Tailwind CSS using a custom design token system.

## Files and Subdirectories Overview
- **Direct files:**
  - `ViewWorkflowButton.tsx` - Workflow visualization trigger button with network icon
  - `accordion.tsx` - Collapsible content sections with smooth animations
  - `alert.tsx` - Status messages and notifications with variant support
  - `avatar.tsx` - User profile images with fallback support
  - `badge.tsx` - Status indicators and labels with type-based styling
  - `button.tsx` - Primary action component with variants, sizes, and tooltip support
  - `card.tsx` - Content containers with header, body, and footer sections
  - `chart.tsx` - Data visualization components built on Recharts
  - `dialog.tsx` - Modal dialogs and overlays
  - `dropdown-menu.tsx` - Contextual menus with keyboard navigation
  - `input.tsx` - Form input fields with validation styling
  - `menu.tsx` - Custom menu component with keyboard navigation
  - `popover.tsx` - Floating content containers
  - `popoverManual.tsx` - Manual popover with custom positioning
  - `resizable.tsx` - Resizable panel layouts
  - `select.tsx` - Dropdown selection components
  - `separator.tsx` - Visual dividers
  - `sheet.tsx` - Slide-out panels and drawers
  - `side-panel.tsx` - Resizable side panels with touch support
  - `sidebar.tsx` - Navigation sidebar with collapsible states
  - `skeleton.tsx` - Loading placeholders
  - `spinner.tsx` - Loading indicators with size and color variants
  - `table.tsx` - Data tables with sorting and selection
  - `tabs.tsx` - Tabbed content navigation
  - `textarea.tsx` - Multi-line text input
  - `toast-container.tsx` - Toast notification container
  - `tooltip.tsx` - Contextual help and information

- **Subdirectories:**
  - `chat/` - Complete chat interface components and hooks for messaging functionality

## Developer API Reference

### Direct Files

#### ViewWorkflowButton.tsx
**Purpose:** Specialized button for triggering workflow visualization with network icon
**Import:** `import { ViewWorkflowButton } from "@/lib/components/ui/ViewWorkflowButton"`

**Components:**
- `ViewWorkflowButton` - Button with network icon for workflow actions
  - Props: `onClick: () => void`, `text?: string`

#### accordion.tsx
**Purpose:** Collapsible content sections with smooth expand/collapse animations
**Import:** `import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from "@/lib/components/ui/accordion"`

**Components:**
- `Accordion` - Root container for accordion sections
- `AccordionItem` - Individual collapsible section
- `AccordionTrigger` - Clickable header that toggles content
- `AccordionContent` - Collapsible content area

#### alert.tsx
**Purpose:** Status messages and notifications with variant-based styling
**Import:** `import { Alert, AlertTitle, AlertDescription } from "@/lib/components/ui/alert"`

**Components:**
- `Alert` - Main alert container with variant support (`default`, `destructive`)
- `AlertTitle` - Alert heading text
- `AlertDescription` - Alert body content

#### avatar.tsx
**Purpose:** User profile images with automatic fallback handling
**Import:** `import { Avatar, AvatarImage, AvatarFallback } from "@/lib/components/ui/avatar"`

**Components:**
- `Avatar` - Container for user profile image
- `AvatarImage` - Profile image component
- `AvatarFallback` - Fallback content when image fails to load

#### badge.tsx
**Purpose:** Status indicators and labels with semantic color coding
**Import:** `import { Badge } from "@/lib/components/ui/badge"`

**Components:**
- `Badge` - Status indicator with variants (`default`, `secondary`, `destructive`, `outline`) and types (`error`, `warning`, `info`, `success`)

#### button.tsx
**Purpose:** Primary action component with comprehensive variant and size support
**Import:** `import { Button } from "@/lib/components/ui/button"`

**Components:**
- `Button` - Main action button with variants (`default`, `destructive`, `outline`, `secondary`, `ghost`, `link`), sizes (`default`, `sm`, `lg`, `icon`), and built-in tooltip support
  - Props: `variant?`, `size?`, `tooltip?`, `testid?`, `asChild?`

#### card.tsx
**Purpose:** Content containers with structured layout sections
**Import:** `import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter, CardAction } from "@/lib/components/ui/card"`

**Components:**
- `Card` - Main container with shadow and border
- `CardHeader` - Header section with title and description
- `CardTitle` - Card heading
- `CardDescription` - Card subtitle
- `CardContent` - Main content area
- `CardFooter` - Footer section for actions
- `CardAction` - Action button area in header

#### chart.tsx
**Purpose:** Data visualization components built on Recharts with theming support
**Import:** `import { ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, type ChartConfig } from "@/lib/components/ui/chart"`

**Components:**
- `ChartContainer` - Main chart wrapper with configuration
- `ChartTooltip` - Interactive chart tooltips
- `ChartTooltipContent` - Customizable tooltip content
- `ChartLegend` - Chart legend component
- `ChartLegendContent` - Customizable legend content
- `useChart` - Hook for accessing chart configuration

#### dialog.tsx
**Purpose:** Modal dialogs and overlays with accessibility features
**Import:** `import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose } from "@/lib/components/ui/dialog"`

**Components:**
- `Dialog` - Root dialog component
- `DialogTrigger` - Element that opens the dialog
- `DialogContent` - Modal content container
- `DialogHeader` - Dialog header section
- `DialogTitle` - Dialog title
- `DialogDescription` - Dialog description
- `DialogFooter` - Dialog footer for actions
- `DialogClose` - Close button component

#### dropdown-menu.tsx
**Purpose:** Contextual menus with keyboard navigation and accessibility
**Import:** `import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem, DropdownMenuCheckboxItem, DropdownMenuRadioItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuSubContent, DropdownMenuGroup, DropdownMenuRadioGroup } from "@/lib/components/ui/dropdown-menu"`

**Components:**
- `DropdownMenu` - Root menu component
- `DropdownMenuTrigger` - Element that opens the menu
- `DropdownMenuContent` - Menu content container
- `DropdownMenuItem` - Individual menu item with variant support
- `DropdownMenuCheckboxItem` - Checkbox menu item
- `DropdownMenuRadioItem` - Radio button menu item
- `DropdownMenuLabel` - Menu section label
- `DropdownMenuSeparator` - Visual divider
- `DropdownMenuShortcut` - Keyboard shortcut display
- `DropdownMenuSub` - Submenu container
- `DropdownMenuSubTrigger` - Submenu trigger
- `DropdownMenuSubContent` - Submenu content

#### input.tsx
**Purpose:** Form input fields with validation styling and focus states
**Import:** `import { Input } from "@/lib/components/ui/input"`

**Components:**
- `Input` - Text input with validation styling and focus states

#### menu.tsx
**Purpose:** Custom menu component with keyboard navigation and accessibility
**Import:** `import { Menu, type MenuAction, type MenuProps } from "@/lib/components/ui/menu"`

**Components:**
- `Menu` - Custom menu with action-based configuration
  - Props: `actions: MenuAction[]`, `className?`
- `MenuAction` - Menu item configuration interface

#### popover.tsx
**Purpose:** Floating content containers with automatic positioning
**Import:** `import { Popover, PopoverTrigger, PopoverContent, PopoverAnchor } from "@/lib/components/ui/popover"`

**Components:**
- `Popover` - Root popover component
- `PopoverTrigger` - Element that opens the popover
- `PopoverContent` - Floating content container
- `PopoverAnchor` - Positioning anchor

#### popoverManual.tsx
**Purpose:** Manual popover with custom positioning and lifecycle control
**Import:** `import { PopoverManual } from "@/lib/components/ui/popoverManual"`

**Components:**
- `PopoverManual` - Manually controlled popover with custom positioning
  - Props: `isOpen`, `onClose`, `anchorRef`, `placement?`, `offset?`, `closeOnClickOutside?`, `closeOnEscape?`

#### resizable.tsx
**Purpose:** Resizable panel layouts with drag handles
**Import:** `import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/lib/components/ui/resizable"`

**Components:**
- `ResizablePanelGroup` - Container for resizable panels
- `ResizablePanel` - Individual resizable panel
- `ResizableHandle` - Drag handle for resizing

#### select.tsx
**Purpose:** Dropdown selection components with search and grouping
**Import:** `import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, SelectLabel, SelectSeparator, SelectGroup, SelectScrollUpButton, SelectScrollDownButton } from "@/lib/components/ui/select"`

**Components:**
- `Select` - Root select component
- `SelectTrigger` - Select trigger button with size variants
- `SelectContent` - Dropdown content container
- `SelectItem` - Individual option item
- `SelectValue` - Selected value display
- `SelectLabel` - Option group label
- `SelectSeparator` - Visual divider
- `SelectGroup` - Option grouping

#### separator.tsx
**Purpose:** Visual dividers for content sections
**Import:** `import { Separator } from "@/lib/components/ui/separator"`

**Components:**
- `Separator` - Horizontal or vertical divider line

#### sheet.tsx
**Purpose:** Slide-out panels and drawers from screen edges
**Import:** `import { Sheet, SheetTrigger, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetFooter, SheetClose } from "@/lib/components/ui/sheet"`

**Components:**
- `Sheet` - Root sheet component
- `SheetTrigger` - Element that opens the sheet
- `SheetContent` - Sliding panel content with side positioning
- `SheetHeader` - Sheet header section
- `SheetTitle` - Sheet title
- `SheetDescription` - Sheet description
- `SheetFooter` - Sheet footer
- `SheetClose` - Close button

#### side-panel.tsx
**Purpose:** Resizable side panels with touch support and keyboard navigation
**Import:** `import { SidePanel, type SidePanelProps } from "@/lib/components/ui/side-panel"`

**Components:**
- `SidePanel` - Resizable side panel with position and size controls
  - Props: `defaultWidth?`, `minWidth?`, `maxWidth?`, `position?`, `resizable?`, `onWidthChange?`

#### sidebar.tsx
**Purpose:** Navigation sidebar with collapsible states and mobile support
**Import:** `import { SidebarProvider, Sidebar, SidebarContent, SidebarHeader, SidebarFooter, SidebarMenu, SidebarMenuItem, SidebarMenuButton, SidebarTrigger, useSidebar } from "@/lib/components/ui/sidebar"`

**Components:**
- `SidebarProvider` - Context provider for sidebar state
- `Sidebar` - Main sidebar container with variants and collapsible modes
- `SidebarContent` - Scrollable content area
- `SidebarHeader` - Sidebar header section
- `SidebarFooter` - Sidebar footer section
- `SidebarMenu` - Menu container
- `SidebarMenuItem` - Individual menu item
- `SidebarMenuButton` - Menu button with tooltip support
- `SidebarTrigger` - Toggle button for sidebar
- `useSidebar` - Hook for sidebar state management

#### skeleton.tsx
**Purpose:** Loading placeholders with pulse animation
**Import:** `import { Skeleton } from "@/lib/components/ui/skeleton"`

**Components:**
- `Skeleton` - Animated loading placeholder

#### spinner.tsx
**Purpose:** Loading indicators with size and color variants
**Import:** `import { Spinner } from "@/lib/components/ui/spinner"`

**Components:**
- `Spinner` - Loading spinner with size (`small`, `medium`, `large`) and variant (`primary`, `secondary`, `muted`, `foreground`) options

#### table.tsx
**Purpose:** Data tables with sorting, selection, and responsive design
**Import:** `import { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption } from "@/lib/components/ui/table"`

**Components:**
- `Table` - Main table container with responsive wrapper
- `TableHeader` - Table header section
- `TableBody` - Table body content
- `TableFooter` - Table footer section
- `TableHead` - Header cell component
- `TableRow` - Table row with hover states
- `TableCell` - Table data cell
- `TableCaption` - Table caption

#### tabs.tsx
**Purpose:** Tabbed content navigation with keyboard support
**Import:** `import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/lib/components/ui/tabs"`

**Components:**
- `Tabs` - Root tabs container
- `TabsList` - Tab navigation list
- `TabsTrigger` - Individual tab button
- `TabsContent` - Tab panel content

#### textarea.tsx
**Purpose:** Multi-line text input with auto-resize capabilities
**Import:** `import { Textarea } from "@/lib/components/ui/textarea"`

**Components:**
- `Textarea` - Multi-line text input component

#### toast-container.tsx
**Purpose:** Container for toast notifications with positioning
**Import:** `import { ToastContainer } from "@/lib/components/ui/toast-container"`

**Components:**
- `ToastContainer` - Fixed positioned container for toast notifications

#### tooltip.tsx
**Purpose:** Contextual help and information with smart positioning
**Import:** `import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from "@/lib/components/ui/tooltip"`

**Components:**
- `TooltipProvider` - Context provider for tooltip configuration
- `Tooltip` - Root tooltip component
- `TooltipTrigger` - Element that triggers the tooltip
- `TooltipContent` - Tooltip content with arrow

### Subdirectory APIs

#### chat/
**Purpose:** Complete chat interface components and hooks for messaging functionality
**Key Exports:** Chat bubbles, message lists, input components, and auto-scroll hooks
**Import Examples:**
```tsx
import { ChatBubble, ChatBubbleMessage } from "@/lib/components/ui/chat/chat-bubble"
import { ChatMessageList } from "@/lib/components/ui/chat/chat-message-list"
import { ChatInput } from "@/lib/components/ui/chat/chat-input"
import { useAutoScroll } from "@/lib/components/ui/chat/hooks/useAutoScroll"
```

## Complete Usage Guide

### 1. Basic Component Usage

```tsx
import { Button } from "@/lib/components/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@/lib/components/ui/card";
import { Input } from "@/lib/components/ui/input";
import { Badge } from "@/lib/components/ui/badge";

function BasicExample

# content_hash: ef3e1cf17fb78511d649138f05f89e97f842de3cc735b89a12d3736ca831dbdf

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

## Section 23: frontend/src/lib/lib_llm.txt

**Source file:** `frontend/src/lib/lib_llm.txt`

# DEVELOPER GUIDE: lib

## Quick Summary
The `lib` directory serves as the core library for a React-based agent management and chat application. It provides a comprehensive architecture with React context providers for state management, a complete component library built on Radix UI, custom hooks for accessing context data, utility functions, type definitions, and a plugin system. The directory combines direct utility files with specialized subdirectories that work together to create a cohesive development framework for building modern web applications with features like real-time chat, workflow visualization, agent management, and theming.

## Files and Subdirectories Overview
- **Direct files:**
  - `constants.ts` - Application-wide constants and configuration values
  - `index.ts` - Main entry point with plugin interfaces and type exports
  - `types.ts` - Core TypeScript type definitions and interfaces
  - `utils.ts` - Utility functions for common operations

- **Subdirectories:**
  - `components/` - Complete React component library with UI elements and feature components
  - `plugins/` - Plugin system for extending UI components with registry management
  - `providers/` - React context providers for global state management

## Developer API Reference

### Direct Files

#### constants.ts
**Purpose:** Defines application-wide constants including plugin types and configuration values
**Import:** `import { PLUGIN_TYPES, DEFAULT_VALUES } from '@/lib/constants'`

**Constants/Variables:**
- `PLUGIN_TYPES` - Object containing plugin type definitions for the plugin system
- Configuration constants for default values and application settings

#### index.ts
**Purpose:** Main entry point that exports plugin interfaces and core types for the library
**Import:** `import { PluginInterface, PluginManagerInterface } from '@/lib'`

**Interfaces:**
- `PluginInterface` - Defines the structure for plugins in the system
- `PluginManagerInterface` - Interface for managing plugin registration and rendering

#### types.ts
**Purpose:** Core TypeScript type definitions for the entire application
**Import:** `import { AgentCard, ChatMessage, TaskStep } from '@/lib/types'`

**Types/Interfaces:**
- Core data types for agents, chat messages, tasks, and UI components
- Type definitions for API responses and application state

#### utils.ts
**Purpose:** Common utility functions used throughout the application
**Import:** `import { formatDate, validateInput, apiRequest } from '@/lib/utils'`

**Functions:**
- Utility functions for data formatting, validation, and common operations
- Helper functions for API requests and data manipulation

### Subdirectory APIs

#### components/
**Purpose:** Complete React component library with UI elements, chat interface, agent management, and workflow visualization
**Key Exports:** UI components, chat system, agent cards, workflow visualization, navigation, pages
**Import Examples:**
```tsx
import { Button, Card, Dialog } from "@/lib/components/ui"
import { ChatInputArea, ChatMessage } from '@/lib/components/chat'
import { AgentDisplayCard } from "@/lib/components/agents/AgentDisplayCard"
import { FlowChartPanel } from '@/lib/components/activities/FlowChartPanel'
import { NavigationSidebar } from '@/lib/components/navigation'
```

#### plugins/
**Purpose:** Plugin system for extending UI components with registration and rendering capabilities
**Key Exports:** PluginRegistry class and plugin management functionality
**Import Examples:**
```tsx
import { pluginRegistry } from "@/lib/plugins/PluginRegistry"
```

#### providers/
**Purpose:** React context providers for global state management including auth, chat, config, CSRF, tasks, and theming
**Key Exports:** AuthProvider, ChatProvider, ConfigProvider, CsrfProvider, TaskProvider, ThemeProvider
**Import Examples:**
```tsx
import { AuthProvider } from "@/lib/providers/AuthProvider"
import { ChatProvider } from "@/lib/providers/ChatProvider"
import { ThemeProvider } from "@/lib/providers/ThemeProvider"
```

## Complete Usage Guide

### 1. Setting Up the Complete Application Structure

```tsx
import React from 'react';
import { 
  ThemeProvider,
  CsrfProvider,
  ConfigProvider,
  AuthProvider,
  TaskProvider,
  ChatProvider 
} from '@/lib/providers';
import { NavigationSidebar } from '@/lib/components/navigation';
import { ChatPage } from '@/lib/components/pages/ChatPage';
import { AgentMeshPage } from '@/lib/components/pages/AgentMeshPage';
import { pluginRegistry } from '@/lib/plugins/PluginRegistry';
import { PLUGIN_TYPES } from '@/lib/constants';

// Register custom plugins
pluginRegistry.registerPlugin({
  type: PLUGIN_TYPES.LAYOUT,
  id: "custom-grid",
  label: "Custom Grid",
  icon: Grid,
  priority: 300,
  render: (data) => <CustomGridLayout agents={data.agents} />
});

function App() {
  return (
    <ThemeProvider>
      <CsrfProvider>
        <ConfigProvider>
          <AuthProvider>
            <TaskProvider>
              <ChatProvider>
                <AppLayout />
              </ChatProvider>
            </TaskProvider>
          </AuthProvider>
        </ConfigProvider>
      </CsrfProvider>
    </ThemeProvider>
  );
}

function AppLayout() {
  const [activeView, setActiveView] = useState('chat');

  return (
    <div className="flex h-screen">
      <NavigationSidebar
        items={navigationItems}
        activeItem={activeView}
        onItemChange={setActiveView}
      />
      <main className="flex-1">
        {activeView === 'chat' && <ChatPage />}
        {activeView === 'agents' && <AgentMeshPage />}
      </main>
    </div>
  );
}
```

### 2. Building a Custom Chat Interface with Workflow Integration

```tsx
import React, { useState } from 'react';
import { 
  ChatInputArea, 
  ChatMessage, 
  ChatSidePanel 
} from '@/lib/components/chat';
import { FlowChartPanel } from '@/lib/components/activities/FlowChartPanel';
import { Button, Card, CardContent } from '@/lib/components/ui';
import { MessageBanner } from '@/lib/components/common/MessageBanner';
import { useChatContext, useTaskContext } from '@/lib/hooks';
import { formatDate } from '@/lib/utils';

function CustomChatInterface() {
  const { 
    messages, 
    agents, 
    isResponding, 
    sendMessage,
    uploadFile 
  } = useChatContext();
  const { processedSteps, isTaskRunning } = useTaskContext();
  const [showWorkflow, setShowWorkflow] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSendMessage = async (content: string, files?: File[]) => {
    try {
      await sendMessage(content, files);
    } catch (err) {
      setError('Failed to send message');
    }
  };

  return (
    <div className="h-screen flex flex-col">
      {/* Error Banner */}
      {error && (
        <MessageBanner
          variant="error"
          message={error}
          dismissible
          onDismiss={() => setError(null)}
        />
      )}

      <div className="flex-1 flex overflow-hidden">
        {/* Main Chat Area */}
        <div className="flex-1 flex flex-col">
          {/* Message History */}
          <div className="flex-1 overflow-y-auto p-4 space-y-4">
            {messages.map((message, index) => (
              <ChatMessage
                key={message.metadata?.messageId || index}
                message={message}
                isLastWithTaskId={index === messages.length - 1}
              />
            ))}
            
            {isResponding && (
              <div className="flex items-center space-x-2 text-gray-500">
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-900"></div>
                <span>Agent is responding...</span>
              </div>
            )}
          </div>

          {/* Input Area */}
          <div className="border-t bg-white dark:bg-gray-800">
            <ChatInputArea 
              agents={agents}
              onSendMessage={handleSendMessage}
              disabled={isResponding}
            />
          </div>
        </div>

        {/* Workflow Visualization Panel */}
        {showWorkflow && (
          <div className="w-1/2 border-l bg-gray-50 dark:bg-gray-900">
            <div className="h-full flex flex-col">
              <div className="p-4 border-b bg-white dark:bg-gray-800">
                <div className="flex items-center justify-between">
                  <h3 className="text-lg font-semibold">Workflow Visualization</h3>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setShowWorkflow(false)}
                  >
                    ✕
                  </Button>
                </div>
              </div>
              <div className="flex-1 overflow-hidden">
                <FlowChartPanel
                  processedSteps={processedSteps}
                  isRightPanelVisible={true}
                  isSidePanelTransitioning={false}
                />
              </div>
            </div>
          </div>
        )}

        {/* Chat Side Panel */}
        <ChatSidePanel
          isSidePanelCollapsed={false}
          setIsSidePanelCollapsed={() => {}}
          onCollapsedToggle={() => {}}
          isSidePanelTransitioning={false}
        />
      </div>

      {/* Floating Action Button */}
      {!showWorkflow && processedSteps.length > 0 && (
        <Button
          className="fixed bottom-20 right-6 rounded-full shadow-lg"
          onClick={() => setShowWorkflow(true)}
        >
          View Workflow ({processedSteps.length})
        </Button>
      )}
    </div>
  );
}
```

### 3. Creating a Custom Agent Management Dashboard

```tsx
import React, { useState, useEffect } from 'react';
import { AgentMeshCards, LayoutSelector } from '@/lib/components/agents';
import { Header } from '@/lib/components/header/Header';
import { JSONViewer } from '@/lib/components/jsonViewer/JSONViewer';
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle,
  Button,
  Card,
  CardContent,
  Tabs,
  TabsList,
  TabsTrigger,
  TabsContent
} from '@/lib/components/ui';
import { pluginRegistry } from '@/lib/plugins/PluginRegistry';
import { PLUGIN_TYPES } from '@/lib/constants';
import type { AgentCard } from '@/lib/types';

function AgentManagementDashboard() {
  const [agents, setAgents] = useState<AgentCard[]>([]);
  const [selectedAgent, setSelectedAgent] = useState<AgentCard | null>(null);
  const [layout, setLayout] = useState('mesh');
  const [activeTab, setActiveTab] = useState('overview');

  // Get available layout plugins
  const layoutPlugins = pluginRegistry.getPluginsByType(PLUGIN_TYPES.LAYOUT);

  const tabs = [
    { 
      id: 'overview', 
      label: 'Overview', 
      isActive: activeTab === 'overview',
      onClick: () => setActiveTab('overview')
    },
    { 
      id: 'details', 
      label: 'Details', 
      isActive: activeTab === 'details',
      onClick: () => setActiveTab('details')
    }
  ];

  const headerButtons = [
    <LayoutSelector
      key="layout"
      currentLayout={layout}
      onLayoutChange={setLayout}
      availableLayouts={layoutPlugins}
    />,
    <Button key="refresh" variant="outline" onClick={loadAgents}>
      Refresh
    </Button>,
    <Button key="add" variant="default" onClick={() => setShowAddDialog(true)}>
      Add Agent
    </Button>
  ];

  const loadAgents = async () => {
    try {
      // Load agents from API
      const response = await fetch('/api/agents');
      const agentData = await response.json();
      setAgents(agentData);
    } catch (error) {
      console.error('Failed to load agents:', error);
    }
  };

  useEffect(() => {
    loadAgents();
  }, []);

  const renderAgentLayout = () => {
    // Use plugin system to render layout
    const renderedLayout = pluginRegistry.renderPlugin(layout, { agents });
    
    if (renderedLayout) {
      return renderedLayout;
    }

    // Fallback to default mesh layout
    return <AgentMeshCards agents={agents} onAgentSelect={setSelectedAgent} />;
  };

  return (
    <div className="h-screen flex flex-col">
      <Header
        title="Agent Management"
        tabs={tabs}
        buttons={headerButtons}
      />

      <main className="flex-1 overflow-hidden">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="h-full flex flex-col">
          <TabsContent value="overview" className="flex-1 overflow-hidden p-6">
            <div className="h-full">
              {renderAgentLayout()}
            </div>
          </TabsContent>

          <TabsContent value="details" className="flex-1 overflow-auto p-6">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {agents.map((agent) => (
                <Card key={agent.id} className="cursor-pointer hover:shadow-md transition-shadow">
                  <CardContent className="p-4">
                    <h3 className="font-semibold mb-2">{agent.display_name || agent.name}</h3>
                    <p className="text-sm text-gray-600 mb-4">{agent.description}</p>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setSelectedAgent(agent)}
                    >
                      View Details
                    </Button>
                  </CardContent>
                </Card>
              ))}
            </div>
          </TabsContent>
        </Tabs>
      </main>

      {/* Agent Details Dialog */}
      <Dialog open={!!selectedAgent} onOpenChange={() => setSelectedAgent(null)}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {selectedAgent?.display_name || selectedAgent?.name}
            </DialogTitle>
          </DialogHeader>
          
          {selectedAgent && (
            <Tabs defaultValue="config" className="w-full">
              <TabsList>
                <TabsTrigger value="config">Configuration</TabsTrigger>
                <TabsTrigger value="status">Status</TabsTrigger>
                <TabsTrigger value="logs">Logs</TabsTrigger>
              </TabsList>

              <TabsContent value="config" className="mt-4">
                <JSONViewer data={selectedAgent} maxDepth={3} />
              </TabsContent>

              <TabsContent value="status" className="mt-4">
                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="text-sm font-medium">Status</label>
                      <p className="text-green-600">Active</p>
                    </div>
                    <div>

# content_hash: f82045d99b0388557e791d24e7717b45e2d45eafe955539989141cfb208be053

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

## Section 24: frontend/src/lib/plugins/plugins_llm.txt

**Source file:** `frontend/src/lib/plugins/plugins_llm.txt`

# DEVELOPER GUIDE: plugins

## Quick Summary
The plugins directory provides a plugin system for extending UI components, specifically for Agent Mesh layouts. It includes a registry system for managing and rendering plugins with support for different plugin types.

## Files Overview
- `PluginRegistry.tsx` - Main plugin registry class that manages plugin registration, retrieval, and rendering

## Developer API Reference

### PluginRegistry.tsx
**Purpose:** Manages plugin registration and rendering for UI components, particularly Agent Mesh layouts
**Import:** `import { pluginRegistry } from "path/to/plugins/PluginRegistry"`

**Classes:**
- `PluginRegistry()` - Main plugin management system that handles registration and rendering of UI plugins
  - `registerPlugin(plugin: PluginInterface) -> void` - Registers a new plugin in the registry
  - `getPluginById(id: string) -> PluginInterface | undefined` - Retrieves a specific plugin by its ID
  - `getPluginsByType(type: string) -> PluginInterface[]` - Gets all plugins of a specific type
  - `renderPlugin(id: string, data: unknown) -> React.ReactNode | undefined` - Renders a plugin component with provided data
  - `plugins: PluginInterface[]` - Read-only property that returns all registered plugins

**Constants/Variables:**
- `pluginRegistry: PluginRegistry` - Singleton instance of the plugin registry

**Usage Examples:**
```tsx
import { pluginRegistry } from "path/to/plugins/PluginRegistry";
import { PLUGIN_TYPES } from "path/to/plugins/constants";
import { Grid } from "lucide-react";

// Register a custom plugin
pluginRegistry.registerPlugin({
  type: PLUGIN_TYPES.LAYOUT,
  id: "my-custom-layout",
  label: "Custom Layout",
  icon: Grid,
  priority: 200,
  render: (data) => <div>Custom layout for {data.agents?.length} agents</div>
});

// Get a specific plugin
const plugin = pluginRegistry.getPluginById("cards");

// Get all layout plugins
const layoutPlugins = pluginRegistry.getPluginsByType(PLUGIN_TYPES.LAYOUT);

// Render a plugin
const agentData = { agents: [/* agent objects */] };
const renderedComponent = pluginRegistry.renderPlugin("cards", agentData);

// Get all registered plugins
const allPlugins = pluginRegistry.plugins;
```

**Note:** This module requires the following interfaces and constants to be imported from the parent directory:
- `PluginInterface` and `PluginManagerInterface` from the index file
- `PLUGIN_TYPES` from the constants file
- `AgentMeshCards` component from the components directory

# content_hash: 2cf1ddf24a4b03fc68f0fdd04e9472fc0f820997a294b3f342451060f42aad5a

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

## Section 25: frontend/src/lib/providers/providers_llm.txt

**Source file:** `frontend/src/lib/providers/providers_llm.txt`

# DEVELOPER GUIDE: providers

## Quick Summary
The providers directory contains React context providers that manage global application state including authentication, chat functionality, configuration, CSRF tokens, task monitoring, and theming. These providers wrap the application to provide centralized state management and API integration.

## Files Overview
- `AuthProvider.tsx` - Manages user authentication state and login/logout functionality
- `ChatProvider.tsx` - Handles chat messages, file uploads, SSE connections, and chat-related UI state
- `ConfigProvider.tsx` - Fetches and provides application configuration from the backend
- `CsrfProvider.tsx` - Manages CSRF token fetching and caching for secure requests
- `TaskProvider.tsx` - Monitors task execution via SSE and provides task visualization data
- `ThemeProvider.tsx` - Manages light/dark theme switching and applies CSS variables

## Developer API Reference

### AuthProvider.tsx
**Purpose:** Provides authentication context and manages user login state
**Import:** `import { AuthProvider } from "@/lib/providers/AuthProvider"`

**Classes:**
- `AuthProvider(props: AuthProviderProps)` - React component that provides authentication context
  - `children: ReactNode` - Child components to wrap with auth context

**Usage Examples:**
```tsx
import { AuthProvider } from "@/lib/providers/AuthProvider";

function App() {
  return (
    <AuthProvider>
      <YourAppComponents />
    </AuthProvider>
  );
}
```

### ChatProvider.tsx
**Purpose:** Manages chat state, messages, file uploads, and SSE connections
**Import:** `import { ChatProvider } from "@/lib/providers/ChatProvider"`

**Classes:**
- `ChatProvider(props: ChatProviderProps)` - React component that provides chat functionality
  - `children: ReactNode` - Child components to wrap with chat context

**Usage Examples:**
```tsx
import { ChatProvider } from "@/lib/providers/ChatProvider";

function App() {
  return (
    <ChatProvider>
      <ChatInterface />
    </ChatProvider>
  );
}
```

### ConfigProvider.tsx
**Purpose:** Fetches and provides application configuration from backend
**Import:** `import { ConfigProvider } from "@/lib/providers/ConfigProvider"`

**Classes:**
- `ConfigProvider(props: ConfigProviderProps)` - React component that provides config context
  - `children: ReactNode` - Child components to wrap with config context

**Constants/Variables:**
- `RETAINED_CONFIG: ConfigContextValue | null` - Cached configuration to prevent re-fetching
- `RETAINED_ERROR: string | null` - Cached error state

**Usage Examples:**
```tsx
import { ConfigProvider } from "@/lib/providers/ConfigProvider";

function App() {
  return (
    <ConfigProvider>
      <YourAppComponents />
    </ConfigProvider>
  );
}
```

### CsrfProvider.tsx
**Purpose:** Manages CSRF token fetching and provides token access
**Import:** `import { CsrfProvider } from "@/lib/providers/CsrfProvider"`

**Classes:**
- `CsrfProvider(props: CsrfProviderProps)` - React component that provides CSRF token management
  - `children: ReactNode` - Child components to wrap with CSRF context

**Functions:**
- `getCsrfToken(retries?: number, delayMs?: number) -> Promise<string | null>` - Fetches CSRF token from backend with retry logic
- `getCookie(name: string) -> string | null` - Utility to read cookies from document

**Usage Examples:**
```tsx
import { CsrfProvider } from "@/lib/providers/CsrfProvider";

function App() {
  return (
    <CsrfProvider>
      <YourAppComponents />
    </CsrfProvider>
  );
}
```

### TaskProvider.tsx
**Purpose:** Monitors task execution via SSE and provides task visualization data
**Import:** `import { TaskProvider } from "@/lib/providers/TaskProvider"`

**Classes:**
- `TaskProvider(props: TaskProviderProps)` - React component that provides task monitoring
  - `children: ReactNode` - Child components to wrap with task context

**Usage Examples:**
```tsx
import { TaskProvider } from "@/lib/providers/TaskProvider";

function App() {
  return (
    <TaskProvider>
      <TaskMonitoringComponents />
    </TaskProvider>
  );
}
```

### ThemeProvider.tsx
**Purpose:** Manages theme state and applies CSS variables for light/dark themes
**Import:** `import { ThemeProvider } from "@/lib/providers/ThemeProvider"`

**Classes:**
- `ThemeProvider(props: ThemeProviderProps)` - React component that provides theme management
  - `children: ReactNode` - Child components to wrap with theme context

**Functions:**
- `getInitialTheme() -> "light" | "dark"` - Determines initial theme from localStorage or system preference
- `applyThemeToDOM(themePalette: ThemePalette, theme: "light" | "dark") -> void` - Applies theme CSS variables to document root
- `generateCustomTheme(themePalette: ThemePalette, theme?: "light" | "dark") -> Record<string, string>` - Generates CSS variables from theme palette
- `paletteToCSSVariables(themePalette: ThemePalette) -> Record<string, string>` - Converts theme palette to CSS custom properties

**Constants/Variables:**
- `LOCAL_STORAGE_KEY: string` - Key used to store theme preference in localStorage ("sam-theme")

**Usage Examples:**
```tsx
import { ThemeProvider } from "@/lib/providers/ThemeProvider";

function App() {
  return (
    <ThemeProvider>
      <YourThemedComponents />
    </ThemeProvider>
  );
}

// Typical provider stack
function AppWithProviders() {
  return (
    <ThemeProvider>
      <CsrfProvider>
        <ConfigProvider>
          <AuthProvider>
            <TaskProvider>
              <ChatProvider>
                <YourApp />
              </ChatProvider>
            </TaskProvider>
          </AuthProvider>
        </ConfigProvider>
      </CsrfProvider>
    </ThemeProvider>
  );
}
```

# content_hash: 60fa604eee760fc4d28aa0bb0816daae7f8b5cfb629370d304d6c2d4b53e02fa

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

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

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

# DEVELOPER GUIDE: src

## Quick Summary
The `src` directory serves as the main source code for a React-based agent management and chat application. It contains the root application components (`App.tsx`, `main.tsx`) that orchestrate the entire application, along with specialized subdirectories for authentication handling (`auth/`) and the core library (`lib/`). The architecture follows a provider-based pattern with React contexts for state management, a comprehensive component library, and a plugin system for extensibility. The application features real-time chat, workflow visualization, agent management, and OAuth authentication.

## Files and Subdirectories Overview
- **Direct files:**
  - `App.tsx` - Main application component with routing, navigation, and provider setup
  - `main.tsx` - Application entry point that renders the App component to the DOM

- **Subdirectories:**
  - `auth/` - OAuth authentication callback handling components
  - `lib/` - Core library with components, providers, hooks, utilities, and plugin system

## Developer API Reference

### Direct Files

#### App.tsx
**Purpose:** Main application component that sets up the provider hierarchy, handles navigation, and renders different pages based on active navigation state
**Import:** `import App from './App'`

**Components:**
- `App()` - Root component that wraps the application in all necessary providers
  - Sets up provider hierarchy: ThemeProvider → CsrfProvider → ConfigProvider → AuthProvider → ChatProvider → TaskProvider → AppContent
  - Returns the complete application wrapped in context providers

- `AppContent()` - Internal component that handles the main application logic
  - Manages navigation state between "chat" and "agentMesh" views
  - Handles authentication flow with login button when not authenticated
  - Renders NavigationSidebar and main content area
  - Includes ToastContainer for notifications

**State Management:**
- `activeNavItem: string` - Controls which page/view is currently displayed
- Uses `useAuthContext()` for authentication state
- Uses `useBeforeUnload()` for preventing accidental page refresh

#### main.tsx
**Purpose:** Application entry point that renders the App component to the DOM root element
**Import:** This file is typically the webpack entry point, not imported directly

**Functions:**
- Creates React root using `createRoot()` and renders `<App />` in StrictMode
- Imports global CSS styles from `"./lib/index.css"`
- Expects DOM element with id "root" to exist

### Subdirectory APIs

#### auth/
**Purpose:** Handles OAuth authentication callbacks by processing tokens from URL fragments
**Key Exports:** AuthCallback component for processing OAuth redirects
**Import Examples:**
```tsx
import AuthCallback from "./auth/authCallback"
```

#### lib/
**Purpose:** Core library providing React components, context providers, hooks, utilities, types, and plugin system
**Key Exports:** Complete component library, state management providers, custom hooks, utility functions
**Import Examples:**
```tsx
import { Button, Card, Dialog } from "@/lib/components/ui"
import { ChatPage, AgentMeshPage } from "@/lib/components"
import { AuthProvider, ChatProvider, ThemeProvider } from "@/lib/providers"
import { useAuthContext, useBeforeUnload } from "@/lib/hooks"
```

## Complete Usage Guide

### 1. Setting Up the Complete Application

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

// Basic setup - main.tsx
createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// The App component automatically sets up all providers:
// ThemeProvider → CsrfProvider → ConfigProvider → AuthProvider → ChatProvider → TaskProvider
```

### 2. Creating a Custom Application Layout

```tsx
import React, { useState } from 'react';
import { 
  NavigationSidebar, 
  ChatPage, 
  AgentMeshPage,
  ToastContainer,
  Button 
} from '@/lib/components';
import { 
  AuthProvider, 
  ChatProvider, 
  ConfigProvider, 
  CsrfProvider, 
  TaskProvider, 
  ThemeProvider 
} from '@/lib/providers';
import { useAuthContext, useBeforeUnload } from '@/lib/hooks';

// Custom navigation items
const customTopNavItems = [
  { id: 'dashboard', label: 'Dashboard', icon: 'dashboard' },
  { id: 'chat', label: 'Chat', icon: 'chat' },
  { id: 'agents', label: 'Agents', icon: 'agents' }
];

const customBottomNavItems = [
  { id: 'settings', label: 'Settings', icon: 'settings' }
];

function CustomApp() {
  return (
    <ThemeProvider>
      <CsrfProvider>
        <ConfigProvider>
          <AuthProvider>
            <ChatProvider>
              <TaskProvider>
                <CustomAppContent />
              </TaskProvider>
            </ChatProvider>
          </AuthProvider>
        </ConfigProvider>
      </CsrfProvider>
    </ThemeProvider>
  );
}

function CustomAppContent() {
  const [activeView, setActiveView] = useState('dashboard');
  const { isAuthenticated, login, useAuthorization } = useAuthContext();
  
  // Enable beforeunload warning
  useBeforeUnload();

  // Handle authentication
  if (useAuthorization && !isAuthenticated) {
    return (
      <div className="bg-background flex h-screen items-center justify-center">
        <div className="text-center space-y-4">
          <h1 className="text-2xl font-bold">Welcome</h1>
          <p className="text-gray-600">Please log in to continue</p>
          <Button onClick={login} size="lg">
            Login with OAuth
          </Button>
        </div>
      </div>
    );
  }

  const handleNavigation = (itemId: string) => {
    const topItem = customTopNavItems.find(item => item.id === itemId);
    const bottomItem = customBottomNavItems.find(item => item.id === itemId);
    
    if (topItem?.onClick && itemId !== "settings") {
      topItem.onClick();
    } else if (bottomItem?.onClick && itemId !== "settings") {
      bottomItem.onClick();
    } else if (itemId !== "settings") {
      setActiveView(itemId);
    }
  };

  const renderContent = () => {
    switch (activeView) {
      case 'dashboard':
        return <CustomDashboard />;
      case 'chat':
        return <ChatPage />;
      case 'agents':
        return <AgentMeshPage />;
      default:
        return <div>Page not found</div>;
    }
  };

  return (
    <div className="relative flex h-screen">
      <NavigationSidebar
        items={customTopNavItems}
        bottomItems={customBottomNavItems}
        activeItem={activeView}
        onItemChange={handleNavigation}
        onHeaderClick={() => setActiveView('dashboard')}
      />
      <main className="h-full w-full flex-1 overflow-auto">
        {renderContent()}
      </main>
      <ToastContainer />
    </div>
  );
}

function CustomDashboard() {
  return (
    <div className="p-6">
      <h1 className="text-3xl font-bold mb-6">Dashboard</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {/* Dashboard content */}
      </div>
    </div>
  );
}
```

### 3. Integrating OAuth Authentication

```tsx
import React from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import App from './App';
import AuthCallback from './auth/authCallback';

// Setup routing with OAuth callback
function AppWithAuth() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/auth/callback" element={<AuthCallback />} />
        <Route path="/*" element={<App />} />
      </Routes>
    </BrowserRouter>
  );
}

// OAuth configuration
const oauthConfig = {
  clientId: 'your-oauth-client-id',
  redirectUri: `${window.location.origin}/auth/callback`,
  scope: 'read write',
  responseType: 'token'
};

// Custom login function
function initiateOAuthLogin() {
  const params = new URLSearchParams({
    client_id: oauthConfig.clientId,
    redirect_uri: oauthConfig.redirectUri,
    scope: oauthConfig.scope,
    response_type: oauthConfig.responseType
  });
  
  window.location.href = `https://your-oauth-provider.com/oauth/authorize?${params}`;
}

// Usage in a component
function LoginButton() {
  return (
    <Button onClick={initiateOAuthLogin}>
      Login with OAuth
    </Button>
  );
}
```

### 4. Building a Multi-Page Application

```tsx
import React, { useState } from 'react';
import { 
  ChatPage, 
  AgentMeshPage, 
  NavigationSidebar,
  Button,
  Card,
  CardContent 
} from '@/lib/components';
import { useAuthContext } from '@/lib/hooks';

// Define custom pages
function AnalyticsPage() {
  return (
    <div className="p-6">
      <h1 className="text-3xl font-bold mb-6">Analytics</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <Card>
          <CardContent className="p-6">
            <h3 className="text-lg font-semibold mb-2">Total Messages</h3>
            <p className="text-3xl font-bold text-blue-600">1,234</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-6">
            <h3 className="text-lg font-semibold mb-2">Active Agents</h3>
            <p className="text-3xl font-bold text-green-600">12</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-6">
            <h3 className="text-lg font-semibold mb-2">Tasks Completed</h3>
            <p className="text-3xl font-bold text-purple-600">567</p>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

function SettingsPage() {
  return (
    <div className="p-6">
      <h1 className="text-3xl font-bold mb-6">Settings</h1>
      <div className="max-w-2xl space-y-6">
        <Card>
          <CardContent className="p-6">
            <h3 className="text-lg font-semibold mb-4">Theme Settings</h3>
            <div className="space-y-2">
              <Button variant="outline" className="w-full justify-start">
                Light Theme
              </Button>
              <Button variant="outline" className="w-full justify-start">
                Dark Theme
              </Button>
              <Button variant="outline" className="w-full justify-start">
                Auto Theme
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

// Navigation configuration
const navigationItems = [
  { id: 'chat', label: 'Chat', icon: 'chat' },
  { id: 'agents', label: 'Agents', icon: 'agents' },
  { id: 'analytics', label: 'Analytics', icon: 'analytics' }
];

const bottomNavigationItems = [
  { 
    id: 'settings', 
    label: 'Settings', 
    icon: 'settings',
    onClick: () => console.log('Settings clicked')
  }
];

function MultiPageApp() {
  const [currentPage, setCurrentPage] = useState('chat');
  const { isAuthenticated } = useAuthContext();

  const handleNavigation = (pageId: string) => {
    const item = navigationItems.find(item => item.id === pageId) || 
                 bottomNavigationItems.find(item => item.id === pageId);

    if (item?.onClick && pageId !== "settings") {
      item.onClick();
    } else if (pageId !== "settings") {
      setCurrentPage(pageId);
    }
  };

  const renderPage = () => {
    switch (currentPage) {
      case 'chat':
        return <ChatPage />;
      case 'agents':
        return <AgentMeshPage />;
      case 'analytics':
        return <AnalyticsPage />;
      case 'settings':
        return <SettingsPage />;
      default:
        return <ChatPage />;
    }
  };

  if (!isAuthenticated) {
    return (
      <div className="flex h-screen items-center justify-center">
        <Button>Login Required</Button>
      </div>
    );
  }

  return (
    <div className="relative flex h-screen">
      <NavigationSidebar
        items={navigationItems}
        bottomItems={bottomNavigationItems}
        activeItem={currentPage}
        onItemChange={handleNavigation}
        onHeaderClick={() => setCurrentPage('chat')}
      />
      <main className="h-full w-full flex-1 overflow-auto">
        {renderPage()}
      </main>
    </div>
  );
}
```

### 5. Common Integration Patterns

```tsx
// Pattern 1: Using all providers together
import { 
  ThemeProvider,
  CsrfProvider, 
  ConfigProvider,
  AuthProvider,
  ChatProvider,
  TaskProvider 
} from '@/lib/providers';

function FullAppSetup({ children }) {
  return (
    <ThemeProvider>
      <CsrfProvider>
        <ConfigProvider>
          <AuthProvider>
            <ChatProvider>
              <TaskProvider>
                {children}
              </TaskProvider>
            </ChatProvider>
          </AuthProvider>
        </ConfigProvider>
      </CsrfProvider>
    </ThemeProvider>
  );
}

// Pattern 2: Accessing context data
import { useAuthContext, useBeforeUnload } from '@/lib/hooks';

function MyComponent() {
  const { isAuthenticated, login, logout, user } = useAuthContext();
  
  // Enable beforeunload protection
  useBeforeUnload();
  
  return (
    <div>
      {isAuthenticated ? (
        <div>Welcome, {user?.name}!</div>
      ) : (
        <Button onClick={login}>Login</Button>
      )}
    </div>
  );
}

// Pattern 3: Building custom layouts
import { NavigationSidebar, ToastContainer } from '@/lib/components';

function CustomLayout({ children }) {
  const [activeItem, setActiveItem] = useState('home');
  
  return (
    <div className="flex h-screen">
      <NavigationSidebar
        items={myNavItems}
        activeItem={activeItem}
        onItemChange={setActiveItem}
      />
      <main className="flex-1 overflow-auto">
        {children}
      </main>
      <ToastContainer />
    </div>
  );
}
```

This comprehensive guide shows how to use the `src` directory components to build complete React applications with authentication, navigation, chat functionality, and agent management. The modular architecture allows for easy customization and extension while maintaining a consistent development experience.

# content_hash: 1398a8d73766e869414cb70c9d7840836e6a2e29463509fed6579b9a352ee764

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

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

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

# DEVELOPER GUIDE for assets

## Quick Summary
The assets directory contains compiled JavaScript bundles for a React application, including authentication callback handling and core React/React-DOM libraries. These are production-ready, minified files that provide the client-side functionality for the web application.

## Files Overview
- `authCallback-DvlO62me.js` - Handles OAuth authentication callback processing and token storage
- `client-bp6u3qVZ.js` - Core React runtime and utilities bundle with React DOM client functionality

## Developer API Reference

### authCallback-DvlO62me.js
**Purpose:** Processes OAuth authentication callbacks and manages token storage
**Import:** This file is typically loaded directly via script tag, not imported as a module

**Functions:**
- `c()` - Main authentication callback component that processes URL hash parameters and stores tokens

**Usage Examples:**
```html
<!-- Load via script tag in HTML -->
<script src="/static/assets/authCallback-DvlO62me.js"></script>
```

**Functionality:**
- Extracts `access_token` and `refresh_token` from URL hash
- Stores tokens in localStorage
- Redirects to root path on success
- Logs errors if no access token found

### client-bp6u3qVZ.js
**Purpose:** Provides React runtime, React DOM, and core client-side functionality
**Import:** 
```javascript
import { r, j as s, d as a } from "./client-bp6u3qVZ.js"
// or
import React from "./client-bp6u3qVZ.js"
```

**Exported Functions:**
- `r` - React hooks and utilities (useEffect, etc.)
- `j` - JSX runtime functions
- `d` - React DOM createRoot and rendering functions
- `Dd` - Default React export
- `Md` - Module utilities
- `li` - React library functions
- `ay` - Additional React utilities

**Classes:**
- React component classes and hooks system
- React DOM rendering system
- Event handling system
- State management utilities

**Usage Examples:**
```javascript
// Using React hooks
import { r } from "./client-bp6u3qVZ.js";
const { useEffect, useState } = r;

// Using JSX runtime
import { j as jsx } from "./client-bp6u3qVZ.js";

// Using React DOM
import { d as ReactDOM } from "./client-bp6u3qVZ.js";
const root = ReactDOM.createRoot(document.getElementById('root'));
```

**Constants/Variables:**
- React version: "19.1.0"
- Various React internal constants and configurations
- Event system configurations
- DOM manipulation utilities

**Note:** These are minified production bundles. The actual API surface matches standard React 19.1.0 and React DOM APIs. For development, refer to official React documentation for the complete API reference.

# content_hash: ee013ec825f58da578f2aad9a38b137f6c15eeea8bb29407bad411b79ea27a6c

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

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

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

# DEVELOPER GUIDE for static

## Quick Summary
The static directory serves as the web application's static asset repository, containing compiled JavaScript bundles for client-side functionality. The primary subdirectory `assets/` houses production-ready, minified JavaScript files that provide React-based frontend functionality including authentication handling and core React runtime libraries.

## Files and Subdirectories Overview
- **Direct files:** None
- **Subdirectories:** 
  - `assets/` - Contains compiled JavaScript bundles for React application frontend

## Developer API Reference

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

### Subdirectory APIs

#### assets/
**Purpose:** Provides compiled JavaScript bundles for React-based web application frontend
**Key Exports:** React runtime, authentication callback handler, JSX utilities, React DOM functionality
**Import Examples:**
```javascript
// React hooks and utilities
import { r } from "/static/assets/client-bp6u3qVZ.js";

// JSX runtime
import { j as jsx } from "/static/assets/client-bp6u3qVZ.js";

// React DOM
import { d as ReactDOM } from "/static/assets/client-bp6u3qVZ.js";
```

**HTML Script Loading:**
```html
<!-- Authentication callback -->
<script src="/static/assets/authCallback-DvlO62me.js"></script>

<!-- Core React bundle -->
<script src="/static/assets/client-bp6u3qVZ.js"></script>
```

## Complete Usage Guide

### 1. Setting Up React Application

```html
<!DOCTYPE html>
<html>
<head>
    <title>React App</title>
</head>
<body>
    <div id="root"></div>
    
    <!-- Load core React bundle -->
    <script src="/static/assets/client-bp6u3qVZ.js"></script>
    
    <script type="module">
        // Import React functionality
        import { r, j as jsx, d as ReactDOM } from "/static/assets/client-bp6u3qVZ.js";
        
        // Use React hooks
        const { useEffect, useState } = r;
        
        // Create and render React component
        function App() {
            const [count, setCount] = useState(0);
            
            useEffect(() => {
                console.log('Component mounted');
            }, []);
            
            return jsx('div', {
                children: [
                    jsx('h1', { children: 'Hello React!' }),
                    jsx('button', {
                        onClick: () => setCount(count + 1),
                        children: `Count: ${count}`
                    })
                ]
            });
        }
        
        // Render to DOM
        const root = ReactDOM.createRoot(document.getElementById('root'));
        root.render(jsx(App));
    </script>
</body>
</html>
```

### 2. Authentication Callback Handling

```html
<!-- On your OAuth callback page -->
<!DOCTYPE html>
<html>
<head>
    <title>Auth Callback</title>
</head>
<body>
    <div id="auth-callback">Processing authentication...</div>
    
    <!-- Load authentication handler -->
    <script src="/static/assets/authCallback-DvlO62me.js"></script>
    
    <!-- The script automatically:
         1. Extracts access_token and refresh_token from URL hash
         2. Stores tokens in localStorage
         3. Redirects to root path on success
         4. Logs errors if tokens not found
    -->
</body>
</html>
```

### 3. Module-based Import Pattern

```javascript
// In your ES6 modules
import { 
    r as React,           // React hooks and utilities
    j as jsx,            // JSX runtime functions
    d as ReactDOM,       // React DOM functionality
    Dd as ReactDefault,  // Default React export
    li as ReactLib       // React library functions
} from "/static/assets/client-bp6u3qVZ.js";

// Create a component using hooks
function MyComponent() {
    const { useState, useEffect } = React;
    const [data, setData] = useState(null);
    
    useEffect(() => {
        // Component logic
        fetchData().then(setData);
    }, []);
    
    return jsx('div', {
        className: 'my-component',
        children: data ? jsx('p', { children: data }) : jsx('p', { children: 'Loading...' })
    });
}

// Render component
const container = document.getElementById('app');
const root = ReactDOM.createRoot(container);
root.render(jsx(MyComponent));
```

### 4. Authentication Flow Integration

```javascript
// Check for stored authentication tokens
function checkAuth() {
    const accessToken = localStorage.getItem('access_token');
    const refreshToken = localStorage.getItem('refresh_token');
    
    if (accessToken && refreshToken) {
        return { accessToken, refreshToken };
    }
    
    // Redirect to OAuth provider
    window.location.href = '/auth/login';
    return null;
}

// Use in React component
import { r as React, j as jsx } from "/static/assets/client-bp6u3qVZ.js";

function AuthenticatedApp() {
    const { useState, useEffect } = React;
    const [auth, setAuth] = useState(null);
    const [loading, setLoading] = useState(true);
    
    useEffect(() => {
        const authData = checkAuth();
        setAuth(authData);
        setLoading(false);
    }, []);
    
    if (loading) {
        return jsx('div', { children: 'Loading...' });
    }
    
    if (!auth) {
        return jsx('div', { children: 'Redirecting to login...' });
    }
    
    return jsx('div', {
        children: [
            jsx('h1', { children: 'Welcome!' }),
            jsx('p', { children: 'You are authenticated.' })
        ]
    });
}
```

### 5. Common Usage Patterns

```javascript
// Pattern 1: Simple component with state
import { r, j as jsx, d as ReactDOM } from "/static/assets/client-bp6u3qVZ.js";

const { useState } = r;

function Counter() {
    const [count, setCount] = useState(0);
    
    return jsx('div', {
        children: [
            jsx('h2', { children: `Count: ${count}` }),
            jsx('button', {
                onClick: () => setCount(count + 1),
                children: 'Increment'
            })
        ]
    });
}

// Pattern 2: Effect hook for side effects
const { useEffect, useState } = r;

function DataFetcher() {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);
    
    useEffect(() => {
        fetch('/api/data')
            .then(response => response.json())
            .then(result => {
                setData(result);
                setLoading(false);
            });
    }, []);
    
    return jsx('div', {
        children: loading 
            ? jsx('p', { children: 'Loading...' })
            : jsx('ul', {
                children: data.map(item => 
                    jsx('li', { key: item.id, children: item.name })
                )
            })
    });
}

// Pattern 3: Rendering multiple components
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(jsx('div', {
    children: [
        jsx(Counter),
        jsx(DataFetcher)
    ]
}));
```

**Note:** These are production-minified bundles based on React 19.1.0. For development and detailed API documentation, refer to the official React documentation. The authentication callback script works automatically when loaded on OAuth callback pages.

# content_hash: 8e5fc1a26d5a9a4a51d77f39a467b999c9e9bfe4e719bb11103342cdc6dd845e

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

## Section 29: 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">

# content_hash: 0856c53d55b1f22e1af65b7d9a1e54b37f83fbcab63582ea849d4c2a177e14f0

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

