npm package: @houslo/chat-ui
Description: Reusable chat UI components for AI agents with streaming, tool execution, and knowledge source visualization
Author: Houslo Agent Team
Latest version: 0.0.52

# @houslo/chat-ui

Production-ready React chat UI components for AI agents with streaming, tool execution visualization, and knowledge source display.

## Features

✅ **Real-time Streaming** - Server-Sent Events (SSE) support  
✅ **Tool Execution Visualization** - Show AI tool calls in real-time  
✅ **Knowledge Sources** - Display retrieved knowledge with relevance scores  
✅ **Chain of Thought** - Multi-step reasoning visualization  
✅ **Model Selection** - Switch between AI models dynamically  
✅ **Context Management** - Attach knowledge contexts to chats  
✅ **Agent Auto-Discovery** - Automatic agent configuration from API  
✅ **Markdown Rendering** - Full markdown support with code highlighting  
✅ **Message Actions** - Like, dislike, share, copy, regenerate  
✅ **Auto-scroll** - Smart scrolling during streaming  
✅ **Dark Mode** - Full dark mode support  
✅ **TypeScript** - Fully typed components  

## Installation

```bash
yarn add @houslo/chat-ui
# or
npm install @houslo/chat-ui
```

### Peer Dependencies

```bash
yarn add react react-dom
```

## Usage

### Basic Example

```typescript
import { ChatContainer } from '@houslo/chat-ui';
import '@houslo/chat-ui/styles.css';

function App() {
  return (
    <ChatContainer
      apiUrl="http://localhost:3000"
      agentId="my-agent"
      authToken={yourJWTToken}
      onSendMessage={(message) => console.log('New message:', message)}
    />
  );
}
```

### Advanced Example with useChatStream Hook

```typescript
import { ChatContainer, useChatStream } from '@houslo/chat-ui';
import '@houslo/chat-ui/styles.css';

function AdvancedChat() {
  const {
    messages,
    isStreaming,
    isLoading,
    sendMessage,
    retryMessage,
    userName,
    userAvatar,
  } = useChatStream({
    apiUrl: process.env.NEXT_PUBLIC_API_URL,
    agentId: 'my-agent',
    authToken: getAuthToken(),
    chatId: 'existing-chat-id', // Optional: continue existing chat
    settings: {
      persist: true, // Enable chat persistence
    },
    onChatCreated: (data) => {
      console.log('Chat created:', data.chatId);
    },
    onKnowledgeSources: (sources) => {
      console.log('Knowledge sources:', sources);
    },
  });

  return (
    <ChatContainer
      messages={messages}
      isStreaming={isStreaming}
      isLoading={isLoading}
      onSendMessage={sendMessage}
      onRetryMessage={retryMessage}
      userName={userName}
      userAvatar={userAvatar}
      agentName="AI Assistant"
      apiUrl={process.env.NEXT_PUBLIC_API_URL}
      autoDiscoverAgent={true} // Auto-fetch agent config
    />
  );
}
```

### With Context Management

```typescript
<ChatContainer
  chatId="chat-123"
  apiUrl="http://localhost:3000"
  enableContextManagement={true}
  maxContextSelections={10}
  // ... other props
/>
```

### With Forced Tool Execution

```typescript
const message = {
  role: 'user',
  content: 'What are the safety requirements?',
  annotation: {
    forced_tools: [
      {
        tool: 'knowledge_search',
        args: { query: 'safety requirements' }
      }
    ]
  }
};

sendMessage(message);
```

## API Reference

### `<ChatContainer />`

Main chat UI component with auto-discovery support.

**Props:**
```typescript
interface ChatContainerProps {
  // Core chat state
  messages: ChatMessage[];
  isLoading: boolean;
  isStreaming: boolean;
  
  // User info
  userName: string;
  userAvatar?: string;
  
  // Agent info (can be provided or auto-discovered)
  agentName?: string;
  agentLogoUrl?: string;
  agentConfig?: AgentConfig;
  
  // Auto-discovery
  autoDiscoverAgent?: boolean; // default: true
  onAgentDiscovered?: (config: AgentConfig) => void;
  
  // API configuration
  apiUrl?: string;
  
  // Context management
  chatId?: string;
  enableContextManagement?: boolean;
  maxContextSelections?: number;
  
  // Message handlers
  onSendMessage: (content: string | ChatMessage) => void;
  onStopStreaming?: () => void;
  onRetryMessage?: (messageId: string) => void;
  onLikeMessage?: (messageId: string) => void;
  onDislikeMessage?: (messageId: string) => void;
  onShareMessage?: (messageId: string) => void;
  
  // Example prompts
  examplePrompts?: (string | PromptSuggestion)[];
  showPromptsWhen?: 'empty' | 'always' | 'never';
  promptsTitle?: string;
  promptsSubtitle?: string;
  
  // Styling
  className?: string;
  messageContainerClassName?: string;
  inputPlaceholder?: string;
}
```

