Commit inicial - upload de todos os arquivos da pasta

This commit is contained in:
2026-01-04 16:14:31 -03:00
commit e3ed1a734b
310 changed files with 62749 additions and 0 deletions

View File

@@ -0,0 +1,497 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/chat/components/AgentInfoDialog.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 14, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import { useState, useEffect } from "react";
import { Agent } from "@/types/agent";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Bot,
Code,
WrenchIcon,
Layers,
Server,
TagIcon,
Share,
Edit,
Loader2,
Download,
} from "lucide-react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import { listApiKeys, ApiKey } from "@/services/agentService";
import { listMCPServers } from "@/services/mcpServerService";
import { availableModels } from "@/types/aiModels";
import { MCPServer } from "@/types/mcpServer";
import { AgentForm } from "@/app/agents/forms/AgentForm";
import { exportAsJson } from "@/lib/utils";
interface AgentInfoDialogProps {
agent: Agent | null;
open: boolean;
onOpenChange: (open: boolean) => void;
onAgentUpdated?: (updatedAgent: Agent) => void;
}
export function AgentInfoDialog({
agent,
open,
onOpenChange,
onAgentUpdated,
}: AgentInfoDialogProps) {
const [activeTab, setActiveTab] = useState("info");
const [isAgentFormOpen, setIsAgentFormOpen] = useState(false);
const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
const [availableMCPs, setAvailableMCPs] = useState<MCPServer[]>([]);
const [agents, setAgents] = useState<Agent[]>([]);
const [isLoading, setIsLoading] = useState(false);
const user =
typeof window !== "undefined"
? JSON.parse(localStorage.getItem("user") || "{}")
: {};
const clientId = user?.client_id || "";
useEffect(() => {
if (!clientId || !open) return;
const loadData = async () => {
try {
const [apiKeysResponse, mcpServersResponse] = await Promise.all([
listApiKeys(clientId),
listMCPServers(),
]);
setApiKeys(apiKeysResponse.data);
setAvailableMCPs(mcpServersResponse.data);
} catch (error) {
console.error("Error loading data for agent form:", error);
}
};
loadData();
}, [clientId, open]);
const getAgentTypeName = (type: string) => {
const agentTypes: Record<string, string> = {
llm: "LLM Agent",
a2a: "A2A Agent",
sequential: "Sequential Agent",
parallel: "Parallel Agent",
loop: "Loop Agent",
workflow: "Workflow Agent",
task: "Task Agent",
};
return agentTypes[type] || type;
};
const handleSaveAgent = async (agentData: Partial<Agent>) => {
if (!agent?.id) return;
setIsLoading(true);
try {
const { updateAgent } = await import("@/services/agentService");
const updated = await updateAgent(agent.id, agentData as any);
if (updated.data && onAgentUpdated) {
onAgentUpdated(updated.data);
}
setIsAgentFormOpen(false);
} catch (error) {
console.error("Error updating agent:", error);
} finally {
setIsLoading(false);
}
};
// Function to export the agent as JSON
const handleExportAgent = async () => {
if (!agent) return;
try {
// First fetch all agents to properly resolve agent_tools references
const { listAgents } = await import("@/services/agentService");
const allAgentsResponse = await listAgents(clientId, 0, 1000);
const allAgents = allAgentsResponse.data || [];
exportAsJson(
agent,
`agent-${agent.name.replace(/\s+/g, "-").toLowerCase()}-${agent.id.substring(0, 8)}`,
true,
allAgents
);
} catch (error) {
console.error("Error exporting agent:", error);
}
};
if (!agent) return null;
const getToolsCount = () => {
let count = 0;
if (agent.config?.tools) count += agent.config.tools.length;
if (agent.config?.custom_tools?.http_tools)
count += agent.config.custom_tools.http_tools.length;
if (agent.config?.agent_tools)
count += agent.config.agent_tools.length;
return count;
};
const getSubAgentsCount = () => {
return agent.config?.sub_agents?.length || 0;
};
const getMCPServersCount = () => {
let count = 0;
if (agent.config?.mcp_servers) count += agent.config.mcp_servers.length;
if (agent.config?.custom_mcp_servers)
count += agent.config.custom_mcp_servers.length;
return count;
};
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[600px] max-h-[85vh] flex flex-col overflow-hidden bg-neutral-900 border-neutral-700">
<DialogHeader className="flex flex-row items-start justify-between pb-2">
<div>
<DialogTitle className="text-xl text-white flex items-center gap-2">
<Bot className="h-5 w-5 text-emerald-400" />
{agent.name}
</DialogTitle>
<DialogDescription className="text-neutral-400 mt-1">
{agent.description || "No description available"}
</DialogDescription>
</div>
<div className="flex items-center gap-2">
<Badge
variant="outline"
className="bg-neutral-800 border-neutral-700 text-emerald-400"
>
{getAgentTypeName(agent.type)}
</Badge>
<Button
variant="outline"
size="icon"
className="h-8 w-8 rounded-full bg-neutral-800 border-neutral-700 hover:bg-emerald-900 hover:text-emerald-400"
onClick={handleExportAgent}
title="Export agent as JSON"
>
<Download className="h-4 w-4" />
</Button>
<Button
variant="outline"
size="icon"
className="h-8 w-8 rounded-full bg-neutral-800 border-neutral-700 hover:bg-emerald-900 hover:text-emerald-400"
onClick={() => setIsAgentFormOpen(true)}
title="Edit agent"
>
<Edit className="h-4 w-4" />
</Button>
</div>
</DialogHeader>
<Tabs
value={activeTab}
onValueChange={setActiveTab}
className="flex-1 overflow-hidden flex flex-col"
>
<TabsList className="bg-neutral-800 p-1 border-b border-neutral-700">
<TabsTrigger
value="info"
className="data-[state=active]:bg-neutral-700 data-[state=active]:text-emerald-400"
>
Information
</TabsTrigger>
<TabsTrigger
value="tools"
className="data-[state=active]:bg-neutral-700 data-[state=active]:text-emerald-400"
>
Tools
</TabsTrigger>
<TabsTrigger
value="config"
className="data-[state=active]:bg-neutral-700 data-[state=active]:text-emerald-400"
>
Configuration
</TabsTrigger>
</TabsList>
<ScrollArea className="flex-1 p-4">
<TabsContent value="info" className="mt-0 space-y-4">
<div className="space-y-3">
<div className="grid grid-cols-3 gap-3">
<div className="bg-neutral-800 p-3 rounded-md border border-neutral-700 flex flex-col items-center justify-center text-center">
<Code className="h-5 w-5 text-emerald-400 mb-1" />
<span className="text-xs text-neutral-400">Model</span>
<span className="text-sm text-neutral-200 mt-1 font-medium">
{agent.model || "Not specified"}
</span>
</div>
<div className="bg-neutral-800 p-3 rounded-md border border-neutral-700 flex flex-col items-center justify-center text-center">
<TagIcon className="h-5 w-5 text-emerald-400 mb-1" />
<span className="text-xs text-neutral-400">Tools</span>
<span className="text-sm text-neutral-200 mt-1 font-medium">
{getToolsCount()}
</span>
</div>
<div className="bg-neutral-800 p-3 rounded-md border border-neutral-700 flex flex-col items-center justify-center text-center">
<Layers className="h-5 w-5 text-emerald-400 mb-1" />
<span className="text-xs text-neutral-400">
Sub-agents
</span>
<span className="text-sm text-neutral-200 mt-1 font-medium">
{getSubAgentsCount()}
</span>
</div>
</div>
<div className="bg-neutral-800 p-4 rounded-md border border-neutral-700">
<h3 className="text-sm font-medium text-emerald-400 mb-2">
Agent Role
</h3>
<p className="text-neutral-300 text-sm">
{agent.role || "Not specified"}
</p>
<h3 className="text-sm font-medium text-emerald-400 mb-2">
Agent Goal
</h3>
<p className="text-neutral-300 text-sm">
{agent.goal || "Not specified"}
</p>
{/* agent instructions: agent.instruction */}
<h3 className="text-sm font-medium text-emerald-400 mb-2">
Agent Instructions
</h3>
<div className="bg-neutral-900 p-3 rounded-md border border-neutral-700 max-h-[200px] overflow-y-auto">
<pre className="text-xs text-neutral-300 whitespace-pre-wrap font-mono">
{agent.instruction || "No instructions provided"}
</pre>
</div>
</div>
</div>
</TabsContent>
<TabsContent value="tools" className="mt-0 space-y-4">
{getToolsCount() > 0 ? (
<div className="space-y-3">
{/* Built-in tools */}
{agent.config?.tools && agent.config.tools.length > 0 && (
<div className="bg-neutral-800 p-4 rounded-md border border-neutral-700">
<h3 className="text-sm font-medium text-emerald-400 mb-2">
Built-in Tools
</h3>
<div className="grid grid-cols-2 gap-2">
{agent.config.tools.map((tool, index) => (
<Badge
key={index}
variant="outline"
className="bg-neutral-900 border-neutral-700 text-neutral-300 p-2 justify-start"
>
<TagIcon className="h-3.5 w-3.5 mr-1.5 text-emerald-400" />
{typeof tool === 'string' ? tool : 'Custom Tool'}
</Badge>
))}
</div>
</div>
)}
{/* Agent Tools */}
{agent.config?.agent_tools && agent.config.agent_tools.length > 0 && (
<div className="bg-neutral-800 p-4 rounded-md border border-neutral-700">
<h3 className="text-sm font-medium text-emerald-400 mb-2">
Agent Tools
</h3>
<div className="space-y-2">
{agent.config.agent_tools.map((agentId, index) => (
<div
key={index}
className="bg-neutral-900 p-2 rounded-md border border-neutral-700 flex items-center"
>
<div className="flex items-center">
<Bot className="h-3.5 w-3.5 mr-2 text-emerald-400" />
<span className="text-sm text-neutral-300">
{agents.find(a => a.id === agentId)?.name || agentId}
</span>
</div>
</div>
))}
</div>
</div>
)}
{/* Custom HTTP tools */}
{agent.config?.custom_tools?.http_tools &&
agent.config.custom_tools.http_tools.length > 0 && (
<div className="bg-neutral-800 p-4 rounded-md border border-neutral-700">
<h3 className="text-sm font-medium text-emerald-400 mb-2">
Custom HTTP Tools
</h3>
<div className="space-y-2">
{agent.config.custom_tools.http_tools.map(
(tool, index) => (
<div
key={index}
className="bg-neutral-900 p-2 rounded-md border border-neutral-700 flex items-center justify-between"
>
<div className="flex items-center">
<Server className="h-3.5 w-3.5 mr-2 text-emerald-400" />
<span className="text-sm text-neutral-300">
{tool.name}
</span>
</div>
<Badge
variant="outline"
className="text-xs bg-neutral-800 border-neutral-700 text-emerald-400"
>
{tool.method}
</Badge>
</div>
)
)}
</div>
</div>
)}
</div>
) : (
<div className="bg-neutral-800 p-6 rounded-md border border-neutral-700 text-center">
<TagIcon className="h-8 w-8 text-neutral-600 mx-auto mb-2" />
<p className="text-neutral-400">
This agent has no tools configured
</p>
</div>
)}
</TabsContent>
<TabsContent value="config" className="mt-0 space-y-4">
<div className="space-y-3">
{/* MCP Servers */}
<div className="bg-neutral-800 p-4 rounded-md border border-neutral-700">
<h3 className="text-sm font-medium text-emerald-400 mb-2">
MCP Servers
</h3>
{getMCPServersCount() > 0 ? (
<div className="space-y-2">
{agent.config?.mcp_servers &&
agent.config.mcp_servers.map((mcp, index) => (
<div
key={index}
className="bg-neutral-900 p-2 rounded-md border border-neutral-700 flex items-center"
>
<Server className="h-3.5 w-3.5 mr-2 text-emerald-400" />
<span className="text-sm text-neutral-300">
{mcp.id}
</span>
</div>
))}
{agent.config?.custom_mcp_servers &&
agent.config.custom_mcp_servers.map((mcp, index) => (
<div
key={index}
className="bg-neutral-900 p-2 rounded-md border border-neutral-700 flex items-center"
>
<Server className="h-3.5 w-3.5 mr-2 text-yellow-400" />
<span className="text-sm text-neutral-300">
{mcp.url}
</span>
</div>
))}
</div>
) : (
<p className="text-neutral-400 text-sm">
No MCP servers configured
</p>
)}
</div>
{/* API Key */}
<div className="bg-neutral-800 p-4 rounded-md border border-neutral-700">
<h3 className="text-sm font-medium text-emerald-400 mb-2">
API Key
</h3>
<p className="text-neutral-300 text-sm">
{agent.api_key_id
? `Key ID: ${agent.api_key_id}`
: "No API key configured"}
</p>
</div>
</div>
</TabsContent>
</ScrollArea>
</Tabs>
<DialogFooter className="pt-2">
<Button
variant="outline"
onClick={() => onOpenChange(false)}
className="bg-neutral-800 hover:bg-neutral-700 border-neutral-700 text-neutral-300"
>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Agent Edit Form Dialog */}
{isAgentFormOpen && agent && (
<AgentForm
open={isAgentFormOpen}
onOpenChange={setIsAgentFormOpen}
initialValues={agent}
apiKeys={apiKeys}
availableModels={availableModels}
availableMCPs={availableMCPs}
agents={agents}
onOpenApiKeysDialog={() => {}}
onOpenMCPDialog={() => {}}
onOpenCustomMCPDialog={() => {}}
onSave={handleSaveAgent}
isLoading={isLoading}
getAgentNameById={(id) => id}
clientId={clientId}
/>
)}
</>
);
}

