Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add logic for clearing and starting new session #39

Merged
merged 3 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 59 additions & 1 deletion codeaide/logic/chat_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@
AI_PROVIDERS,
DEFAULT_MODEL,
DEFAULT_PROVIDER,
INITIAL_MESSAGE,
)
from codeaide.utils.cost_tracker import CostTracker
from codeaide.utils.environment_manager import EnvironmentManager
from codeaide.utils.file_handler import FileHandler
from codeaide.utils.terminal_manager import TerminalManager
from codeaide.utils.general_utils import generate_session_id
from codeaide.utils.logging_config import get_logger
from codeaide.utils.logging_config import get_logger, setup_logger
from PyQt5.QtWidgets import QMessageBox

logger = get_logger()


class ChatHandler:
Expand All @@ -39,6 +43,9 @@ def __init__(self):
self.session_id = generate_session_id()
self.cost_tracker = CostTracker()
self.file_handler = FileHandler(session_id=self.session_id)
self.session_dir = (
self.file_handler.session_dir
) # Store the specific session directory
self.logger = get_logger()
self.conversation_history = self.file_handler.load_chat_history()
self.env_manager = EnvironmentManager()
Expand All @@ -54,6 +61,7 @@ def __init__(self):

self.api_key_valid, self.api_key_message = self.check_api_key()
self.logger.info(f"New session started with ID: {self.session_id}")
self.logger.info(f"Session directory: {self.session_dir}")

