Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix OpenCode Go session headers in Studio (#15780)

AAFI MALEK07353799baf2
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 67912a2984c..4f2a7db67cf 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -15,6 +15,7 @@ import random
import re
import threading
import time
+import uuid
import weakref
import wave
from typing import Any, AsyncGenerator, Awaitable, Callable, Literal, NamedTuple, Optional, Union
@@ -1563,6 +1564,23 @@ class ExternalProviderClient:
headers.update(provider_info.get("extra_headers", {}))
return headers
+ def _chat_headers(self, thread_id: Optional[str]) -> dict[str, str]:
+ headers = self._auth_headers()
+ base = urlparse(self.base_url)
+ if (
+ base.scheme == "https"
+ and base.hostname == "opencode.ai"
+ and (base.path == "/inference/go" or base.path.startswith("/inference/go/"))
+ ):
+ # Hashed so the raw conversation ID never leaves Studio; titles and probes have no thread.
+ headers["x-opencode-session"] = (
+ hashlib.sha256(thread_id.encode("utf-8")).hexdigest()
+ if thread_id
+ else uuid.uuid4().hex
+ )
+ headers["User-Agent"] = "unsloth-studio"
+ return headers
+
def _is_openai_compatible(self) -> bool:
"""Return False for providers needing request/response translation (e.g. Anthropic)."""
from core.inference.providers import get_provider_info
@@ -1692,6 +1710,7 @@ class ExternalProviderClient:
response_format,
stream = stream if self.provider_type == "custom" else True,
compaction_fallback = compaction_fallback,
+ thread_id = thread_id,
):
yield line
return
@@ -1883,7 +1902,7 @@ class ExternalProviderClient:
_loopback_http_client if getattr(self, "_managed_loopback", False) else _client(),
url,
body,
- headers = self._auth_headers(),
+ headers = self._chat_headers(thread_id),
timeout = self._stream_timeout,
) as response:
if response.status_code != 200:
@@ -5431,6 +5450,7 @@ class ExternalProviderClient:
response_format: Optional[dict[str, Any]] = None,
stream: bool = True,
compaction_fallback: Optional[CompactionFallback] = None,
+ thread_id: Optional[str] = None,
) -> AsyncGenerator[str, None]:
"""Responses takes input and instructions, not messages; presence_penalty and top_k are dropped."""
import json as _json
@@ -5967,7 +5987,7 @@ class ExternalProviderClient:
"POST",
url,
json = attempt_body,
- headers = self._auth_headers(),
+ headers = self._chat_headers(thread_id),
timeout = self._stream_timeout,
) as response:
if response.status_code != 200:
@@ -6018,6 +6038,7 @@ class ExternalProviderClient:
tool_choice = tool_choice,
response_format = response_format,
stream = stream,
+ thread_id = thread_id,
):
yield fallback_line
return
@@ -7075,17 +7096,18 @@ class ExternalProviderClient:
body["max_tokens"] = max_tokens
url = f"{self.base_url}/chat/completions"
+ headers = self._chat_headers(None)
response = await _client().post(
url,
json = body,
- headers = self._auth_headers(),
+ headers = headers,
timeout = self._timeout,
)
if "max_tokens" in body and _rejects_max_tokens(response.status_code, response.text):
response = await _client().post(
url,
json = _with_max_completion_tokens(body),
- headers = self._auth_headers(),
+ headers = headers,
timeout = self._timeout,
)
response.raise_for_status()
diff --git a/studio/backend/tests/test_opencode_go_session.py b/studio/backend/tests/test_opencode_go_session.py
new file mode 100644
index 00000000000..8fc9bd73c74
--- /dev/null
+++ b/studio/backend/tests/test_opencode_go_session.py
@@ -0,0 +1,131 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import asyncio
+import json
+
+import httpx
+import pytest
+
+from core.inference import external_provider as ep
+
+
[email protected]("stream", [True, False])
+def test_opencode_go_chat_sends_conversation_session(monkeypatch, stream):
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ if stream:
+ return httpx.Response(
+ 200, headers = {"content-type": "text/event-stream"}, content = "data: [DONE]\n\n"
+ )
+ return httpx.Response(
+ 200, json = {"choices": [{"message": {"role": "assistant", "content": "ok"}}]}
+ )
+
+ async def run():
+ async with httpx.AsyncClient(transport = httpx.MockTransport(handler)) as http:
+ monkeypatch.setattr(ep, "_client", lambda: http)
+ client = ep.ExternalProviderClient(
+ "custom", "https://opencode.ai/inference/go/v1", "key"
+ )
+ for thread_id in ("conversation-1", "conversation-1", "conversation-2"):
+ async for _ in client.stream_chat_completion(
+ messages = [{"role": "user", "content": "hi"}],
+ model = "test-model",
+ stream = stream,
+ thread_id = thread_id,
+ ):
+ pass
+
+ asyncio.run(run())
+ sessions = [request.headers.get("x-opencode-session") for request in requests]
+ assert len(sessions) == 3
+ assert sessions[0] and sessions[0] == sessions[1]
+ assert sessions[2] and sessions[2] != sessions[0]
+
+
[email protected]("base_url", ["https://example.org/v1", "https://opencode.ai/inference/v1"])
+def test_other_providers_do_not_receive_opencode_session(monkeypatch, base_url):
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ return httpx.Response(
+ 200, headers = {"content-type": "text/event-stream"}, content = "data: [DONE]\n\n"
+ )
+
+ async def run():
+ async with httpx.AsyncClient(transport = httpx.MockTransport(handler)) as http:
+ monkeypatch.setattr(ep, "_client", lambda: http)
+ client = ep.ExternalProviderClient("custom", base_url, "key")
+ async for _ in client.stream_chat_completion(
+ messages = [{"role": "user", "content": "hi"}],
+ model = "test-model",
+ thread_id = "conversation-1",
+ ):
+ pass
+
+ asyncio.run(run())
+ assert len(requests) == 1
+ assert "x-opencode-session" not in requests[0].headers
+
+
+def test_opencode_go_responses_sends_conversation_session(monkeypatch):
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ return httpx.Response(200, json = {"id": "resp_test", "status": "completed", "output": []})
+
+ async def run():
+ async with httpx.AsyncClient(transport = httpx.MockTransport(handler)) as http:
+ monkeypatch.setattr(ep, "_client", lambda: http)
+ client = ep.ExternalProviderClient(
+ "custom", "https://opencode.ai/inference/go/openai/v1", "key", api_type = "responses"
+ )
+ async for _ in client.stream_chat_completion(
+ messages = [{"role": "user", "content": "hi"}],
+ model = "test-model",
+ stream = False,
+ thread_id = "conversation-1",
+ ):
+ pass
+
+ asyncio.run(run())
+ assert len(requests) == 1
+ assert requests[0].headers.get("x-opencode-session")
+
+
+def test_opencode_go_request_without_thread_still_sends_session(monkeypatch):
+ requests = []
+
+ def handler(request):
+ requests.append(request)
+ if json.loads(request.content).get("stream"):
+ return httpx.Response(
+ 200, headers = {"content-type": "text/event-stream"}, content = "data: [DONE]\n\n"
+ )
+ return httpx.Response(
+ 200, json = {"choices": [{"message": {"role": "assistant", "content": "ok"}}]}
+ )
+
+ async def run():
+ async with httpx.AsyncClient(transport = httpx.MockTransport(handler)) as http:
+ monkeypatch.setattr(ep, "_client", lambda: http)
+ client = ep.ExternalProviderClient(
+ "custom", "https://opencode.ai/inference/go/v1", "key"
+ )
+ async for _ in client.stream_chat_completion(
+ messages = [{"role": "user", "content": "title this"}],
+ model = "test-model",
+ ):
+ pass
+ await client.chat_completion(
+ messages = [{"role": "user", "content": "ping"}], model = "test-model"
+ )
+
+ asyncio.run(run())
+ assert len(requests) == 2
+ assert all(request.headers.get("x-opencode-session") for request in requests)