View File

@@ -0,0 +1,158 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/chat/components/AttachedFiles.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: August 24, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import React from "react";
import { formatFileSize, isImageFile } from "@/lib/file-utils";
import { File, FileText, Download, Image } from "lucide-react";
import { toast } from "@/hooks/use-toast";
interface AttachedFile {
filename: string;
content_type: string;
data?: string;
size?: number;
preview_url?: string;
}
interface AttachedFilesProps {
files: AttachedFile[];
className?: string;
}
export function AttachedFiles({ files, className = "" }: AttachedFilesProps) {
if (!files || files.length === 0) return null;
const downloadFile = (file: AttachedFile) => {
if (!file.data) {
toast({
title: "File without data for download",
description: file.filename,
});
return;
}
try {
const link = document.createElement("a");
const dataUrl = file.data.startsWith("data:")
? file.data
: `data:${file.content_type};base64,${file.data}`;
link.href = dataUrl;
link.download = file.filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
toast({
title: "Error downloading file",
description: file.filename,
});
}
};
return (
<div className={`flex flex-col gap-2 mt-2 ${className}`}>
<div className="text-xs text-neutral-400 mb-1">Attached files:</div>
<div className="flex flex-wrap gap-2">
{files
.map((file, index) => {
if (!file.data) {
toast({
title: "File without data for display",
description: file.filename,
});
return null;
}
return (
<div
key={index}
className="flex flex-col bg-[#333] rounded-md overflow-hidden border border-[#444] hover:border-[#666] transition-colors"
>
{isImageFile(file.content_type) && file.data && (
<div className="w-full max-w-[200px] h-[120px] bg-black flex items-center justify-center">
<img
src={
file.preview_url ||
(file.data.startsWith("data:")
? file.data
: `data:${file.content_type};base64,${file.data}`)
}
alt={file.filename}
className="max-w-full max-h-full object-contain"
onError={(e) => {
toast({
title: "Error loading image",
description: file.filename,
});
(e.target as HTMLImageElement).src =
"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZjY2NjYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBjbGFzcz0ibHVjaWRlIGx1Y2lkZS1pbWFnZS1vZmYiPjxsaW5lIHgxPSIyIiB5MT0iMiIgeDI9IjIyIiB5Mj0iMjIiLz48PHJlY3QgdyA";
}}
/>
</div>
)}
<div className="p-2 flex items-center gap-2">
<div className="flex-shrink-0">
{isImageFile(file.content_type) ? (
<Image className="h-4 w-4 text-emerald-400" />
) : file.content_type === "application/pdf" ? (
<FileText className="h-4 w-4 text-emerald-400" />
) : (
<File className="h-4 w-4 text-emerald-400" />
)}
</div>
<div className="flex-1 min-w-0">
<div className="text-xs font-medium truncate max-w-[150px]">
{file.filename}
</div>
{file.size && (
<div className="text-[10px] text-neutral-400">
{formatFileSize(file.size)}
</div>
)}
</div>
{file.data && (
<button
onClick={() => downloadFile(file)}
className="text-emerald-400 hover:text-white transition-colors"
title="Download"
>
<Download className="h-4 w-4" />
</button>
)}
</div>
</div>
);
})
.filter(Boolean)}
</div>
</div>
);
}

View File