def check_api_key(self):
"""
Expand Down Expand Up @@ -529,3 +537,53 @@ def get_latest_version(self):

def set_latest_version(self, version):
self.latest_version = version

def start_new_session(self, chat_window):
logger.info("Starting new session")

# Log the previous session path correctly
logger.info(f"Previous session path: {self.session_dir}")

# Generate new session ID
new_session_id = generate_session_id()

# Create new FileHandler with new session ID
new_file_handler = FileHandler(session_id=new_session_id)

# Copy existing log to new session and set up new logger
self.file_handler.copy_log_to_new_session(new_session_id)
setup_logger(new_file_handler.session_dir)

# Update instance variables
self.session_id = new_session_id
self.file_handler = new_file_handler
self.session_dir = new_file_handler.session_dir # Update the session directory

# Clear conversation history
self.conversation_history = []

# Clear chat display in UI
chat_window.clear_chat_display()

# Close code pop-up if it exists
chat_window.close_code_popup()

# Add system message about previous session
system_message = f"A new session has been started. The previous chat will not be visible to the agent. Previous session data saved in: {self.session_dir}"
chat_window.add_to_chat("System", system_message)
chat_window.add_to_chat("AI", INITIAL_MESSAGE)

logger.info(f"New session started with ID: {self.session_id}")
logger.info(f"New session directory: {self.session_dir}")

# New method to load a previous session
def load_previous_session(self, session_id, chat_window):
logger.info(f"Loading previous session: {session_id}")
self.session_id = session_id
self.file_handler = FileHandler(session_id=session_id)
self.session_dir = self.file_handler.session_dir

# Load chat contents
chat_window.load_chat_contents()

logger.info(f"Loaded previous session with ID: {self.session_id}")
49 changes: 48 additions & 1 deletion codeaide/ui/chat_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def __init__(self, chat_handler):
self.cost_tracker = getattr(chat_handler, "cost_tracker", None)
self.code_popup = None
self.waiting_for_api_key = False
self.chat_contents = []
self.setup_ui()

# Check API key status
Expand Down Expand Up @@ -133,6 +134,10 @@ def setup_ui(self):
self.example_button.clicked.connect(self.load_example)
button_layout.addWidget(self.example_button)

self.new_session_button = QPushButton("New Session")
self.new_session_button.clicked.connect(self.on_new_session_clicked)
button_layout.addWidget(self.new_session_button)

self.exit_button = QPushButton("Exit", self)
self.exit_button.clicked.connect(self.on_exit)
button_layout.addWidget(self.exit_button)
Expand Down Expand Up @@ -198,7 +203,15 @@ def add_to_chat(self, sender, message):
self.chat_display.append(html_message + "<br>")
self.chat_display.ensureCursorVisible()

self.logger.debug(f"Adding message to chat from {sender}: {message}")
self.logger.debug(
f"Adding message to chat from {sender}: {message}"
) # Log first 50 chars

# Add message to chat contents
self.chat_contents.append({"sender": sender, "message": message})

# Save chat contents
self.chat_handler.file_handler.save_chat_contents(self.chat_contents)

def display_thinking(self):
self.add_to_chat("AI", "Thinking... 🤔")
Expand Down Expand Up @@ -344,3 +357,37 @@ def update_chat_handler(self):
)

self.add_to_chat("System", switch_message)

def on_new_session_clicked(self):
self.logger.info("User clicked New Session button")
reply = QMessageBox.question(
self,
"New Session",
"This will start a new session with a new chat history. Are you sure you'd like to proceed?",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.No,
)

if reply == QMessageBox.Yes:
self.logger.info("User confirmed starting a new session")
self.chat_handler.start_new_session(self)
else:
self.logger.info("User cancelled starting a new session")

def clear_chat_display(self):
self.chat_display.clear()
self.chat_contents = []
self.chat_handler.file_handler.save_chat_contents(self.chat_contents)
self.logger.info("Cleared chat display and contents in UI")

def close_code_popup(self):
if self.code_popup:
self.code_popup.close()
self.code_popup = None
self.logger.info("Closed code pop-up")

def load_chat_contents(self):
self.chat_contents = self.chat_handler.file_handler.load_chat_contents()
for item in self.chat_contents:
self.add_to_chat(item["sender"], item["message"])
self.logger.info(f"Loaded {len(self.chat_contents)} messages from chat log")
51 changes: 51 additions & 0 deletions codeaide/utils/file_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ def __init__(self, base_dir=None, session_id=None):
if self.session_dir
else None
)
self.chat_window_log_file = (
os.path.join(self.session_dir, "chat_window_log.json")
if self.session_dir
else None
)
self._ensure_output_dirs_exist()

if self.session_dir:
Expand Down Expand Up @@ -117,10 +122,56 @@ def load_chat_history(self):
self.logger.error(f"Error loading chat history: {str(e)}")
return []

def save_chat_contents(self, chat_contents):
if not self.session_dir:
self.logger.error("Session directory not set. Cannot save chat contents.")
return

try:
with open(self.chat_window_log_file, "w", encoding="utf-8") as f:
json.dump(chat_contents, f, ensure_ascii=False, indent=2)
self.logger.info(f"Chat contents saved to {self.chat_window_log_file}")
except Exception as e:
self.logger.error(f"Error saving chat contents: {str(e)}")

def load_chat_contents(self):
if not os.path.exists(self.chat_window_log_file):
self.logger.info(f"No chat log file found at {self.chat_window_log_file}")
return []

try:
with open(self.chat_window_log_file, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
self.logger.error(f"Error loading chat contents: {str(e)}")
return []

def set_session_id(self, session_id):
self.session_id = session_id
self.session_dir = os.path.join(self.output_dir, self.session_id)
self.chat_history_file = os.path.join(self.session_dir, "chat_history.json")
self._ensure_output_dirs_exist()
setup_logger(self.session_dir)
self.logger = get_logger()

def copy_log_to_new_session(self, new_session_id):
new_session_dir = os.path.join(self.output_dir, new_session_id)
os.makedirs(new_session_dir, exist_ok=True)

old_log_file = os.path.join(self.session_dir, "codeaide.log")
new_log_file = os.path.join(new_session_dir, "codeaide.log")

os.makedirs(os.path.dirname(new_log_file), exist_ok=True)

if os.path.exists(old_log_file):
shutil.copy2(old_log_file, new_log_file)

# Append a message to the old log file
with open(old_log_file, "a") as f:
f.write("\nNew session created. Log continued in new file.\n")

self.logger.info(f"Copied log file to new session: {new_session_id}")
else:
self.logger.warning(
f"No existing log file found to copy for new session: {new_session_id}"
)
Loading