'use client'; import { FormEvent, useEffect, useRef, useState } from 'react'; import { IconBrain, IconCheck, IconChevronDown, IconChevronRight, IconCode, IconEdit, IconEye, IconFile, IconListCheck, IconLoader2, IconPaperclip, IconSearch, IconTerminal2, IconX, } from '@tabler/icons-react'; import ReactMarkdown from 'react-markdown'; import remarkBreaks from 'remark-breaks'; import remarkGfm from 'remark-gfm'; import { Button } from '@kandev/ui/button'; import { Textarea } from '@kandev/ui/textarea'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@kandev/ui/dropdown-menu'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@kandev/ui/select'; import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip'; import { cn } from '@/lib/utils'; import { useAppStore } from '@/components/state-provider'; import type { Comment } from '@/lib/types/http'; type AgentOption = { id: string; label: string; }; type TaskChatPanelProps = { agents: AgentOption[]; onSend: (message: string) => void; isLoading?: boolean; isAgentWorking?: boolean; }; type ToolCallMetadata = { tool_call_id?: string; tool_name?: string; title?: string; status?: 'pending' | 'running' | 'complete' | 'error'; args?: Record; result?: string; }; function getToolIconElement(toolName?: string, className?: string) { const name = toolName?.toLowerCase() ?? ''; // Match ACP ToolKind values: read, edit, delete, move, search, execute if (name === 'edit' || name.includes('edit') || name.includes('replace') || name.includes('write') || name.includes('save')) { return ; } if (name === 'read' || name.includes('view') || name.includes('read')) { return ; } if (name === 'search' || name.includes('search') || name.includes('find') || name.includes('retrieval')) { return ; } if (name === 'execute' || name.includes('terminal') || name.includes('exec') || name.includes('launch') || name.includes('process')) { return ; } if (name === 'delete' || name === 'move' || name.includes('file') || name.includes('create')) { return ; } return ; } function getStatusIcon(status?: string) { switch (status) { case 'complete': return ; case 'error': return ; case 'running': return ; default: return null; } } function ToolCallCard({ comment }: { comment: Comment }) { const [isExpanded, setIsExpanded] = useState(false); const metadata = comment.metadata as ToolCallMetadata | undefined; const toolName = metadata?.tool_name ?? ''; const title = metadata?.title ?? comment.content ?? 'Tool call'; const status = metadata?.status; const args = metadata?.args; const result = metadata?.result; const toolIcon = getToolIconElement( toolName, 'h-4 w-4 text-amber-600 dark:text-amber-400 flex-shrink-0' ); const hasDetails = args && Object.keys(args).length > 0; // Extract file path from various possible sources let filePath: string | undefined; const rawPath = args?.path ?? args?.file ?? args?.file_path; if (typeof rawPath === 'string') { filePath = rawPath; } // Also try to get path from locations array if available if (!filePath && Array.isArray(args?.locations) && args.locations.length > 0) { const firstLoc = args.locations[0] as { path?: string } | undefined; if (firstLoc?.path) { filePath = firstLoc.path; } } return (
{isExpanded && hasDetails && (
{args && Object.entries(args).map(([key, value]) => { const strValue = typeof value === 'string' ? value : JSON.stringify(value, null, 2); const isLongValue = strValue.length > 100 || strValue.includes('\n'); return (
{key}: {isLongValue ? (
                    {strValue}
                  
) : ( {strValue} )}
); })} {result && (
Result:
                {result}
              
)}
)}
); } function TypingIndicator() { return (
Agent
); } export function TaskChatPanel({ agents, onSend, isLoading, isAgentWorking }: TaskChatPanelProps) { const [messageInput, setMessageInput] = useState(''); const [selectedAgent, setSelectedAgent] = useState(agents[0]?.id ?? ''); const [planModeEnabled, setPlanModeEnabled] = useState(false); const [isSending, setIsSending] = useState(false); const [isAwaitingResponse, setIsAwaitingResponse] = useState(false); const messagesEndRef = useRef(null); const lastAgentMessageCountRef = useRef(0); const commentsState = useAppStore((state) => state.comments); const comments = commentsState?.items ?? []; const commentsLoading = commentsState?.isLoading ?? false; // Filter to only show message, content, and tool_call types (not progress, etc) const visibleComments = comments.filter( (c) => c.type === 'message' || c.type === 'content' || c.type === 'tool_call' || !c.type ); // Count agent messages to detect new responses const agentMessageCount = visibleComments.filter((c) => c.author_type !== 'user').length; // Clear awaiting state when a new agent message arrives useEffect(() => { if (agentMessageCount > lastAgentMessageCountRef.current) { setIsAwaitingResponse(false); } lastAgentMessageCountRef.current = agentMessageCount; }, [agentMessageCount]); // Show typing indicator when awaiting response AND agent session is active const showTypingIndicator = isAwaitingResponse && isAgentWorking; // Scroll to bottom when new comments arrive or when typing indicator appears useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [visibleComments.length, showTypingIndicator]); const handleSubmit = async (event: FormEvent) => { event.preventDefault(); const trimmed = messageInput.trim(); if (!trimmed || isSending) return; setIsSending(true); setIsAwaitingResponse(true); setMessageInput(''); try { await onSend(trimmed); } finally { setIsSending(false); } }; const formatContent = (comment: Comment) => { // For content type comments, the content might be streamed chunks // For message type, show as-is return comment.content || '(empty)'; }; return ( <>
{(isLoading || commentsLoading) && (
Loading comments...
)} {!isLoading && !commentsLoading && visibleComments.length === 0 && (
No messages yet. Start the conversation!
)} {visibleComments.map((comment) => { // Tool call comments have a special rendering if (comment.type === 'tool_call') { return ; } // Regular message or agent response - render as markdown const isUser = comment.author_type === 'user'; return (

{isUser ? 'You' : 'Agent'}

{isUser ? (

{formatContent(comment)}

) : (
{formatContent(comment)}
)}
); })} {showTypingIndicator && }