Skip to content

The agent that grows with you

fix(tui_gateway): mounting a finalized session no longer reopens its row — the first real turn does (#85303)

Brooklyn Nicholsonf963a86b4a2e
diff --git a/gateway/session.py b/gateway/session.py
index 17067df2298..6e6c6dd2926 100644
--- a/gateway/session.py
+++ b/gateway/session.py
@@ -1272,6 +1272,9 @@ class SessionStore(
log=lambda e: logger.debug("Session DB end_session failed: %s", e),
)
if self._db_for_key(session_key):
+ # An explicit /resume/handoff/branch repoint is real user activity: the row is
+ # reopened (a repoint onto a finalized row must resume it, not write into a dead row).
+ # Mount-time reads (TUI session.resume) no longer reopen (#85303) — only this path does.
self._reopen_session_row(
session_key, target_session_id, log_prefix="Session DB reopen_session failed"
)
diff --git a/tests/tui_gateway/test_resume_readonly_mount.py b/tests/tui_gateway/test_resume_readonly_mount.py
new file mode 100644
index 00000000000..939400dc906
--- /dev/null
+++ b/tests/tui_gateway/test_resume_readonly_mount.py
@@ -0,0 +1,112 @@
+"""Mounting a finalized session is read-only (#85303): session.resume / its deferred
+hydration / the lazy watch path must NOT clear ``ended_at``/``end_reason`` — only the
+first real turn (prompt.submit) reopens the row, so DB-derived liveness cannot re-light
+a finished session just because someone opened it."""
+
+import threading
+
+import pytest
+
+from hermes_state import SessionDB
+from tui_gateway import server
+
+
+def _finalized_db(tmp_path, *, ended_reason="agent_close"):
+ home = tmp_path / "home"
+ home.mkdir(exist_ok=True)
+ db = SessionDB(home / "state.db")
+ db.create_session("finalized", source="desktop")
+ db.append_message("finalized", "user", "old ask", timestamp=100.0)
+ db.append_message("finalized", "assistant", "old answer", timestamp=101.0)
+ db.end_session("finalized", ended_reason)
+ return db, home
+
+
+def _mount(monkeypatch, db, home, tmp_path, *, defer_history=False):
+ events = []
+ built = threading.Event()
+ monkeypatch.setattr("hermes_state_registry.acquire", lambda db_path=None, **kwargs: db)
+ monkeypatch.setattr(server, "_profile_home", lambda p: home if p else None)
+ monkeypatch.setattr(server, "_profile_configured_cwd", lambda _: str(tmp_path))
+ monkeypatch.setattr(server, "_default_session_cwd", lambda: str(tmp_path))
+ monkeypatch.setattr(server, "_get_db", lambda: db)
+ monkeypatch.setattr(server, "_enable_gateway_prompts", lambda: None)
+ monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)
+ monkeypatch.setattr(server, "_maybe_schedule_auto_continue", lambda *args: None)
+ monkeypatch.setattr(server, "_start_agent_build", lambda *args: built.set())
+ monkeypatch.setattr(server, "_emit", lambda kind, sid, payload: events.append((kind, payload)))
+ return events, built
+
+
[email protected]("defer_history", [False, True])
+def test_resume_mount_keeps_finalized_row_ended(tmp_path, monkeypatch, defer_history):
+ db, home = _finalized_db(tmp_path)
+ events, built = _mount(monkeypatch, db, home, tmp_path)
+ sid = None
+ try:
+ response = server.handle_request({"id": "resume", "method": "session.resume", "params": {
+ "session_id": "finalized", "source": "desktop", "defer_history": defer_history,
+ }})
+ assert response is not None and "error" not in response, response
+ sid = response["result"]["session_id"]
+ if defer_history:
+ session = server._sessions[sid]
+ assert session["resume_history_ready"].wait(5)
+ else:
+ assert built.wait(5)
+ row = db.get_session("finalized")
+ assert row["ended_at"] is not None, "mounting a finalized session must not reopen its row (#85303)"
+ assert row["end_reason"] == "agent_close"
+ finally:
+ if sid is not None:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
+def test_lazy_watch_mount_keeps_finalized_row_ended(tmp_path, monkeypatch):
+ db, home = _finalized_db(tmp_path)
+ events, built = _mount(monkeypatch, db, home, tmp_path)
+ sid = None
+ try:
+ response = server.handle_request({"id": "resume", "method": "session.resume", "params": {
+ "session_id": "finalized", "source": "desktop", "lazy": True,
+ }})
+ assert response is not None and "error" not in response, response
+ row = db.get_session("finalized")
+ assert row["ended_at"] is not None, "the lazy watch mount must not reopen a finalized row"
+ finally:
+ if sid is not None:
+ server._sessions.pop(sid, None)
+ db.close()
+
+
+def test_first_real_turn_reopens_a_finalized_row(tmp_path, monkeypatch):
+ """The activity gate: prompt.submit (a real send) is what clears ended_at, not the mount."""
+ from tui_gateway import methods_prompt
+
+ db, home = _finalized_db(tmp_path)
+ events, built = _mount(monkeypatch, db, home, tmp_path)
+ reopened = []
+ monkeypatch.setattr(db, "reopen_session", lambda sid: reopened.append(sid) or
+ SessionDB.reopen_session(db, sid))
+ reopened_row = db.get_session("finalized")
+ assert reopened_row["ended_at"] is not None
+ # The submit path's reopen helper: the row is finalized, so a real send reopens it.
+ methods_prompt._reopen_if_finalized(db, "finalized")
+ assert reopened == ["finalized"]
+ row = db.get_session("finalized")
+ assert row["ended_at"] is None, "the first real turn must reopen the finalized row"
+ db.close()
+
+
+def test_reopen_if_finalized_leaves_live_rows_untouched(tmp_path):
+ db, home = _finalized_db(tmp_path)
+ from tui_gateway import methods_prompt
+
+ db.create_session("live", source="desktop")
+ db.append_message("live", "user", "ask", timestamp=100.0)
+ methods_prompt._reopen_if_finalized(db, "live")
+ methods_prompt._reopen_if_finalized(db, "missing-entirely")
+ row = db.get_session("live")
+ assert row["ended_at"] is None and row["end_reason"] is None
+ db.close()
diff --git a/tests/tui_gateway/test_session_resume_db_ownership.py b/tests/tui_gateway/test_session_resume_db_ownership.py
index d0778933f03..6472b157f61 100644
--- a/tests/tui_gateway/test_session_resume_db_ownership.py
+++ b/tests/tui_gateway/test_session_resume_db_ownership.py
@@ -47,6 +47,7 @@ class _RecordingDB:
self.closed = 0
self.rows: dict = {}
self.reopen_error: Exception | None = None
+ self.read_error: Exception | None = None
def close(self):
self.closed += 1
@@ -65,9 +66,13 @@ class _RecordingDB:
raise self.reopen_error
def get_resume_conversations(self, _target):
+ if self.read_error is not None:
+ raise self.read_error
return ([], [])
def get_ancestor_display_prefix(self, _target):
+ if self.read_error is not None:
+ raise self.read_error
return []
def get_messages_as_conversation(self, _target, **_kwargs):
@@ -157,12 +162,17 @@ def test_deferred_desktop_resume_keeps_stored_workspace_provenance(
def test_resume_closes_profile_db_when_reopen_fails(profile_dbs, monkeypatch):
- """The 'resume failed' early return must not leak the handle."""
+ """The 'resume failed' early return must not leak the handle.
+
+ #85303 made the mount read-only (resume no longer calls ``reopen_session``),
+ so the failure this guards against moved to the history read: a read that
+ raises must still surface as a resume error AND close the profile handle.
+ """
def _factory(db_path=None, **kwargs):
db = _RecordingDB(db_path=db_path, **kwargs)
db.rows["s1"] = {"id": "s1", "cwd": ""}
- db.reopen_error = RuntimeError("database is locked")
+ db.read_error = RuntimeError("database is locked")
profile_dbs.append(db)
return db
@@ -171,8 +181,6 @@ def test_resume_closes_profile_db_when_reopen_fails(profile_dbs, monkeypatch):
resp = _resume(session_id="s1", profile="work")
assert resp["error"]["code"] == 5000
- # Plain "could not reopen" lead; the raw cause survives on the Details line.
- assert "Could not reopen" in resp["error"]["message"]
assert "database is locked" in resp["error"]["message"]
assert profile_dbs[0].closed == 1
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index 743ae91cbfe..4f5dd16a8af 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -536,6 +536,25 @@ def _storage_error_data(failure, raw) -> dict:
return {"code": failure.code, "cause": failure.cause, "details": storage_failure_details(raw)}
+def _reopen_if_finalized(db, session_id: str) -> None:
+ """The first real turn is what reopens a finalized session (#85303).
+
+ Mounting a chat (``session.resume``/hydration) is a READ and no longer clears
+ ``ended_at``/``end_reason`` — opening a finished session must not re-light DB-derived
+ liveness with no new activity. This runs on the submit path (the user actually sent
+ something) before the turn's first transcript write, so the row the turn writes is
+ live again. Best-effort: a failed read must not block the send."""
+ if not session_id:
+ return
+ try:
+ row = db.get_session(session_id)
+ except Exception:
+ logger.debug("finalized-session reopen check failed for %s", session_id, exc_info=True)
+ return
+ if row is not None and row.get("ended_at") is not None:
+ db.reopen_session(session_id)
+
+
def _persist_session_row_for_submit(rid, session, text=None, display_kind=None):
"""Lazily persist the DB row now that the user sent a message (a branch becomes real
here), then the message itself (#111868: a freeze during the first build must leave a
@@ -551,6 +570,11 @@ def _persist_session_row_for_submit(rid, session, text=None, display_kind=None):
data=_storage_error_data(failure, _db_error))
else:
_persist_branch_seed(session)
+ # The first real turn reopens a finalized row (#85303): resume is read-only, so
+ # an ended_at set at mount time is cleared HERE, before the turn's first write.
+ with _session_db(session) as db:
+ if db is not None:
+ _reopen_if_finalized(db, str(session.get("session_key") or ""))
_persist_submit_user_row(session, text, display_kind)
return None
except Exception as exc:
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index cafdd5966e7..b5371c7b11b 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -692,8 +692,11 @@ class _Resume:
def read_history(self) -> tuple:
"""One lineage SELECT, two projections: model-fed copy alternation-repaired (healed once
- here instead of every turn's pre-request repair), display copy verbatim."""
- self.db.reopen_session(self.target)
+ here instead of every turn's pre-request repair), display copy verbatim.
+
+ Read-only mount: an ended row stays ended — resume must not clear ``ended_at``/``end_reason``
+ with no new activity, or the DB-derived liveness paints a finalized session live the moment
+ it is opened (#85303). The first real turn (``prompt.submit``) reopens it."""
if self.omit_messages:
return self.child_history(repair=True), []
return self.db.get_resume_conversations(self.target)
@@ -908,7 +911,7 @@ def _resume_lazy(ctx: _Resume) -> dict:
inside the parent's turn, so the window needs stored history + a transport; prompt.submit upgrades it."""
sid, source, cwd = ctx.mint(prompts=False)
try:
- ctx.db.reopen_session(ctx.target)
+ # Read-only mount (#85303): an ended row stays ended; the first real turn reopens it.
# repair_alternation heals a durable ``user;user`` once here.
history = ctx.child_history(repair=True)
except Exception as e:
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 9dad9cc00bc..22fce15c3ba 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -2975,7 +2975,8 @@ def _schedule_resume_hydration(sid: str, stored_id: str, db, *, close_db: bool =
if session is None:
return
_emit("session.resume_progress", sid, {"phase": "history", "status": "loading"})
- db.reopen_session(stored_id)
+ # Read-only mount (#85303): hydration is a read; an ended row stays ended —
+ # the first real turn (prompt.submit) reopens it.
raw_history, display_history, prefix = _load_resume_transcript(
db, stored_id, model_history_only=model_history_only)
# Display keeps the full transcript; the model-fed history uses the