Skip to content

The agent that grows with you

fix(tui): avoid writable Kanban opens on empty polls

joncaldwell9058286878efaf
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index b64d54e53ab..113e34842ec 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -9773,6 +9773,9 @@ def count_notify_subs(
board: Optional[str] = None,
notifier_profiles: Optional[Iterable[str]] = None,
include_unowned: bool = False,
+ platform: Optional[str] = None,
+ chat_id: Optional[str] = None,
+ thread_id: Optional[str] = None,
) -> int:
"""Count ``kanban_notify_subs`` rows via a read-only connection.
@@ -9786,7 +9789,10 @@ def count_notify_subs(
DB, or a legacy DB that predates the subscriptions table, counts as
zero. When ``notifier_profiles`` is supplied, only subscriptions owned
by those profiles are counted; ``include_unowned`` also includes legacy
- rows without an owner stamp. Path resolution matches :func:`connect`
+ rows without an owner stamp. Optional platform/chat/thread filters narrow
+ the probe to one notification owner without changing the unfiltered count.
+ Platform matching is case-insensitive, matching notifier routing; chat and
+ thread identifiers are exact. Path resolution matches :func:`connect`
(explicit ``db_path``, else ``board`` via :func:`kanban_db_path`). Raises
:class:`sqlite3.Error` when the DB exists but cannot be read
(locked, corrupt); callers choose their own fallback.
@@ -9800,10 +9806,24 @@ def count_notify_subs(
owner_where, owner_params = _notify_profile_filter(
notifier_profiles, include_unowned=include_unowned,
)
- sql = "SELECT COUNT(*) FROM kanban_notify_subs"
+ clauses: list[str] = []
+ params: list[Any] = []
if owner_where:
- sql += " WHERE " + owner_where
- row = conn.execute(sql, owner_params).fetchone()
+ clauses.append(f"({owner_where})")
+ params.extend(owner_params)
+ if platform is not None:
+ clauses.append("LOWER(platform) = LOWER(?)")
+ params.append(platform)
+ if chat_id is not None:
+ clauses.append("chat_id = ?")
+ params.append(chat_id)
+ if thread_id is not None:
+ clauses.append("thread_id = ?")
+ params.append(thread_id)
+ query = "SELECT COUNT(*) FROM kanban_notify_subs"
+ if clauses:
+ query += " WHERE " + " AND ".join(clauses)
+ row = conn.execute(query, params).fetchone()
except sqlite3.OperationalError as exc:
if "no such table" in str(exc).lower():
return 0
diff --git a/tests/hermes_cli/test_kanban_count_notify_subs.py b/tests/hermes_cli/test_kanban_count_notify_subs.py
index c8c419133e8..f55c3580455 100644
--- a/tests/hermes_cli/test_kanban_count_notify_subs.py
+++ b/tests/hermes_cli/test_kanban_count_notify_subs.py
@@ -32,11 +32,49 @@ def test_missing_db_counts_zero_and_creates_nothing(kanban_home):
db_path = kb.kanban_db_path(board="default")
assert not db_path.exists()
assert kb.count_notify_subs(board="default") == 0
+ assert kb.count_notify_subs(
+ board="default", platform="tui", chat_id="session-1"
+ ) == 0
assert not db_path.exists(), "read-only probe must not create the DB"
+def test_optional_filters_narrow_count_without_changing_unfiltered_count(kanban_home):
+ conn = kb.connect(board="default")
+ try:
+ tid = kb.create_task(conn, title="t", assignee="w")
+ kb.add_notify_sub(conn, task_id=tid, platform="tui", chat_id="session-1")
+ kb.add_notify_sub(
+ conn,
+ task_id=tid,
+ platform="TUI",
+ chat_id="session-2",
+ thread_id="thread-2",
+ )
+ kb.add_notify_sub(
+ conn, task_id=tid, platform="telegram", chat_id="session-1"
+ )
+ finally:
+ conn.close()
-
+ assert kb.count_notify_subs(board="default") == 3
+ assert kb.count_notify_subs(board="default", platform="tui") == 2
+ assert kb.count_notify_subs(board="default", chat_id="session-1") == 2
+ assert kb.count_notify_subs(board="default", thread_id="thread-2") == 1
+ assert kb.count_notify_subs(
+ board="default", platform="tui", chat_id="session-1"
+ ) == 1
+ assert kb.count_notify_subs(
+ board="default", platform="tui", chat_id="session-1", thread_id=""
+ ) == 1
+ assert kb.count_notify_subs(
+ board="default",
+ platform="tui",
+ chat_id="session-2",
+ thread_id="thread-2",
+ ) == 1
+ assert kb.count_notify_subs(
+ board="default", platform="tui", chat_id="other-session"
+ ) == 0
def test_legacy_db_without_subs_table_counts_zero_and_stays_unmigrated(tmp_path):
@@ -48,6 +86,9 @@ def test_legacy_db_without_subs_table_counts_zero_and_stays_unmigrated(tmp_path)
finally:
conn.close()
assert kb.count_notify_subs(db_path=legacy) == 0
+ assert kb.count_notify_subs(
+ db_path=legacy, platform="tui", chat_id="session-1"
+ ) == 0
# The probe must not have run schema init on the foreign/legacy DB.
conn = sqlite3.connect(legacy)
try:
@@ -88,4 +129,3 @@ def test_count_notify_subs_filters_profile_owners(tmp_path):
notifier_profiles={"default"},
include_unowned=True,
) == 2
-
diff --git a/tests/tui_gateway/test_kanban_notify_poller.py b/tests/tui_gateway/test_kanban_notify_poller.py
index fd4374bb0be..59fe4b8e990 100644
--- a/tests/tui_gateway/test_kanban_notify_poller.py
+++ b/tests/tui_gateway/test_kanban_notify_poller.py
@@ -12,6 +12,7 @@ unsubscribe) and ``_format_kanban_event_text``.
"""
from types import SimpleNamespace
+from unittest.mock import patch
from hermes_cli import kanban_db as kb
from tui_gateway.server import (
@@ -53,6 +54,17 @@ def _sub_rows(tid: str) -> list:
class TestCollectKanbanNotifications:
+ def test_zero_sub_board_is_never_opened_writable(self):
+ conn = kb.connect()
+ conn.close()
+ kb.create_board("second-board")
+
+ with patch.object(kb, "connect", wraps=kb.connect) as spy_connect:
+ texts = _collect_kanban_notifications(_session())
+
+ assert texts == []
+ spy_connect.assert_not_called()
+
def test_delivers_completed_event_and_unsubscribes(self):
tid = _create_subscribed_task()
_complete(tid, summary="shipped the fix")
@@ -66,45 +78,74 @@ class TestCollectKanbanNotifications:
# Task is at a final status -> subscription removed.
assert _sub_rows(tid) == []
- def test_claim_advances_cursor_so_second_poll_is_empty(self):
+ def test_matching_tui_sub_delivers_and_advances_cursor(self):
tid = _create_subscribed_task()
+ pre_cursor = _sub_rows(tid)[0]["last_event_id"]
conn = kb.connect()
try:
kb.block_task(conn, tid, reason="waiting on review")
finally:
conn.close()
- first = _collect_kanban_notifications(_session())
- second = _collect_kanban_notifications(_session())
+ with patch.object(kb, "connect", wraps=kb.connect) as spy_connect:
+ first = _collect_kanban_notifications(_session())
+ second = _collect_kanban_notifications(_session())
assert len(first) == 1
assert "blocked" in first[0]
assert "waiting on review" in first[0]
assert second == []
+ assert spy_connect.called
# Blocked is not a final status -> subscription stays alive so a
# respawned task's next terminal event still reaches the user.
- assert len(_sub_rows(tid)) == 1
+ rows = _sub_rows(tid)
+ assert len(rows) == 1
+ assert rows[0]["last_event_id"] > pre_cursor
- def test_ignores_other_sessions_and_platforms(self):
- tid_other_session = _create_subscribed_task(chat_id="some-other-session")
- tid_gateway = _create_subscribed_task(platform="telegram", chat_id="chat-1")
+ def test_non_tui_subscription_does_not_open_board_writable(self):
+ tid = _create_subscribed_task(platform="telegram", chat_id="chat-1")
# New subs start caught up at creation time (issue #29905); record the
# pre-completion cursors so we can assert they were never claimed.
- pre_cursors = {
- tid: _sub_rows(tid)[0]["last_event_id"]
- for tid in (tid_other_session, tid_gateway)
- }
- _complete(tid_other_session)
- _complete(tid_gateway)
+ pre_cursor = _sub_rows(tid)[0]["last_event_id"]
+ _complete(tid)
- texts = _collect_kanban_notifications(_session())
+ with patch.object(kb, "connect", wraps=kb.connect) as spy_connect:
+ texts = _collect_kanban_notifications(_session())
assert texts == []
- # Foreign subscriptions untouched: cursors unclaimed, rows still there.
- for tid in (tid_other_session, tid_gateway):
- rows = _sub_rows(tid)
- assert len(rows) == 1
- assert rows[0]["last_event_id"] == pre_cursors[tid]
+ spy_connect.assert_not_called()
+ rows = _sub_rows(tid)
+ assert len(rows) == 1
+ assert rows[0]["last_event_id"] == pre_cursor
+
+ def test_other_tui_session_does_not_open_board_writable(self):
+ tid = _create_subscribed_task(chat_id="some-other-session")
+ pre_cursor = _sub_rows(tid)[0]["last_event_id"]
+ _complete(tid)
+
+ with patch.object(kb, "connect", wraps=kb.connect) as spy_connect:
+ texts = _collect_kanban_notifications(_session())
+
+ assert texts == []
+ spy_connect.assert_not_called()
+ rows = _sub_rows(tid)
+ assert len(rows) == 1
+ assert rows[0]["last_event_id"] == pre_cursor
+
+ def test_probe_error_falls_back_to_writable_delivery(self, monkeypatch):
+ tid = _create_subscribed_task()
+ _complete(tid, summary="fallback delivery")
+
+ def fail_probe(*args, **kwargs):
+ raise OSError("probe unavailable")
+
+ monkeypatch.setattr(kb, "count_notify_subs", fail_probe)
+ with patch.object(kb, "connect", wraps=kb.connect) as spy_connect:
+ texts = _collect_kanban_notifications(_session())
+
+ assert len(texts) == 1
+ assert tid in texts[0]
+ spy_connect.assert_called_once()
def test_no_session_key_is_a_noop(self):
tid = _create_subscribed_task()
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index a3475fc11ec..b2dfc34e2a0 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -8910,6 +8910,20 @@ def _collect_kanban_notifications(session: dict) -> list:
if resolved in seen_db_paths:
continue
seen_db_paths.add(resolved)
+ # A poller runs per live TUI/Desktop session. Avoid opening this board
+ # writable unless it has a subscription owned by this exact session;
+ # subscriptions for gateways or other sessions are not actionable here.
+ try:
+ if _kb.count_notify_subs(
+ board=slug,
+ platform="tui",
+ chat_id=session_key,
+ ) == 0:
+ continue
+ except Exception:
+ # Preserve delivery if the read-only probe cannot inspect a
+ # locked, corrupt, or otherwise unusual database.
+ pass
try:
conn = _kb.connect(board=slug)
except Exception: