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.

refactor(settings): singleton SettingsStore with auto-reload on file change

cyh22b902ce2af9
diff --git a/config/v2_settings.py b/config/v2_settings.py
index 193df6c54..8c5eaa40a 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -126,12 +126,47 @@ def _routing_to_dict(routing: RoutingSettings) -> dict:
class SettingsStore:
+ # ------------------------------------------------------------------
+ # Singleton: one store shared by bot process AND UI API handlers.
+ # ------------------------------------------------------------------
+ _instance: Optional["SettingsStore"] = None
+ _instance_lock = threading.Lock()
+
+ @classmethod
+ def get_instance(cls, settings_path: Optional[Path] = None) -> "SettingsStore":
+ """Return the process-wide singleton, creating it on first call.
+
+ Automatically reloads from disk if the file has changed.
+ """
+ with cls._instance_lock:
+ if cls._instance is None:
+ cls._instance = cls(settings_path)
+ else:
+ cls._instance.maybe_reload()
+ return cls._instance
+
+ @classmethod
+ def reset_instance(cls) -> None:
+ """Reset singleton (for tests only)."""
+ with cls._instance_lock:
+ cls._instance = None
+
def __init__(self, settings_path: Optional[Path] = None):
self.settings_path = settings_path or paths.get_settings_path()
self.settings: SettingsState = SettingsState()
self._bind_lock = threading.Lock() # Guards atomic bind operations
+ self._file_mtime: float = 0
self._load()
+ def maybe_reload(self) -> None:
+ """Reload from disk if the file has been modified since last load."""
+ try:
+ mtime = self.settings_path.stat().st_mtime
+ if mtime > self._file_mtime:
+ self._load()
+ except FileNotFoundError:
+ pass
+
def _load(self) -> None:
if not self.settings_path.exists():
return
@@ -200,6 +235,10 @@ class SettingsStore:
)
self.settings = SettingsState(channels=channels, users=users, bind_codes=bind_codes)
+ try:
+ self._file_mtime = self.settings_path.stat().st_mtime
+ except FileNotFoundError:
+ self._file_mtime = 0
def save(self) -> None:
paths.ensure_data_dirs()
@@ -241,6 +280,10 @@ class SettingsStore:
)
self.settings_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+ try:
+ self._file_mtime = self.settings_path.stat().st_mtime
+ except FileNotFoundError:
+ self._file_mtime = 0
# --- Channel helpers ---
@@ -293,9 +336,9 @@ class SettingsStore:
Thread-safe: uses a lock to prevent concurrent bind races.
"""
with self._bind_lock:
- # Reload from disk so we pick up bind codes created by the UI API
- # (which uses a separate SettingsStore instance).
- self._load()
+ # Ensure we have the latest data from disk (UI API may have
+ # created bind codes via the same singleton after we last read).
+ self.maybe_reload()
# Check already bound
if self.is_bound_user(user_id):
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index 2e1d20fbc..f10c579a7 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -1,5 +1,4 @@
import logging
-import hashlib
import time
from dataclasses import asdict, dataclass, field
from typing import Any, Dict, List, Optional, Union
@@ -103,10 +102,8 @@ class SettingsManager:
def __init__(self, settings_file: Optional[str] = None):
paths.ensure_data_dirs()
self.settings_file = Path(settings_file) if settings_file else paths.get_settings_path()
- self._settings_mtime_ns: Optional[int] = None
- self._settings_fingerprint: Optional[str] = None
self.settings: Dict[Union[int, str], UserSettings] = {}
- self.store = SettingsStore(self.settings_file)
+ self.store = SettingsStore.get_instance(self.settings_file)
self.sessions_store = SessionsStore()
self.sessions_store.load()
self._load_settings()
@@ -199,58 +196,26 @@ class SettingsManager:
def _load_settings(self):
"""Load settings from JSON file"""
- self.store = SettingsStore(self.settings_file)
- self.settings = {}
-
- if not self.store.settings.channels:
- logger.info("No settings file found, starting with empty settings")
- return
+ self.store = SettingsStore.get_instance(self.settings_file)
+ self._rebuild_runtime_settings()
+ def _reload_if_changed(self) -> None:
+ """Reload runtime settings if the underlying store has changed on disk."""
+ old_mtime = self.store._file_mtime
+ self.store.maybe_reload()
+ if self.store._file_mtime != old_mtime:
+ logger.info("Settings file changed on disk, rebuilding runtime settings")
+ self._rebuild_runtime_settings()
+
+ def _rebuild_runtime_settings(self) -> None:
+ """Rebuild the in-memory settings dict from the store."""
+ self.settings = {}
for channel_id, channel_settings in self.store.settings.channels.items():
key = str(channel_id)
- # Skip legacy channel entries that collide with bound users —
- # the authoritative source for bound users is store.settings.users
if key in self.store.settings.users:
- logger.info("Skipping channels[%s] — shadowed by users[%s]", key, key)
- continue
+ continue # authoritative source is users dict
self.settings[key] = self._from_channel_settings(channel_settings)
-
- try:
- self._settings_mtime_ns = self.settings_file.stat().st_mtime_ns
- self._settings_fingerprint = self._compute_settings_fingerprint()
- except FileNotFoundError:
- self._settings_mtime_ns = None
- self._settings_fingerprint = None
-
- logger.info(f"Loaded settings for {len(self.settings)} channels")
-
- def _compute_settings_fingerprint(self) -> Optional[str]:
- try:
- data = self.settings_file.read_bytes()
- except FileNotFoundError:
- return None
- return hashlib.sha256(data).hexdigest()
-
- def _reload_if_changed(self) -> None:
- if not self.settings_file.exists():
- return
- try:
- mtime_ns = self.settings_file.stat().st_mtime_ns
- except FileNotFoundError:
- return
- fingerprint = None
- if self._settings_mtime_ns is None or mtime_ns != self._settings_mtime_ns:
- fingerprint = self._compute_settings_fingerprint()
- elif self._settings_fingerprint is None:
- fingerprint = self._compute_settings_fingerprint()
- if fingerprint and fingerprint != self._settings_fingerprint:
- logger.info("Settings file changed on disk, reloading")
- self._load_settings()
- elif fingerprint:
- self._settings_fingerprint = fingerprint
- self._settings_mtime_ns = mtime_ns
- else:
- self._settings_mtime_ns = mtime_ns
+ logger.info(f"Rebuilt runtime settings for {len(self.settings)} channels")
def _is_bound_user_key(self, key: str) -> bool:
"""Check if a settings key belongs to a bound DM user (not a channel)."""
@@ -281,12 +246,6 @@ class SettingsManager:
channels[sk] = channel_settings
self.store.settings.channels = channels
self.store.save()
- try:
- self._settings_mtime_ns = self.settings_file.stat().st_mtime_ns
- self._settings_fingerprint = self._compute_settings_fingerprint()
- except FileNotFoundError:
- self._settings_mtime_ns = None
- self._settings_fingerprint = None
logger.info("Settings saved successfully")
except Exception as e:
logger.error(f"Error saving settings: {e}")
diff --git a/vibe/api.py b/vibe/api.py
index d5e6f8a2d..b2e458eeb 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -104,12 +104,12 @@ def config_to_payload(config: V2Config) -> dict:
def get_settings() -> dict:
- store = SettingsStore()
+ store = SettingsStore.get_instance()
return _settings_to_payload(store)
def save_settings(payload: dict) -> dict:
- store = SettingsStore()
+ store = SettingsStore.get_instance()
channels = {}
for channel_id, channel_payload in (payload.get("channels") or {}).items():
channels[channel_id] = ChannelSettings(
@@ -1098,7 +1098,7 @@ def lark_list_chats(app_id: str, app_secret: str, domain: str = "feishu") -> dic
def get_users() -> dict:
"""Get all bound users."""
- store = SettingsStore()
+ store = SettingsStore.get_instance()
users = {}
for user_id, u in store.settings.users.items():
users[user_id] = {
@@ -1118,7 +1118,7 @@ def save_users(payload: dict) -> dict:
Preserves admin invariant: if there were admins before, at least one must remain.
"""
- store = SettingsStore()
+ store = SettingsStore.get_instance()
had_admins = store.has_any_admin()
users = {}
@@ -1151,7 +1151,7 @@ def save_users(payload: dict) -> dict:
def toggle_admin(user_id: str, is_admin: bool) -> dict:
"""Toggle admin status for a user."""
- store = SettingsStore()
+ store = SettingsStore.get_instance()
if not store.set_admin(user_id, is_admin):
if not store.is_bound_user(user_id):
return {"ok": False, "error": "User not found"}
@@ -1161,7 +1161,7 @@ def toggle_admin(user_id: str, is_admin: bool) -> dict:
def remove_user(user_id: str) -> dict:
"""Remove a bound user."""
- store = SettingsStore()
+ store = SettingsStore.get_instance()
user = store.get_user(user_id)
if user is None:
return {"ok": False, "error": "User not found"}
@@ -1176,7 +1176,7 @@ def remove_user(user_id: str) -> dict:
def get_bind_codes() -> dict:
"""Get all bind codes."""
- store = SettingsStore()
+ store = SettingsStore.get_instance()
codes = []
for bc in store.get_bind_codes():
codes.append(
@@ -1198,7 +1198,7 @@ def create_bind_code(code_type: str = "one_time", expires_at: Optional[str] = No
return {"ok": False, "error": "type must be 'one_time' or 'expiring'"}
if code_type == "expiring" and not expires_at:
return {"ok": False, "error": "expires_at is required for expiring bind codes"}
- store = SettingsStore()
+ store = SettingsStore.get_instance()
bc = store.create_bind_code(code_type, expires_at)
return {
"ok": True,
@@ -1214,7 +1214,7 @@ def create_bind_code(code_type: str = "one_time", expires_at: Optional[str] = No
def delete_bind_code(code: str) -> dict:
"""Deactivate a bind code."""
- store = SettingsStore()
+ store = SettingsStore.get_instance()
if store.deactivate_bind_code(code):
return {"ok": True}
return {"ok": False, "error": "Bind code not found"}
@@ -1222,7 +1222,7 @@ def delete_bind_code(code: str) -> dict:
def get_first_bind_code() -> dict:
"""Get or create the initial bind code for setup wizard."""
- store = SettingsStore()
+ store = SettingsStore.get_instance()
# If any valid (active + not expired) code exists, return it
for bc in store.get_bind_codes():
if bc.is_active and store.validate_bind_code(bc.code) is not None: