Skip to content

Commit

Permalink
remove rooms based conversations
Browse files Browse the repository at this point in the history
  • Loading branch information
wtfsayo committed Feb 28, 2025
1 parent 65663c4 commit 67c11fa
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 456 deletions.
118 changes: 5 additions & 113 deletions packages/agent/src/server/api/agent.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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
Expand All @@ -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}`);
Expand All @@ -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;
}

4 changes: 0 additions & 4 deletions packages/client/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,6 @@ function App() {
path="chat/:agentId"
element={<Chat />}
/>
<Route
path="chat/:agentId/:roomId"
element={<Chat />}
/>
<Route
path="settings/:agentId"
element={<Overview />}
Expand Down
68 changes: 9 additions & 59 deletions packages/client/src/components/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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;
Expand Down Expand Up @@ -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<File | null>(null);
const [input, setInput] = useState("");
const [isLoadingOlder, setIsLoadingOlder] = useState(false);
const inputRef = useRef<HTMLTextAreaElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const formRef = useRef<HTMLFormElement>(null);
const queryClient = useQueryClient();
const worldId = WorldManager.getWorldId();

const { loadOlderMessages, hasOlderMessages } = useMessages(agentId, roomId);

console.log({hasOlderMessages})

const messages =
queryClient.getQueryData<ContentWithUser[]>(["messages", agentId, roomId, worldId]) ||
[];
const { messages } = useAgentMessages(agentId);

const getMessageVariant = (role: string) =>
role !== "user" ? "received" : "sent";
Expand All @@ -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<HTMLTextAreaElement>) => {
if (e.key === "Enter" && !e.shiftKey) {
Expand Down Expand Up @@ -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);
Expand All @@ -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) => ({
Expand Down Expand Up @@ -260,26 +230,6 @@ export default function Page({ agentId, roomId }: { agentId: UUID, roomId: UUID
scrollToBottom={scrollToBottom}
disableAutoScroll={disableAutoScroll}
>
{hasOlderMessages && (
<div className="flex justify-center my-2">
<Button
variant="outline"
size="sm"
className="flex items-center gap-1"
onClick={handleLoadOlderMessages}
disabled={isLoadingOlder}
>
{isLoadingOlder ? (
<>Loading...</>
) : (
<>
<ChevronUp className="h-4 w-4" />
Load older messages
</>
)}
</Button>
</div>
)}
{messages.map((message: ContentWithUser) => {
return (
<div
Expand Down
Loading

0 comments on commit 67c11fa

Please sign in to comment.