Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(settings): normalize user_id to string consistently and migrate legacy int keys\n\n- Always store and access user keys as string (works for Slack and Telegram)\n- Migrate any legacy int keys in memory on load/access/update\n- Keep JSON keys naturally as strings

cyhhao00afb6a8aeb5
diff --git a/modules/claude_client.py b/modules/claude_client.py
index 3742e4090..d66a7d531 100644
--- a/modules/claude_client.py
+++ b/modules/claude_client.py
@@ -32,7 +32,9 @@ class ClaudeClient:
system_prompt=config.system_prompt,
)
- def format_message(self, message, get_relative_path: Optional[Callable[[str], str]] = None) -> str:
+ def format_message(
+ self, message, get_relative_path: Optional[Callable[[str], str]] = None
+ ) -> str:
"""Format different types of messages according to specified rules"""
try:
if isinstance(message, SystemMessage):
@@ -51,7 +53,9 @@ class ClaudeClient:
logger.error(f"Error formatting message: {e}")
return self.formatter.format_error(f"Error formatting message: {str(e)}")
- def _process_content_blocks(self, content_blocks, get_relative_path: Optional[Callable[[str], str]] = None) -> list:
+ def _process_content_blocks(
+ self, content_blocks, get_relative_path: Optional[Callable[[str], str]] = None
+ ) -> list:
"""Process content blocks (TextBlock, ToolUseBlock) and return formatted parts"""
formatted_parts = []
@@ -93,11 +97,17 @@ class ClaudeClient:
# Fallback to original path if any error
return full_path
- def _format_tool_use_block(self, block: ToolUseBlock, get_relative_path: Optional[Callable[[str], str]] = None) -> str:
+ def _format_tool_use_block(
+ self,
+ block: ToolUseBlock,
+ get_relative_path: Optional[Callable[[str], str]] = None,
+ ) -> str:
"""Format ToolUseBlock using formatter"""
# Prefer caller-provided get_relative_path (per-session cwd), fallback to self
rel = get_relative_path if get_relative_path else self._get_relative_path
- return self.formatter.format_tool_use(block.name, block.input, get_relative_path=rel)
+ return self.formatter.format_tool_use(
+ block.name, block.input, get_relative_path=rel
+ )
def _format_tool_result_block(self, block: ToolResultBlock) -> str:
"""Format ToolResultBlock using formatter"""
@@ -109,12 +119,20 @@ class ClaudeClient:
session_id = message.data.get("session_id", None)
return self.formatter.format_system_message(cwd, message.subtype, session_id)
- def _format_assistant_message(self, message: AssistantMessage, get_relative_path: Optional[Callable[[str], str]] = None) -> str:
+ def _format_assistant_message(
+ self,
+ message: AssistantMessage,
+ get_relative_path: Optional[Callable[[str], str]] = None,
+ ) -> str:
"""Format AssistantMessage using formatter"""
content_parts = self._process_content_blocks(message.content, get_relative_path)
return self.formatter.format_assistant_message(content_parts)
- def _format_user_message(self, message: UserMessage, get_relative_path: Optional[Callable[[str], str]] = None) -> str:
+ def _format_user_message(
+ self,
+ message: UserMessage,
+ get_relative_path: Optional[Callable[[str], str]] = None,
+ ) -> str:
"""Format UserMessage using formatter"""
content_parts = self._process_content_blocks(message.content, get_relative_path)
return self.formatter.format_user_message(content_parts)
@@ -134,4 +152,3 @@ class ClaudeClient:
if not message.content:
return True
return False
-
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index bf3bd6c8e..56f45f60b 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -12,24 +12,27 @@ logger = logging.getLogger(__name__)
@dataclass
class UserSettings:
"""User personalization settings"""
- hidden_message_types: List[str] = field(default_factory=list) # Message types to hide
+
+ hidden_message_types: List[str] = field(
+ default_factory=list
+ ) # Message types to hide
custom_cwd: Optional[str] = None # Custom working directory
# Nested map: {base_session_id: {working_path: claude_session_id}}
session_mappings: Dict[str, Dict[str, str]] = field(default_factory=dict)
-
+
def to_dict(self) -> dict:
"""Convert to dictionary for JSON serialization"""
return asdict(self)
-
+
@classmethod
- def from_dict(cls, data: dict) -> 'UserSettings':
+ def from_dict(cls, data: dict) -> "UserSettings":
"""Create from dictionary"""
return cls(**data)
class SettingsManager:
"""Manages user personalization settings with JSON persistence"""
-
+
def __init__(self, settings_file: str = "user_settings.json"):
self.settings_file = Path(settings_file)
self.settings: Dict[Union[int, str], UserSettings] = {}
@@ -38,39 +41,32 @@ class SettingsManager:
# ---------------------------------------------
# Internal helpers
# ---------------------------------------------
- def _normalize_user_id(self, user_id: Union[int, str]) -> Union[int, str]:
- """Normalize user_id to avoid duplicate keys (e.g. '123' vs 123)
+ def _normalize_user_id(self, user_id: Union[int, str]) -> str:
+ """Normalize user_id consistently to string.
- - If user_id is a numeric string, convert to int (Telegram case)
- - Otherwise keep as string (Slack IDs are non-numeric strings)
+ Rationale: JSON object keys are strings; Slack IDs are strings; unifying to
+ string avoids mixed-type keys (e.g., 123 vs "123").
"""
- if isinstance(user_id, int):
- return user_id
- if isinstance(user_id, str) and user_id.isdigit():
- return int(user_id)
- return user_id
-
+ return str(user_id)
+
def _load_settings(self):
"""Load settings from JSON file"""
try:
if self.settings_file.exists():
- with open(self.settings_file, 'r') as f:
+ with open(self.settings_file, "r") as f:
data = json.load(f)
for user_id_str, user_data in data.items():
# Clean up old format session mappings, only keep nested dict format
- if 'session_mappings' in user_data:
+ if "session_mappings" in user_data:
cleaned_mappings = {}
- for key, value in user_data['session_mappings'].items():
+ for key, value in user_data["session_mappings"].items():
# Only keep nested dictionary format
if isinstance(value, dict):
cleaned_mappings[key] = value
- user_data['session_mappings'] = cleaned_mappings
-
- # Try to convert to int for Telegram, keep as string for Slack
- try:
- user_id = int(user_id_str)
- except ValueError:
- user_id = user_id_str
+ user_data["session_mappings"] = cleaned_mappings
+
+ # Always keep user_id as string in memory
+ user_id = user_id_str
self.settings[user_id] = UserSettings.from_dict(user_data)
logger.info(f"Loaded settings for {len(self.settings)} users")
else:
@@ -78,121 +74,139 @@ class SettingsManager:
except Exception as e:
logger.error(f"Error loading settings: {e}")
self.settings = {}
-
+
def _save_settings(self):
"""Save settings to JSON file"""
try:
data = {
- str(user_id): settings.to_dict()
+ str(user_id): settings.to_dict()
for user_id, settings in self.settings.items()
}
- with open(self.settings_file, 'w') as f:
+ with open(self.settings_file, "w") as f:
json.dump(data, f, indent=2)
logger.info("Settings saved successfully")
except Exception as e:
logger.error(f"Error saving settings: {e}")
-
+
def get_user_settings(self, user_id: Union[int, str]) -> UserSettings:
"""Get settings for a specific user"""
normalized_id = self._normalize_user_id(user_id)
- # Try to merge stray duplicate key (e.g. both '123' and 123 exist)
- other_form = str(normalized_id) if isinstance(normalized_id, int) else None
- if isinstance(normalized_id, int) and other_form in self.settings:
- # Prefer normalized (int). If int not present, migrate string value
- if normalized_id not in self.settings:
- self.settings[normalized_id] = self.settings[other_form]
- del self.settings[other_form]
- self._save_settings()
+ # Migrate any legacy int key to string key to keep single source of truth
+ try:
+ int_form = int(normalized_id)
+ if int_form in self.settings: # legacy in-memory int key
+ if normalized_id not in self.settings:
+ self.settings[normalized_id] = self.settings[int_form]
+ del self.settings[int_form]
+ self._save_settings()
+ except Exception:
+ pass
# Return existing or create new
if normalized_id not in self.settings:
self.settings[normalized_id] = UserSettings()
self._save_settings()
return self.settings[normalized_id]
-
+
def update_user_settings(self, user_id: Union[int, str], settings: UserSettings):
"""Update settings for a specific user"""
normalized_id = self._normalize_user_id(user_id)
- # Remove stray duplicate under the other representation to keep single source
- if isinstance(normalized_id, int):
- stray_key = str(normalized_id)
- if stray_key in self.settings and self.settings.get(normalized_id) is not self.settings[stray_key]:
- del self.settings[stray_key]
+ # Remove legacy int key if exists
+ try:
+ int_form = int(normalized_id)
+ if int_form in self.settings and self.settings.get(normalized_id) is not self.settings[int_form]:
+ del self.settings[int_form]
+ except Exception:
+ pass
self.settings[normalized_id] = settings
self._save_settings()
-
- def toggle_hidden_message_type(self, user_id: Union[int, str], message_type: str) -> bool:
+
+ def toggle_hidden_message_type(
+ self, user_id: Union[int, str], message_type: str
+ ) -> bool:
"""Toggle a message type in hidden list, returns new state"""
settings = self.get_user_settings(user_id)
-
+
if message_type in settings.hidden_message_types:
settings.hidden_message_types.remove(message_type)
is_hidden = False
else:
settings.hidden_message_types.append(message_type)
is_hidden = True
-
+
self.update_user_settings(user_id, settings)
return is_hidden
-
+
def set_custom_cwd(self, user_id: Union[int, str], cwd: str):
"""Set custom working directory for user"""
settings = self.get_user_settings(user_id)
settings.custom_cwd = cwd
self.update_user_settings(user_id, settings)
-
+
def get_custom_cwd(self, user_id: Union[int, str]) -> Optional[str]:
"""Get custom working directory for user"""
settings = self.get_user_settings(user_id)
return settings.custom_cwd
-
- def is_message_type_hidden(self, user_id: Union[int, str], message_type: str) -> bool:
+
+ def is_message_type_hidden(
+ self, user_id: Union[int, str], message_type: str
+ ) -> bool:
"""Check if a message type is hidden for user"""
settings = self.get_user_settings(user_id)
return message_type in settings.hidden_message_types
-
+
def save_user_settings(self, user_id: Union[int, str], settings: UserSettings):
"""Save settings for a specific user (alias for update_user_settings)"""
self.update_user_settings(user_id, settings)
-
+
def get_available_message_types(self) -> List[str]:
"""Get list of available message types that can be hidden"""
- return [
- "system",
- "user",
- "assistant",
- "result"
- ]
-
+ return ["system", "user", "assistant", "result"]
+
def get_message_type_display_names(self) -> Dict[str, str]:
"""Get display names for message types"""
return {
"system": "System",
"user": "Response", # Renamed from 'user' for clarity
"assistant": "Assistant",
- "result": "Result"
+ "result": "Result",
}
-
- def set_session_mapping(self, user_id: Union[int, str], base_session_id: str, working_path: str, claude_session_id: str):
+
+ def set_session_mapping(
+ self,
+ user_id: Union[int, str],
+ base_session_id: str,
+ working_path: str,
+ claude_session_id: str,
+ ):
"""Store mapping between base session ID, working path, and Claude session ID"""
settings = self.get_user_settings(user_id)
if base_session_id not in settings.session_mappings:
settings.session_mappings[base_session_id] = {}
settings.session_mappings[base_session_id][working_path] = claude_session_id
self.update_user_settings(user_id, settings)
- logger.info(f"Stored session mapping for user {user_id}: {base_session_id}[{working_path}] -> {claude_session_id}")
-
- def get_claude_session_id(self, user_id: Union[int, str], base_session_id: str, working_path: str) -> Optional[str]:
+ logger.info(
+ f"Stored session mapping for user {user_id}: {base_session_id}[{working_path}] -> {claude_session_id}"
+ )
+
+ def get_claude_session_id(
+ self, user_id: Union[int, str], base_session_id: str, working_path: str
+ ) -> Optional[str]:
"""Get Claude session ID for given base session ID and working path"""
settings = self.get_user_settings(user_id)
if base_session_id in settings.session_mappings:
return settings.session_mappings[base_session_id].get(working_path)
return None
-
- def clear_session_mapping(self, user_id: Union[int, str], base_session_id: str, working_path: Optional[str] = None):
+
+ def clear_session_mapping(
+ self,
+ user_id: Union[int, str],
+ base_session_id: str,
+ working_path: Optional[str] = None,
+ ):
"""Clear session mapping for given base session ID and optionally working path"""
settings = self.get_user_settings(user_id)
if base_session_id in settings.session_mappings:
@@ -200,13 +214,17 @@ class SettingsManager:
# Clear specific path mapping
if working_path in settings.session_mappings[base_session_id]:
del settings.session_mappings[base_session_id][working_path]
- logger.info(f"Cleared session mapping for user {user_id}: {base_session_id}[{working_path}]")
+ logger.info(
+ f"Cleared session mapping for user {user_id}: {base_session_id}[{working_path}]"
+ )
else:
# Clear all mappings for this base session
del settings.session_mappings[base_session_id]
- logger.info(f"Cleared all session mappings for user {user_id}: {base_session_id}")
+ logger.info(
+ f"Cleared all session mappings for user {user_id}: {base_session_id}"
+ )
self.update_user_settings(user_id, settings)
-
+
def clear_all_session_mappings(self, user_id: Union[int, str]):
"""Clear all session mappings for a user"""
settings = self.get_user_settings(user_id)
@@ -214,4 +232,4 @@ class SettingsManager:
count = len(settings.session_mappings)
settings.session_mappings.clear()
logger.info(f"Cleared all {count} session mappings for user {user_id}")
- self.update_user_settings(user_id, settings)
\ No newline at end of file
+ self.update_user_settings(user_id, settings)