Skip to content

The agent that grows with you

fix(tui_gateway): a spared durable row survives agent.close() too

kshitijk4poordfc40a50a909
diff --git a/tests/tui_gateway/test_finalize_session_persist.py b/tests/tui_gateway/test_finalize_session_persist.py
index 9a02d574ef0..f5ddf7aa353 100644
--- a/tests/tui_gateway/test_finalize_session_persist.py
+++ b/tests/tui_gateway/test_finalize_session_persist.py
@@ -268,136 +268,3 @@ class TestOnSessionEndHook:
model="claude-sonnet-4",
platform="tui",
)
-
-
-class TestDesktopAutomaticCleanupPreservesDurableRow:
- """Automatic Desktop cleanup (ws_orphan_reap, idle_timeout, etc.) must NOT
- end the durable session row — the conversation stays open and resumable
- until the user explicitly closes or archives it.
-
- Regression test for #105588.
- """
-
- @patch("tui_gateway.server._other_runtime_lease_guard")
- @patch("tui_gateway.server._get_db")
- @patch("tui_gateway.server._session_source", return_value="desktop")
- def test_ws_orphan_reap_skips_end_session(
- self, _mock_source, mock_get_db, mock_lease_guard
- ):
- """ws_orphan_reap on a Desktop session must not call db.end_session."""
- from tui_gateway.server import _finalize_session
-
- mock_db = MagicMock()
- mock_get_db.return_value = mock_db
- # Simulate no other runtime owning the lifecycle (TUI owns it).
- mock_lease_guard.__enter__ = MagicMock(return_value=False)
- mock_lease_guard.__exit__ = MagicMock(return_value=False)
-
- agent = _make_agent(session_id="sess_orphan_001")
- session = _make_session(
- agent=agent,
- history=[{"role": "user", "content": "hello"}],
- )
- session["source"] = "desktop"
-
- _finalize_session(session, end_reason="ws_orphan_reap")
-
- mock_db.end_session.assert_not_called()
-
- @patch("tui_gateway.server._other_runtime_lease_guard")
- @patch("tui_gateway.server._get_db")
- @patch("tui_gateway.server._session_source", return_value="desktop")
- def test_idle_timeout_skips_end_session(
- self, _mock_source, mock_get_db, mock_lease_guard
- ):
- """idle_timeout on a Desktop session must not call db.end_session."""
- from tui_gateway.server import _finalize_session
-
- mock_db = MagicMock()
- mock_get_db.return_value = mock_db
- mock_lease_guard.__enter__ = MagicMock(return_value=False)
- mock_lease_guard.__exit__ = MagicMock(return_value=False)
-
- agent = _make_agent(session_id="sess_idle_001")
- session = _make_session(
- agent=agent,
- history=[{"role": "user", "content": "hello"}],
- )
- session["source"] = "desktop"
-
- _finalize_session(session, end_reason="idle_timeout")
-
- mock_db.end_session.assert_not_called()
-
- @patch("tui_gateway.server._other_runtime_lease_guard")
- @patch("tui_gateway.server._get_db")
- @patch("tui_gateway.server._session_source", return_value="desktop")
- def test_lru_evict_skips_end_session(
- self, _mock_source, mock_get_db, mock_lease_guard
- ):
- """lru_evict on a Desktop session must not call db.end_session."""
- from tui_gateway.server import _finalize_session
-
- mock_db = MagicMock()
- mock_get_db.return_value = mock_db
- mock_lease_guard.__enter__ = MagicMock(return_value=False)
- mock_lease_guard.__exit__ = MagicMock(return_value=False)
-
- agent = _make_agent(session_id="sess_lru_001")
- session = _make_session(
- agent=agent,
- history=[{"role": "user", "content": "hello"}],
- )
- session["source"] = "desktop"
-
- _finalize_session(session, end_reason="lru_evict")
-
- mock_db.end_session.assert_not_called()
-
- @patch("tui_gateway.server._other_runtime_lease_guard")
- @patch("tui_gateway.server._get_db")
- @patch("tui_gateway.server._session_source", return_value="desktop")
- def test_explicit_close_still_calls_end_session(
- self, _mock_source, mock_get_db, _mock_lease_guard
- ):
- """Explicit user close (tui_close) must still call db.end_session —
- only automatic cleanup reasons skip it."""
- from tui_gateway.server import _finalize_session
-
- mock_db = MagicMock()
- mock_get_db.return_value = mock_db
-
- agent = _make_agent(session_id="sess_close_001")
- session = _make_session(
- agent=agent,
- history=[{"role": "user", "content": "hello"}],
- )
- session["source"] = "desktop"
-
- _finalize_session(session, end_reason="tui_close")
-
- mock_db.end_session.assert_called_once_with("sess_close_001", "tui_close")
-
- @patch("tui_gateway.server._other_runtime_lease_guard")
- @patch("tui_gateway.server._get_db")
- @patch("tui_gateway.server._session_source", return_value="tui")
- def test_non_desktop_source_still_calls_end_session(
- self, _mock_source, mock_get_db, _mock_lease_guard
- ):
- """ws_orphan_reap on a NON-desktop source (e.g. TUI) must still call
- db.end_session — the fix only applies to Desktop sessions."""
- from tui_gateway.server import _finalize_session
-
- mock_db = MagicMock()
- mock_get_db.return_value = mock_db
-
- agent = _make_agent(session_id="sess_tui_001")
- session = _make_session(
- agent=agent,
- history=[{"role": "user", "content": "hello"}],
- )
- # No source set → falls back to platform which we patch as "tui"
-
- _finalize_session(session, end_reason="ws_orphan_reap")
-
- mock_db.end_session.assert_called_once_with("sess_tui_001", "ws_orphan_reap")
diff --git a/tests/tui_gateway/test_gateway_owned_session_reap.py b/tests/tui_gateway/test_gateway_owned_session_reap.py
index e3766db49df..4ca4c9444e5 100644
--- a/tests/tui_gateway/test_gateway_owned_session_reap.py
+++ b/tests/tui_gateway/test_gateway_owned_session_reap.py
@@ -11,6 +11,8 @@ loops. The TUI is only a viewer of those sessions.
import threading
from unittest.mock import MagicMock, patch
+import pytest
+
from tui_gateway.server import _finalize_session, _is_gateway_owned_source, _teardown_session
@@ -74,6 +76,7 @@ def _make_real_session(tmp_path, monkeypatch, *, source, session_id):
session = _make_session(session_id)
session["agent"] = agent
session["profile_home"] = str(hermes_home)
+ session["source"] = source
return db_path, session, agent
@@ -125,3 +128,33 @@ class TestGatewayOwnedSessionTeardown:
assert row["ended_at"] is None
assert row["end_reason"] is None
assert agent._end_session_on_close is False
+
+
+class TestDesktopAutomaticReclaimTeardown:
+ """#105588: automatic Desktop cleanup reclaims runtime but leaves the durable row open THROUGH the full
+ teardown — ``_finalize_session`` skipping ``end_session`` is not enough, ``agent.close()`` ends the row
+ as ``agent_close`` unless the spare decision reaches the agent."""
+
+ @pytest.mark.parametrize("reason", ["ws_orphan_reap", "idle_timeout", "lru_evict"])
+ def test_automatic_reclaim_leaves_desktop_row_open(self, tmp_path, monkeypatch, reason):
+ db_path, session, agent = _make_real_session(
+ tmp_path, monkeypatch, source="desktop", session_id=f"desktop-{reason}"
+ )
+
+ _teardown_session(session, end_reason=reason)
+
+ row = _read_real_row(db_path, f"desktop-{reason}")
+ assert (row["ended_at"], row["end_reason"]) == (None, None)
+ assert agent._end_session_on_close is False
+
+ @pytest.mark.parametrize("source,reason", [("desktop", "tui_close"), ("tui", "ws_orphan_reap")])
+ def test_explicit_close_and_non_desktop_reap_still_end_row(self, tmp_path, monkeypatch, source, reason):
+ db_path, session, _agent = _make_real_session(
+ tmp_path, monkeypatch, source=source, session_id=f"{source}-{reason}"
+ )
+
+ _teardown_session(session, end_reason=reason)
+
+ row = _read_real_row(db_path, f"{source}-{reason}")
+ assert row["ended_at"] is not None
+ assert row["end_reason"] == reason
diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.py
index ab74a5972b7..4721771222c 100644
--- a/tui_gateway/session_lifecycle.py
+++ b/tui_gateway/session_lifecycle.py
@@ -271,13 +271,15 @@ def _finalize_session(session: dict | None, end_reason: str = "tui_close") -> No
# compression splits back to the reaped child, forever).
if _is_gateway_owned_source((db.get_session(session_id) or {}).get("source", "")):
_tui_owns_lifecycle = False
- if agent is not None:
- agent._end_session_on_close = _tui_owns_lifecycle
elif _tui_owns_lifecycle and not _desktop_automatic_cleanup:
# Automatic Desktop cleanup (ws_orphan_reap, idle_timeout, etc.) reclaims
# runtime but must not end the durable row — the conversation stays open
# and resumable until the user explicitly closes or archives it. #105588
db.end_session(session_id, end_reason)
+ # ``_teardown_session`` follows with ``agent.close()``, whose ``_finalize_owned_session_row`` ends the row as
+ # ``agent_close`` through the agent's own handle — every spare decision above would be undone one call later.
+ if agent is not None and (_desktop_automatic_cleanup or not _tui_owns_lifecycle):
+ agent._end_session_on_close = False
# In-flight async delegations end WITH the session (no return address left). Always interrupt by THIS live UI
# sid; by durable session_key only when the TUI owns the lifecycle — a viewer tab must not kill gateway work.
with contextlib.suppress(Exception):