Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

feat(agents): send a stable session header and app user-agent with OpenAI requests (#1249)

Tássio Noronhaf4ab1f10abb8
diff --git a/backend/app/agents/api/conversations.py b/backend/app/agents/api/conversations.py
index 8d50578d..06ae0f7b 100644
--- a/backend/app/agents/api/conversations.py
+++ b/backend/app/agents/api/conversations.py
@@ -118,6 +118,9 @@ async def generate_title(
provider, model = await _provider_and_model_for(session, agent)
if not model:
return conv
+ # Same per-conversation session id the chat run sends, so backends
+ # that require it accept the title request too.
+ provider.session_id = str(conversation_id)
prompt_messages = [
ChatMessage(role="system", content=_TITLE_PROMPT),
ChatMessage(role="user", content="\n".join(transcript)),
diff --git a/backend/app/agents/providers/base.py b/backend/app/agents/providers/base.py
index ef23f581..c695465e 100644
--- a/backend/app/agents/providers/base.py
+++ b/backend/app/agents/providers/base.py
@@ -113,6 +113,9 @@ class LLMProvider(ABC):
self.api_key = api_key
self.base_url: str = base_url or ""
self.default_model = model
+ # Stable per-conversation id, set by the executor before each run.
+ # Providers whose backends route on it send it as a request header.
+ self.session_id: Optional[str] = None
@abstractmethod
def chat_stream(
diff --git a/backend/app/agents/providers/openai.py b/backend/app/agents/providers/openai.py
index 3551e980..3f7752b3 100644
--- a/backend/app/agents/providers/openai.py
+++ b/backend/app/agents/providers/openai.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import json
import re
+from importlib.metadata import PackageNotFoundError, version as _pkg_version
from typing import AsyncIterator, Optional
from urllib.parse import urlparse
@@ -95,6 +96,22 @@ def _raise_for_status(status: int, body: str) -> None:
raise LLMUnavailableError(f"OpenAI {status}: {body}", status=status)
+def _app_user_agent() -> str:
+ """Client identity for model backends.
+
+ Backends see the HTTP library name by default (e.g. `python-httpx/0.x`);
+ a few of them ask for the real client instead. Identifying as
+ `securo/<version>` keeps the logs on their side meaningful.
+ """
+ try:
+ return f"securo/{_pkg_version('securo-backend')}"
+ except PackageNotFoundError:
+ return "securo"
+
+
+_APP_USER_AGENT = _app_user_agent()
+
+
class OpenAIProvider(LLMProvider):
name = "openai"
@@ -110,6 +127,11 @@ class OpenAIProvider(LLMProvider):
h = {"Content-Type": "application/json"}
if self.api_key:
h["Authorization"] = f"Bearer {self.api_key}"
+ # Identify the client to model backends; a few OpenAI-compatible
+ # endpoints also route on a per-conversation session id.
+ h["User-Agent"] = _APP_USER_AGENT
+ if self.session_id:
+ h["x-opencode-session"] = self.session_id
return h
async def chat_stream(
diff --git a/backend/app/agents/runtime/executor.py b/backend/app/agents/runtime/executor.py
index 0d923357..5ac4fd40 100644
--- a/backend/app/agents/runtime/executor.py
+++ b/backend/app/agents/runtime/executor.py
@@ -431,6 +431,9 @@ class AgentExecutor:
logger.exception("provider resolution failed; falling back to legacy path")
provider = _provider_for(agent)
model = _model_for(agent)
+ # Some OpenAI-compatible backends route on a per-conversation
+ # session id; providers that support it read this as a header.
+ provider.session_id = str(conversation_id)
if not model:
yield ExecutorEvent(
type="error",
diff --git a/backend/tests/test_agents_api.py b/backend/tests/test_agents_api.py
index db788d16..bdd96721 100644
--- a/backend/tests/test_agents_api.py
+++ b/backend/tests/test_agents_api.py
@@ -383,9 +383,10 @@ async def test_generate_title_uses_llm(
])
await session.commit()
+ provider = _Scripted()
with patch(
"app.agents.runtime.executor._provider_and_model_for",
- return_value=(_Scripted(), "gpt-4o-mini"),
+ return_value=(provider, "gpt-4o-mini"),
):
r = await client.post(
f"/api/agents/conversations/{conv.id}/generate-title",
@@ -393,6 +394,8 @@ async def test_generate_title_uses_llm(
)
assert r.status_code == 200, r.text
assert r.json()["title"] == "Brazilian Cuisine Picks"
+ # The title request carries the same session id as the chat run.
+ assert provider.session_id == str(conv.id)
async def test_generate_title_strips_reasoning_tags(
diff --git a/backend/tests/test_agents_executor.py b/backend/tests/test_agents_executor.py
index 80daaed4..8969b749 100644
--- a/backend/tests/test_agents_executor.py
+++ b/backend/tests/test_agents_executor.py
@@ -602,3 +602,24 @@ async def test_history_window_never_opens_on_an_orphaned_tool_result(
("user", "q2"), ("assistant", "a2"),
("user", "new question"),
]
+
+
+async def test_provider_receives_stable_conversation_session_id(
+ session, test_user, test_agent: Agent, test_conversation: Conversation
+):
+ """The executor hands the provider the conversation id, so backends
+ that route on a per-conversation session id can send it as a header."""
+ provider = _ScriptedProvider([[
+ ChatChunk(type="text_delta", text="ok"),
+ ChatChunk(type="finish", finish_reason="stop"),
+ ]])
+ with _patch_provider(provider):
+ await _drain(
+ AgentExecutor(mcp=_FakeMCP(tools=[])),
+ session=session,
+ agent=test_agent,
+ user_id=test_user.id,
+ conversation_id=test_conversation.id,
+ user_message="hi",
+ )
+ assert provider.session_id == str(test_conversation.id)
diff --git a/backend/tests/test_agents_providers.py b/backend/tests/test_agents_providers.py
index 7334b564..ff4b0365 100644
--- a/backend/tests/test_agents_providers.py
+++ b/backend/tests/test_agents_providers.py
@@ -26,6 +26,7 @@ from app.agents.providers.base import (
Usage,
)
from app.agents.providers.openai import (
+ OpenAIProvider,
_serialize_messages as openai_serialize,
_serialize_tools as openai_tools,
normalize_openai_base_url,
@@ -234,3 +235,39 @@ async def test_chat_helper_aggregates_text_and_tool_calls():
assert len(res.tool_calls) == 1
assert res.tool_calls[0].name == "list_accounts"
assert res.tool_calls[0].arguments == {"x": 1}
+
+
+# --- Outbound request headers ----------------------------------------------
+#
+# A few OpenAI-compatible backends identify the client by user agent and
+# route on a per-conversation session id. These tests pin the wire headers
+# so the client keeps sending both.
+
+
+def test_openai_headers_identify_securo_and_omit_session_by_default():
+ provider = OpenAIProvider(api_key="k")
+ h = provider._headers()
+ assert h["Content-Type"] == "application/json"
+ assert h["Authorization"] == "Bearer k"
+ # The client identifies as securo; the version suffix is present when
+ # the distribution metadata is available and the bare name otherwise.
+ ua = h["User-Agent"]
+ assert ua == "securo" or ua.startswith("securo/")
+ assert "x-opencode-session" not in h
+
+
+def test_openai_headers_carry_conversation_session_when_set():
+ provider = OpenAIProvider(api_key="k")
+ provider.session_id = "conv-42"
+ h = provider._headers()
+ assert h["x-opencode-session"] == "conv-42"
+
+
+def test_openai_user_agent_falls_back_without_distribution(monkeypatch):
+ import app.agents.providers.openai as mod
+
+ def _missing(*args, **kwargs):
+ raise mod.PackageNotFoundError("securo-backend")
+
+ monkeypatch.setattr(mod, "_pkg_version", _missing)
+ assert mod._app_user_agent() == "securo"