{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chat-reasoning-demo",
  "registryDependencies": [
    "@delta/ai-elements"
  ],
  "files": [
    {
      "path": "examples/chat-reasoning-demo.tsx",
      "content": "\"use client\"\n\nimport { useCallback, useRef, useState } from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { ChatContainer } from \"@/components/ui/ai-elements/chat-container\"\nimport {\n  Conversation,\n  ConversationContent,\n  ConversationScrollButton,\n} from \"@/components/ui/ai-elements/conversation\"\nimport {\n  Message,\n  MessageContent,\n} from \"@/components/ui/ai-elements/message\"\nimport {\n  PromptInput,\n  PromptInputActionAddAttachments,\n  PromptInputActionMenu,\n  PromptInputActionMenuContent,\n  PromptInputActionMenuTrigger,\n  PromptInputAttachment,\n  PromptInputAttachments,\n  PromptInputBody,\n  PromptInputFooter,\n  PromptInputModelSelect,\n  PromptInputModelSelectContent,\n  PromptInputModelSelectItem,\n  PromptInputModelSelectTrigger,\n  PromptInputModelSelectValue,\n  PromptInputSubmit,\n  PromptInputTextarea,\n  PromptInputTools,\n  type PromptInputMessage,\n} from \"@/components/ui/ai-elements/prompt-input\"\nimport {\n  Reasoning,\n  ReasoningContent,\n  ReasoningTrigger,\n} from \"@/components/ui/ai-elements/reasoning\"\nimport { Response } from \"@/components/ui/ai-elements/response\"\n\ntype MessageType = {\n  key: string\n  from: \"user\" | \"assistant\"\n  content: string\n  reasoning?: {\n    content: string\n    isStreaming?: boolean\n  }\n  avatar: string\n  name: string\n}\n\nconst initialMessages: MessageType[] = []\n\nconst models = [\n  { id: \"gpt-4\", name: \"GPT-4\" },\n  { id: \"claude-2\", name: \"Claude 2\" },\n  { id: \"palm-2\", name: \"PaLM 2\" },\n]\n\nconst reasoningTexts = [\n  \"The user is asking about implementing a complex feature. Let me break this down systematically:\\n\\n1. First, I need to understand the technical requirements and constraints\\n2. Consider the existing architecture and how this fits in\\n3. Think about potential edge cases and error handling\\n4. Evaluate different implementation approaches\\n5. Consider performance implications and scalability\\n\\nBased on the context, I should provide a comprehensive solution that addresses both the immediate need and long-term maintainability. I'll structure my response to include code examples, best practices, and potential pitfalls to avoid.\",\n\n  \"This is an interesting technical question that requires careful analysis. Let me think through this step by step:\\n\\n• The user seems to be dealing with a state management issue\\n• There are multiple approaches we could take here\\n• I need to consider the trade-offs between different solutions\\n• Performance and user experience are key factors\\n• Code maintainability is also important\\n\\nI should recommend the most appropriate solution based on their specific use case, while also explaining why other approaches might not be optimal. I'll provide practical examples and explain the reasoning behind my recommendations.\",\n\n  \"This question touches on several important concepts in modern web development. Let me organize my thoughts:\\n\\n**Key considerations:**\\n- Browser compatibility and progressive enhancement\\n- Accessibility requirements and WCAG guidelines\\n- Performance optimization strategies\\n- Security implications and best practices\\n- Testing approaches for robustness\\n\\nI need to provide a balanced answer that considers both the technical implementation details and the broader implications for user experience. I'll include specific code examples and explain the rationale behind each recommendation.\",\n\n  \"The user is asking about a common development challenge. Let me approach this methodically:\\n\\n1. **Problem Analysis**: Understanding the root cause and requirements\\n2. **Solution Design**: Evaluating different architectural patterns\\n3. **Implementation Strategy**: Breaking down the work into manageable steps\\n4. **Risk Assessment**: Identifying potential issues and mitigation strategies\\n5. **Testing Plan**: Ensuring reliability and edge case coverage\\n\\nI should provide a comprehensive response that not only solves their immediate problem but also helps them understand the underlying principles so they can apply this knowledge to similar challenges in the future.\",\n\n  \"This is a nuanced question that requires me to consider multiple factors:\\n\\n• **Technical feasibility**: What's possible with current technologies\\n• **Performance implications**: How will this affect application speed and responsiveness\\n• **User experience**: How will users interact with this feature\\n• **Maintenance overhead**: Long-term code sustainability\\n• **Team considerations**: Skill level and development workflow\\n\\nI need to balance these competing concerns and provide a recommendation that's both technically sound and practically implementable. I'll explain my reasoning process so the user understands not just what to do, but why it's the best approach for their situation.\",\n]\n\nconst responses = [\n  \"Based on my analysis, here's the approach I'd recommend:\\n\\n```typescript\\n// Example implementation\\nconst useFeature = () => {\\n  const [state, setState] = useState(initialState);\\n  \\n  const handleUpdate = useCallback((data) => {\\n    // Validate input\\n    if (!data || typeof data !== 'object') {\\n      throw new Error('Invalid data provided');\\n    }\\n    \\n    // Update state with proper error handling\\n    setState(prev => ({ ...prev, ...data }));\\n  }, []);\\n  \\n  return { state, handleUpdate };\\n};\\n```\\n\\n**Key considerations:**\\n- Type safety with TypeScript for better developer experience\\n- Proper error handling to prevent crashes\\n- Performance optimization with useCallback\\n- Immutable state updates for predictable behavior\\n\\nThis pattern scales well and provides a solid foundation for future enhancements.\",\n\n  'Here\\'s a comprehensive solution that addresses your requirements:\\n\\n## Implementation Strategy\\n\\n1. **Component Architecture**\\n   ```jsx\\n   // Main component structure\\n   const MyComponent = ({ data, onUpdate }) => {\\n     return (\\n       <div className=\"container\">\\n         <Header data={data} />\\n         <Content onUpdate={onUpdate} />\\n         <Footer />\\n       </div>\\n     );\\n   };\\n   ```\\n\\n2. **State Management**\\n   - Use React Context for global state\\n   - Local state for component-specific data\\n   - Custom hooks for reusable logic\\n\\n3. **Performance Optimizations**\\n   - Implement proper memoization\\n   - Use lazy loading for heavy components\\n   - Optimize bundle size with code splitting\\n\\nThis approach provides excellent maintainability while keeping performance optimal.',\n\n  \"After analyzing the requirements, here's my recommended solution:\\n\\n## Technical Implementation\\n\\n```javascript\\n// Core functionality\\nclass DataProcessor {\\n  constructor(options = {}) {\\n    this.options = { timeout: 5000, ...options };\\n    this.cache = new Map();\\n  }\\n  \\n  async process(input) {\\n    const cacheKey = this.generateKey(input);\\n    \\n    if (this.cache.has(cacheKey)) {\\n      return this.cache.get(cacheKey);\\n    }\\n    \\n    const result = await this.performProcessing(input);\\n    this.cache.set(cacheKey, result);\\n    \\n    return result;\\n  }\\n}\\n```\\n\\n## Best Practices Applied\\n\\n- **Caching**: Improves performance for repeated operations\\n- **Error Handling**: Robust error management throughout\\n- **Modularity**: Clean separation of concerns\\n- **Testing**: Easy to unit test each component\\n\\nThis solution handles edge cases gracefully and provides excellent performance characteristics.\",\n\n  \"Here's a complete implementation that follows modern best practices:\\n\\n## Solution Overview\\n\\n```typescript\\ninterface Config {\\n  apiUrl: string;\\n  timeout: number;\\n  retryAttempts: number;\\n}\\n\\nclass ApiClient {\\n  private config: Config;\\n  \\n  constructor(config: Config) {\\n    this.config = config;\\n  }\\n  \\n  async makeRequest<T>(endpoint: string, options?: RequestOptions): Promise<T> {\\n    for (let attempt = 1; attempt <= this.config.retryAttempts; attempt++) {\\n      try {\\n        const response = await fetch(`${this.config.apiUrl}${endpoint}`, {\\n          ...options,\\n          signal: AbortSignal.timeout(this.config.timeout)\\n        });\\n        \\n        if (!response.ok) {\\n          throw new Error(`HTTP ${response.status}: ${response.statusText}`);\\n        }\\n        \\n        return await response.json();\\n      } catch (error) {\\n        if (attempt === this.config.retryAttempts) {\\n          throw error;\\n        }\\n        await this.delay(1000 * attempt); // Exponential backoff\\n      }\\n    }\\n  }\\n}\\n```\\n\\n## Key Features\\n\\n- **Type Safety**: Full TypeScript support\\n- **Error Handling**: Comprehensive error management\\n- **Retry Logic**: Automatic retry with exponential backoff\\n- **Timeout Handling**: Prevents hanging requests\\n- **Extensibility**: Easy to extend for additional features\\n\\nThis implementation is production-ready and handles real-world scenarios effectively.\",\n\n  'Based on my analysis, here\\'s a robust solution:\\n\\n## Architecture Decision\\n\\nI recommend using a **microservices approach** with the following structure:\\n\\n```yaml\\n# docker-compose.yml\\nversion: \\'3.8\\'\\nservices:\\n  api:\\n    build: ./api\\n    ports:\\n      - \"3001:3001\"\\n    environment:\\n      - NODE_ENV=production\\n      - DB_HOST=database\\n    depends_on:\\n      - database\\n      - redis\\n  \\n  frontend:\\n    build: ./frontend\\n    ports:\\n      - \"3000:3000\"\\n    depends_on:\\n      - api\\n  \\n  database:\\n    image: postgres:15\\n    environment:\\n      POSTGRES_DB: myapp\\n      POSTGRES_USER: user\\n      POSTGRES_PASSWORD: password\\n  \\n  redis:\\n    image: redis:7-alpine\\n```\\n\\n## Implementation Benefits\\n\\n- **Scalability**: Each service can scale independently\\n- **Maintainability**: Clear separation of concerns\\n- **Reliability**: Fault isolation between services\\n- **Development**: Teams can work on services independently\\n- **Deployment**: Independent deployment pipelines\\n\\nThis architecture supports your current needs while providing room for future growth and complexity.',\n]\n\nconst Example = () => {\n  const [model, setModel] = useState<string>(models[0].id)\n  const [text, setText] = useState<string>(\"\")\n  const [status, setStatus] = useState<\n    \"submitted\" | \"streaming\" | \"ready\" | \"error\"\n  >(\"ready\")\n  const [messages, setMessages] = useState<MessageType[]>(initialMessages)\n  const shouldCancelRef = useRef<boolean>(false)\n  const textareaRef = useRef<HTMLTextAreaElement>(null)\n\n  const stop = useCallback(() => {\n    shouldCancelRef.current = true\n    setStatus(\"ready\")\n  }, [])\n\n  const streamReasoningText = useCallback(\n    async (messageKey: string, reasoningContent: string) => {\n      const words = reasoningContent.split(\" \")\n      let currentContent = \"\"\n\n      for (let i = 0; i < words.length; i++) {\n        if (shouldCancelRef.current) {\n          return\n        }\n\n        currentContent += (i > 0 ? \" \" : \"\") + words[i]\n\n        setMessages((prev) =>\n          prev.map((msg) =>\n            msg.key === messageKey\n              ? {\n                  ...msg,\n                  reasoning: {\n                    ...msg.reasoning!,\n                    content: currentContent,\n                  },\n                }\n              : msg\n          )\n        )\n\n        await new Promise((resolve) =>\n          setTimeout(resolve, Math.random() * 80 + 40)\n        )\n      }\n    },\n    []\n  )\n\n  const streamResponseText = useCallback(\n    async (messageKey: string, responseContent: string) => {\n      const words = responseContent.split(\" \")\n      let currentContent = \"\"\n\n      for (let i = 0; i < words.length; i++) {\n        if (shouldCancelRef.current) {\n          return\n        }\n\n        currentContent += (i > 0 ? \" \" : \"\") + words[i]\n\n        setMessages((prev) =>\n          prev.map((msg) =>\n            msg.key === messageKey ? { ...msg, content: currentContent } : msg\n          )\n        )\n\n        await new Promise((resolve) =>\n          setTimeout(resolve, Math.random() * 100 + 50)\n        )\n      }\n    },\n    []\n  )\n\n  const addUserMessage = useCallback(\n    async (content: string) => {\n      const userMessage: MessageType = {\n        key: `user-${Date.now()}`,\n        from: \"user\",\n        content,\n        avatar: \"https://patrickprunty.com/icon.webp\",\n        name: \"User\",\n      }\n\n      setMessages((prev) => [...prev, userMessage])\n\n      // Add assistant message with empty reasoning\n      const assistantMessage: MessageType = {\n        key: `assistant-${Date.now()}`,\n        from: \"assistant\",\n        content: \"\",\n        reasoning: {\n          content: \"\",\n          isStreaming: true,\n        },\n        avatar: \"https://github.com/openai.png\",\n        name: \"Assistant\",\n      }\n\n      setMessages((prev) => [...prev, assistantMessage])\n      setStatus(\"streaming\")\n\n      // Stream reasoning text\n      const selectedReasoningText =\n        reasoningTexts[Math.floor(Math.random() * reasoningTexts.length)]\n      await streamReasoningText(assistantMessage.key, selectedReasoningText)\n\n      if (!shouldCancelRef.current) {\n        // Mark reasoning as complete\n        setMessages((prev) =>\n          prev.map((msg) =>\n            msg.key === assistantMessage.key\n              ? {\n                  ...msg,\n                  reasoning: {\n                    ...msg.reasoning!,\n                    isStreaming: false,\n                  },\n                }\n              : msg\n          )\n        )\n\n        // Wait a moment then start streaming response\n        setTimeout(async () => {\n          if (!shouldCancelRef.current) {\n            const selectedResponse =\n              responses[Math.floor(Math.random() * responses.length)]\n            await streamResponseText(assistantMessage.key, selectedResponse)\n            setStatus(\"ready\")\n          }\n        }, 500)\n      }\n    },\n    [streamReasoningText, streamResponseText]\n  )\n\n  const handleSubmit = (message: PromptInputMessage) => {\n    if (status === \"streaming\") {\n      stop()\n      return\n    }\n\n    const hasText = Boolean(message.text)\n    const hasAttachments = Boolean(message.files?.length)\n\n    if (!(hasText || hasAttachments)) {\n      return\n    }\n\n    setStatus(\"submitted\")\n    addUserMessage(message.text || \"Sent with attachments\")\n    setText(\"\")\n  }\n\n  return (\n    <ChatContainer>\n      <Conversation>\n        <ConversationContent>\n          {messages.map((message) => (\n            <Message\n              from={message.from}\n              key={message.key}\n              className={cn(\n                message.from === \"user\" ? \"items-end justify-end\" : undefined,\n                \"group/message\"\n              )}\n            >\n              <div>\n                {message.reasoning && (\n                  <Reasoning\n                    isStreaming={message.reasoning.isStreaming}\n                    defaultOpen={true}\n                  >\n                    <ReasoningTrigger />\n                    <ReasoningContent>\n                      {message.reasoning.content}\n                    </ReasoningContent>\n                  </Reasoning>\n                )}\n                <MessageContent\n                  className={cn(\n                    message.from === \"assistant\" ? \"max-w-full\" : \"\",\n                    message.from === \"user\" && \"ml-auto w-fit\"\n                  )}\n                >\n                  <div className=\"text-base leading-[1.65rem]\">\n                    {message.content && <Response>{message.content}</Response>}\n                  </div>\n                </MessageContent>\n              </div>\n            </Message>\n          ))}\n        </ConversationContent>\n        <ConversationScrollButton />\n      </Conversation>\n      <div className=\"grid shrink-0 gap-4\">\n        <div className=\"w-full px-4 pb-4\">\n          <PromptInput globalDrop multiple onSubmit={handleSubmit}>\n            <PromptInputBody>\n              <PromptInputAttachments>\n                {(attachment: any) => (\n                  <PromptInputAttachment data={attachment} />\n                )}\n              </PromptInputAttachments>\n              <PromptInputTextarea\n                onChange={(event: any) => setText(event.target.value)}\n                ref={textareaRef}\n                value={text}\n                className=\"text-base leading-[1.65rem]\"\n                placeholder=\"Ask anything...\"\n              />\n            </PromptInputBody>\n            <PromptInputFooter>\n              <PromptInputTools>\n                <PromptInputActionMenu>\n                  <PromptInputActionMenuTrigger />\n                  <PromptInputActionMenuContent>\n                    <PromptInputActionAddAttachments />\n                  </PromptInputActionMenuContent>\n                </PromptInputActionMenu>\n              </PromptInputTools>\n              <PromptInputTools>\n                <PromptInputModelSelect onValueChange={setModel} value={model}>\n                  <PromptInputModelSelectTrigger>\n                    <PromptInputModelSelectValue />\n                  </PromptInputModelSelectTrigger>\n                  <PromptInputModelSelectContent>\n                    {models.map((model: any) => (\n                      <PromptInputModelSelectItem\n                        key={model.id || model.name}\n                        value={model.id || model.name}\n                      >\n                        {model.name || model.id}\n                      </PromptInputModelSelectItem>\n                    ))}\n                  </PromptInputModelSelectContent>\n                </PromptInputModelSelect>\n                <PromptInputSubmit\n                  disabled={(!text.trim() && !status) || status === \"streaming\"}\n                  status={status}\n                />\n              </PromptInputTools>\n            </PromptInputFooter>\n          </PromptInput>\n        </div>\n      </div>\n    </ChatContainer>\n  )\n}\n\nexport default Example\n",
      "type": "registry:example"
    }
  ],
  "type": "registry:example"
}