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(sessions): stop legacy mapping reconciliation from flattening session activity (#1821)

Call White3cf295fedc04
diff --git a/config/v2_sessions.py b/config/v2_sessions.py
index fde9b32f3..ec34eb6c1 100644
--- a/config/v2_sessions.py
+++ b/config/v2_sessions.py
@@ -156,6 +156,25 @@ def infer_platform_from_thread_ids(agent_maps: Dict[str, Dict[str, str]]) -> Opt
return None
+def is_legacy_session_mapping_key(key: str, agent_maps: Dict[str, Dict[str, str]]) -> bool:
+ """Whether a ``session_mappings`` key is a legacy raw key needing a platform.
+
+ A legacy raw key is a *non-empty* key with no platform prefix that still
+ holds mappings: it used to be a bare channel or user ID. The empty key is
+ not one of those. ``_legacy_scope_key`` collapses a Session with no Scope
+ onto it, so prefixing it would assert those Sessions belong to some
+ platform, and the rows behind it record no legacy scope key for the
+ migration to act on -- which is why treating it as legacy made every startup
+ re-run the migration and re-save the whole session state.
+
+ This is the single definition of "legacy raw key". Every caller that has to
+ agree on it -- the startup migration and the import preflight that decides
+ whether a platform is required -- must ask this function, or the preflight
+ rejects state that the migration would then leave untouched anyway.
+ """
+ return bool(key) and "::" not in str(key) and bool(agent_maps)
+
+
def migrate_session_state_active_polls(state: SessionState, default_platform: str) -> bool:
migrated = False
for _sid, data in state.active_polls.items():
@@ -177,14 +196,12 @@ def migrate_session_state_active_polls(state: SessionState, default_platform: st
def migrate_session_state_mappings(state: SessionState, default_platform: str) -> tuple[int, int, int]:
"""Migrate legacy raw session keys to platform-prefixed keys.
+ See ``is_legacy_session_mapping_key`` for what counts as legacy.
+
Returns ``(migrated_entries, legacy_keys, empty_keys_removed)``.
"""
mappings = state.session_mappings
- old_keys = [
- k
- for k in list(mappings.keys())
- if "::" not in k and mappings[k]
- ]
+ old_keys = [k for k in list(mappings.keys()) if is_legacy_session_mapping_key(k, mappings[k])]
if not old_keys:
empty_keys = [k for k in list(mappings.keys()) if not mappings[k]]
for key in empty_keys:
diff --git a/storage/importer.py b/storage/importer.py
index cad9dafb7..4efe145c3 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -17,6 +17,7 @@ from config.discovered_chats import DiscoveredChatsStore
from config.v2_sessions import (
SessionState,
infer_platform_from_thread_ids,
+ is_legacy_session_mapping_key,
load_session_state_from_json,
migrate_session_state_active_polls,
migrate_session_state_mappings,
@@ -429,7 +430,10 @@ def _migrate_session_state_for_import(state: SessionState, *, primary_platform:
if not needs_default_platform:
for scope_key, agent_maps in state.session_mappings.items():
- if "::" in str(scope_key) or not agent_maps:
+ # Only a legacy raw key can need a platform; ask the one definition
+ # the migration itself uses, so the preflight cannot reject state
+ # that the migration would leave untouched.
+ if not is_legacy_session_mapping_key(scope_key, agent_maps):
continue
if not infer_platform_from_thread_ids(agent_maps):
needs_default_platform = True
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 4f9bbe2ef..2b756a7af 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -1928,7 +1928,12 @@ class SQLiteSessionsService:
"status": stmt.excluded.status,
"metadata_json": stmt.excluded.metadata_json,
"updated_at": stmt.excluded.updated_at,
- "last_active_at": stmt.excluded.last_active_at,
+ # ``last_active_at`` is deliberately absent: it is the
+ # session-list ranking column and only real activity may
+ # move it. ``now`` is computed once per call, so writing it
+ # here stamped every reconciled row with one identical
+ # value and collapsed the ranking to its tiebreakers.
+ # New rows still get their stamp from ``values()`` above.
},
)
)
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index ac139532c..4799382f6 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -7927,3 +7927,206 @@ def test_releasing_a_reservation_holds_the_write_lock_at_its_decision_read(
"nothing adopted the reservation, so the release must still remove it: a fix that "
"makes the cleanup stop working is not a fix"
)
+
+
+def _activity_stamps(service: SQLiteSessionsService) -> dict[str, tuple[str, str]]:
+ """Every row's ranking-relevant timestamps, keyed by session id."""
+
+ with service.engine.connect() as conn:
+ return {
+ str(row["id"]): (str(row["last_active_at"]), str(row["updated_at"]))
+ for row in conn.execute(
+ select(
+ agent_sessions.c.id,
+ agent_sessions.c.last_active_at,
+ agent_sessions.c.updated_at,
+ )
+ ).mappings()
+ }
+
+
+def test_save_state_does_not_move_last_active_at_of_any_existing_row(tmp_path: Path) -> None:
+ """``save_state`` imports legacy mappings; it is not session activity.
+
+ ``now`` is computed once per call, so a row it restamps is not merely wrong
+ by a few microseconds -- every row it touches ends up sharing one identical
+ value, which collapses the session list's ``last_active_at DESC`` ordering
+ onto its tiebreakers. The assertion is therefore that *no* pre-existing row
+ moved, seeded with one row of every shape this loop can reach rather than a
+ list of the shapes it is expected to skip.
+ """
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ with service.engine.begin() as conn:
+ adopted_scope = resolve_scope_from_legacy_key(conn, "slack::C_ADOPT", now="2026-07-01T00:00:00Z")
+ archived_scope = resolve_scope_from_legacy_key(conn, "slack::C_ARCHIVED", now="2026-07-01T00:00:00Z")
+ routed_scope = resolve_scope_from_legacy_key(conn, "slack::C_ROUTED", now="2026-07-01T00:00:00Z")
+
+ # Shape 1: the imported mapping matches this row and its backend.
+ adopted_id = create_agent_session_row(
+ conn,
+ scope_id=adopted_scope,
+ agent_backend="codex",
+ agent_variant="codex",
+ session_anchor="slack_100.001",
+ native_session_id="codex-native",
+ workdir="/tmp",
+ metadata={"legacy_scope_key": "slack::C_ADOPT"},
+ now="2026-07-10T00:00:00+00:00",
+ require_workdir=False,
+ )
+ # Shape 2: an archived row owns the anchor, so the import is skipped.
+ archived_id = create_agent_session_row(
+ conn,
+ scope_id=archived_scope,
+ agent_backend="claude",
+ agent_variant="claude",
+ session_anchor="slack_200.002",
+ native_session_id="archived-native",
+ status="archived",
+ workdir="/tmp",
+ metadata={"legacy_scope_key": "slack::C_ARCHIVED"},
+ now="2026-07-11T00:00:00+00:00",
+ require_workdir=False,
+ )
+ # Shape 3: a backend-owned route the import must not relabel.
+ routed_id = create_agent_session_row(
+ conn,
+ scope_id=routed_scope,
+ agent_backend="claude",
+ agent_variant="claude",
+ session_anchor="slack_300.003",
+ native_session_id="claude-native",
+ workdir="/tmp",
+ metadata={"legacy_scope_key": "slack::C_ROUTED"},
+ now="2026-07-12T00:00:00+00:00",
+ require_workdir=False,
+ )
+ # Shape 4: a Session with no Scope at all.
+ scopeless_id = create_agent_session_row(
+ conn,
+ scope_id=None,
+ agent_backend="codex",
+ agent_variant="codex",
+ session_anchor="standalone_400.004",
+ native_session_id="scopeless-native",
+ workdir="/tmp",
+ metadata={},
+ now="2026-07-13T00:00:00+00:00",
+ require_workdir=False,
+ )
+
+ before = _activity_stamps(service)
+ assert set(before) == {adopted_id, archived_id, routed_id, scopeless_id}
+
+ service.save_state(
+ SessionState(
+ session_mappings={
+ "slack::C_ADOPT": {"codex": {"slack_100.001": "codex-native"}},
+ "slack::C_ARCHIVED": {"codex": {"slack_200.002": "codex-native"}},
+ "slack::C_ROUTED": {"codex": {"slack_300.003": "codex-native"}},
+ "": {"codex": {"standalone_400.004": "scopeless-native"}},
+ # A mapping with no row yet: this one must still be stamped.
+ "slack::C_NEW": {"codex": {"slack_500.005": "new-native"}},
+ }
+ )
+ )
+
+ after = _activity_stamps(service)
+ for session_id, stamps in before.items():
+ assert after[session_id][0] == stamps[0], (
+ f"save_state moved last_active_at of {session_id}: "
+ f"{stamps[0]} -> {after[session_id][0]}"
+ )
+
+ created = set(after) - set(before)
+ assert created, "save_state imported no new row, so the insert path proved nothing"
+ for session_id in created:
+ assert after[session_id][0], f"newly imported row {session_id} has no last_active_at"
+ finally:
+ service.close()
+
+
+def test_startup_mapping_migration_does_not_restamp_sessions_without_scope(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A Session with no Scope must not make every startup re-save the state.
+
+ ``_legacy_scope_key`` collapses a row with no Scope and no recorded legacy
+ scope key onto the empty key. Treating that as a legacy raw key made the
+ startup migration "migrate" it on every boot -- and each of those saves
+ rewrote the whole state, so the fix has to hold across restarts, not just
+ once.
+ """
+
+ sessions_path = tmp_path / "sessions.json"
+ store = SessionsStore(sessions_path)
+ try:
+ with store._service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, "slack::C123", now="2026-07-01T00:00:00Z")
+ create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="claude",
+ session_anchor="slack_171717.123",
+ native_session_id="claude-native",
+ workdir="/tmp",
+ metadata={"legacy_scope_key": "slack::C123"},
+ now="2026-07-20T00:00:00+00:00",
+ require_workdir=False,
+ )
+ create_agent_session_row(
+ conn,
+ scope_id=None,
+ agent_backend="codex",
+ agent_variant="codex",
+ session_anchor="archived:seed",
+ native_session_id="codex-native",
+ status="archived",
+ workdir="/tmp",
+ metadata={},
+ now="2026-07-21T00:00:00+00:00",
+ require_workdir=False,
+ )
+ before = _activity_stamps(store._service)
+ finally:
+ store.close()
+
+ save_calls: list[object] = []
+ original_save_state = SQLiteSessionsService.save_state
+
+ def _spy(self: SQLiteSessionsService, state: SessionState) -> None:
+ save_calls.append(state)
+ return original_save_state(self, state)
+
+ monkeypatch.setattr(SQLiteSessionsService, "save_state", _spy)
+
+ for _ in range(2):
+ restarted = SessionsStore(sessions_path)
+ try:
+ assert "archived:seed" in restarted.state.session_mappings.get("", {}).get("codex", {}), (
+ "the scope-less row no longer loads under the empty key, so this test "
+ f"no longer reproduces the trigger: {restarted.state.session_mappings!r}"
+ )
+ restarted.migrate_session_mappings("slack")
+ assert "slack::" not in restarted.state.session_mappings, (
+ "the empty key was prefixed onto a platform it has no relation to"
+ )
+ assert "archived:seed" in restarted.state.session_mappings.get("", {}).get("codex", {}), (
+ "the migration dropped the scope-less Session's mapping"
+ )
+ finally:
+ restarted.close()
+
+ assert save_calls == [], (
+ f"the startup migration still re-saved the whole session state {len(save_calls)} time(s)"
+ )
+
+ verify = SQLiteSessionsService(sessions_path.with_name("vibe.sqlite"))
+ try:
+ assert _activity_stamps(verify) == before
+ finally:
+ verify.close()
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index e4d38e262..51dca55ce 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -6800,3 +6800,71 @@ def test_the_initial_drift_reset_still_clears_an_unreleased_database(tmp_path: P
surviving = _surviving_tables(db_path)
assert drifted not in surviving
assert "alembic_version" not in surviving
+
+
+def test_legacy_sessions_import_preflight_matches_the_migration_on_every_key_shape(
+ tmp_path: Path,
+) -> None:
+ """The preflight must require a platform exactly when the migration needs one.
+
+ ``_migrate_session_state_for_import`` decides whether ``primary_platform``
+ is mandatory, then hands the state to ``migrate_session_state_mappings``.
+ Two independent copies of "is this a legacy raw key?" can disagree, and the
+ failure is asymmetric: the preflight refuses to import state the migration
+ would have left untouched, so a user with that state cannot start at all.
+ Seed one key of every shape rather than listing the ones that are exempt.
+ """
+ state_dir = tmp_path / "state"
+ state_dir.mkdir()
+ db_path = state_dir / "vibe.sqlite"
+ (state_dir / "sessions.json").write_text(
+ json.dumps(
+ {
+ "session_mappings": {
+ # A Session with no Scope: no platform in the key and none
+ # inferable from the anchors, yet not legacy.
+ "": {"codex": {"archived:seed": "codex-session-scopeless"}},
+ # Already prefixed.
+ "slack::C123": {"codex": {"slack_1774074591.762089": "codex-session-1"}},
+ # Legacy, but the platform is inferable from the anchors.
+ "D456": {"codex": {"discord_1485641561998889093:/repo": "codex-session-2"}},
+ # Legacy key with nothing left in it.
+ "C999": {},
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ report = ensure_sqlite_state(db_path=db_path, state_dir=state_dir)
+
+ assert report.imported is True
+ with sqlite3.connect(db_path) as conn:
+ anchors = {
+ row[0]
+ for row in conn.execute("select session_anchor from agent_sessions").fetchall()
+ }
+ assert "archived:seed" in anchors, "the scope-less Session was dropped by the import"
+
+
+def test_legacy_sessions_import_still_requires_platform_for_an_unresolvable_legacy_key(
+ tmp_path: Path,
+) -> None:
+ """Exempting the empty key must not exempt a real legacy key beside it."""
+ state_dir = tmp_path / "state"
+ state_dir.mkdir()
+ db_path = state_dir / "vibe.sqlite"
+ (state_dir / "sessions.json").write_text(
+ json.dumps(
+ {
+ "session_mappings": {
+ "": {"codex": {"archived:seed": "codex-session-scopeless"}},
+ "C123": {"codex": {"1774074591.762089:/repo": "codex-session-1"}},
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ with pytest.raises(ValueError, match="primary_platform is required"):
+ ensure_sqlite_state(db_path=db_path, state_dir=state_dir)
diff --git a/tests/test_v2_sessions.py b/tests/test_v2_sessions.py
index 37558c0c2..2412bde88 100644
--- a/tests/test_v2_sessions.py
+++ b/tests/test_v2_sessions.py
@@ -4,7 +4,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
-from config.v2_sessions import SessionsStore
+from config.v2_sessions import SessionState, SessionsStore, migrate_session_state_mappings
from modules.sessions_facade import SessionsFacade
@@ -362,3 +362,37 @@ def test_migrate_session_mappings_is_idempotent(tmp_path, monkeypatch):
assert set(store2.state.session_mappings.keys()) == {"slack::C123"}
assert store2.state.session_mappings["slack::C123"]["opencode"]["slack_123.456"] == "ses_abc"
+
+
+def test_migrate_session_state_mappings_leaves_the_scopeless_empty_key_alone():
+ """The empty key is a Session with no Scope, not a pre-split raw channel ID.
+
+ ``_legacy_scope_key`` collapses a row with no Scope onto ``""``. Prefixing it
+ asserts those Sessions belong to ``default_platform``, and because the rows
+ behind it record no legacy scope key the migration can never actually fix
+ them -- so treating it as legacy made every startup re-run the migration and
+ re-save the whole session state.
+ """
+ state = SessionState(
+ session_mappings={
+ "": {"codex": {"archived:seed": "ses_scopeless"}},
+ "C123": {"opencode": {"slack_123.456:/work": "ses_legacy"}},
+ "slack::C999": {"opencode": {"slack_999.001": "ses_prefixed"}},
+ }
+ )
+
+ migrated, legacy_keys, empty_removed = migrate_session_state_mappings(state, "slack")
+
+ # A real legacy key still migrates; the empty key is not one of them.
+ assert (migrated, legacy_keys, empty_removed) == (1, 1, 0)
+ assert "C123" not in state.session_mappings
+ assert state.session_mappings["slack::C123"] == {"opencode": {"slack_123.456:/work": "ses_legacy"}}
+ assert state.session_mappings[""] == {"codex": {"archived:seed": "ses_scopeless"}}
+
+
+def test_migrate_session_state_mappings_is_a_noop_for_only_the_empty_key():
+ """With nothing but the empty key present, the migration must not save."""
+ state = SessionState(session_mappings={"": {"codex": {"archived:seed": "ses_scopeless"}}})
+
+ assert migrate_session_state_mappings(state, "slack") == (0, 0, 0)
+ assert list(state.session_mappings) == [""]