The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): let POST /api/sessions titles yield to ended empty ghosts
kshitijk4poora557e6ede868
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 0031de039f5..bbb97ea0725 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -3194,11 +3194,11 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):if title is not None:clean_title = db.sanitize_title(str(title))if clean_title:- conflict = conn.execute(- "SELECT id FROM sessions WHERE title = ? AND id != ?", (clean_title, session_id)).fetchone()- if conflict:+ try:+ db._resolve_title_conflict(conn, session_id, clean_title)+ except ValueError as exc: # the DB's uniqueness rule; undo the INSERTconn.execute("DELETE FROM sessions WHERE id = ?", (session_id,))- return None, f"title:Title already in use by session {conflict['id']}"+ return None, f"title:{exc}"conn.execute("UPDATE sessions SET title = ? WHERE id = ?", (clean_title, session_id))session_row = conn.execute("SELECT * FROM sessions WHERE id = ?", (session_id,)).fetchone()return (dict(session_row) if session_row else {diff --git a/hermes_state_titles.py b/hermes_state_titles.pyindex 7ed002bd275..a8d176a59de 100644--- a/hermes_state_titles.py+++ b/hermes_state_titles.py@@ -111,32 +111,7 @@ class SessionTitlesMixin:if not is_user and current["title"] is not None and self._title_rank(current["title_source"]) >= new_rank:return 0if title:- conflict = conn.execute(- f"SELECT id, archived, hidden, {self._EMPTY_SESSION_WHERE} AS ghost "- "FROM sessions WHERE title = ? AND id != ?", (title, session_id),- ).fetchone()- if conflict:- conflict_id = conflict["id"]- # A hidden compressed ancestor holding the title cannot be freed by the- # user, so transfer it onto the tip (uniqueness + lineage kept).- if self._is_compression_ancestor(conn, ancestor_id=conflict_id, descendant_id=session_id):- conn.execute("UPDATE sessions SET title = NULL WHERE id = ?", (conflict_id,))- # A deliberately archived hidden Bot Chat is a retired registry- # entry, not a live identity. Retire its name in the same title- # transaction so a replacement can become the sole canonical row;- # the old session remains archived and otherwise untouched.- # An ended, empty, visible ghost (abandoned new chat that listings filter- # out, so the user cannot find it to free the name) yields too (#81888).- # The full index stays: a ``message_count > 0`` partial index would make- # the ghost's first append_message fail with IntegrityError.- elif (title == self.CANONICAL_BOT_CHAT_TITLE and bool(conflict["archived"])- and bool(conflict["hidden"])) or (conflict["ghost"] and not conflict["hidden"]):- conn.execute(- "UPDATE sessions SET title = NULL, title_source = NULL WHERE id = ?",- (conflict_id,),- )- else:- raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")+ self._resolve_title_conflict(conn, session_id, title)# CAS on the values just read (``IS`` is NULL-safe): a concurrent write between# the SELECT and here loses instead of being overwritten.return conn.execute(@@ -146,6 +121,38 @@ class SessionTitlesMixin:return self._execute_write(_do) > 0+ def _resolve_title_conflict(self, conn, session_id: str, title: str) -> None:+ """Free ``title`` for ``session_id`` inside the caller's write transaction, or raise+ ValueError when another session legitimately holds it. The one place the uniqueness+ rule lives, shared by renames and the API server's create-with-title."""+ conflict = conn.execute(+ f"SELECT id, archived, hidden, {self._EMPTY_SESSION_WHERE} AS ghost "+ "FROM sessions WHERE title = ? AND id != ?", (title, session_id),+ ).fetchone()+ if not conflict:+ return+ conflict_id = conflict["id"]+ # A hidden compressed ancestor holding the title cannot be freed by the+ # user, so transfer it onto the tip (uniqueness + lineage kept).+ if self._is_compression_ancestor(conn, ancestor_id=conflict_id, descendant_id=session_id):+ conn.execute("UPDATE sessions SET title = NULL WHERE id = ?", (conflict_id,))+ # A deliberately archived hidden Bot Chat is a retired registry+ # entry, not a live identity. Retire its name in the same title+ # transaction so a replacement can become the sole canonical row;+ # the old session remains archived and otherwise untouched.+ # An ended, empty, visible ghost (abandoned new chat that listings filter+ # out, so the user cannot find it to free the name) yields too (#81888).+ # The full index stays: a ``message_count > 0`` partial index would make+ # the ghost's first append_message fail with IntegrityError.+ elif (title == self.CANONICAL_BOT_CHAT_TITLE and bool(conflict["archived"])+ and bool(conflict["hidden"])) or (conflict["ghost"] and not conflict["hidden"]):+ conn.execute(+ "UPDATE sessions SET title = NULL, title_source = NULL WHERE id = ?",+ (conflict_id,),+ )+ else:+ raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")+def set_session_title(self, session_id: str, title: str) -> bool:"""Set a title on the user's behalf (``user`` provenance). Empty clears it. RaisesValueError on conflict or validation failure."""diff --git a/tests/gateway/test_session_api.py b/tests/gateway/test_session_api.pyindex 675ec6a8891..74de5b125c4 100644--- a/tests/gateway/test_session_api.py+++ b/tests/gateway/test_session_api.py@@ -728,8 +728,19 @@ def _patch_api_server_runtime(monkeypatch):@pytest.mark.asyncioasync def test_create_session_respects_browser_source_and_model_lock(adapter, session_db):+ # The requested title is held by an ended empty visible ghost, which must yield (#81888);+ # a live holder must still reject the create without leaving a half-made row.+ session_db.create_session("ghost", "desktop")+ session_db.set_session_title("ghost", "Browser lock")+ session_db.end_session("ghost", "user_exit")+ session_db.create_session("live", "desktop")+ session_db.set_session_title("live", "Taken")app = _create_session_app(adapter)async with TestClient(TestServer(app)) as cli:+ taken = await cli.post("/api/sessions", json={"id": "dup", "title": "Taken"})+ assert taken.status == 400+ assert (await taken.json())["error"]["code"] == "invalid_title"+ assert session_db.get_session("dup") is Noneresp = await cli.post("/api/sessions",json={@@ -757,6 +768,8 @@ async def test_create_session_respects_browser_source_and_model_lock(adapter, seassert model_config["browser_model_lock"]["provider"] == "nous"assert model_config["browser_model_lock"]["model"] == "x-ai/grok-4.5"assert model_config["browser_model_lock"]["confirmed"] is True+ assert row["title"] == "Browser lock"+ assert session_db.get_session("ghost")["title"] is None@pytest.mark.asyncio