From 67c11fa836bfe7329a94741560ed0fd72ba4236e Mon Sep 17 00:00:00 2001 From: Sayo Date: Fri, 28 Feb 2025 15:53:39 +0530 Subject: [PATCH] remove rooms based conversations --- packages/agent/src/server/api/agent.ts | 118 +------- packages/client/src/App.tsx | 4 - packages/client/src/components/chat.tsx | 68 +---- packages/client/src/components/room-list.tsx | 270 ------------------- packages/client/src/hooks/use-query-hooks.ts | 17 +- packages/client/src/routes/chat.tsx | 12 +- 6 files changed, 33 insertions(+), 456 deletions(-) delete mode 100644 packages/client/src/components/room-list.tsx diff --git a/packages/agent/src/server/api/agent.ts b/packages/agent/src/server/api/agent.ts index 72466b844aa..05077a8308a 100644 --- a/packages/agent/src/server/api/agent.ts +++ b/packages/agent/src/server/api/agent.ts @@ -1,4 +1,4 @@ -import type { Character, IAgentRuntime, Media, UUID } from '@elizaos/core'; +import type { Character, IAgentRuntime, Media } from '@elizaos/core'; import { ChannelType, composeContext, generateMessageResponse, logger, ModelClass, stringToUuid, validateCharacterConfig, validateUuid } from '@elizaos/core'; import express from 'express'; import fs from 'node:fs'; @@ -852,22 +852,11 @@ export function agentRouter( return null; } - // Get the most recent message for this room - const recentMemories = await runtime.databaseAdapter.getMemoriesByRoomIds({ - tableName: 'memories', - agentId: runtime.agentId, - roomIds: [roomId], - limit: 1 - }); - - const lastMessage = recentMemories.length > 0 ? recentMemories[0].content.text : null; - return { id: roomId, name: roomData.name || new Date().toLocaleString(), source: roomData.source, - worldId: roomData.worldId, - lastMessage + worldId: roomData.worldId }; } catch (error) { logger.error(`[ROOMS GET] Error getting details for room ${roomId}:`, error); @@ -876,10 +865,8 @@ export function agentRouter( }) ); - // Filter out any null results and sort by most recent - const validRooms = roomDetails - .filter(room => room !== null) - + // Filter out any null results + const validRooms = roomDetails.filter(room => room !== null); logger.debug(`[ROOMS GET] Retrieved ${validRooms.length} rooms for agent: ${agentId}`); res.json(validRooms); @@ -916,7 +903,7 @@ export function agentRouter( } try { - const { name, worldId, roomId } = req.body; + const { name, worldId, roomId, userId } = req.body; const roomName = name || `Chat ${new Date().toLocaleString()}`; // Create the room @@ -932,7 +919,6 @@ export function agentRouter( await runtime.ensureParticipantInRoom(runtime.agentId, roomName); // Add the default user to the room - const userId = "00000000-0000-0000-0000-000000000000" as UUID; await runtime.ensureParticipantInRoom(userId, roomId); logger.debug(`[ROOM CREATE] Created room ${roomId} for agent: ${agentId} in world: ${worldId}`); @@ -949,100 +935,6 @@ export function agentRouter( } }); - router.get('/:agentId/:roomId', async (req, res) => { - const agentId = validateUuid(req.params.agentId); - const roomId = validateUuid(req.params.roomId); - - if (!agentId || !roomId) { - logger.warn("[ROOM MESSAGES] Invalid agent ID or room ID format"); - return; - } - - logger.info(`[ROOM MESSAGES] Retrieving conversation for agent: ${agentId}, room: ${roomId}`); - let runtime = agents.get(agentId); - - if (!runtime) { - logger.debug(`[ROOM MESSAGES] Agent not found by ID, trying to find by name: ${agentId}`); - runtime = Array.from(agents.values()).find( - (a) => a.character.name.toLowerCase() === agentId.toLowerCase() - ); - } - - if (!runtime) { - logger.warn(`[ROOM MESSAGES] Agent not found: ${agentId}`); - res.status(404).json({ error: 'Agent not found' }); - return; - } - - logger.debug(`[ROOM MESSAGES] Found agent: ${runtime.character.name}, fetching messages`); - try { - const { limit, before, after } = req.query; - const limitValue = limit ? Number.parseInt(limit as string, 10) : 50; // Default to 50 messages - const beforeValue = before ? Number.parseInt(before as string, 10) : undefined; - const afterValue = after ? Number.parseInt(after as string, 10) : undefined; - - const memories = await runtime.messageManager.getMemories({ - roomId, - count: limitValue, - end: beforeValue, - start: afterValue, - }); - - logger.debug(`[ROOM MESSAGES] Retrieved ${memories.length} messages for room: ${roomId}`); - - // Also get room info for additional context - const roomData = await runtime.databaseAdapter.getRoom(roomId, runtime.agentId); - - logger.info(`[ROOM DATA] Room data: ${JSON.stringify(roomData)}`); - - const response = { - agentId, - roomId, - room: roomData ? { - name: roomData.name, - source: roomData.source, - worldId: roomData.worldId, - } : null, - messages: memories.map((memory) => ({ - id: memory.id, - userId: memory.userId, - agentId: memory.agentId, - createdAt: memory.createdAt, - content: { - text: memory.content.text, - action: memory.content.action, - source: memory.content.source, - url: memory.content.url, - inReplyTo: memory.content.inReplyTo, - attachments: memory.content.attachments?.map( - (attachment) => ({ - id: attachment.id, - url: attachment.url, - title: attachment.title, - source: attachment.source, - description: attachment.description, - text: attachment.text, - contentType: attachment.contentType, - }) - ), - }, - roomId: memory.roomId, - })), - pagination: { - hasMore: memories.length >= limitValue, - oldestTimestamp: memories.length > 0 ? Math.min(...memories.map(m => m.createdAt)) : null, - newestTimestamp: memories.length > 0 ? Math.max(...memories.map(m => m.createdAt)) : null, - } - }; - - res.json(response); - logger.debug(`[ROOM MESSAGES] Successfully returned ${memories.length} messages`); - } catch (error) { - logger.error('[ROOM MESSAGES] Error fetching messages:', error); - res.status(500).json({ error: 'Failed to fetch messages' }); - } - }); - return router; } diff --git a/packages/client/src/App.tsx b/packages/client/src/App.tsx index ad60effa038..ac35c47ebb6 100644 --- a/packages/client/src/App.tsx +++ b/packages/client/src/App.tsx @@ -96,10 +96,6 @@ function App() { path="chat/:agentId" element={} /> - } - /> } diff --git a/packages/client/src/components/chat.tsx b/packages/client/src/components/chat.tsx index ab6dddf81e9..58fc55a7c43 100644 --- a/packages/client/src/components/chat.tsx +++ b/packages/client/src/components/chat.tsx @@ -13,7 +13,7 @@ import { WorldManager } from "@/lib/world-manager"; import type { IAttachment } from "@/types"; import type { Content, UUID } from "@elizaos/core"; import { useMutation, useQueryClient } from "@tanstack/react-query"; -import { Paperclip, Send, X, ChevronUp } from "lucide-react"; +import { Paperclip, Send, X } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import AIWriter from "react-aiwriter"; import { AudioRecorder } from "./audio-recorder"; @@ -23,7 +23,7 @@ import { Badge } from "./ui/badge"; import ChatTtsButton from "./ui/chat/chat-tts-button"; import { useAutoScroll } from "./ui/chat/hooks/useAutoScroll"; import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip"; -import { useMessages } from "@/hooks/use-query-hooks"; +import { useAgentMessages } from "@/hooks/use-query-hooks"; type ExtraContentFields = { user: string; @@ -97,24 +97,17 @@ function MessageContent({ ); } -export default function Page({ agentId, roomId }: { agentId: UUID, roomId: UUID }) { +export default function Page({ agentId }: { agentId: UUID }) { const { toast } = useToast(); const [selectedFile, setSelectedFile] = useState(null); const [input, setInput] = useState(""); - const [isLoadingOlder, setIsLoadingOlder] = useState(false); const inputRef = useRef(null); const fileInputRef = useRef(null); const formRef = useRef(null); const queryClient = useQueryClient(); const worldId = WorldManager.getWorldId(); - const { loadOlderMessages, hasOlderMessages } = useMessages(agentId, roomId); - - console.log({hasOlderMessages}) - - const messages = - queryClient.getQueryData(["messages", agentId, roomId, worldId]) || - []; + const { messages } = useAgentMessages(agentId); const getMessageVariant = (role: string) => role !== "user" ? "received" : "sent"; @@ -125,31 +118,11 @@ export default function Page({ agentId, roomId }: { agentId: UUID, roomId: UUID useEffect(() => { scrollToBottom(); - }, [queryClient.getQueryData(["messages", agentId, roomId, worldId])]); + }, [queryClient.getQueryData(["messages", agentId, worldId])]); useEffect(() => { scrollToBottom(); }, []); - - const handleLoadOlderMessages = async () => { - setIsLoadingOlder(true); - try { - const hasMore = await loadOlderMessages(); - if (!hasMore) { - toast({ - description: "No more messages to load", - }); - } - } catch (error) { - toast({ - variant: "destructive", - title: "Error loading messages", - description: error instanceof Error ? error.message : "An unknown error occurred", - }); - } finally { - setIsLoadingOlder(false); - } - }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Enter" && !e.shiftKey) { @@ -191,14 +164,13 @@ export default function Page({ agentId, roomId }: { agentId: UUID, roomId: UUID ]; queryClient.setQueryData( - ["messages", agentId, roomId, worldId], + ["messages", agentId, worldId], (old: ContentWithUser[] = []) => [...old, ...newMessages] ); sendMessageMutation.mutate({ message: input, selectedFile: selectedFile ? selectedFile : null, - roomId, }); setSelectedFile(null); @@ -213,19 +185,17 @@ export default function Page({ agentId, roomId }: { agentId: UUID, roomId: UUID }, []); const sendMessageMutation = useMutation({ - mutationKey: ["send_message", agentId, roomId], + mutationKey: ["send_message", agentId], mutationFn: ({ message, selectedFile, - roomId, }: { message: string; selectedFile?: File | null; - roomId: UUID; - }) => apiClient.sendMessage(agentId, message, selectedFile, roomId), + }) => apiClient.sendMessage(agentId, message, selectedFile), onSuccess: (newMessages: ContentWithUser[]) => { queryClient.setQueryData( - ["messages", agentId, roomId, worldId], + ["messages", agentId, worldId], (old: ContentWithUser[] = []) => [ ...old.filter((msg) => !msg.isLoading), ...newMessages.map((msg) => ({ @@ -260,26 +230,6 @@ export default function Page({ agentId, roomId }: { agentId: UUID, roomId: UUID scrollToBottom={scrollToBottom} disableAutoScroll={disableAutoScroll} > - {hasOlderMessages && ( -
- -
- )} {messages.map((message: ContentWithUser) => { return (
(null); - - // Fetch rooms for this agent - const { data: rooms = [], isLoading, error } = useQuery({ - queryKey: ["rooms", agentId], - queryFn: () => apiClient.getRooms(agentId), - }); - - // Create a new room - const createRoomMutation = useMutation({ - mutationFn: () => apiClient.createRoom(agentId, newRoomName || `Chat ${new Date().toLocaleString()}`), - onSuccess: (newRoom) => { - queryClient.invalidateQueries({ queryKey: ["rooms", agentId] }); - setIsCreateDialogOpen(false); - setNewRoomName(""); - navigate(`/chat/${agentId}/${newRoom.id}`); - }, - onError: (error) => { - toast({ - variant: "destructive", - title: "Failed to create room", - description: error instanceof Error ? error.message : "An unknown error occurred", - }); - }, - }); - - const handleCreateRoom = () => { - createRoomMutation.mutate(); - }; - - const navigateToRoom = (roomId: UUID) => { - navigate(`/chat/${agentId}/${roomId}`); - }; - - // Function to toggle expanded state for a room - const toggleRoomExpanded = (roomId: UUID, e: React.MouseEvent) => { - e.stopPropagation(); - if (expandedRoomId === roomId) { - setExpandedRoomId(null); - } else { - setExpandedRoomId(roomId); - // Fetch messages for this room when expanded - queryClient.prefetchQuery({ - queryKey: ['messages', agentId, roomId, WorldManager.getWorldId()], - queryFn: () => apiClient.getMemories(agentId, roomId) - }); - } - }; - - // Get messages for the expanded room - const expandedRoomMessages = expandedRoomId - ? queryClient.getQueryData([ - 'messages', - agentId, - expandedRoomId, - WorldManager.getWorldId() - ]) || [] - : []; - - if (isLoading) { - return ( -
- -
- ); - } - - if (error) { - return ( -
-

Failed to load rooms

-

- {error instanceof Error ? error.message : "Unknown error"} -

-
- ); - } - - return ( -
-
-

Conversations

- - - - - - - Create a new conversation - - Give your conversation a name or leave it blank for a default name. - - - setNewRoomName(e.target.value)} - /> - - - - - -
- - {rooms.length === 0 ? ( -
- -

No conversations yet

-

- Start a new conversation to chat with this agent. -

- -
- ) : ( -
- {rooms.map((room: Room) => ( -
- -
- - - {room.lastMessage ? ( -
- - - {expandedRoomId === room.id && expandedRoomMessages.length > 0 && ( -
- {expandedRoomMessages.slice(0, 3).map((msg: ContentWithUser) => ( -
-
- {msg.user === 'user' ? 'You' : 'Agent'} -
-

- {msg.text} -

-
- ))} - {expandedRoomMessages.length > 3 && ( -
- -
- )} -
- )} -
- ) : ( -
-

No messages yet

-
- )} -
- ))} -
- )} -
- ); -} \ No newline at end of file diff --git a/packages/client/src/hooks/use-query-hooks.ts b/packages/client/src/hooks/use-query-hooks.ts index 188cf4a19ff..2ca5f0c5394 100644 --- a/packages/client/src/hooks/use-query-hooks.ts +++ b/packages/client/src/hooks/use-query-hooks.ts @@ -353,7 +353,22 @@ export function useDeleteCharacter() { }); } -// Hook for fetching messages for a specific agent and room +// Hook for fetching messages directly for a specific agent without requiring a room +export function useAgentMessages(agentId: UUID) { + const queryClient = useQueryClient(); + const worldId = WorldManager.getWorldId(); + + // Get messages from cache or set default empty array + const messages = queryClient.getQueryData( + ['messages', agentId, worldId] + ) || []; + + return { + messages + }; +} + +// The original useMessages hook remains for backward compatibility export function useMessages(agentId: UUID, roomId: UUID): { data: TransformedMessage[] | undefined; isLoading: boolean; diff --git a/packages/client/src/routes/chat.tsx b/packages/client/src/routes/chat.tsx index e37533635e7..3ee85aa65ae 100644 --- a/packages/client/src/routes/chat.tsx +++ b/packages/client/src/routes/chat.tsx @@ -1,18 +1,12 @@ import { useParams } from "react-router"; import Chat from "@/components/chat"; -import RoomList from "@/components/room-list"; import type { UUID } from "@elizaos/core"; export default function AgentRoute() { - const { agentId, roomId } = useParams<{ agentId: UUID, roomId?: UUID }>(); + const { agentId } = useParams<{ agentId: UUID }>(); if (!agentId) return
No data.
; - // If no roomId is provided, show the room list - if (!roomId) { - return ; - } - - // If a roomId is provided, show the chat - return ; + // Go directly to the chat with the agent, skipping the room selection + return ; }