@@ -0,0 +1,190 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/chat/components/ChatContainer.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 14, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import React, { useRef, useEffect, useState } from "react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { MessageSquare, Loader2, Bot, Zap } from "lucide-react";
import { ChatMessage } from "./ChatMessage";
import { ChatInput } from "./ChatInput";
import { ChatMessage as ChatMessageType } from "@/services/sessionService";
import { cn } from "@/lib/utils";
interface FunctionMessageContent {
title: string;
content: string;
author?: string;
}
interface ChatContainerProps {
messages: ChatMessageType[];
isLoading: boolean;
onSendMessage: (message: string) => void;
agentColor: string;
expandedFunctions: Record<string, boolean>;
toggleFunctionExpansion: (messageId: string) => void;
containsMarkdown: (text: string) => boolean;
getMessageText: (message: ChatMessageType) => string | FunctionMessageContent;
agentName?: string;
containerClassName?: string;
messagesContainerClassName?: string;
inputContainerClassName?: string;
sessionId?: string;
}
export function ChatContainer({
messages,
isLoading,
onSendMessage,
agentColor,
expandedFunctions,
toggleFunctionExpansion,
containsMarkdown,
getMessageText,
agentName = "Agent",
containerClassName = "",
messagesContainerClassName = "",
inputContainerClassName = "",
sessionId,
}: ChatContainerProps) {
const messagesContainerRef = useRef<HTMLDivElement>(null);
const [isInitializing, setIsInitializing] = useState(false);
const scrollToBottom = () => {
if (messagesContainerRef.current) {
messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight;
}
};
useEffect(() => {
if (messages.length > 0) {
setTimeout(scrollToBottom, 100);
}
}, [messages]);
// Simulate initial loading for smoother UX
useEffect(() => {
if (sessionId) {
setIsInitializing(true);
const timer = setTimeout(() => {
setIsInitializing(false);
}, 1000);
return () => clearTimeout(timer);
}
}, [sessionId]);
const isEmpty = messages.length === 0;
return (
<div className={cn(
"flex-1 flex flex-col overflow-hidden bg-gradient-to-b from-neutral-900 to-neutral-950",
containerClassName
)}>
<div
className={cn(
"flex-1 overflow-hidden p-5",
messagesContainerClassName
)}
style={{ filter: isLoading && !isInitializing ? "blur(1px)" : "none" }}
>
<ScrollArea
ref={messagesContainerRef}
className="h-full pr-4"
>
{isInitializing ? (
<div className="flex flex-col items-center justify-center h-full">
<div className="w-12 h-12 rounded-full bg-gradient-to-br from-emerald-500 to-emerald-700 flex items-center justify-center shadow-lg mb-4 animate-pulse">
<Zap className="h-5 w-5 text-white" />
</div>
<p className="text-neutral-400 mb-2">Loading conversation...</p>
<div className="flex items-center space-x-2">
<span className="w-2 h-2 rounded-full bg-emerald-500 animate-bounce"
style={{ animationDelay: '0ms' }}></span>
<span className="w-2 h-2 rounded-full bg-emerald-500 animate-bounce"
style={{ animationDelay: '150ms' }}></span>
<span className="w-2 h-2 rounded-full bg-emerald-500 animate-bounce"
style={{ animationDelay: '300ms' }}></span>
</div>
</div>
) : isEmpty ? (
<div className="h-full flex flex-col items-center justify-center text-center p-6">
<div className="w-14 h-14 rounded-full bg-gradient-to-br from-blue-500/20 to-emerald-500/20 flex items-center justify-center shadow-lg mb-5 border border-emerald-500/30">
<MessageSquare className="h-6 w-6 text-emerald-400" />
</div>
<h3 className="text-lg font-medium text-neutral-300 mb-2">
{`Chat with ${agentName}`}
</h3>
<p className="text-neutral-500 text-sm max-w-md">
Type your message below to start the conversation. This chat will help you interact with the agent and explore its capabilities.
</p>
</div>
) : (
<div className="space-y-6 py-4 flex-1">
{messages.map((message) => {
const messageContent = getMessageText(message);
const isExpanded = expandedFunctions[message.id] || false;
return (
<ChatMessage
key={message.id}
message={message}
agentColor={agentColor}
isExpanded={isExpanded}
toggleExpansion={toggleFunctionExpansion}
containsMarkdown={containsMarkdown}
messageContent={messageContent}
sessionId={sessionId}
/>
);
})}
</div>
)}
</ScrollArea>
</div>
<div className={cn(
"p-3 border-t border-neutral-800 bg-neutral-900",
inputContainerClassName
)}>
{isLoading && !isInitializing && (
<div className="px-4 py-2 mb-3 rounded-lg bg-neutral-800/50 text-sm text-neutral-400 flex items-center">
<Loader2 className="h-3 w-3 mr-2 animate-spin text-emerald-400" />
Agent is thinking...
</div>
)}
<ChatInput
onSendMessage={onSendMessage}
isLoading={isLoading}
placeholder="Type your message..."
autoFocus={true}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,270 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/chat/components/ChatInput.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 14, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import React, { useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Loader2, Send, Paperclip, X, Image, FileText, File } from "lucide-react";
import { FileData, formatFileSize, isImageFile } from "@/lib/file-utils";
import { toast } from "@/hooks/use-toast";
interface ChatInputProps {
onSendMessage: (message: string, files?: FileData[]) => void;
isLoading?: boolean;
placeholder?: string;
className?: string;
buttonClassName?: string;
containerClassName?: string;
autoFocus?: boolean;
}
export function ChatInput({
onSendMessage,
isLoading = false,
placeholder = "Type your message...",
className = "",
buttonClassName = "",
containerClassName = "",
autoFocus = true,
}: ChatInputProps) {
const [messageInput, setMessageInput] = useState("");
const [selectedFiles, setSelectedFiles] = useState<FileData[]>([]);
const [resetFileUpload, setResetFileUpload] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Autofocus the textarea when the component is mounted
React.useEffect(() => {
// Small timeout to ensure focus is applied after the complete rendering
if (autoFocus) {
const timer = setTimeout(() => {
if (textareaRef.current && !isLoading) {
textareaRef.current.focus();
}
}, 100);
return () => clearTimeout(timer);
}
}, [isLoading, autoFocus]);
const handleSendMessage = (e: React.FormEvent) => {
e.preventDefault();
if (!messageInput.trim() && selectedFiles.length === 0) return;
onSendMessage(messageInput, selectedFiles.length > 0 ? selectedFiles : undefined);
setMessageInput("");
setSelectedFiles([]);
setResetFileUpload(true);
setTimeout(() => {
setResetFileUpload(false);
// Keep the focus on the textarea after sending the message
if (autoFocus && textareaRef.current) {
textareaRef.current.focus();
}
}, 100);
const textarea = document.querySelector("textarea");
if (textarea) textarea.style.height = "auto";
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSendMessage(e as unknown as React.FormEvent);
}
};
const autoResizeTextarea = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const textarea = e.target;
textarea.style.height = "auto";
const maxHeight = 10 * 24;
const newHeight = Math.min(textarea.scrollHeight, maxHeight);
textarea.style.height = `${newHeight}px`;
setMessageInput(textarea.value);
};
const handleFilesSelected = async (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files || e.target.files.length === 0) return;
const newFiles = Array.from(e.target.files);
const maxFileSize = 10 * 1024 * 1024; // 10MB
if (selectedFiles.length + newFiles.length > 5) {
toast({
title: `You can only attach up to 5 files.`,
variant: "destructive",
});
return;
}
const validFiles: FileData[] = [];
for (const file of newFiles) {
if (file.size > maxFileSize) {
toast({
title: `File ${file.name} exceeds the maximum size of ${formatFileSize(maxFileSize)}.`,
variant: "destructive",
});
continue;
}
try {
const reader = new FileReader();
const readFile = new Promise<string>((resolve, reject) => {
reader.onload = () => {
const base64 = reader.result as string;
const base64Data = base64.split(',')[1];
resolve(base64Data);
};
reader.onerror = reject;
});
reader.readAsDataURL(file);
const base64Data = await readFile;
const previewUrl = URL.createObjectURL(file);
validFiles.push({
filename: file.name,
content_type: file.type,
data: base64Data,
size: file.size,
preview_url: previewUrl
});
} catch (error) {
console.error("Error processing file:", error);
toast({
title: `Error processing file ${file.name}`,
variant: "destructive",
});
}
}
if (validFiles.length > 0) {
const updatedFiles = [...selectedFiles, ...validFiles];
setSelectedFiles(updatedFiles);
}
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
};
const openFileSelector = () => {
fileInputRef.current?.click();
};
return (
<div className={`flex flex-col w-full ${containerClassName}`}>
{selectedFiles.length > 0 && (
<div className="flex flex-wrap gap-2 px-2 mb-3 mt-1">
{selectedFiles.map((file, index) => (
<div
key={index}
className="flex items-center gap-1.5 bg-gradient-to-br from-neutral-800 to-neutral-900 text-white rounded-lg p-2 text-xs border border-neutral-700/50 shadow-sm"
>
{isImageFile(file.content_type) ? (
<Image className="h-4 w-4 text-emerald-400" />
) : file.content_type === 'application/pdf' ? (
<FileText className="h-4 w-4 text-emerald-400" />
) : (
<File className="h-4 w-4 text-emerald-400" />
)}
<span className="max-w-[120px] truncate">{file.filename}</span>
<span className="text-neutral-400">({formatFileSize(file.size)})</span>
<button
onClick={() => {
const updatedFiles = selectedFiles.filter((_, i) => i !== index);
setSelectedFiles(updatedFiles);
}}
className="ml-1 text-neutral-400 hover:text-white transition-colors bg-neutral-700/30 rounded-full p-1"
>
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
)}
<form
onSubmit={handleSendMessage}
className="flex w-full items-center gap-2 px-2"
>
{selectedFiles.length < 5 && (
<button
onClick={(e) => {
e.preventDefault();
openFileSelector();
}}
type="button"
className="flex items-center justify-center w-9 h-9 rounded-full hover:bg-neutral-800/60 text-neutral-400 hover:text-emerald-400 transition-all border border-neutral-700/30"
title="Attach file"
>
<Paperclip className="h-4 w-4" />
</button>
)}
<Textarea
value={messageInput}
onChange={autoResizeTextarea}
onKeyDown={handleKeyDown}
placeholder={placeholder}
className={`flex-1 bg-neutral-800/40 border-neutral-700/50 text-white focus-visible:ring-emerald-500/50 focus-visible:border-emerald-500/50 min-h-[40px] max-h-[240px] resize-none rounded-xl ${className}`}
disabled={isLoading}
rows={1}
ref={textareaRef}
/>
<Button
type="submit"
disabled={isLoading || (!messageInput.trim() && selectedFiles.length === 0)}
className={`bg-gradient-to-r from-emerald-500 to-emerald-600 text-white hover:from-emerald-600 hover:to-emerald-700 rounded-full shadow-md h-9 w-9 p-0 ${buttonClassName}`}
>
{isLoading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Send className="h-4 w-4" />
)}
</Button>
<input
type="file"
ref={fileInputRef}
onChange={handleFilesSelected}
className="hidden"
multiple
/>
</form>
</div>
);
}

View File

@@ -0,0 +1,375 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/chat/components/ChatMessage.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { ChatMessage as ChatMessageType } from "@/services/sessionService";
import { ChevronDown, ChevronRight, Copy, Check, User, Bot, Terminal } from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { useState } from "react";
import { InlineDataAttachments } from "./InlineDataAttachments";
import { cn } from "@/lib/utils";
interface FunctionMessageContent {
title: string;
content: string;
author?: string;
}
interface AttachedFile {
filename: string;
content_type: string;
data: string;
size: number;
preview_url?: string;
}
interface ChatMessageProps {
message: ChatMessageType;
agentColor: string;
isExpanded: boolean;
toggleExpansion: (messageId: string) => void;
containsMarkdown: (text: string) => boolean;
messageContent: string | FunctionMessageContent;
sessionId?: string;
}
export function ChatMessage({
message,
agentColor,
isExpanded,
toggleExpansion,
containsMarkdown,
messageContent,
sessionId,
}: ChatMessageProps) {
const [isCopied, setIsCopied] = useState(false);
const isUser = message.author === "user";
const hasFunctionCall = message.content.parts.some(
(part) => part.functionCall || part.function_call
);
const hasFunctionResponse = message.content.parts.some(
(part) => part.functionResponse || part.function_response
);
const isFunctionMessage = hasFunctionCall || hasFunctionResponse;
const isTaskExecutor = typeof messageContent === "object" &&
"author" in messageContent &&
typeof messageContent.author === "string" &&
messageContent.author.endsWith("- Task executor");
const inlineDataParts = message.content.parts.filter(part => part.inline_data);
const hasInlineData = inlineDataParts.length > 0;
const copyToClipboard = () => {
const textToCopy = typeof messageContent === "string"
? messageContent
: messageContent.content;
navigator.clipboard.writeText(textToCopy).then(() => {
setIsCopied(true);
setTimeout(() => setIsCopied(false), 2000);
});
};
// Generate appropriate avatar content
const getAvatar = () => {
if (isUser) {
return (
<Avatar className="bg-gradient-to-br from-emerald-500 to-emerald-700 shadow-md border-0">
<AvatarFallback className="bg-transparent">
<User className="h-4 w-4 text-white" />
</AvatarFallback>
</Avatar>
);
} else {
return (
<Avatar className={`shadow-md border-0 ${
isFunctionMessage
? "bg-gradient-to-br from-emerald-600 to-emerald-800"
: "bg-gradient-to-br from-purple-600 to-purple-800"
}`}>
<AvatarFallback className="bg-transparent">
{isFunctionMessage ?
<Terminal className="h-4 w-4 text-white" /> :
<Bot className="h-4 w-4 text-white" />
}
</AvatarFallback>
</Avatar>
);
}
};
return (
<div
key={message.id}
className="flex w-full"
style={{
justifyContent: isUser ? "flex-end" : "flex-start"
}}
>
<div
className="flex gap-3 max-w-[90%]"
style={{
flexDirection: isUser ? "row-reverse" : "row"
}}
>
{getAvatar()}
<div
className={`rounded-lg p-3 overflow-hidden relative group shadow-md ${
isFunctionMessage || isTaskExecutor
? "bg-gradient-to-br from-neutral-800 to-neutral-900 border border-neutral-700/50 text-emerald-300 font-mono text-sm"
: isUser
? "bg-emerald-500 text-white"
: "bg-gradient-to-br from-neutral-800 to-neutral-900 border border-neutral-700/50 text-white"
}`}
style={{
wordBreak: "break-word",
maxWidth: "calc(100% - 3rem)",
width: "100%"
}}
>
{isFunctionMessage || isTaskExecutor ? (
<div className="w-full">
<div
className="flex items-center gap-2 cursor-pointer hover:bg-[#444] rounded px-1 py-0.5 transition-colors"
onClick={() => toggleExpansion(message.id)}
>
{typeof messageContent === "object" &&
"title" in messageContent && (
<>
<div className="flex-1 font-semibold">
{(messageContent as FunctionMessageContent).title}
</div>
<div className="flex items-center justify-center w-5 h-5 text-emerald-400">
{isExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</div>
</>
)}
{isTaskExecutor && (
<>
<div className="flex-1 font-semibold">
Task Execution
</div>
<div className="flex items-center justify-center w-5 h-5 text-emerald-400">
{isExpanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</div>
</>
)}
</div>
{isExpanded && (
<div className="mt-2 pt-2 border-t border-[#555]">
{typeof messageContent === "object" &&
"content" in messageContent && (
<div className="max-w-full overflow-x-auto">
<pre className="whitespace-pre-wrap text-xs max-w-full" style={{
wordWrap: "break-word",
maxWidth: "100%",
wordBreak: "break-all"
}}>
{(messageContent as FunctionMessageContent).content}
</pre>
</div>
)}
</div>
)}
</div>
) : (
<div className="markdown-content break-words max-w-full overflow-x-auto">
{typeof messageContent === "object" &&
"author" in messageContent &&
messageContent.author !== "user" &&
!isTaskExecutor && (
<div className="text-xs text-neutral-400 mb-1">
{messageContent.author}
</div>
)}
{((typeof messageContent === "string" &&
containsMarkdown(messageContent)) ||
(typeof messageContent === "object" &&
"content" in messageContent &&
typeof messageContent.content === "string" &&
containsMarkdown(messageContent.content))) &&
!isTaskExecutor ? (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
h1: ({ ...props }) => (
<h1 className="text-xl font-bold my-4" {...props} />
),
h2: ({ ...props }) => (
<h2 className="text-lg font-bold my-3" {...props} />
),
h3: ({ ...props }) => (
<h3 className="text-base font-bold my-2" {...props} />
),
h4: ({ ...props }) => (
<h4 className="font-semibold my-2" {...props} />
),
p: ({ ...props }) => <p className="mb-3" {...props} />,
ul: ({ ...props }) => (
<ul
className="list-disc pl-6 mb-3 space-y-1"
{...props}
/>
),
ol: ({ ...props }) => (
<ol
className="list-decimal pl-6 mb-3 space-y-1"
{...props}
/>
),
li: ({ ...props }) => <li className="mb-1" {...props} />,
a: ({ ...props }) => (
<a
className="text-emerald-300 underline hover:opacity-80 transition-opacity"
target="_blank"
rel="noopener noreferrer"
{...props}
/>
),
blockquote: ({ ...props }) => (
<blockquote
className="border-l-4 border-[#444] pl-4 py-1 italic my-3 text-neutral-300"
{...props}
/>
),
code: ({ className, children, ...props }: any) => {
const match = /language-(\w+)/.exec(className || "");
const isInline =
!match &&
typeof children === "string" &&
!children.includes("\n");
if (isInline) {
return (
<code
className="bg-[#333] px-1.5 py-0.5 rounded text-emerald-300 text-sm font-mono"
{...props}
>
{children}
</code>
);
}
return (
<div className="my-3 relative group/code">
<div className="bg-[#1a1a1a] rounded-t-md border-b border-[#333] p-2 text-xs text-neutral-400 flex justify-between items-center">
<span>{match?.[1] || "Code"}</span>
<button
onClick={copyToClipboard}
className="text-neutral-400 hover:text-emerald-300 transition-colors"
title="Copy code"
>
{isCopied ? (
<Check className="h-3.5 w-3.5" />
) : (
<Copy className="h-3.5 w-3.5" />
)}
</button>
</div>
<pre className="bg-[#1a1a1a] p-3 rounded-b-md overflow-x-auto whitespace-pre text-sm">
<code {...props}>{children}</code>
</pre>
</div>
);
},
table: ({ ...props }) => (
<div className="overflow-x-auto my-3">
<table
className="min-w-full border border-[#333] rounded"
{...props}
/>
</div>
),
thead: ({ ...props }) => (
<thead className="bg-[#1a1a1a]" {...props} />
),
tbody: ({ ...props }) => <tbody {...props} />,
tr: ({ ...props }) => (
<tr
className="border-b border-[#333] last:border-0"
{...props}
/>
),
th: ({ ...props }) => (
<th
className="px-4 py-2 text-left text-xs font-semibold text-neutral-300"
{...props}
/>
),
td: ({ ...props }) => (
<td className="px-4 py-2 text-sm" {...props} />
),
}}
>
{typeof messageContent === "string"
? messageContent
: messageContent.content}
</ReactMarkdown>
) : (
<div className="whitespace-pre-wrap">
{typeof messageContent === "string"
? messageContent
: messageContent.content}
</div>
)}
{hasInlineData && (
<InlineDataAttachments parts={inlineDataParts} sessionId={sessionId} />
)}
</div>
)}
<button
onClick={copyToClipboard}
className="absolute top-2 right-2 p-1.5 rounded-full bg-neutral-800/80 text-neutral-400 hover:text-white opacity-0 group-hover:opacity-100 transition-all hover:bg-neutral-700/80"
title="Copy message"
>
{isCopied ? (
<Check className="h-3.5 w-3.5" />
) : (
<Copy className="h-3.5 w-3.5" />
)}
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,185 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/chat/components/FileUpload.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: August 24, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import React, { useState, useRef, useEffect } from "react";
import { FileData, formatFileSize, isImageFile } from "@/lib/file-utils";
import { Paperclip, X, Image, File, FileText } from "lucide-react";
import { toast } from "@/hooks/use-toast";
interface FileUploadProps {
onFilesSelected: (files: FileData[]) => void;
maxFileSize?: number;
maxFiles?: number;
className?: string;
reset?: boolean;
}
export function FileUpload({
onFilesSelected,
maxFileSize = 10 * 1024 * 1024, // 10MB
maxFiles = 5,
className = "",
reset = false, // Default false
}: FileUploadProps) {
const [selectedFiles, setSelectedFiles] = useState<FileData[]>([]);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (reset && selectedFiles.length > 0) {
setSelectedFiles([]);
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
}
}, [reset]);
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
if (!e.target.files || e.target.files.length === 0) return;
const newFiles = Array.from(e.target.files);
if (selectedFiles.length + newFiles.length > maxFiles) {
toast({
title: `You can only attach up to ${maxFiles} files.`,
variant: "destructive",
});
return;
}
const validFiles: FileData[] = [];
for (const file of newFiles) {
if (file.size > maxFileSize) {
toast({
title: `File ${file.name} exceeds the maximum size of ${formatFileSize(maxFileSize)}.`,
variant: "destructive",
});
continue;
}
try {
const reader = new FileReader();
const readFile = new Promise<string>((resolve, reject) => {
reader.onload = () => {
const base64 = reader.result as string;
const base64Data = base64.split(',')[1];
resolve(base64Data);
};
reader.onerror = reject;
});
reader.readAsDataURL(file);
const base64Data = await readFile;
const previewUrl = URL.createObjectURL(file);
validFiles.push({
filename: file.name,
content_type: file.type,
data: base64Data,
size: file.size,
preview_url: previewUrl
});
} catch (error) {
console.error("Error processing file:", error);
toast({
title: `Error processing file ${file.name}`,
variant: "destructive",
});
}
}
if (validFiles.length > 0) {
const updatedFiles = [...selectedFiles, ...validFiles];
setSelectedFiles(updatedFiles);
onFilesSelected(updatedFiles);
}
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
};
const removeFile = (index: number) => {
const updatedFiles = selectedFiles.filter((_, i) => i !== index);
setSelectedFiles(updatedFiles);
onFilesSelected(updatedFiles);
};
return (
<div className={`flex gap-2 items-center ${className}`}>
{selectedFiles.length > 0 && (
<div className="flex gap-2 flex-wrap items-center flex-1">
{selectedFiles.map((file, index) => (
<div
key={index}
className="flex items-center gap-1 bg-[#333] text-white rounded-md p-1.5 text-xs group relative"
>
{isImageFile(file.content_type) ? (
<Image className="h-4 w-4 text-emerald-400" />
) : file.content_type === 'application/pdf' ? (
<FileText className="h-4 w-4 text-emerald-400" />
) : (
<File className="h-4 w-4 text-emerald-400" />
)}
<span className="max-w-[120px] truncate">{file.filename}</span>
<span className="text-neutral-400">({formatFileSize(file.size)})</span>
<button
onClick={() => removeFile(index)}
className="ml-1 text-neutral-400 hover:text-white transition-colors"
>
<X className="h-3.5 w-3.5" />
</button>
</div>
))}
</div>
)}
{selectedFiles.length < maxFiles && (
<button
onClick={() => fileInputRef.current?.click()}
type="button"
className="flex items-center justify-center w-8 h-8 rounded-full hover:bg-[#333] text-neutral-400 hover:text-emerald-400 transition-colors"
title="Attach file"
>
<Paperclip className="h-5 w-5" />
<input
type="file"
ref={fileInputRef}
onChange={handleFileChange}
className="hidden"
multiple
/>
</button>
)}
</div>
);
}

