The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui-gateway): digest session rows for sessions.changed
ajbmachondf4ed4bb6191
diff --git a/tests/tui_gateway/test_change_watcher.py b/tests/tui_gateway/test_change_watcher.pyindex 7641f073ed4..a008fa2f5e2 100644--- a/tests/tui_gateway/test_change_watcher.py+++ b/tests/tui_gateway/test_change_watcher.py@@ -8,6 +8,7 @@ and the pet signature only moves for a *renderable* pet."""import os+import sqlite3import timeimport pytest@@ -27,6 +28,7 @@ def watcher_home(tmp_path, monkeypatch):monkeypatch.setattr(server, "_change_broadcast_at", {})monkeypatch.setattr(server, "_bot_relay_outbox_seen", 0)monkeypatch.setattr(server, "_pairing_roots_cache", None, raising=False)+ monkeypatch.setattr(server, "_sessions_db_sig_cache", {})events = []monkeypatch.setattr(@@ -35,6 +37,21 @@ def watcher_home(tmp_path, monkeypatch):return tmp_path, events+def _write_session_change(db_path, title):+ conn = sqlite3.connect(db_path)+ conn.execute(+ "CREATE TABLE IF NOT EXISTS sessions "+ "(id TEXT PRIMARY KEY, title TEXT, last_activity_at REAL, message_count INTEGER)"+ )+ conn.execute(+ "INSERT INTO sessions(id, title, last_activity_at, message_count) VALUES ('s1', ?, 1, 1) "+ "ON CONFLICT(id) DO UPDATE SET title = excluded.title",+ (title,),+ )+ conn.commit()+ conn.close()++def test_first_sighting_seeds_without_broadcasting(watcher_home):home, events = watcher_home(home / "cron" / "jobs.json").write_text("[]")@@ -59,7 +76,7 @@ def test_state_db_move_broadcasts_sessions_changed(watcher_home):home, events = watcher_homeserver._broadcast_watched_changes(now=0.0)- (home / "state.db").write_text("x")+ _write_session_change(home / "state.db", "created")server._broadcast_watched_changes(now=10.0)assert ("sessions.changed", {}) in events@@ -119,7 +136,7 @@ def test_served_profile_store_move_broadcasts_sessions_changed(watcher_home, monassert server._profile_home("bot") == bot_homeserver._broadcast_watched_changes(now=0.0)- (bot_home / "state.db").write_text("x")+ _write_session_change(bot_home / "state.db", "created")server._broadcast_watched_changes(now=10.0)assert ("sessions.changed", {}) in events@@ -220,13 +237,13 @@ def test_sessions_floor_coalesces_burst_but_keeps_trailing_edge(watcher_home):home, events = watcher_homeserver._broadcast_watched_changes(now=0.0)- (home / "state.db").write_text("x")+ _write_session_change(home / "state.db", "first")server._broadcast_watched_changes(now=10.0)events.clear()# A second write lands inside the 2s floor: no broadcast yet…time.sleep(0.02)- (home / "state.db").write_text("xy")+ _write_session_change(home / "state.db", "second")server._broadcast_watched_changes(now=11.0)assert events == []@@ -351,7 +368,7 @@ def test_broken_probe_never_kills_the_pass(watcher_home, monkeypatch):"cron.changed",(1.0, lambda: (_ for _ in ()).throw(RuntimeError("boom")), lambda: {}),)- (home / "state.db").write_text("x")+ _write_session_change(home / "state.db", "created")server._broadcast_watched_changes(now=10.0)# The broken cron probe is skipped; sessions still broadcasts.diff --git a/tests/tui_gateway/test_change_watcher_sessions.py b/tests/tui_gateway/test_change_watcher_sessions.pynew file mode 100644index 00000000000..61eff569e62--- /dev/null+++ b/tests/tui_gateway/test_change_watcher_sessions.py@@ -0,0 +1,61 @@+from __future__ import annotations++import sqlite3++import tui_gateway.server as server+++def _seed_store(path):+ conn = sqlite3.connect(path)+ conn.executescript(+ """+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ title TEXT,+ last_activity_at REAL,+ message_count INTEGER,+ archived INTEGER DEFAULT 0,+ pinned INTEGER DEFAULT 0+ );+ CREATE TABLE gateway_heartbeats (+ backend_id TEXT PRIMARY KEY,+ last_heartbeat REAL+ );+ INSERT INTO sessions(id, title, last_activity_at, message_count)+ VALUES ('session-1', 'Original', 100, 1);+ INSERT INTO gateway_heartbeats(backend_id, last_heartbeat)+ VALUES ('backend-1', 100);+ """+ )+ conn.commit()+ conn.close()+++def test_sessions_signature_ignores_gateway_heartbeat_only_writes(tmp_path, monkeypatch):+ db_path = tmp_path / "state.db"+ _seed_store(db_path)+ monkeypatch.setattr(server, "_watcher_home", lambda: tmp_path)+ monkeypatch.setattr(server, "_served_profile_homes", [])++ before = getattr(server, "_sessions_sig")()+ conn = sqlite3.connect(db_path)+ conn.execute("UPDATE gateway_heartbeats SET last_heartbeat = 200")+ conn.commit()+ conn.close()++ assert getattr(server, "_sessions_sig")() == before+++def test_sessions_signature_changes_for_session_metadata_updates(tmp_path, monkeypatch):+ db_path = tmp_path / "state.db"+ _seed_store(db_path)+ monkeypatch.setattr(server, "_watcher_home", lambda: tmp_path)+ monkeypatch.setattr(server, "_served_profile_homes", [])++ before = getattr(server, "_sessions_sig")()+ conn = sqlite3.connect(db_path)+ conn.execute("UPDATE sessions SET title = 'Renamed' WHERE id = 'session-1'")+ conn.commit()+ conn.close()++ assert getattr(server, "_sessions_sig")() != beforediff --git a/tui_gateway/change_watcher.py b/tui_gateway/change_watcher.pyindex 2531be7eee0..1a1ee2f0039 100644--- a/tui_gateway/change_watcher.py+++ b/tui_gateway/change_watcher.py@@ -4,6 +4,8 @@ rebound onto server.py's globals at install time (method_ctx.bind_module)."""from __future__ import annotations+from pathlib import Path+from .method_ctx import HandlerRegistry, bind_module_registry = HandlerRegistry()@@ -117,18 +119,81 @@ def _pet_changed_payload() -> dict:return {"enabled": False}+_SESSION_SIGNATURE_FIELDS = (+ "id", "source", "session_key", "display_name", "model", "parent_session_id",+ "started_at", "ended_at", "end_reason", "message_count", "tool_call_count",+ "cwd", "git_branch", "git_repo_root", "title", "title_source",+ "last_activity_at", "last_activity_description", "profile_name", "archived",+ "pinned", "hidden", "last_read_at", "handoff_state",+)+# path -> (database/WAL mtime, session-table digest). The mtime guard keeps the+# normal 0.5 s watch pass stat-only; SQLite is read only after another process+# actually commits.+_sessions_db_sig_cache: dict[str, tuple[int | None, tuple | None]] = {}+++def _session_db_content_sig(db_path: Path):+ """Digest list/transcript-relevant session rows, excluding unrelated tables.++ ``gateway_heartbeats`` shares state.db and writes every minute. Using the+ database mtime directly therefore emits sessions.changed while no session+ changed (#98005). Cache behind the DB/WAL mtime, then inspect only the+ sessions columns that drive Desktop projections. Legacy stores safely use+ the subset of columns they have.+ """+ mtime = _newest_mtime_ns((db_path, db_path.with_name(f"{db_path.name}-wal")))+ cache_key = str(db_path)+ cached = _sessions_db_sig_cache.get(cache_key)++ if cached is not None and cached[0] == mtime:+ return cached[1]+ if not db_path.exists():+ _sessions_db_sig_cache[cache_key] = (mtime, None)++ return None++ conn = None+ try:+ import hashlib+ import sqlite3+ from urllib.parse import quote++ conn = sqlite3.connect(f"file:{quote(str(db_path))}?mode=ro", uri=True, timeout=0.05)+ available = {row[1] for row in conn.execute("PRAGMA table_info(sessions)")}+ fields = tuple(field for field in _SESSION_SIGNATURE_FIELDS if field in available)+ if not fields:+ signature = None+ else:+ order = " ORDER BY id" if "id" in available else ""+ rows = conn.execute(f"SELECT {', '.join(fields)} FROM sessions{order}")+ digest = hashlib.blake2b(digest_size=16)+ for row in rows:+ digest.update(repr(tuple(row)).encode("utf-8", "backslashreplace"))+ digest.update(b"\0")+ signature = (fields, digest.digest())+ except Exception: # noqa: BLE001 - preserve the old wake-up signal if the read probe cannot run+ signature = ("mtime-fallback", mtime)+ finally:+ if conn is not None:+ conn.close()++ _sessions_db_sig_cache[cache_key] = (mtime, signature)++ return signature++def _sessions_sig():- """Newest mtime across state.db + WAL: the one thing messaging-gateway turns and cron runs- all move. Served sibling profile homes are probed too, else a routed Bot Chat never refreshes.+ """Session-table content across the active and served profile stores.- signal. Messaging-gateway turns and cron runs are written by OTHER processes that never touch this- gateway's transports; the shared SQLite file is the one thing they all move (#58671). A backend serving- several profiles owns one store per profile, so every served sibling home is+ Messaging-gateway turns and cron runs are written by other processes that+ never touch this gateway's transports, so their session rows are the shared+ change signal. Hashing only those rows avoids false Desktop refreshes from+ unrelated state.db writes such as gateway heartbeats."""- return _newest_mtime_ns(- root / name+ return tuple(+ _session_db_content_sig(root / "state.db")for root in (_watcher_home(), *_served_profile_homes)- for name in ("state.db", "state.db-wal"))+ )def _projects_sig():