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(state): honor primary platform in sqlite bootstrap

cyh5b80f66c7e94
diff --git a/config/v2_sessions.py b/config/v2_sessions.py
index 8db038e61..f2187cdb6 100644
--- a/config/v2_sessions.py
+++ b/config/v2_sessions.py
@@ -223,10 +223,14 @@ class SessionsStore:
return
if self._service is not None:
self._service.close()
- from storage.importer import ensure_sqlite_state
+ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.sessions_service import SQLiteSessionsService
- ensure_sqlite_state(db_path=target_db, state_dir=Path(self.sessions_path).parent)
+ ensure_sqlite_state(
+ db_path=target_db,
+ state_dir=Path(self.sessions_path).parent,
+ primary_platform=resolve_primary_platform_from_config(),
+ )
self.db_path = target_db
self._service = SQLiteSessionsService(target_db)
diff --git a/config/v2_settings.py b/config/v2_settings.py
index cd595a71b..8be5a4c98 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -352,10 +352,14 @@ class SettingsStore:
self.settings: SettingsState = SettingsState()
self._bind_lock = threading.Lock() # Guards atomic bind operations
self._file_mtime: float = 0
- from storage.importer import ensure_sqlite_state
+ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.settings_service import SQLiteSettingsService
- ensure_sqlite_state(db_path=self.db_path, state_dir=self.settings_path.parent)
+ ensure_sqlite_state(
+ db_path=self.db_path,
+ state_dir=self.settings_path.parent,
+ primary_platform=resolve_primary_platform_from_config(),
+ )
self._service = SQLiteSettingsService(self.db_path)
self._load()
self._service.has_external_write()
diff --git a/storage/importer.py b/storage/importer.py
index 8b29ada06..9629e4f44 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -94,6 +94,31 @@ def ensure_sqlite_state(
engine.dispose()
+def resolve_primary_platform_from_config() -> str | None:
+ """Best-effort primary platform lookup for store-level SQLite bootstrap."""
+ try:
+ config_path = paths.get_config_path()
+ if not config_path.exists():
+ return None
+ payload = json.loads(config_path.read_text(encoding="utf-8"))
+ except Exception:
+ return None
+
+ if not isinstance(payload, dict):
+ return None
+
+ platforms = payload.get("platforms")
+ if isinstance(platforms, dict):
+ primary = platforms.get("primary")
+ if isinstance(primary, str) and primary.strip():
+ return primary.strip()
+
+ platform = payload.get("platform")
+ if isinstance(platform, str) and platform.strip():
+ return platform.strip()
+ return None
+
+
def _has_import_marker(conn: Connection) -> bool:
return (
conn.execute(select(schema_meta.c.value).where(schema_meta.c.key == JSON_IMPORT_MARKER)).scalar_one_or_none()
@@ -178,11 +203,30 @@ def _load_sessions_from_copy(source: Path, *, primary_platform: str | None) -> S
def _load_discovered_chats_strict(source: Path) -> DiscoveredChatsStore:
if source.exists():
payload = json.loads(source.read_text(encoding="utf-8"))
- if not isinstance(payload, dict):
- raise ValueError("discovered_chats.json must contain a JSON object")
+ _validate_discovered_chats_payload(payload)
return DiscoveredChatsStore(source)
+def _validate_discovered_chats_payload(payload: Any) -> None:
+ if not isinstance(payload, dict):
+ raise ValueError("discovered_chats.json must contain a JSON object")
+
+ raw_platforms = payload.get("platforms", {})
+ if raw_platforms is None:
+ return
+ if not isinstance(raw_platforms, dict):
+ raise ValueError("discovered_chats.json platforms must contain a JSON object")
+
+ for platform, chats in raw_platforms.items():
+ if not isinstance(chats, dict):
+ raise ValueError(f"discovered_chats.json platform {platform!r} must contain a JSON object")
+ for chat_id, chat_payload in chats.items():
+ if not isinstance(chat_payload, dict):
+ raise ValueError(
+ f"discovered_chats.json chat {platform!r}/{chat_id!r} must contain a JSON object"
+ )
+
+
def _migrate_session_state_for_import(state: SessionState, *, primary_platform: str | None) -> None:
if primary_platform is not None and not primary_platform.strip():
raise ValueError("primary_platform must be non-empty when provided")
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index 55e3e7477..ac8a5eaa2 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
from pathlib import Path
+from config import paths
from config.v2_sessions import ActivePollInfo, SessionState, SessionsStore
from storage.sessions_service import SQLiteSessionsService
@@ -96,6 +97,40 @@ def test_sessions_store_reloads_external_sqlite_writes(tmp_path: Path) -> None:
store.close()
+def test_sessions_store_bootstrap_uses_config_primary_platform(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ paths.get_config_path().write_text(
+ json.dumps({"platform": "lark", "platforms": {"enabled": ["lark"], "primary": "lark"}}),
+ encoding="utf-8",
+ )
+ paths.get_sessions_path().write_text(
+ json.dumps(
+ {
+ "session_mappings": {"chat-1": {"codex": {"1774074591.762089:/repo": "session-1"}}},
+ "active_polls": {
+ "oc-1": {
+ "opencode_session_id": "oc-1",
+ "base_session_id": "base-1",
+ "channel_id": "chat-1",
+ "thread_id": "1774074591.762089",
+ "settings_key": "chat-1",
+ "working_path": "/repo",
+ }
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ store = SessionsStore(paths.get_sessions_path())
+ try:
+ assert "lark::chat-1" in store.state.session_mappings
+ assert store.state.active_polls["oc-1"]["platform"] == "lark"
+ finally:
+ store.close()
+
+
def test_sessions_store_preserves_legacy_non_string_session_values(tmp_path: Path) -> None:
sessions_path = tmp_path / "sessions.json"
store = SessionsStore(sessions_path)
diff --git a/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.py
index 3e807710f..3e33345ef 100644
--- a/tests/test_sqlite_settings_store.py
+++ b/tests/test_sqlite_settings_store.py
@@ -3,7 +3,9 @@ from __future__ import annotations
import json
from pathlib import Path
+from config import paths
from config.v2_settings import ChannelSettings, SettingsState, SettingsStore, UserSettings
+from storage.sessions_service import SQLiteSessionsService
from storage.settings_service import SQLiteSettingsService
@@ -59,3 +61,41 @@ def test_settings_store_reloads_external_sqlite_writes(tmp_path: Path) -> None:
finally:
external.close()
store.close()
+
+
+def test_settings_store_bootstrap_uses_config_primary_platform(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ paths.ensure_data_dirs()
+ paths.get_config_path().write_text(
+ json.dumps({"platform": "discord", "platforms": {"enabled": ["discord"], "primary": "discord"}}),
+ encoding="utf-8",
+ )
+ sessions_path = paths.get_sessions_path()
+ sessions_path.write_text(
+ json.dumps(
+ {
+ "session_mappings": {"G123": {"codex": {"1774074591.762089:/repo": "session-1"}}},
+ "active_polls": {
+ "oc-1": {
+ "opencode_session_id": "oc-1",
+ "base_session_id": "base-1",
+ "channel_id": "G123",
+ "thread_id": "1774074591.762089",
+ "settings_key": "G123",
+ "working_path": "/repo",
+ }
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ store = SettingsStore(paths.get_settings_path())
+ sessions = SQLiteSessionsService(paths.get_sqlite_state_path())
+ try:
+ state = sessions.load_state()
+ assert "discord::G123" in state.session_mappings
+ assert state.active_polls["oc-1"]["platform"] == "discord"
+ finally:
+ sessions.close()
+ store.close()
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index 26afb1492..f193672b3 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -173,6 +173,33 @@ def test_invalid_discovered_chats_import_does_not_mark_complete_and_can_retry(tm
assert report.counts["discovered_chats"] == 1
+def test_malformed_discovered_chats_structure_does_not_mark_complete(tmp_path: Path) -> None:
+ state_dir = tmp_path / "state"
+ state_dir.mkdir()
+ db_path = state_dir / "vibe.sqlite"
+ _write_current_settings(state_dir / "settings.json")
+ _write_current_sessions(state_dir / "sessions.json")
+ (state_dir / "discovered_chats.json").write_text(
+ json.dumps({"schema_version": 1, "platforms": {"telegram": ["not", "a", "map"]}}),
+ encoding="utf-8",
+ )
+
+ with pytest.raises(ValueError, match="platform 'telegram'"):
+ ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
+
+ with sqlite3.connect(db_path) as conn:
+ marker = conn.execute(
+ "select value from schema_meta where key = 'json_import_completed_at'",
+ ).fetchone()
+ assert marker is None
+
+ _write_discovered_chats(state_dir / "discovered_chats.json")
+ report = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")
+
+ assert report.imported is True
+ assert report.counts["discovered_chats"] == 1
+
+
def test_data_version_probe_detects_external_write(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
run_migrations(db_path)