diff --git a/cheddahbot/agent.py b/cheddahbot/agent.py index a0f4173..13dcb73 100644 --- a/cheddahbot/agent.py +++ b/cheddahbot/agent.py @@ -100,10 +100,9 @@ class Agent: self.db.create_conversation(self.conv_id, agent_name=self.name) return self.conv_id - def new_conversation(self) -> str: - self.conv_id = uuid.uuid4().hex[:12] - self.db.create_conversation(self.conv_id, agent_name=self.name) - return self.conv_id + def new_conversation(self): + """Reset conversation state. DB row is created lazily by ensure_conversation().""" + self.conv_id = None def load_conversation(self, conv_id: str) -> list[dict]: """Load an existing conversation by ID. Returns message list.""" diff --git a/cheddahbot/db.py b/cheddahbot/db.py index b5af9aa..d6a4d45 100644 --- a/cheddahbot/db.py +++ b/cheddahbot/db.py @@ -95,20 +95,32 @@ class Database: return conv_id def list_conversations(self, limit: int = 50, agent_name: str | None = None) -> list[dict]: + # Only return conversations that have at least one message if agent_name: rows = self._conn.execute( - "SELECT id, title, updated_at, agent_name FROM conversations" - " WHERE agent_name = ? ORDER BY updated_at DESC LIMIT ?", + "SELECT c.id, c.title, c.updated_at, c.agent_name" + " FROM conversations c" + " WHERE c.agent_name = ?" + " AND EXISTS (SELECT 1 FROM messages m WHERE m.conv_id = c.id)" + " ORDER BY c.updated_at DESC LIMIT ?", (agent_name, limit), ).fetchall() else: rows = self._conn.execute( - "SELECT id, title, updated_at, agent_name FROM conversations" - " ORDER BY updated_at DESC LIMIT ?", + "SELECT c.id, c.title, c.updated_at, c.agent_name" + " FROM conversations c" + " WHERE EXISTS (SELECT 1 FROM messages m WHERE m.conv_id = c.id)" + " ORDER BY c.updated_at DESC LIMIT ?", (limit,), ).fetchall() return [dict(r) for r in rows] + def get_conversation_title(self, conv_id: str) -> str | None: + row = self._conn.execute( + "SELECT title FROM conversations WHERE id = ?", (conv_id,) + ).fetchone() + return row["title"] if row else None + def update_conversation_title(self, conv_id: str, title: str): self._conn.execute( "UPDATE conversations SET title = ? WHERE id = ?", (title, conv_id) diff --git a/cheddahbot/ui.py b/cheddahbot/ui.py index 07a3c83..5813852 100644 --- a/cheddahbot/ui.py +++ b/cheddahbot/ui.py @@ -442,9 +442,6 @@ def create_ui( if conv_id and agent: messages = agent.load_conversation(conv_id) chatbot_msgs = _messages_to_chatbot(messages) - elif agent: - agent.ensure_conversation() - conv_id = agent.conv_id convs = _refresh_conv_list(agent_name) new_browser = {"agent_name": agent_name, "conv_id": conv_id}