"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(session): preserve live updates while generating conversation titles
Rudy Celeklia8a5575bc74d
diff --git a/agent/src/api/sessions_routes.py b/agent/src/api/sessions_routes.pyindex 06a7d0ab3..7b1a521d2 100644--- a/agent/src/api/sessions_routes.py+++ b/agent/src/api/sessions_routes.py@@ -744,6 +744,15 @@ def register_sessions_routes(app: FastAPI) -> None:if not title:raise HTTPException(status_code=502, detail="empty title from model")+ # Generation yields to other requests. Reload their persisted metadata+ # and recheck a manual rename before this synchronous commit section.+ session = svc.store.get_session(session_id)+ if not session:+ raise HTTPException(status_code=404, detail=f"Session {session_id} not found")+ current = (session.title or "").strip()+ if current and current != auto_prefix:+ return {"status": "kept", "session_id": session_id, "title": current}+session.title = titlesession.updated_at = datetime.now(timezone.utc).isoformat()svc.update_session(session)diff --git a/agent/tests/test_session_search_title_updates.py b/agent/tests/test_session_search_title_updates.pyindex fcdcf68dd..372585157 100644--- a/agent/tests/test_session_search_title_updates.py+++ b/agent/tests/test_session_search_title_updates.py@@ -3,6 +3,7 @@import asyncioimport jsonimport sys+import threadingfrom types import SimpleNamespaceimport pytest@@ -15,8 +16,8 @@ from src.session.store import SessionStorefrom src.tools.session_search_tool import SessionSearchTool[email protected]("automatic", [False, True])-def test_registered_title_route_updates_actual_search(tmp_path, monkeypatch, automatic):+def owned_title_routes(tmp_path, monkeypatch):index = SessionSearchIndex(tmp_path / "search.db")monkeypatch.setattr("src.session.service.get_shared_index", lambda: index)monkeypatch.setattr("src.session.search.get_shared_index", lambda: index)@@ -48,6 +49,17 @@ def test_registered_title_route_updates_actual_search(tmp_path, monkeypatch, autmonkeypatch.setitem(sys.modules, "api_server", host)app = FastAPI()register_sessions_routes(app)+ try:+ yield service, index, app, session, sibling, before+ finally:+ index.close()++[email protected]("automatic", [False, True])+def test_registered_title_route_updates_actual_search(+ owned_title_routes, monkeypatch, automatic+):+ service, index, app, session, sibling, before = owned_title_routestitle = "Renamed synthetic analysis"if automatic:from src.providers import chat@@ -73,25 +85,101 @@ def test_registered_title_route_updates_actual_search(tmp_path, monkeypatch, autresult = asyncio.run(route.endpoint(session.session_id, UpdateSessionRequest(title=title)))- try:- assert result["status"] == "updated"- assert service.store.get_session(session.session_id).title == title- reply = json.loads(SessionSearchTool().execute(query="volatility"))- assert reply["status"] == "ok"- match = reply["results"][0]- assert match["title"] == title- assert match["session_id"] == session.session_id- assert match["message_count"] == before.message_count == 1+ assert result["status"] == "updated"+ assert service.store.get_session(session.session_id).title == title+ reply = json.loads(SessionSearchTool().execute(query="volatility"))+ assert reply["status"] == "ok"+ match = reply["results"][0]+ assert match["title"] == title+ assert match["session_id"] == session.session_id+ assert match["message_count"] == before.message_count == 1+ assert match["started_at"] == before.started_at+ assert (+ service.store.get_session(sibling.session_id).title == "Unrelated conversation"+ )+ assert (+ index._get_conn()+ .execute("SELECT title FROM sessions WHERE id = ?", (sibling.session_id,))+ .fetchone()[0]+ == "Unrelated conversation"+ )++[email protected]("manual_rename", [False, True])+def test_auto_title_wait_preserves_live_session_updates(+ owned_title_routes, monkeypatch, manual_rename+):+ service, index, app, session, sibling, before = owned_title_routes+ from src.providers import chat++ provider_started, provider_release = threading.Event(), threading.Event()+ provider_closed = threading.Event()++ class OwnedTitleProvider:+ def chat(self, messages, timeout):+ provider_started.set()+ assert provider_release.wait(3)+ return SimpleNamespace(content="Generated synthetic title")++ def close(self):+ provider_closed.set()++ monkeypatch.setattr(chat, "ChatLLM", OwnedTitleProvider)+ auto = next(+ r.endpoint for r in app.routes if r.path == "/sessions/{session_id}/title/auto"+ )+ patch = next(+ r.endpoint+ for r in app.routes+ if r.path == "/sessions/{session_id}" and "PATCH" in r.methods+ )++ async def hold_agent_execution(*args, **kwargs):+ # Real send_message admission persists its attempt/config/message.+ # Only external agent execution is held so no model/tool is invoked.+ await asyncio.Event().wait()++ monkeypatch.setattr(service, "_run_attempt", hold_agent_execution)++ async def scenario():+ generation = asyncio.create_task(auto(session.session_id))+ try:+ assert await asyncio.to_thread(provider_started.wait, 2)+ admission = await service.send_message(+ session.session_id,+ "volatility accepted while naming",+ include_shell_tools=True,+ )+ if manual_rename:+ await patch(+ session.session_id,+ UpdateSessionRequest(title="Manual protected title"),+ )+ finally:+ provider_release.set()+ result = await generation+ current = service.store.get_session(session.session_id)+ expected = (+ "Manual protected title" if manual_rename else "Generated synthetic title"+ )+ assert current.last_attempt_id == admission["attempt_id"]+ assert current.config["include_shell_tools"] is True+ assert current.title == expected+ assert result["status"] == ("kept" if manual_rename else "updated")+ assert provider_closed.is_set()+ assert len(service.get_messages(session.session_id)) == 2+ match = json.loads(SessionSearchTool().execute(query="volatility"))["results"][+ 0+ ]+ assert match["title"] == expected+ assert match["message_count"] == 2assert match["started_at"] == before.started_atassert (service.store.get_session(sibling.session_id).title== "Unrelated conversation")- assert (- index._get_conn()- .execute("SELECT title FROM sessions WHERE id = ?", (sibling.session_id,))- .fetchone()[0]- == "Unrelated conversation"- )- finally:- index.close()+ for task in service._active_tasks.values():+ task.cancel()+ await asyncio.gather(*service._active_tasks.values(), return_exceptions=True)++ asyncio.run(scenario())