diff --git a/src/mail/message_store.py b/src/mail/message_store.py index c9d3343..efcdac7 100644 --- a/src/mail/message_store.py +++ b/src/mail/message_store.py @@ -83,7 +83,17 @@ class MessageStore: self, current_index: int ) -> Tuple[Optional[int], Optional[int]]: """Find the next valid message ID and its index""" - if not self.envelopes or current_index >= len(self.envelopes) - 1: + if not self.envelopes: + return None, None + + # Clamp current_index to valid range in case list shrunk during async operations + if current_index >= len(self.envelopes): + current_index = len(self.envelopes) - 1 + if current_index < 0: + current_index = 0 + + # If already at or past the end, no next item + if current_index >= len(self.envelopes) - 1: return None, None # Start from current index + 1 @@ -99,7 +109,17 @@ class MessageStore: self, current_index: int ) -> Tuple[Optional[int], Optional[int]]: """Find the previous valid message ID and its index""" - if not self.envelopes or current_index <= 0: + if not self.envelopes: + return None, None + + # Clamp current_index to valid range in case list shrunk during async operations + if current_index >= len(self.envelopes): + current_index = len(self.envelopes) - 1 + if current_index < 0: + current_index = 0 + + # If at the beginning, no previous item + if current_index <= 0: return None, None # Start from current index - 1