### `useChatStream()`

React hook for SSE streaming chat.

**Parameters:**
```typescript
interface UseChatStreamOptions {
  apiUrl: string;
  agentId: string;
  authToken?: string;
  chatId?: string; // Pass existing chatId to continue conversation
  settings?: {
    persist?: boolean;
    model?: string;
    contextIds?: string[];
  };
  onChatCreated?: (data: { chatId: string }) => void;
  onChunk?: (text: string) => void;
  onToolStep?: (step: ToolStep) => void;
  onKnowledgeSources?: (sources: KnowledgeSource[]) => void;
  onComplete?: () => void;
  onError?: (error: string) => void;
}
```

**Returns:**
```typescript
{
  messages: ChatMessage[];
  isStreaming: boolean;
  isLoading: boolean;
  currentChatId: string | null;
  sendMessage: (content: string | ChatMessage) => Promise<void>;
  retryMessage: (messageId: string) => Promise<void>;
  stopStreaming: () => void;
  clearMessages: () => void;
  // Feedback actions
  likeMessage: (messageId: string) => void;
  dislikeMessage: (messageId: string) => void;
  shareMessage: (messageId: string) => void;
  copyMessage: (messageId: string) => void;
  // User profile from JWT
  userProfile: UserProfile | null;
  userName: string;
  userAvatar: string | undefined;
  userInitials: string;
}
```

### `useAgentConfig()`

Hook for auto-discovering agent configuration.

```typescript
const { agentConfig, isLoading, error } = useAgentConfig(apiUrl, {
  autoDiscover: true,
});
```

## Components

### Message Components
- `ChatMessage` - Individual message with avatar and actions
- `MessageMarkdown` - Markdown rendering with syntax highlighting

### Tool Components
- `ToolVisualization` - Tool execution display
- `ChainOfThought` - Collapsible reasoning display

### Input Components
- `PromptInput` - Feature-rich message input
- `PromptSuggestions` - Clickable prompt suggestions

### Chart Components
- `BarChart` - Bar chart visualization
- `LineChart` - Line chart visualization
- `DataTable` - Data table display
- `StatCard` / `StatGrid` - Statistics cards

### Context Components
- `ContextPopover` - Context selection modal
- `ContextCategories` - Category-based context browsing

## Styling

### Tailwind CSS

The package uses Tailwind CSS. Include the styles:

```typescript
import '@houslo/chat-ui/styles.css';
```

### CSS Variables

Customize colors with CSS variables:

```css
:root {
  --background: 0 0% 100%;
  --foreground: 222.2 84% 4.9%;
  --primary: 221.2 83.2% 53.3%;
  --secondary: 210 40% 96.1%;
  --muted: 210 40% 96.1%;
  --border: 214.3 31.8% 91.4%;
}

.dark {
  --background: 222.2 84% 4.9%;
  --foreground: 210 40% 98%;
  --primary: 217.2 91.2% 59.8%;
  --secondary: 217.2 32.6% 17.5%;
  --muted: 217.2 32.6% 17.5%;
  --border: 217.2 32.6% 17.5%;
}
```

## SSE Events

The package handles these Server-Sent Events:

- `chat-created` - New chat was created
- `response-chunk` - Text delta from AI
- `tool-step` - Tool execution update
- `knowledge-sources` - Knowledge search results
- `response-complete` - Stream finished
- `error` - Error occurred

## Development

```bash
# Install dependencies
yarn install

# Development mode
yarn dev

# Build package
yarn build

# Type check
yarn type-check
```

## License

MIT

## Support

For issues and feature requests, please open an issue on GitHub.