View File

@@ -0,0 +1,182 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/chat/components/InlineDataAttachments.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: August 29, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import React, { useState, useEffect } from "react";
import { formatFileSize, isImageFile } from "@/lib/file-utils";
import { File, FileText, Download, Image } from "lucide-react";
import { ChatPart } from "@/services/sessionService";
interface InlineDataAttachmentsProps {
parts: ChatPart[];
className?: string;
sessionId?: string;
}
interface ProcessedFile {
filename: string;
content_type: string;
data: string;
size: number;
preview_url?: string;
}
export function InlineDataAttachments({ parts, className = "", sessionId }: InlineDataAttachmentsProps) {
const [processedFiles, setProcessedFiles] = useState<ProcessedFile[]>([]);
const [isProcessed, setIsProcessed] = useState(false);
useEffect(() => {
if (isProcessed) return;
const validParts = parts.filter(part => part.inline_data && part.inline_data.data);
if (validParts.length === 0) {
setIsProcessed(true);
return;
}
const files = validParts.map((part, index) => {
const { mime_type, data } = part.inline_data!;
const extension = mime_type.split('/')[1] || 'file';
let filename = '';
if (part.inline_data?.metadata?.filename) {
filename = part.inline_data.metadata.filename;
}
else if (part.file_data?.filename) {
filename = part.file_data.filename;
}
else {
filename = `media_${index + 1}.${extension}`;
}
let preview_url = undefined;
if (data && isImageFile(mime_type)) {
preview_url = data.startsWith('data:')
? data
: `data:${mime_type};base64,${data}`;
}
const fileData: ProcessedFile = {
filename,
content_type: mime_type,
size: data.length,
data,
preview_url
};
return fileData;
});
setProcessedFiles(files);
setIsProcessed(true);
}, [parts, isProcessed]);
if (processedFiles.length === 0) return null;
const downloadFile = (file: ProcessedFile) => {
try {
const link = document.createElement("a");
const dataUrl = file.data.startsWith('data:')
? file.data
: `data:${file.content_type};base64,${file.data}`;
link.href = dataUrl;
link.download = file.filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.error(`Error downloading file ${file.filename}:`, error);
}
};
const getFileUrl = (file: ProcessedFile) => {
return file.preview_url || (file.data.startsWith('data:')
? file.data
: `data:${file.content_type};base64,${file.data}`);
};
return (
<div className={`flex flex-col gap-2 mt-2 ${className}`}>
<div className="text-xs text-neutral-400 mb-1">
<span>Attached files:</span>
</div>
<div className="flex flex-wrap gap-2">
{processedFiles.map((file, index) => (
<div
key={index}
className="flex flex-col bg-[#333] rounded-md overflow-hidden border border-[#444] hover:border-[#666] transition-colors"
>
{isImageFile(file.content_type) && (
<div className="w-full max-w-[200px] h-[120px] bg-black flex items-center justify-center">
<img
src={getFileUrl(file)}
alt={file.filename}
className="max-w-full max-h-full object-contain"
onError={(e) => {
console.error(`Error loading image ${file.filename}`);
(e.target as HTMLImageElement).src = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNmZjY2NjYiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIiBjbGFzcz0ibHVjaWRlIGx1Y2lkZS1pbWFnZS1vZmYiPjxsaW5lIHgxPSIyIiB5MT0iMiIgeDI9IjIyIiB5Mj0iMjIiLz48cmVjdCB3aWR0aD0iMjAiIGhlaWdodD0iMjAiIHg9IjIiIHk9IjIiIHJ4PSIyIiByeT0iMiIvPjxsaW5lIHgxPSI4IiB5MT0iMTAiIHgyPSI4IiB5Mj0iMTAiLz48bGluZSB4MT0iMTIiIHkxPSIxNCIgeDI9IjEyIiB5Mj0iMTQiLz48L3N2Zz4=";
}}
/>
</div>
)}
<div className="p-2 flex items-center gap-2">
<div className="flex-shrink-0">
{isImageFile(file.content_type) ? (
<Image className="h-4 w-4 text-emerald-400" />
) : file.content_type === "application/pdf" ? (
<FileText className="h-4 w-4 text-emerald-400" />
) : (
<File className="h-4 w-4 text-emerald-400" />
)}
</div>
<div className="flex-1 min-w-0">
<div className="text-xs font-medium truncate max-w-[150px]">
{file.filename}
</div>
<div className="text-[10px] text-neutral-400">
{formatFileSize(file.size)}
</div>
</div>
<button
onClick={() => downloadFile(file)}
className="text-emerald-400 hover:text-white transition-colors"
title="Download"
>
<Download className="h-4 w-4" />
</button>
</div>
</div>
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,248 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/chat/components/SessionList.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Search, Filter, Plus, Loader2 } from "lucide-react";
import { ChatSession } from "@/services/sessionService";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
interface SessionListProps {
sessions: ChatSession[];
agents: any[];
selectedSession: string | null;
isLoading: boolean;
searchTerm: string;
selectedAgentFilter: string;
showAgentFilter: boolean;
setSearchTerm: (value: string) => void;
setSelectedAgentFilter: (value: string) => void;
setShowAgentFilter: (value: boolean) => void;
setSelectedSession: (value: string | null) => void;
setIsNewChatDialogOpen: (value: boolean) => void;
}
export function SessionList({
sessions,
agents,
selectedSession,
isLoading,
searchTerm,
selectedAgentFilter,
showAgentFilter,
setSearchTerm,
setSelectedAgentFilter,
setShowAgentFilter,
setSelectedSession,
setIsNewChatDialogOpen,
}: SessionListProps) {
const filteredSessions = sessions.filter((session) => {
const matchesSearchTerm = session.id
.toLowerCase()
.includes(searchTerm.toLowerCase());
if (selectedAgentFilter === "all") {
return matchesSearchTerm;
}
const sessionAgentId = session.id.split("_")[1];
return matchesSearchTerm && sessionAgentId === selectedAgentFilter;
});
const sortedSessions = [...filteredSessions].sort((a, b) => {
const updateTimeA = new Date(a.update_time).getTime();
const updateTimeB = new Date(b.update_time).getTime();
return updateTimeB - updateTimeA;
});
const formatDateTime = (dateTimeStr: string) => {
try {
const date = new Date(dateTimeStr);
const day = date.getDate().toString().padStart(2, "0");
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const year = date.getFullYear();
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
return `${day}/${month}/${year} ${hours}:${minutes}`;
} catch (error) {
return "Invalid date";
}
};
const getExternalId = (sessionId: string) => {
return sessionId.split("_")[0];
};
return (
<div className="w-64 border-r border-neutral-700 flex flex-col bg-neutral-900">
<div className="p-4 border-b border-neutral-700">
<div className="flex items-center justify-between mb-4">
<Button
onClick={() => setIsNewChatDialogOpen(true)}
className="bg-emerald-800 text-emerald-100 hover:bg-emerald-700 border-emerald-700"
size="sm"
>
<Plus className="h-4 w-4 mr-1" /> New Conversation
</Button>
</div>
<div className="space-y-2">
<div className="relative">
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-neutral-500" />
<Input
placeholder="Search conversations..."
className="pl-9 bg-neutral-800 border-neutral-700 text-neutral-200 focus-visible:ring-emerald-500"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
</div>
<div className="flex items-center justify-between">
<Button
variant="ghost"
size="sm"
className="text-neutral-400 hover:text-white hover:bg-neutral-800"
onClick={() => setShowAgentFilter(!showAgentFilter)}
>
<Filter className="h-4 w-4 mr-1" />
Filter
</Button>
{selectedAgentFilter !== "all" && (
<Button
variant="ghost"
size="sm"
onClick={() => setSelectedAgentFilter("all")}
className="text-neutral-400 hover:text-white hover:bg-neutral-800"
>
Clear filter
</Button>
)}
</div>
{showAgentFilter && (
<div className="pt-1">
<Select
value={selectedAgentFilter}
onValueChange={setSelectedAgentFilter}
>
<SelectTrigger className="bg-neutral-800 border-neutral-700 text-neutral-200">
<SelectValue placeholder="Filter by agent" />
</SelectTrigger>
<SelectContent className="bg-neutral-900 border-neutral-700 text-white">
<SelectItem
value="all"
className="data-[selected]:bg-neutral-800 data-[highlighted]:bg-neutral-800 !text-white hover:text-emerald-400 data-[selected]:!text-emerald-400"
>
All agents
</SelectItem>
{agents.map((agent) => (
<SelectItem
key={agent.id}
value={agent.id}
className="data-[selected]:bg-neutral-800 data-[highlighted]:bg-neutral-800 !text-white hover:text-emerald-400 data-[selected]:!text-emerald-400"
>
{agent.name.slice(0, 15)}{" "}
{agent.name.length > 15 && "..."}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
{isLoading ? (
<div className="flex justify-center items-center h-24">
<Loader2 className="h-5 w-5 text-emerald-400 animate-spin" />
</div>
) : sortedSessions.length > 0 ? (
<div className="px-4 pt-2 space-y-2">
{sortedSessions.map((session) => {
const agentId = session.id.split("_")[1];
const agentInfo = agents.find((a) => a.id === agentId);
const externalId = getExternalId(session.id);
return (
<div
key={session.id}
className={`p-3 rounded-md cursor-pointer transition-colors group relative ${
selectedSession === session.id
? "bg-emerald-800/20 border border-emerald-600/40"
: "bg-neutral-800 hover:bg-neutral-700 border border-transparent"
}`}
onClick={() => setSelectedSession(session.id)}
>
<div className="flex items-center">
<div className="w-2 h-2 rounded-full bg-emerald-500 mr-2"></div>
<div className="text-neutral-200 font-medium truncate max-w-[180px]">
{externalId}
</div>
</div>
<div className="mt-1 flex items-center gap-2">
{agentInfo && (
<Badge className="bg-neutral-700 text-emerald-400 border-neutral-600 text-xs">
{agentInfo.name.slice(0, 15)}
{agentInfo.name.length > 15 && "..."}
</Badge>
)}
<div className="text-xs text-neutral-500 ml-auto">
{formatDateTime(session.update_time)}
</div>
</div>
</div>
);
})}
</div>
) : searchTerm || selectedAgentFilter !== "all" ? (
<div className="text-center py-4 text-neutral-400">
No results found
</div>
) : (
<div className="text-center py-4 text-neutral-400">
Click "New" to start
</div>
)}
</div>
</div>
);
}

881
frontend/app/chat/page.tsx Normal file
View File

@@ -0,0 +1,881 @@
/*
┌──────────────────────────────────────────────────────────────────────────────┐
│ @author: Davidson Gomes │
│ @file: /app/chat/page.tsx │
│ Developed by: Davidson Gomes │
│ Creation date: May 13, 2025 │
│ Contact: contato@evolution-api.com │
├──────────────────────────────────────────────────────────────────────────────┤
│ @copyright © Evolution API 2025. All rights reserved. │
│ Licensed under the Apache License, Version 2.0 │
│ │
│ You may not use this file except in compliance with the License. │
│ You may obtain a copy of the License at │
│ │
│ http://www.apache.org/licenses/LICENSE-2.0 │
│ │
│ Unless required by applicable law or agreed to in writing, software │
│ distributed under the License is distributed on an "AS IS" BASIS, │
│ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
│ See the License for the specific language governing permissions and │
│ limitations under the License. │
├──────────────────────────────────────────────────────────────────────────────┤
│ @important │
│ For any future changes to the code in this file, it is recommended to │
│ include, together with the modification, the information of the developer │
│ who changed it and the date of modification. │
└──────────────────────────────────────────────────────────────────────────────┘
*/
"use client";
import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
MessageSquare,
Send,
Plus,
Search,
Loader2,
X,
Trash2,
Bot,
} from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import {
Dialog,
DialogContent,
DialogTitle,
DialogHeader,
DialogDescription,
DialogFooter,
} from "@/components/ui/dialog";
import { listAgents } from "@/services/agentService";
import {
listSessions,
getSessionMessages,
ChatMessage,
deleteSession,
ChatSession,
ChatPart
} from "@/services/sessionService";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useAgentWebSocket } from "@/hooks/use-agent-webSocket";
import { getAccessTokenFromCookie } from "@/lib/utils";
import { ChatMessage as ChatMessageComponent } from "./components/ChatMessage";
import { SessionList } from "./components/SessionList";
import { ChatInput } from "./components/ChatInput";
import { FileData } from "@/lib/file-utils";
import { AgentInfoDialog } from "./components/AgentInfoDialog";
interface FunctionMessageContent {
title: string;
content: string;
author?: string;
}
export default function Chat() {
const [isLoading, setIsLoading] = useState(true);
const [agents, setAgents] = useState<any[]>([]);
const [sessions, setSessions] = useState<ChatSession[]>([]);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [searchTerm, setSearchTerm] = useState("");
const [agentSearchTerm, setAgentSearchTerm] = useState("");
const [selectedAgentFilter, setSelectedAgentFilter] = useState<string>("all");
const [messageInput, setMessageInput] = useState("");
const [selectedSession, setSelectedSession] = useState<string | null>(null);
const [currentAgentId, setCurrentAgentId] = useState<string | null>(null);
const [isSending, setIsSending] = useState(false);
const [isNewChatDialogOpen, setIsNewChatDialogOpen] = useState(false);
const [showAgentFilter, setShowAgentFilter] = useState(false);
const [expandedFunctions, setExpandedFunctions] = useState<
Record<string, boolean>
>({});
const [isAgentInfoDialogOpen, setIsAgentInfoDialogOpen] = useState(false);
const messagesContainerRef = useRef<HTMLDivElement>(null);
const { toast } = useToast();
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const user =
typeof window !== "undefined"
? JSON.parse(localStorage.getItem("user") || "{}")
: {};
const clientId = user?.client_id || "test";
const scrollToBottom = () => {
if (messagesContainerRef.current) {
messagesContainerRef.current.scrollTop =
messagesContainerRef.current.scrollHeight;
}
};
useEffect(() => {
const loadData = async () => {
setIsLoading(true);
try {
const agentsResponse = await listAgents(clientId);
setAgents(agentsResponse.data);
const sessionsResponse = await listSessions(clientId);
setSessions(sessionsResponse.data);
} catch (error) {
console.error("Error loading data:", error);
} finally {
setIsLoading(false);
}
};
loadData();
}, [clientId]);
useEffect(() => {
if (!selectedSession) {
setMessages([]);
return;
}
const loadMessages = async () => {
try {
setIsLoading(true);
const response = await getSessionMessages(selectedSession);
setMessages(response.data);
const agentId = selectedSession.split("_")[1];
setCurrentAgentId(agentId);
setTimeout(scrollToBottom, 100);
} catch (error) {
console.error("Error loading messages:", error);
} finally {
setIsLoading(false);
}
};
loadMessages();
}, [selectedSession]);
useEffect(() => {
if (messages.length > 0) {
setTimeout(scrollToBottom, 100);
}
}, [messages]);
const filteredSessions = sessions.filter((session) => {
const matchesSearchTerm = session.id
.toLowerCase()
.includes(searchTerm.toLowerCase());
if (selectedAgentFilter === "all") {
return matchesSearchTerm;
}
const sessionAgentId = session.id.split("_")[1];
return matchesSearchTerm && sessionAgentId === selectedAgentFilter;
});
const sortedSessions = [...filteredSessions].sort((a, b) => {
const updateTimeA = new Date(a.update_time).getTime();
const updateTimeB = new Date(b.update_time).getTime();
return updateTimeB - updateTimeA;
});
const formatDateTime = (dateTimeStr: string) => {
try {
const date = new Date(dateTimeStr);
const day = date.getDate().toString().padStart(2, "0");
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const year = date.getFullYear();
const hours = date.getHours().toString().padStart(2, "0");
const minutes = date.getMinutes().toString().padStart(2, "0");
return `${day}/${month}/${year} ${hours}:${minutes}`;
} catch (error) {
return "Invalid date";
}
};
const filteredAgents = agents.filter(
(agent) =>
agent.name.toLowerCase().includes(agentSearchTerm.toLowerCase()) ||
(agent.description &&
agent.description.toLowerCase().includes(agentSearchTerm.toLowerCase()))
);
const selectAgent = (agentId: string) => {
setCurrentAgentId(agentId);
setSelectedSession(null);
setMessages([]);
setIsNewChatDialogOpen(false);
};
const handleSendMessage = async (e: React.FormEvent) => {
e.preventDefault();
if (!messageInput.trim() || !currentAgentId) return;
setIsSending(true);
setMessages((prev) => [
...prev,
{
id: `temp-${Date.now()}`,
content: {
parts: [{ text: messageInput }],
role: "user",
},
author: "user",
timestamp: Date.now() / 1000,
},
]);
wsSendMessage(messageInput);
setMessageInput("");
const textarea = document.querySelector("textarea");
if (textarea) textarea.style.height = "auto";
};
const handleSendMessageWithFiles = (message: string, files?: FileData[]) => {
if ((!message.trim() && (!files || files.length === 0)) || !currentAgentId)
return;
setIsSending(true);
const messageParts: ChatPart[] = [];
if (message.trim()) {
messageParts.push({ text: message });
}
if (files && files.length > 0) {
files.forEach(file => {
messageParts.push({
inline_data: {
data: file.data,
mime_type: file.content_type,
metadata: {
filename: file.filename
}
}
});
});
}
setMessages((prev) => [
...prev,
{
id: `temp-${Date.now()}`,
content: {
parts: messageParts,
role: "user"
},
author: "user",
timestamp: Date.now() / 1000,
},
]);
wsSendMessage(message, files);
setMessageInput("");
const textarea = document.querySelector("textarea");
if (textarea) textarea.style.height = "auto";
};
const generateExternalId = () => {
const now = new Date();
return (
now.getFullYear().toString() +
(now.getMonth() + 1).toString().padStart(2, "0") +
now.getDate().toString().padStart(2, "0") +
now.getHours().toString().padStart(2, "0") +
now.getMinutes().toString().padStart(2, "0") +
now.getSeconds().toString().padStart(2, "0") +
now.getMilliseconds().toString().padStart(3, "0")
);
};
const currentAgent = agents.find((agent) => agent.id === currentAgentId);
const getCurrentSessionInfo = () => {
if (!selectedSession) return null;
const parts = selectedSession.split("_");
try {
const dateStr = parts[0];
if (dateStr.length >= 8) {
const year = dateStr.substring(0, 4);
const month = dateStr.substring(4, 6);
const day = dateStr.substring(6, 8);
return {
externalId: parts[0],
agentId: parts[1],
displayDate: `${day}/${month}/${year}`,
};
}
} catch (e) {
console.error("Error processing session ID:", e);
}
return {
externalId: parts[0],
agentId: parts[1],
displayDate: "Session",
};
};
const getExternalId = (sessionId: string) => {
return sessionId.split("_")[0];
};
const containsMarkdown = (text: string): boolean => {
if (!text || text.length < 3) return false;
const markdownPatterns = [
/[*_]{1,2}[^*_]+[*_]{1,2}/, // bold/italic
/\[[^\]]+\]\([^)]+\)/, // links
/^#{1,6}\s/m, // headers
/^[-*+]\s/m, // unordered lists
/^[0-9]+\.\s/m, // ordered lists
/^>\s/m, // block quotes
/`[^`]+`/, // inline code
/```[\s\S]*?```/, // code blocks
/^\|(.+\|)+$/m, // tables
/!\[[^\]]*\]\([^)]+\)/, // images
];
return markdownPatterns.some((pattern) => pattern.test(text));
};
const getMessageText = (
message: ChatMessage
): string | FunctionMessageContent => {
const author = message.author;
const parts = message.content.parts;
if (!parts || parts.length === 0) return "Empty content";
const functionCallPart = parts.find(
(part) => part.functionCall || part.function_call
);
const functionResponsePart = parts.find(
(part) => part.functionResponse || part.function_response
);
const inlineDataParts = parts.filter((part) => part.inline_data);
if (functionCallPart) {
const funcCall =
functionCallPart.functionCall || functionCallPart.function_call || {};
const args = funcCall.args || {};
const name = funcCall.name || "unknown";
const id = funcCall.id || "no-id";
return {
author,
title: `📞 Function call: ${name}`,
content: `ID: ${id}
Args: ${
Object.keys(args).length > 0
? `\n${JSON.stringify(args, null, 2)}`
: "{}"
}`,
} as FunctionMessageContent;
}
if (functionResponsePart) {
const funcResponse =
functionResponsePart.functionResponse ||
functionResponsePart.function_response ||
{};
const response = funcResponse.response || {};
const name = funcResponse.name || "unknown";
const id = funcResponse.id || "no-id";
const status = response.status || "unknown";
const statusEmoji = status === "error" ? "❌" : "✅";
let resultText = "";
if (status === "error") {
resultText = `Error: ${response.error_message || "Unknown error"}`;
} else if (response.report) {
resultText = `Result: ${response.report}`;
} else if (response.result && response.result.content) {
const content = response.result.content;
if (Array.isArray(content) && content.length > 0 && content[0].text) {
try {
const textContent = content[0].text;
const parsedJson = JSON.parse(textContent);
resultText = `Result: \n${JSON.stringify(parsedJson, null, 2)}`;
} catch (e) {
resultText = `Result: ${content[0].text}`;
}
} else {
resultText = `Result:\n${JSON.stringify(response, null, 2)}`;
}
} else {
resultText = `Result:\n${JSON.stringify(response, null, 2)}`;
}
return {
author,
title: `${statusEmoji} Function response: ${name}`,
content: `ID: ${id}\n${resultText}`,
} as FunctionMessageContent;
}
if (parts.length === 1 && parts[0].text) {
return {
author,
content: parts[0].text,
title: "Message",
} as FunctionMessageContent;
}
const textParts = parts
.filter((part) => part.text)
.map((part) => part.text)
.filter((text) => text);
if (textParts.length > 0) {
return {
author,
content: textParts.join("\n\n"),
title: "Message",
} as FunctionMessageContent;
}
return "Empty content";
};
const toggleFunctionExpansion = (messageId: string) => {
setExpandedFunctions((prev) => ({
...prev,
[messageId]: !prev[messageId],
}));
};
const agentColors: Record<string, string> = {
Assistant: "bg-emerald-400",
Programmer: "bg-[#00cc7d]",
Writer: "bg-[#00b8ff]",
Researcher: "bg-[#ff9d00]",
Planner: "bg-[#9d00ff]",
default: "bg-[#333]",
};
const getAgentColor = (agentName: string) => {
return agentColors[agentName] || agentColors.default;
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSendMessage(e as unknown as React.FormEvent);
}
};
const autoResizeTextarea = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const textarea = e.target;
textarea.style.height = "auto";
const maxHeight = 10 * 24;
const newHeight = Math.min(textarea.scrollHeight, maxHeight);
textarea.style.height = `${newHeight}px`;
setMessageInput(textarea.value);
};
const handleDeleteSession = async () => {
if (!selectedSession) return;
try {
await deleteSession(selectedSession);
setSessions(sessions.filter((session) => session.id !== selectedSession));
setSelectedSession(null);
setMessages([]);
setCurrentAgentId(null);
setIsDeleteDialogOpen(false);
toast({
title: "Session deleted successfully",
});
} catch (error) {
console.error("Error deleting session:", error);
toast({
title: "Error deleting session",
variant: "destructive",
});
}
};
const onEvent = useCallback((event: any) => {
setMessages((prev) => [...prev, event]);
}, []);
const onTurnComplete = useCallback(() => {
setIsSending(false);
}, []);
const handleAgentInfoClick = () => {
setIsAgentInfoDialogOpen(true);
};
const handleAgentUpdated = (updatedAgent: any) => {
setAgents(agents.map(agent =>
agent.id === updatedAgent.id ? updatedAgent : agent
));
toast({
title: "Agent updated successfully",
description: "The agent has been updated with the new settings.",
});
};
const jwt = getAccessTokenFromCookie();
const agentId = useMemo(() => currentAgentId || "", [currentAgentId]);
const externalId = useMemo(
() =>
selectedSession ? getExternalId(selectedSession) : generateExternalId(),
[selectedSession]
);
const { sendMessage: wsSendMessage, disconnect: _ } = useAgentWebSocket({
agentId,
externalId,
jwt,
onEvent,
onTurnComplete,
});
return (
<div className="flex h-screen max-h-screen bg-[#121212]">
<SessionList
sessions={sessions}
agents={agents}
selectedSession={selectedSession}
isLoading={isLoading}
searchTerm={searchTerm}
selectedAgentFilter={selectedAgentFilter}
showAgentFilter={showAgentFilter}
setSearchTerm={setSearchTerm}
setSelectedAgentFilter={setSelectedAgentFilter}
setShowAgentFilter={setShowAgentFilter}
setSelectedSession={setSelectedSession}
setIsNewChatDialogOpen={setIsNewChatDialogOpen}
/>
<div className="flex-1 flex flex-col overflow-hidden">
{selectedSession || currentAgentId ? (
<>
<div className="p-4 border-b border-[#333] bg-neutral-900 shadow-md">
{(() => {
const sessionInfo = getCurrentSessionInfo();
return (
<div className="flex justify-between items-center">
<h2 className="text-xl font-bold text-white flex items-center gap-2">
<div className="p-1 rounded-full bg-emerald-500/20">
<MessageSquare className="h-5 w-5 text-emerald-400" />
</div>
{selectedSession
? `Session ${
sessionInfo?.externalId || selectedSession
}`
: "New Conversation"}
</h2>
<div className="flex items-center gap-2">
{currentAgent && (
<Badge
className="bg-emerald-500 text-white px-3 py-1 text-sm border-0 cursor-pointer hover:bg-emerald-600 transition-colors"
onClick={handleAgentInfoClick}
>
{currentAgent.name || currentAgentId}
</Badge>
)}
{selectedSession && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-neutral-400 hover:text-red-500 hover:bg-[#333]"
onClick={() => setIsDeleteDialogOpen(true)}
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
</div>
);
})()}
</div>
<div
ref={messagesContainerRef}
className="flex-1 overflow-y-auto p-4 bg-neutral-950"
>
{isLoading ? (
<div className="flex flex-col items-center justify-center h-full">
<div className="w-12 h-12 rounded-full bg-gradient-to-br from-emerald-500 to-emerald-700 flex items-center justify-center shadow-lg mb-4 relative">
<Loader2 className="h-6 w-6 text-white animate-spin" />
<div className="absolute inset-0 rounded-full blur-md bg-emerald-400/20 animate-pulse"></div>
</div>
<p className="text-neutral-400 mb-2">Loading conversation...</p>
</div>
) : messages.length === 0 ? (
<div className="flex flex-col h-full items-center justify-center text-center p-6">
<div className="w-14 h-14 rounded-full bg-gradient-to-br from-emerald-500/20 to-emerald-700/20 flex items-center justify-center shadow-lg mb-5 border border-emerald-500/30">
<MessageSquare className="h-6 w-6 text-emerald-400" />
</div>
<h3 className="text-lg font-medium text-neutral-300 mb-2">
{currentAgent ? `Chat with ${currentAgent.name}` : "New Conversation"}
</h3>
<p className="text-neutral-500 text-sm max-w-md">
Type your message below to start the conversation. This chat will help you interact with the agent and explore its capabilities.
</p>
</div>
) : (
<div className="space-y-4 w-full max-w-full">
{messages.map((message) => {
const messageContent = getMessageText(message);
const agentColor = getAgentColor(message.author);
const isExpanded = expandedFunctions[message.id] || false;
return (
<ChatMessageComponent
key={message.id}
message={message}
agentColor={agentColor}
isExpanded={isExpanded}
toggleExpansion={toggleFunctionExpansion}
containsMarkdown={containsMarkdown}
messageContent={messageContent}
sessionId={selectedSession as string}
/>
);
})}
{isSending && (
<div className="flex justify-start">
<div className="flex gap-3 max-w-[80%]">
<Avatar
className="bg-gradient-to-br from-purple-600 to-purple-800 shadow-md border-0"
>
<AvatarFallback className="bg-transparent">
<Bot className="h-4 w-4 text-white" />
</AvatarFallback>
</Avatar>
<div className="rounded-lg p-3 bg-gradient-to-br from-neutral-800 to-neutral-900 border border-neutral-700/50 shadow-md">
<div className="flex space-x-2">
<div className="h-2 w-2 rounded-full bg-emerald-400 animate-bounce"></div>
<div className="h-2 w-2 rounded-full bg-emerald-400 animate-bounce [animation-delay:0.2s]"></div>
<div className="h-2 w-2 rounded-full bg-emerald-400 animate-bounce [animation-delay:0.4s]"></div>
</div>
</div>
</div>
</div>
)}
</div>
)}
</div>
<div className="px-4 pt-4 pb-6 border-t border-[#333] bg-neutral-900 shadow-inner">
{isSending && !isLoading && (
<div className="px-4 py-2 mb-3 rounded-lg bg-neutral-800/50 border border-neutral-700/30 text-sm text-neutral-400 flex items-center shadow-sm">
<div className="mr-2 relative">
<Loader2 className="h-3.5 w-3.5 animate-spin text-emerald-400" />
<div className="absolute inset-0 blur-sm bg-emerald-400/20 rounded-full animate-pulse"></div>
</div>
Agent is thinking...
</div>
)}
<div className="rounded-lg shadow-md bg-neutral-800/20 border border-neutral-700/30 p-1">
<ChatInput
onSendMessage={handleSendMessageWithFiles}
isLoading={isSending || isLoading}
placeholder="Type your message..."
autoFocus={true}
/>
</div>
</div>
</>
) : (
<div className="flex flex-col items-center justify-center h-full text-center">
<div className="w-20 h-20 rounded-full bg-emerald-500/20 flex items-center justify-center shadow-lg mb-6 border border-emerald-500/30">
<MessageSquare className="h-10 w-10 text-emerald-400" />
</div>
<h2 className="text-2xl font-semibold text-white mb-3">
Select a conversation
</h2>
<p className="text-neutral-400 mb-8 max-w-md">
Choose an existing conversation or start a new one.
</p>
<Button
onClick={() => setIsNewChatDialogOpen(true)}
className="bg-emerald-500 text-white hover:bg-emerald-600 px-6 py-6 h-auto shadow-md rounded-xl"
>
<Plus className="mr-2 h-5 w-5" />
New Conversation
</Button>
</div>
)}
</div>
<Dialog open={isNewChatDialogOpen} onOpenChange={setIsNewChatDialogOpen}>
<DialogContent className="bg-neutral-900 border-neutral-800 text-white shadow-xl">
<DialogHeader>
<div className="flex items-center gap-2 mb-1">
<div className="p-1.5 rounded-full bg-emerald-500/20">
<MessageSquare className="h-5 w-5 text-emerald-400" />
</div>
<DialogTitle className="text-xl font-medium text-white">
New Conversation
</DialogTitle>
</div>
<DialogDescription className="text-neutral-400">
Select an agent to start a new conversation.
</DialogDescription>
</DialogHeader>
<div className="mt-4 space-y-4">
<div className="relative">
<div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-500">
<Search className="h-4 w-4" />
</div>
<Input
placeholder="Search agents..."
className="pl-10 bg-neutral-800/40 border-neutral-700/50 text-white focus-visible:ring-emerald-500/50 focus-visible:border-emerald-500/50 shadow-inner rounded-xl"
value={agentSearchTerm}
onChange={(e) => setAgentSearchTerm(e.target.value)}
/>
{agentSearchTerm && (
<button
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-neutral-400 hover:text-emerald-500 transition-colors"
onClick={() => setAgentSearchTerm("")}
>
<X className="h-4 w-4" />
</button>
)}
</div>
<div className="text-sm text-neutral-300 mb-2">Choose an agent:</div>
<ScrollArea className="h-[300px] pr-2">
{isLoading ? (
<div className="flex flex-col items-center justify-center py-8">
<div className="relative">
<Loader2 className="h-8 w-8 text-emerald-400 animate-spin" />
<div className="absolute inset-0 rounded-full blur-md bg-emerald-400/20 animate-pulse"></div>
</div>
<p className="text-neutral-400 mt-4">Loading agents...</p>
</div>
) : filteredAgents.length > 0 ? (
<div className="space-y-2">
{filteredAgents.map((agent) => (
<div
key={agent.id}
className="p-3 rounded-md cursor-pointer transition-all bg-neutral-800 hover:bg-neutral-800/90 border border-neutral-700/30 hover:border-emerald-500/30 shadow-sm hover:shadow-md group"
onClick={() => selectAgent(agent.id)}
>
<div className="flex items-center gap-2 mb-1">
<div className="p-1 rounded-full bg-emerald-500/20 group-hover:bg-emerald-500/30 transition-colors">
<MessageSquare size={14} className="text-emerald-400" />
</div>
<span className="font-medium text-white group-hover:text-emerald-50">
{agent.name}
</span>
</div>
<div className="flex items-center justify-between mt-1">
<Badge className="text-xs bg-neutral-800/60 text-emerald-400 border border-emerald-500/30">
{agent.type}
</Badge>
{agent.model && (
<span className="text-xs text-neutral-400">
{agent.model}
</span>
)}
</div>
{agent.description && (
<p className="text-xs text-neutral-300 mt-2 line-clamp-2 group-hover:text-neutral-200">
{agent.description}
</p>
)}
</div>
))}
</div>
) : agentSearchTerm ? (
<div className="text-center py-4 text-neutral-400">
No agent found with "{agentSearchTerm}"
</div>
) : (
<div className="text-center py-4 text-neutral-400">
<p>No agents available</p>
<p className="text-sm mt-2">
Create agents in the Agent Management screen
</p>
</div>
)}
</ScrollArea>
</div>
<DialogFooter>
<Button
onClick={() => setIsNewChatDialogOpen(false)}
variant="outline"
className="bg-neutral-800/40 border-neutral-700/50 text-neutral-300 hover:bg-neutral-700/50 hover:text-white hover:border-neutral-600"
>
Cancel
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<DialogContent className="bg-neutral-900 border-neutral-800 text-white shadow-xl">
<DialogHeader>
<div className="flex items-center gap-2 mb-1">
<div className="p-1.5 rounded-full bg-red-500/20">
<Trash2 className="h-5 w-5 text-red-400" />
</div>
<DialogTitle className="text-xl font-medium text-white">
Delete Session
</DialogTitle>
</div>
<DialogDescription className="text-neutral-400">
Are you sure you want to delete this session? This action cannot
be undone.
</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2">
<Button
onClick={() => setIsDeleteDialogOpen(false)}
variant="outline"
className="bg-neutral-800/40 border-neutral-700/50 text-neutral-300 hover:bg-neutral-700/50 hover:text-white hover:border-neutral-600"
>
Cancel
</Button>
<Button
onClick={handleDeleteSession}
className="bg-red-600 hover:bg-red-700 text-white border-0 shadow-md"
>
Delete
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Agent Info Dialog */}
<AgentInfoDialog
agent={currentAgent}
open={isAgentInfoDialogOpen}
onOpenChange={setIsAgentInfoDialogOpen}
onAgentUpdated={handleAgentUpdated}
/>
</div>
);
}