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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Unsloth Studio: add ChatGPT subscription chat with Codex tools (#8511)
Wasim Yousef Saidef8daca43e9a
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex 019e157b901..5bd2007f1e5 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -19,6 +19,14 @@ from urllib.parse import urlparseimport httpximport structlog++from core.inference.openai_responses_shared import (+ normalize_function_schema,+ responses_function_call,+ responses_function_output,+ response_event_type,+)+# Local servers, not hosted APIs: each applies the model's own chat template on the way# in, so a prompt built here is templated just like an in-process one (#7066). "custom" is# a user-supplied OpenAI-compatible base_url (routes/providers.py:207-213), i.e. how a@@ -4717,13 +4725,7 @@ class ExternalProviderClient:else:_output_text = content if isinstance(content, str) else ""if _call_id:- input_items.append(- {- "type": "function_call_output",- "call_id": _call_id,- "output": _output_text,- }- )+ input_items.append(responses_function_output(_call_id, _output_text))continue# Translate assistant tool_calls into `function_call` items, skipping@@ -4785,12 +4787,7 @@ class ExternalProviderClient:skipped_server_builtin_call_ids.add(_call_id_out)continueinput_items.append(- {- "type": "function_call",- "call_id": _call_id_out,- "name": _fn["name"],- "arguments": _args_raw,- }+ responses_function_call(_call_id_out, _fn["name"], _args_raw))# Assistant text already emitted above (in order) so we don't# fall through to the generic content branches.@@ -5014,7 +5011,7 @@ class ExternalProviderClient:if _fn.get("description"):_entry["description"] = _fn["description"]if isinstance(_fn.get("parameters"), dict):- _entry["parameters"] = _fn["parameters"]+ _entry["parameters"] = normalize_function_schema(_fn["parameters"])responses_user_function_tools.append(_entry)# Translate tool_choice into the Responses shape.@@ -5495,7 +5492,7 @@ class ExternalProviderClient:except _json.JSONDecodeError:continue- event_type = event.get("type")+ event_type = response_event_type(event)_record_openai_response_id(event)if event_type == "response.output_text.delta":diff --git a/studio/backend/core/inference/openai_codex_auth.py b/studio/backend/core/inference/openai_codex_auth.pynew file mode 100644index 00000000000..0a49da1f30c--- /dev/null+++ b/studio/backend/core/inference/openai_codex_auth.py@@ -0,0 +1,856 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""ChatGPT/Codex public-client OAuth owned by the Studio backend.++OAuth transient material never crosses the API boundary: callers receive only an+opaque flow id and safe user-facing authorization metadata.+"""++from __future__ import annotations++import asyncio+import base64+import hashlib+import json+import secrets+import time+from contextlib import asynccontextmanager+from dataclasses import dataclass, field+from typing import Any, Awaitable, Callable, Literal+from urllib.parse import parse_qs, urlencode, urlparse++import httpx++from filelock import FileLock, Timeout as FileLockTimeout++from storage import credential_secrets++from utils.paths import studio_db_path++OPENAI_CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"+OPENAI_CODEX_ISSUER = "https://auth.openai.com"+OPENAI_CODEX_AUTHORIZE_URL = f"{OPENAI_CODEX_ISSUER}/oauth/authorize"+OPENAI_CODEX_TOKEN_URL = f"{OPENAI_CODEX_ISSUER}/oauth/token"+OPENAI_CODEX_DEVICE_CODE_URL = f"{OPENAI_CODEX_ISSUER}/api/accounts/deviceauth/usercode"+OPENAI_CODEX_DEVICE_TOKEN_URL = f"{OPENAI_CODEX_ISSUER}/api/accounts/deviceauth/token"+OPENAI_CODEX_SCOPE = "openid profile email offline_access"+OPENAI_CODEX_LOOPBACK_PORTS = (1455,)+OPENAI_CODEX_CALLBACK_PATH = "/auth/callback"++OPENAI_CODEX_DEVICE_REDIRECT_URI = f"{OPENAI_CODEX_ISSUER}/deviceauth/callback"+OPENAI_CODEX_ORIGINATOR = "unsloth_studio"+OPENAI_CODEX_API_BASE = "https://chatgpt.com/backend-api"+OPENAI_CODEX_RESPONSES_URL = f"{OPENAI_CODEX_API_BASE}/codex/responses"+OPENAI_CODEX_USER_AGENT = "unsloth-studio/1"+OPENAI_CODEX_COMPATIBILITY_INSTRUCTIONS = (+ "You are operating inside Unsloth Studio. Follow the user's instructions, "+ "use only tools supplied in this request, and return concise, accurate results."+)++_FLOW_TTL_SECONDS = 15 * 60+_REFRESH_SKEW_SECONDS = 5 * 60++_FLOW_TERMINAL_RETENTION_SECONDS = 60+++class CodexAuthError(RuntimeError):+ """Sanitized authentication failure safe to return to the UI."""+++class CodexReauthorizationRequired(CodexAuthError):+ """The saved refresh credential was permanently rejected."""+++@dataclass+class OAuthFlow:+ id: str+ provider_id: str+ method: Literal["browser", "device"]+ created_at: float+ expires_at: float+ state: str = ""+ verifier: str = ""+ redirect_uri: str = ""+ authorization_url: str = ""+ verification_url: str = ""+ user_code: str = ""+ device_auth_id: str = ""+ interval: float = 5.0+ status: Literal["pending", "connected", "error", "cancelled"] = "pending"+ message: str = ""++ marker: str = ""+ consumed: bool = False+ server: asyncio.AbstractServer | None = field(default = None, repr = False)+ task: asyncio.Task | None = field(default = None, repr = False)++ cleanup_task: asyncio.Task | None = field(default = None, repr = False)++ persist_bundle: Callable[[str, dict[str, Any]], Awaitable[None] | None] | None = field(+ default = None, repr = False+ )+++_flows: dict[str, OAuthFlow] = {}+_flows_lock = asyncio.Lock()+_refresh_locks: dict[str, asyncio.Lock] = {}+++def _provider_file_lock(provider_id: str) -> FileLock:+ lock_name = hashlib.sha256(provider_id.encode()).hexdigest()[:24]+ return FileLock(+ str(studio_db_path().parent / f".openai-codex-refresh-{lock_name}.lock"),+ timeout = 30,+ thread_local = False,+ )+++@asynccontextmanager+async def provider_oauth_write_guard(provider_id: str):+ """Serialize refresh and deletion across Studio workers without blocking the event loop."""+ file_lock = _provider_file_lock(provider_id)+ try:+ await asyncio.to_thread(file_lock.acquire)+ except FileLockTimeout as exc:+ raise CodexAuthError("ChatGPT credential update is busy. Please retry.") from exc+ try:+ yield+ finally:+ await asyncio.to_thread(file_lock.release)+++def _flow_is_stale(flow: OAuthFlow, now: float) -> bool:+ if flow.status == "pending":+ return now >= flow.expires_at+ return now >= min(flow.expires_at, flow.created_at + _FLOW_TERMINAL_RETENTION_SECONDS)+++async def _prune_flows() -> None:+ now = time.time()+ for flow_id, flow in list(_flows.items()):+ if _flow_is_stale(flow, now):+ await cancel_flow(flow_id)+++async def _expire_and_remove_flow(flow: OAuthFlow) -> None:+ """Expire a pending flow at its deadline, then discard terminal metadata."""+ while flow.status == "pending" and time.time() < flow.expires_at:+ await asyncio.sleep(min(0.5, max(0.0, flow.expires_at - time.time())))+ if flow.marker and not oauth_flow_marker_is_current(flow.provider_id, flow.marker):+ await cancel_flow(flow.id)+ return+ if _flows.get(flow.id) is not flow:+ return+ if flow.status == "pending":+ flow.status = "error"+ flow.message = "Authorization expired. Start a new connection."++ await _persist_terminal_flow(flow)+ if flow.task:+ flow.task.cancel()+ if flow.server:+ flow.server.close()+ await flow.server.wait_closed()+ flow.server = None+ await asyncio.sleep(_FLOW_TERMINAL_RETENTION_SECONDS)+ if _flows.get(flow.id) is flow:+ await cancel_flow(flow.id)+++async def shutdown_flows() -> None:+ """Cancel every loopback listener/device poll during application shutdown."""+ for flow_id in list(_flows):+ await cancel_flow(flow_id)+++def mark_reauthorization_required(+ provider_id: str, expected_access_token: str | None = None+) -> None:+ bundle = load_oauth_bundle(provider_id)+ if bundle and (+ expected_access_token is None+ or secrets.compare_digest(bundle["access_token"], expected_access_token)+ ):+ bundle["reauthorization_required"] = True+ save_oauth_bundle(provider_id, bundle)+++def _b64url(data: bytes) -> str:+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")+++def create_pkce() -> tuple[str, str]:+ verifier = _b64url(secrets.token_bytes(48))+ challenge = _b64url(hashlib.sha256(verifier.encode("ascii")).digest())+ return verifier, challenge+++def extract_chatgpt_account_id(access_token: str) -> str:+ """Decode only the bounded JWT payload needed as an upstream routing hint."""+ parts = access_token.split(".")+ if len(parts) < 2 or len(parts[1]) > 16_384:+ raise CodexAuthError("ChatGPT returned an invalid access token.")+ try:+ raw = base64.urlsafe_b64decode(parts[1] + "=" * (-len(parts[1]) % 4))+ payload = json.loads(raw)+ except Exception as exc:+ raise CodexAuthError("ChatGPT returned an invalid access token.") from exc+ account_id = payload.get("https://api.openai.com/auth", {}).get("chatgpt_account_id")+ if not isinstance(account_id, str) or not account_id or len(account_id) > 512:+ account_id = payload.get("https://api.openai.com/auth.chatgpt_account_id")+ if not isinstance(account_id, str) or not account_id or len(account_id) > 512:+ raise CodexAuthError("The ChatGPT account identifier was missing.")+ return account_id+++def _validate_token_payload(body: Any, previous_refresh_token: str = "") -> dict[str, Any]:+ if not isinstance(body, dict):+ raise CodexAuthError("ChatGPT returned an invalid token response.")+ access_token = body.get("access_token")+ refresh_token = body.get("refresh_token") or previous_refresh_token+ expires_in = body.get("expires_in", 3600)+ if not isinstance(access_token, str) or not access_token:+ raise CodexAuthError("ChatGPT returned an invalid token response.")+ if not isinstance(refresh_token, str) or not refresh_token:+ raise CodexAuthError("ChatGPT did not return a refresh token.")+ try:+ expires_in = max(60, min(int(expires_in), 30 * 24 * 3600))+ except (TypeError, ValueError) as exc:+ raise CodexAuthError("ChatGPT returned an invalid token lifetime.") from exc+ return {+ "access_token": access_token,+ "refresh_token": refresh_token,+ "expires_at": int(time.time()) + expires_in,+ "account_id": extract_chatgpt_account_id(access_token),+ }+++def save_oauth_bundle(provider_id: str, bundle: dict[str, Any]) -> None:+ credential_secrets.upsert_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_KIND,+ provider_id,+ json.dumps(bundle, separators = (",", ":")),+ )+++def load_oauth_bundle(provider_id: str) -> dict[str, Any] | None:+ raw = credential_secrets.get_secret(credential_secrets.OPENAI_CODEX_OAUTH_KIND, provider_id)+ if not raw:+ return None+ try:+ bundle = json.loads(raw)+ except Exception:+ return None+ required = ("access_token", "refresh_token", "expires_at", "account_id")+ return bundle if isinstance(bundle, dict) and all(bundle.get(key) for key in required) else None+++def auth_status(provider_id: str) -> str:+ bundle = load_oauth_bundle(provider_id)+ if not bundle:+ return "disconnected"+ # An expired access token is still usable after refresh. Only a permanent+ # refresh rejection should ask the user to reconnect.+ return "reauthorization_required" if bundle.get("reauthorization_required") else "connected"+++async def _token_request(data: dict[str, Any]) -> dict[str, Any]:+ try:+ async with httpx.AsyncClient(+ timeout = 30.0, follow_redirects = False, trust_env = False+ ) as client:+ response = await client.post(OPENAI_CODEX_TOKEN_URL, data = data)+ except httpx.HTTPError as exc:+ raise CodexAuthError("Could not reach ChatGPT authentication.") from exc+ if response.status_code >= 400:+ error_code = ""+ try:+ error = response.json().get("error")+ error_code = error.get("code", "") if isinstance(error, dict) else str(error or "")+ except Exception:+ pass+ if data.get("grant_type") == "refresh_token" and error_code in {+ "invalid_grant",+ "invalid_refresh_token",+ "refresh_token_expired",+ }:+ raise CodexReauthorizationRequired(+ "ChatGPT authorization is no longer valid. Please reconnect."+ )+ raise CodexAuthError("ChatGPT authorization failed. Please reconnect.")+ try:+ return response.json()+ except Exception as exc:+ raise CodexAuthError("ChatGPT returned an invalid authorization response.") from exc+++async def _exchange_code(+ flow: OAuthFlow,+ code: str,+ *,+ verifier: str | None = None,+ redirect_uri: str | None = None,+) -> None:+ if flow.consumed:+ raise CodexAuthError("Authorization callback was already used.")+ flow.consumed = True+ try:+ body = await _token_request(+ {+ "grant_type": "authorization_code",+ "client_id": OPENAI_CODEX_CLIENT_ID,+ "code": code,+ "redirect_uri": redirect_uri or flow.redirect_uri,+ "code_verifier": verifier or flow.verifier,+ }+ )+ bundle = _validate_token_payload(body)+ if flow.persist_bundle is None or flow.status != "pending":+ raise CodexAuthError("Authorization flow was cancelled before credentials were saved.")+ persisted = flow.persist_bundle(flow.provider_id, bundle)+ if persisted is not None:+ await persisted+ except Exception:+ flow.status = "error"+ flow.message = "ChatGPT authorization failed. Please reconnect."+ await _persist_terminal_flow(flow)+ raise+ flow.status = "connected"+ if flow.server:+ flow.server.close()+ flow.server = None+++async def _loopback_handler(+ flow: OAuthFlow, reader: asyncio.StreamReader, writer: asyncio.StreamWriter+) -> None:+ try:+ first = await asyncio.wait_for(reader.readline(), timeout = 5)+ target = first.decode("ascii", "ignore").split(" ")[1]+ parsed = urlparse(target)+ query = parse_qs(parsed.query)+ if parsed.path != OPENAI_CODEX_CALLBACK_PATH or query.get("state", [""])[0] != flow.state:+ raise CodexAuthError("Authorization state did not match.")+ code = query.get("code", [""])[0]+ if not code or flow.consumed:+ raise CodexAuthError("Authorization callback was invalid or already used.")+ await _exchange_code(flow, code)+ message = "ChatGPT connected. You can close this window."+ except Exception as exc:+ # Stray requests and state mismatches must not poison the active flow.+ if flow.consumed and flow.status == "pending":+ flow.status = "error"+ flow.message = str(exc) if isinstance(exc, CodexAuthError) else "Authorization failed."+ message = "Authorization failed. Return to Unsloth Studio and try again."+ body = (+ "<!doctype html><meta charset=utf-8><title>Unsloth Studio</title>"+ + "<p>"+ + message.replace("&", "&").replace("<", "<")+ + "</p>"+ ).encode()+ writer.write(+ b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nCache-Control: no-store\r\nContent-Length: "+ + str(len(body)).encode()+ + b"\r\nConnection: close\r\n\r\n"+ + body+ )+ await writer.drain()+ writer.close()+ await writer.wait_closed()+++async def _start_browser_flow(+ provider_id: str,+ persist_bundle: Callable[[str, dict[str, Any]], Awaitable[None] | None],+ marker: str = "",+) -> OAuthFlow:+ verifier, challenge = create_pkce()+ flow = OAuthFlow(+ id = secrets.token_urlsafe(24),+ provider_id = provider_id,+ method = "browser",+ created_at = time.time(),+ expires_at = time.time() + _FLOW_TTL_SECONDS,+ state = secrets.token_urlsafe(32),+ verifier = verifier,+ marker = marker,+ persist_bundle = persist_bundle,+ )+ bound_port: int | None = None+ for port in OPENAI_CODEX_LOOPBACK_PORTS:+ try:+ flow.server = await asyncio.start_server(+ lambda r, w, f = flow: _loopback_handler(f, r, w), "127.0.0.1", port+ )+ bound_port = port+ break+ except OSError:+ continue+ # The callback URL must match the verifier exchange even when no listener+ # can bind. Manual completion remains valid with the canonical URL.+ callback_port = bound_port or OPENAI_CODEX_LOOPBACK_PORTS[0]+ # OpenAI registers localhost redirect URIs; the listener itself remains+ # pinned to 127.0.0.1 so it can never accept non-loopback traffic.+ flow.redirect_uri = f"http://localhost:{callback_port}{OPENAI_CODEX_CALLBACK_PATH}"+ flow.authorization_url = (+ OPENAI_CODEX_AUTHORIZE_URL+ + "?"+ + urlencode(+ {+ "client_id": OPENAI_CODEX_CLIENT_ID,+ "response_type": "code",+ "redirect_uri": flow.redirect_uri,+ "scope": OPENAI_CODEX_SCOPE,+ "code_challenge": challenge,+ "code_challenge_method": "S256",+ "state": flow.state,+ "originator": OPENAI_CODEX_ORIGINATOR,+ "codex_cli_simplified_flow": "true",+ "id_token_add_organizations": "true",+ }+ )+ )+ return flow+++async def _device_poll(flow: OAuthFlow) -> None:+ while flow.status == "pending" and time.time() < flow.expires_at:+ await asyncio.sleep(flow.interval)+ try:+ async with httpx.AsyncClient(+ timeout = 30.0, follow_redirects = False, trust_env = False+ ) as client:+ response = await client.post(+ OPENAI_CODEX_DEVICE_TOKEN_URL,+ json = {+ "device_auth_id": flow.device_auth_id,+ "user_code": flow.user_code,+ },+ )+ if response.status_code in (403, 404):+ continue+ if response.status_code >= 400:+ error_code = ""+ server_interval: Any = None+ try:+ error_body = response.json()+ error = error_body.get("error")+ error_code = (+ error.get("code", "") if isinstance(error, dict) else str(error or "")+ )+ server_interval = error_body.get("interval")+ except Exception:+ pass+ if error_code == "deviceauth_authorization_pending":+ continue+ if error_code == "slow_down" or response.status_code == 429:+ try:+ requested = float(server_interval)+ except (TypeError, ValueError):+ requested = flow.interval + 5+ flow.interval = min(30.0, max(flow.interval + 5, requested))+ continue+ raise CodexAuthError(+ "Device authorization failed. Enable device-code login in ChatGPT settings and retry."+ )+ body = response.json()+ code = body.get("authorization_code")+ verifier = body.get("code_verifier")+ if (+ not isinstance(code, str)+ or not code+ or not isinstance(verifier, str)+ or not verifier+ ):+ raise CodexAuthError("ChatGPT returned an invalid device authorization response.")+ await _exchange_code(+ flow,+ code,+ verifier = verifier,+ redirect_uri = OPENAI_CODEX_DEVICE_REDIRECT_URI,+ )+ return+ except asyncio.CancelledError:+ return+ except CodexAuthError as exc:+ flow.status = "error"+ flow.message = str(exc)++ await _persist_terminal_flow(flow)+ return+ except Exception:+ flow.status = "error"+ flow.message = "Device authorization failed. Please retry."++ await _persist_terminal_flow(flow)+ return+ if flow.status == "pending":+ flow.status = "error"+ flow.message = "Device authorization expired. Start a new connection."++ await _persist_terminal_flow(flow)+++async def _start_device_flow(+ provider_id: str,+ persist_bundle: Callable[[str, dict[str, Any]], Awaitable[None] | None],+ marker: str = "",+) -> OAuthFlow:+ try:+ async with httpx.AsyncClient(+ timeout = 30.0, follow_redirects = False, trust_env = False+ ) as client:+ response = await client.post(+ OPENAI_CODEX_DEVICE_CODE_URL, json = {"client_id": OPENAI_CODEX_CLIENT_ID}+ )+ except httpx.HTTPError as exc:+ raise CodexAuthError("Could not reach ChatGPT authentication.") from exc+ if response.status_code >= 400:+ raise CodexAuthError(+ "Device login is unavailable. Enable device-code login in ChatGPT settings."+ )+ try:+ body = response.json()+ device_auth_id = body["device_auth_id"]+ user_code = body["user_code"]+ verification_url = (+ body.get("verification_uri_complete")+ or body.get("verification_uri")+ or "https://auth.openai.com/codex/device"+ )+ except Exception as exc:+ raise CodexAuthError("ChatGPT returned an invalid device authorization response.") from exc+ flow = OAuthFlow(+ id = secrets.token_urlsafe(24),+ provider_id = provider_id,+ method = "device",+ created_at = time.time(),+ expires_at = time.time()+ + min(int(body.get("expires_in", _FLOW_TTL_SECONDS)), _FLOW_TTL_SECONDS),+ device_auth_id = str(device_auth_id),+ user_code = str(user_code),+ verification_url = str(verification_url),+ interval = max(1.0, min(float(body.get("interval", 5)), 30.0)),+ redirect_uri = OPENAI_CODEX_DEVICE_REDIRECT_URI,+ marker = marker,+ persist_bundle = persist_bundle,+ )+ flow.task = asyncio.create_task(_device_poll(flow))+ return flow+++async def start_flow(+ provider_id: str,+ method: Literal["browser", "device"],+ persist_bundle: Callable[[str, dict[str, Any]], Awaitable[None] | None],+ marker: str = "",+) -> OAuthFlow:+ async with _flows_lock:+ await _prune_flows()+ for old in list(_flows.values()):+ if old.provider_id == provider_id and old.status == "pending":+ await cancel_flow(old.id)+ flow = await (+ _start_browser_flow(provider_id, persist_bundle, marker)+ if method == "browser"+ else _start_device_flow(provider_id, persist_bundle, marker)+ )+ _flows[flow.id] = flow++ flow.cleanup_task = asyncio.create_task(_expire_and_remove_flow(flow))+ return flow+++def safe_flow(flow: OAuthFlow) -> dict[str, Any]:+ return {+ "flow_id": flow.id,+ "method": flow.method,+ "status": flow.status,+ "expires_at": int(flow.expires_at),+ "authorization_url": flow.authorization_url or None,+ "verification_url": flow.verification_url or None,+ "user_code": flow.user_code or None,+ "message": flow.message or None,+ }+++def get_flow(provider_id: str, flow_id: str) -> OAuthFlow:+ flow = _flows.get(flow_id)+ if (+ flow is not None+ and flow.provider_id == provider_id+ and (flow.server is None and flow.task is None and flow.persist_bundle is None)+ ):+ persisted = _load_persisted_oauth_flow(provider_id, flow_id)+ if persisted is None:+ _flows.pop(flow_id, None)+ raise CodexAuthError("Authorization flow was not found or expired.")+ flow = persisted+ _flows[flow.id] = flow+ elif flow is None or flow.provider_id != provider_id:+ flow = _load_persisted_oauth_flow(provider_id, flow_id)+ if flow is None:+ raise CodexAuthError("Authorization flow was not found or expired.")+ _flows[flow.id] = flow+ if time.time() >= flow.expires_at and flow.status == "pending":+ flow.status = "error"+ flow.message = "Authorization expired. Start a new connection."+ if flow.task:+ flow.task.cancel()+ if flow.server:+ flow.server.close()+ return flow+++async def complete_browser_flow(provider_id: str, flow_id: str, callback_url: str) -> OAuthFlow:+ flow = get_flow(provider_id, flow_id)+ if flow.method != "browser" or flow.status != "pending" or flow.consumed:+ raise CodexAuthError("Authorization flow is no longer active.")+ parsed = urlparse(callback_url)+ expected = urlparse(flow.redirect_uri)+ if (+ parsed.scheme != expected.scheme+ or parsed.hostname != expected.hostname+ or parsed.port != expected.port+ or parsed.path != expected.path+ or parsed.fragment+ ):+ raise CodexAuthError("Paste the complete localhost ChatGPT callback URL.")+ query = parse_qs(parsed.query)+ if not secrets.compare_digest(query.get("state", [""])[0], flow.state):+ raise CodexAuthError("Authorization state did not match.")+ code = query.get("code", [""])[0]+ if not code:+ raise CodexAuthError("The callback URL did not contain an authorization code.")+ await _exchange_code(flow, code)+ return flow+++async def cancel_flow(flow_id: str) -> None:+ flow = _flows.pop(flow_id, None)+ if not flow:+ return+ flow.status = "cancelled"+ if flow.task:+ flow.task.cancel()+ if flow.cleanup_task and flow.cleanup_task is not asyncio.current_task():+ flow.cleanup_task.cancel()+ if flow.server:+ flow.server.close()+ await flow.server.wait_closed()+++async def cancel_provider_flows(provider_id: str) -> None:+ """Stop transient authorization work without touching persisted credentials."""+ for flow_id, flow in list(_flows.items()):+ if flow.provider_id == provider_id:+ await cancel_flow(flow_id)+++def delete_oauth_bundle(provider_id: str) -> None:+ """Delete persisted authorization synchronously inside a credential guard."""+ credential_secrets.delete_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_KIND,+ provider_id,+ )+++def _oauth_flow_record(provider_id: str) -> dict[str, Any] | None:+ raw = credential_secrets.get_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_FLOW_KIND, provider_id+ )+ if not raw:+ return None+ try:+ value = json.loads(raw)+ except Exception:+ return {"marker": raw, "status": "pending"}+ return value if isinstance(value, dict) else None+++def save_oauth_flow_marker(+ provider_id: str,+ marker: str,+ flow: OAuthFlow | None = None,+) -> None:+ value = marker+ if flow is not None:+ value = json.dumps(+ {+ "marker": marker,+ "flow_id": flow.id,+ "method": flow.method,+ "created_at": flow.created_at,+ "expires_at": flow.expires_at,+ "state": flow.state,+ "verifier": flow.verifier,+ "redirect_uri": flow.redirect_uri,+ "authorization_url": flow.authorization_url,+ "verification_url": flow.verification_url,+ "user_code": flow.user_code,+ "device_auth_id": flow.device_auth_id,+ "interval": flow.interval,+ "status": flow.status,+ "message": flow.message,+ },+ separators = (",", ":"),+ )+ credential_secrets.upsert_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_FLOW_KIND,+ provider_id,+ value,+ )+++def set_oauth_flow_marker_status(+ provider_id: str,+ marker: str,+ status: str,+ message: str = "",+) -> None:+ record = _oauth_flow_record(provider_id)+ if not record or record.get("marker") != marker:+ return+ if "flow_id" not in record:+ delete_oauth_flow_marker(provider_id, marker)+ return+ record["status"] = status+ record["message"] = message++ if status != "pending":+ record["terminal_at"] = time.time()+ for key in ("state", "verifier", "device_auth_id", "user_code"):+ record[key] = ""+ credential_secrets.upsert_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_FLOW_KIND,+ provider_id,+ json.dumps(record, separators = (",", ":")),+ )+++async def _persist_terminal_flow(flow: OAuthFlow) -> None:+ """Publish a device-flow terminal state for status requests served by other workers."""+ if flow.status == "pending" or not flow.marker:+ return+ try:+ async with provider_oauth_write_guard(flow.provider_id):+ set_oauth_flow_marker_status(flow.provider_id, flow.marker, flow.status, flow.message)+ except CodexAuthError:+ # Keep the originating worker's terminal state even if another credential+ # write holds the cross-worker lock long enough for this best-effort update.+ return+++def _load_persisted_oauth_flow(provider_id: str, flow_id: str) -> OAuthFlow | None:+ record = _oauth_flow_record(provider_id)+ if not record or record.get("flow_id") != flow_id:+ return None+ method = record.get("method")+ status = record.get("status")+ if method not in {"browser", "device"} or status not in {+ "pending",+ "connected",+ "error",+ "cancelled",+ }:+ return None+ try:+ return OAuthFlow(+ id = flow_id,+ provider_id = provider_id,+ method = method,+ created_at = float(record["created_at"]),+ expires_at = float(record["expires_at"]),+ state = str(record.get("state", "")),+ verifier = str(record.get("verifier", "")),+ redirect_uri = str(record.get("redirect_uri", "")),+ authorization_url = str(record.get("authorization_url", "")),+ verification_url = str(record.get("verification_url", "")),+ user_code = str(record.get("user_code", "")),+ device_auth_id = str(record.get("device_auth_id", "")),+ interval = float(record.get("interval", 5.0)),+ status = status,+ message = str(record.get("message", "")),+ marker = str(record.get("marker", "")),+ )+ except (KeyError, TypeError, ValueError):+ return None+++def oauth_flow_marker_is_current(provider_id: str, marker: str) -> bool:+ record = _oauth_flow_record(provider_id)+ return bool(record and record.get("marker") == marker)+++def oauth_flow_marker_matches(provider_id: str, marker: str) -> bool:+ record = _oauth_flow_record(provider_id)+ return bool(+ record and record.get("marker") == marker and record.get("status", "pending") == "pending"+ )+++def delete_oauth_flow_marker(provider_id: str, marker: str | None = None) -> None:+ if marker is not None:+ record = _oauth_flow_record(provider_id)+ if not record or record.get("marker") != marker:+ return+ credential_secrets.delete_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_FLOW_KIND,+ provider_id,+ )+++async def resolve_access(+ provider_id: str,+ *,+ force_refresh: bool = False,+ expected_access_token: str | None = None,+) -> tuple[str, str]:+ lock = _refresh_locks.setdefault(provider_id, asyncio.Lock())+ async with lock:+ bundle = load_oauth_bundle(provider_id)+ if not bundle:+ raise CodexAuthError("ChatGPT connection requires authorization.")++ if bundle.get("reauthorization_required"):+ raise CodexAuthError("ChatGPT authorization is no longer valid. Please reconnect.")+ if not force_refresh and bundle["expires_at"] > time.time() + _REFRESH_SKEW_SECONDS:+ return bundle["access_token"], bundle["account_id"]++ # Multiple Studio workers may share the installation DB. Serialize with+ # disconnect/delete and re-read so a completed refresh is reused.+ async with provider_oauth_write_guard(provider_id):+ bundle = load_oauth_bundle(provider_id)+ if not bundle:+ raise CodexAuthError("ChatGPT connection requires authorization.")++ if expected_access_token is not None and not secrets.compare_digest(+ bundle["access_token"], expected_access_token+ ):+ return bundle["access_token"], bundle["account_id"]+ if not force_refresh and bundle["expires_at"] > time.time() + _REFRESH_SKEW_SECONDS:+ return bundle["access_token"], bundle["account_id"]+ previous_refresh_token = bundle["refresh_token"]+ try:+ body = await _token_request(+ {+ "grant_type": "refresh_token",+ "client_id": OPENAI_CODEX_CLIENT_ID,+ "refresh_token": previous_refresh_token,+ }+ )+ except CodexReauthorizationRequired:+ current = load_oauth_bundle(provider_id)+ if current and current.get("refresh_token") == previous_refresh_token:+ current["reauthorization_required"] = True+ save_oauth_bundle(provider_id, current)+ raise+ refreshed = _validate_token_payload(body, previous_refresh_token)+ current = load_oauth_bundle(provider_id)+ if not current:+ raise CodexAuthError("ChatGPT connection was disconnected during refresh.")+ if current.get("refresh_token") != previous_refresh_token:+ return current["access_token"], current["account_id"]+ save_oauth_bundle(provider_id, refreshed)+ return refreshed["access_token"], refreshed["account_id"]diff --git a/studio/backend/core/inference/openai_codex_client.py b/studio/backend/core/inference/openai_codex_client.pynew file mode 100644index 00000000000..b4771c27c59--- /dev/null+++ b/studio/backend/core/inference/openai_codex_client.py@@ -0,0 +1,721 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Fixed-host ChatGPT Codex Responses transport and SSE normalization."""++from __future__ import annotations++import asyncio++from contextlib import asynccontextmanager+import hashlib+import json+import secrets+import threading+import time+from typing import Any, AsyncGenerator, Awaitable, Callable+from urllib.parse import urlparse++import httpx++from core.inference.openai_codex_auth import (+ OPENAI_CODEX_COMPATIBILITY_INSTRUCTIONS,+ OPENAI_CODEX_ORIGINATOR,+ OPENAI_CODEX_RESPONSES_URL,+ OPENAI_CODEX_USER_AGENT,+ CodexReauthorizationRequired,+)+from core.inference.openai_responses_shared import (+ normalize_function_schema,+ responses_function_call,+ responses_function_output,+ response_event_type,+ responses_usage_to_chat,+)+++class CodexTransportError(RuntimeError):+ def __init__(+ self,+ message: str,+ *,+ status: int = 502,+ metadata: dict[str, Any] | None = None,+ ):+ super().__init__(message)+ self.status = status+ self.metadata = metadata or {}+++class CodexReauthorizationError(CodexTransportError):+ pass+++class CodexQuotaError(CodexTransportError):+ pass+++def _codex_call_id(value: Any) -> str | None:+ """Return a stable Responses-compatible call ID (the API caps IDs at 64 chars)."""+ if not isinstance(value, str) or not value:+ return None+ if len(value) <= 64:+ return value+ digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:32]+ return f"{value[:31]}_{digest}"+++def _responses_input(messages: list[dict[str, Any]]) -> tuple[str, list[dict[str, Any]]]:+ """Translate chat history to the Responses input shape used by Pi/Codex."""+ instructions = [OPENAI_CODEX_COMPATIBILITY_INSTRUCTIONS]+ items: list[dict[str, Any]] = []+ assistant_index = 0+ for message in messages:+ role, content = message.get("role"), message.get("content", "")+ if role == "system":+ if isinstance(content, str) and content:+ instructions.append(content)+ elif isinstance(content, list):+ instructions.extend(+ part["text"]+ for part in content+ if isinstance(part, dict)+ and part.get("type") in ("text", "input_text")+ and isinstance(part.get("text"), str)+ and part["text"]+ )+ continue+ if role == "tool":+ call_id = _codex_call_id(message.get("tool_call_id"))+ if call_id:+ output = content if isinstance(content, str) else json.dumps(content)+ items.append(responses_function_output(call_id, output))+ continue+ if role == "assistant":+ extra = message.get("extra_content")+ for item in extra.get("openai_codex_reasoning", []) if isinstance(extra, dict) else []:+ if (+ isinstance(item, dict)+ and item.get("type") == "reasoning"+ and isinstance(item.get("encrypted_content"), str)+ ):+ replay = {+ "type": "reasoning",+ "encrypted_content": item["encrypted_content"],+ "summary": item.get("summary", []),+ }+ if isinstance(item.get("id"), str):+ replay["id"] = item["id"]+ items.append(replay)+ function_calls: list[dict[str, Any]] = []+ for call in message.get("tool_calls") or []:+ function = call.get("function") if isinstance(call, dict) else None+ if isinstance(function, dict) and function.get("name"):+ arguments = function.get("arguments", "")+ if not isinstance(arguments, str):+ arguments = json.dumps(arguments)+ call_id = _codex_call_id(call.get("id"))+ if call_id:+ function_calls.append(+ responses_function_call(call_id, function["name"], arguments)+ )+ output_parts: list[dict[str, Any]] = []+ if isinstance(content, str) and content:+ output_parts.append({"type": "output_text", "text": content, "annotations": []})+ elif isinstance(content, list):+ for part in content:+ if isinstance(part, dict) and part.get("type") == "text":+ output_parts.append(+ {"type": "output_text", "text": part.get("text", ""), "annotations": []}+ )+ if output_parts:+ items.append(+ {+ "type": "message",+ "id": f"msg_unsloth_{assistant_index}",+ "role": "assistant",+ "content": output_parts,+ "status": "completed",+ }+ )+ assistant_index += 1++ items.extend(function_calls)+ continue+ if role != "user":+ continue+ if isinstance(content, str):+ if content:+ items.append({"role": "user", "content": [{"type": "input_text", "text": content}]})+ elif isinstance(content, list):+ parts = []+ for part in content:+ if not isinstance(part, dict):+ continue+ if part.get("type") == "text":+ parts.append({"type": "input_text", "text": part.get("text", "")})+ elif part.get("type") == "image_url":+ url = (part.get("image_url") or {}).get("url")+ if url:+ parts.append({"type": "input_image", "detail": "auto", "image_url": url})+ if parts:+ items.append({"role": "user", "content": parts})+ return "\n\n".join(instructions), items+++def _chunk(+ completion_id: str,+ model: str,+ delta: dict[str, Any],+ finish_reason: str | None = None,+ usage: Any = None,+) -> str:+ body: dict[str, Any] = {+ "id": completion_id,+ "object": "chat.completion.chunk",+ "created": int(time.time()),+ "model": model,+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],+ }+ if usage is not None:+ body["usage"] = usage+ return "data: " + json.dumps(body, separators = (",", ":"))+++def _create_http_client() -> httpx.AsyncClient:+ kwargs = {"timeout": httpx.Timeout(120.0, connect = 20.0), "follow_redirects": False}+ try:+ return httpx.AsyncClient(**kwargs)+ except (ImportError, ValueError) as exc:+ if "Unknown scheme for proxy URL" not in str(exc) and "socksio" not in str(exc):+ raise+ return httpx.AsyncClient(**kwargs, trust_env = False)+++def _validated_responses_url() -> str:+ parsed = urlparse(OPENAI_CODEX_RESPONSES_URL)+ if (+ parsed.scheme != "https"+ or parsed.hostname != "chatgpt.com"+ or parsed.port is not None+ or parsed.path != "/backend-api/codex/responses"+ or parsed.query+ or parsed.fragment+ or parsed.username+ or parsed.password+ ):+ raise RuntimeError("ChatGPT Codex endpoint configuration is invalid.")+ return OPENAI_CODEX_RESPONSES_URL+++def _quota_metadata(response: httpx.Response) -> dict[str, Any]:+ values = {+ "retry_after": response.headers.get("retry-after"),+ "requests_reset": response.headers.get("x-ratelimit-reset-requests"),+ "tokens_reset": response.headers.get("x-ratelimit-reset-tokens"),+ }+ return {key: value for key, value in values.items() if value}+++async def _upstream_error_detail(response: httpx.Response) -> str | None:+ """Extract only structured, bounded upstream error text; never echo HTML."""+ try:+ await response.aread()+ payload = response.json()+ except (ValueError, json.JSONDecodeError, httpx.HTTPError, AttributeError):+ return None+ error = payload.get("error") if isinstance(payload, dict) else None+ if isinstance(error, dict):+ message = error.get("message")+ code = error.get("code") or error.get("type")+ detail = message if isinstance(message, str) and message.strip() else code+ else:+ detail = error if isinstance(error, str) else None+ if not isinstance(detail, str):+ return None+ return " ".join(detail.split())[:500] or None+++async def _wait_for_cancel(cancel_event: threading.Event) -> None:+ while not cancel_event.is_set():+ await asyncio.sleep(0.05)+++@asynccontextmanager+async def _stream_response(+ client: httpx.AsyncClient,+ *,+ url: str,+ headers: dict[str, str],+ body: dict[str, Any],+ cancel_event: threading.Event | None,+):+ """Open a streaming response while allowing pre-header cancellation."""+ context = client.stream("POST", url, headers = headers, json = body)+ if cancel_event is None:+ async with context as response:+ yield response+ return+ if cancel_event.is_set():+ yield None+ return++ enter_task = asyncio.create_task(context.__aenter__())+ cancel_task = asyncio.create_task(_wait_for_cancel(cancel_event))+ done, _pending = await asyncio.wait(+ {enter_task, cancel_task}, return_when = asyncio.FIRST_COMPLETED+ )+ if cancel_task in done and cancel_event.is_set():+ enter_task.cancel()+ await asyncio.gather(enter_task, return_exceptions = True)+ yield None+ return++ cancel_task.cancel()+ await asyncio.gather(cancel_task, return_exceptions = True)+ response = await enter_task+ try:+ yield response+ finally:+ await context.__aexit__(None, None, None)+++_RETRYABLE_STATUSES = frozenset({429, 500, 502, 503, 504})+_MAX_TRANSIENT_RETRIES = 2+++def _is_terminal_quota(detail: str | None) -> bool:+ if not detail:+ return False+ lowered = detail.lower()+ return any(+ marker in lowered+ for marker in (+ "usage limit",+ "insufficient_quota",+ "out of budget",+ "quota exceeded",+ "available balance",+ "billing",+ )+ )+++def _retry_delay_seconds(response: httpx.Response, attempt: int) -> float:+ raw = response.headers.get("retry-after-ms")+ if raw:+ try:+ return min(60.0, max(0.0, float(raw) / 1000.0))+ except ValueError:+ pass+ raw = response.headers.get("retry-after")+ if raw:+ try:+ return min(60.0, max(0.0, float(raw)))+ except ValueError:+ pass+ return float(2**attempt)+++async def _retry_pause(delay: float, cancel_event: threading.Event | None) -> None:+ deadline = asyncio.get_running_loop().time() + delay+ while True:+ if cancel_event is not None and cancel_event.is_set():+ return+ remaining = deadline - asyncio.get_running_loop().time()+ if remaining <= 0:+ return+ await asyncio.sleep(min(0.1, remaining))+++@asynccontextmanager+async def _validated_stream_response(+ client: httpx.AsyncClient,+ *,+ url: str,+ headers: dict[str, str],+ body: dict[str, Any],+ cancel_event: threading.Event | None,+ refresh_access: Callable[[], Awaitable[tuple[str, str]]] | None,+):+ refreshed = False++ token = headers.get("Authorization", "").removeprefix("Bearer ")+ for attempt in range(_MAX_TRANSIENT_RETRIES + 1):+ yielded = False+ try:+ async with _stream_response(+ client,+ url = url,+ headers = headers,+ body = body,+ cancel_event = cancel_event,+ ) as response:+ if response is None:+ yield None+ return+ if 200 <= response.status_code < 300:+ yielded = True+ yield response+ return+ if 300 <= response.status_code < 400:+ raise CodexTransportError(+ "ChatGPT Codex endpoint returned a forbidden redirect."+ )+ detail = await _upstream_error_detail(response)+ if response.status_code == 401 and refresh_access is not None and not refreshed:+ try:+ token, account_id = await refresh_access()+ except CodexReauthorizationRequired as exc:+ raise CodexReauthorizationError(+ "ChatGPT authorization expired. Reconnect this connection.",+ status = 401,+ metadata = {"access_token": token},+ ) from exc+ except Exception as exc:+ raise CodexTransportError(+ "Could not refresh ChatGPT authorization. Please retry.",+ status = 502,+ ) from exc+ headers["Authorization"] = f"Bearer {token}"+ headers["chatgpt-account-id"] = account_id+ refreshed = True+ continue+ if response.status_code == 401:+ raise CodexReauthorizationError(+ "ChatGPT authorization expired. Reconnect this connection.",+ status = 401,+ metadata = {"access_token": token},+ )+ retryable = response.status_code in _RETRYABLE_STATUSES and not _is_terminal_quota(+ detail+ )+ if retryable and attempt < _MAX_TRANSIENT_RETRIES:+ await _retry_pause(_retry_delay_seconds(response, attempt), cancel_event)+ if cancel_event is not None and cancel_event.is_set():+ yield None+ return+ continue+ if response.status_code == 429:+ raise CodexQuotaError(+ "ChatGPT subscription quota is temporarily unavailable.",+ status = 429,+ metadata = _quota_metadata(response),+ )+ suffix = f" {detail}" if detail else ""+ raise CodexTransportError(+ f"ChatGPT Codex request failed ({response.status_code}).{suffix}",+ status = response.status_code,+ )+ except httpx.HTTPError as exc:+ if yielded:+ raise+ if attempt >= _MAX_TRANSIENT_RETRIES:+ raise CodexTransportError("Could not reach ChatGPT Codex.") from exc+ await _retry_pause(float(2**attempt), cancel_event)+ if cancel_event is not None and cancel_event.is_set():+ yield None+ return+ raise CodexTransportError("Could not reach ChatGPT Codex.")+++class OpenAICodexClient:+ def __init__(+ self,+ access_token: str,+ account_id: str,+ *,+ refresh_access: Callable[[], Awaitable[tuple[str, str]]] | None = None,+ ) -> None:+ self._token, self._account_id = access_token, account_id+ self._refresh_access = refresh_access+ self._client = _create_http_client()++ async def _refresh_credentials(self) -> tuple[str, str]:+ if self._refresh_access is None:+ raise CodexReauthorizationError(+ "ChatGPT authorization expired. Reconnect this connection.",+ status = 401,+ )+ token, account_id = await self._refresh_access()+ self._token, self._account_id = token, account_id+ return token, account_id++ async def close(self) -> None:+ self._token = ""+ await self._client.aclose()++ async def stream(+ self,+ *,+ provider_id: str,+ thread_id: str | None,+ messages: list[dict[str, Any]],+ model: str,+ max_tokens: int | None,+ reasoning_effort: str | None,+ tools: list[dict[str, Any]] | None,+ tool_choice: Any,+ response_format: dict[str, Any] | None = None,+ cancel_event: threading.Event | None = None,+ ) -> AsyncGenerator[str, None]:+ instructions, input_items = _responses_input(messages)+ conversation_id = thread_id or secrets.token_urlsafe(24)+ affinity = hashlib.sha256(+ f"{provider_id}\0{self._account_id}\0{conversation_id}".encode()+ ).hexdigest()[:48]+ body: dict[str, Any] = {+ "model": model,+ "instructions": instructions,+ "input": input_items,+ "store": False,+ "stream": True,+ "text": {"verbosity": "low"},+ "include": ["reasoning.encrypted_content"],+ "prompt_cache_key": affinity,+ "tool_choice": "auto",+ "parallel_tool_calls": True,+ }+ response_type = response_format.get("type") if isinstance(response_format, dict) else None+ if response_type == "json_object":+ body["text"]["format"] = {"type": "json_object"}+ elif response_type == "json_schema":+ schema = response_format.get("json_schema")+ if isinstance(schema, dict) and isinstance(schema.get("schema"), dict):+ body["text"]["format"] = {+ "type": "json_schema",+ "name": str(schema.get("name") or "response"),+ "schema": schema["schema"],+ "strict": bool(schema.get("strict", True)),+ }+ # Pi intentionally does not forward a token cap here. ChatGPT's Codex+ # Responses endpoint rejects max_output_tokens even though the public+ # Responses API accepts it; the subscription service applies its own cap.+ if reasoning_effort:+ body["reasoning"] = {"effort": reasoning_effort, "summary": "auto"}+ if tools:+ converted = []+ for tool in tools:+ function = (+ tool.get("function")+ if isinstance(tool, dict) and tool.get("type") == "function"+ else None+ )+ if isinstance(function, dict) and function.get("name"):+ converted.append(+ {+ "type": "function",+ "name": function["name"],+ "description": function.get("description", ""),+ "parameters": normalize_function_schema(function.get("parameters")),+ }+ )+ if converted:+ body["tools"] = converted+ if isinstance(tool_choice, str) and tool_choice in ("auto", "none", "required"):+ body["tool_choice"] = tool_choice+ elif isinstance(tool_choice, dict):+ fn = tool_choice.get("function") or {}+ if fn.get("name"):+ body["tool_choice"] = {"type": "function", "name": fn["name"]}+ request_id = hashlib.sha256(f"{affinity}\0{time.time_ns()}".encode()).hexdigest()[:32]+ headers = {+ "Authorization": f"Bearer {self._token}",+ "chatgpt-account-id": self._account_id,+ "originator": OPENAI_CODEX_ORIGINATOR,+ "User-Agent": OPENAI_CODEX_USER_AGENT,+ "OpenAI-Beta": "responses=experimental",+ "Accept": "text/event-stream",+ "Content-Type": "application/json",+ "session-id": affinity,+ "x-client-request-id": request_id,+ }+ completion_id = f"chatcmpl-codex-{request_id}"+ emitted_terminal, saw_tool_call = False, False+ reasoning_items: list[dict[str, Any]] = []+ cancel_task: asyncio.Task | None = None+ try:+ async with _validated_stream_response(+ self._client,+ url = _validated_responses_url(),+ headers = headers,+ body = body,+ cancel_event = cancel_event,+ refresh_access = (+ self._refresh_credentials if self._refresh_access is not None else None+ ),+ ) as response:+ if response is None:+ return+ if cancel_event is not None:++ async def _close_on_cancel() -> None:+ await _wait_for_cancel(cancel_event)+ await response.aclose()++ cancel_task = asyncio.create_task(_close_on_cancel())+ event_name, tool_indexes = "", {}+ try:+ async for line in response.aiter_lines():+ if cancel_event is not None and cancel_event.is_set():+ return+ if not line:+ event_name = ""+ continue+ if line.startswith("event:"):+ event_name = line[6:].strip()+ continue+ if not line.startswith("data:"):+ continue+ raw = line[5:].strip()+ if raw == "[DONE]":+ break+ try:+ event = json.loads(raw)+ kind = response_event_type(event, event_name)+ except (ValueError, json.JSONDecodeError) as exc:+ raise CodexTransportError(+ "ChatGPT returned a malformed stream."+ ) from exc+ if kind in ("response.created", "response.in_progress"):+ continue+ if kind in ("response.output_text.delta", "response.refusal.delta"):+ delta = event.get("delta")+ if not isinstance(delta, str):+ raise CodexTransportError("ChatGPT returned a malformed stream.")+ yield _chunk(completion_id, model, {"content": delta})+ elif kind in (+ "response.reasoning_summary_text.delta",+ "response.reasoning_text.delta",+ ):+ delta = event.get("delta")+ if isinstance(delta, str):+ yield _chunk(completion_id, model, {"reasoning_content": delta})+ elif kind == "response.output_item.added":+ item = event.get("item")+ if isinstance(item, dict) and item.get("type") == "function_call":+ call_id, name = (+ item.get("call_id") or item.get("id"),+ item.get("name"),+ )+ if isinstance(call_id, str) and isinstance(name, str):+ saw_tool_call = True+ index = len(set(tool_indexes.values()))+ tool_indexes[call_id] = index+ if isinstance(item.get("id"), str):+ tool_indexes[item["id"]] = index+ yield _chunk(+ completion_id,+ model,+ {+ "tool_calls": [+ {+ "index": index,+ "id": call_id,+ "type": "function",+ "function": {"name": name, "arguments": ""},+ }+ ]+ },+ )+ elif kind == "response.function_call_arguments.delta":+ call_id, delta = (+ event.get("call_id") or event.get("item_id"),+ event.get("delta"),+ )+ if not isinstance(call_id, str) or not isinstance(delta, str):+ raise CodexTransportError("ChatGPT returned a malformed stream.")+ saw_tool_call = True+ index = tool_indexes.setdefault(+ call_id, len(set(tool_indexes.values()))+ )+ yield _chunk(+ completion_id,+ model,+ {+ "tool_calls": [+ {"index": index, "function": {"arguments": delta}}+ ]+ },+ )+ elif kind == "response.output_item.done":+ item = event.get("item") or {}+ if isinstance(item, dict) and item.get("type") == "function_call":+ call_id = item.get("call_id") or item.get("id")+ if (+ isinstance(call_id, str)+ and call_id not in tool_indexes+ and isinstance(item.get("name"), str)+ ):+ saw_tool_call = True+ index = tool_indexes.setdefault(+ call_id, len(set(tool_indexes.values()))+ )+ yield _chunk(+ completion_id,+ model,+ {+ "tool_calls": [+ {+ "index": index,+ "id": call_id,+ "type": "function",+ "function": {+ "name": item["name"],+ "arguments": item.get("arguments", ""),+ },+ }+ ]+ },+ )+ elif (+ isinstance(item, dict)+ and item.get("type") == "reasoning"+ and isinstance(item.get("encrypted_content"), str)+ ):+ reasoning_items.append(+ {+ "type": "reasoning",+ "id": item.get("id"),+ "encrypted_content": item["encrypted_content"],+ "summary": item.get("summary", []),+ }+ )+ elif kind in ("response.completed", "response.incomplete"):+ response_body = event.get("response") or {}+ delta: dict[str, Any] = {}+ if reasoning_items:+ delta["extra_content"] = {"openai_codex_reasoning": reasoning_items}+ finish = (+ "length"+ if kind == "response.incomplete"+ else ("tool_calls" if saw_tool_call else "stop")+ )+ yield _chunk(+ completion_id,+ model,+ delta,+ finish,+ responses_usage_to_chat(response_body.get("usage")),+ )+ emitted_terminal = True+ break+ elif kind in ("response.failed", "error"):+ error = (+ event.get("error")+ or (event.get("response") or {}).get("error")+ or {}+ )+ code = error.get("code") if isinstance(error, dict) else None+ raise CodexTransportError(+ f"ChatGPT Codex generation failed{f' ({code})' if code else ''}."+ )+ except httpx.HTTPError:+ if cancel_event is not None and cancel_event.is_set():+ return+ raise+ finally:+ if cancel_task is not None:+ cancel_task.cancel()+ if not emitted_terminal and not (cancel_event is not None and cancel_event.is_set()):+ raise CodexTransportError("ChatGPT stream ended before completion.")diff --git a/studio/backend/core/inference/openai_codex_tool_loop.py b/studio/backend/core/inference/openai_codex_tool_loop.pynew file mode 100644index 00000000000..3b0be95b121--- /dev/null+++ b/studio/backend/core/inference/openai_codex_tool_loop.py@@ -0,0 +1,325 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Studio-owned tool execution loop for the ChatGPT Codex subscription transport."""++from __future__ import annotations++import asyncio+import json+import threading++from dataclasses import dataclass+from collections.abc import AsyncIterator+from typing import Any++from core.inference.openai_codex_client import OpenAICodexClient+from core.inference.tool_loop_controller import strip_result_for_model+from core.inference.tools import build_rag_autoinject, execute_tool, is_high_risk_tool_call+from state.tool_approvals import (+ TOOL_REJECTED_MESSAGE,+ abort_tool_decision,+ begin_tool_decision,+ new_approval_id,+ wait_tool_decision,+)+++_TOOL_BUDGET_EXHAUSTED = (+ "Studio did not execute this tool call because the per-message tool-call limit was reached. "+ "Continue with the available results and answer without calling another tool."+)+++def _sse(payload: dict[str, Any]) -> str:+ return "data: " + json.dumps(payload, separators = (",", ":"))+++def _chunk_payload(line: str) -> dict[str, Any] | None:+ if not line.startswith("data:"):+ return None+ raw = line[5:].strip()+ if not raw or raw == "[DONE]":+ return None+ try:+ value = json.loads(raw)+ except (TypeError, ValueError, json.JSONDecodeError):+ return None+ return value if isinstance(value, dict) else None+++def _normalized_call(call: dict[str, Any]) -> dict[str, Any] | None:+ call_id = call.get("id")+ function = call.get("function")+ if not isinstance(call_id, str) or not call_id or not isinstance(function, dict):+ return None+ name = function.get("name")+ arguments = function.get("arguments", "")+ if not isinstance(name, str) or not name:+ return None+ if not isinstance(arguments, str):+ arguments = json.dumps(arguments)+ try:+ parsed = json.loads(arguments or "{}")+ except (TypeError, ValueError, json.JSONDecodeError):+ parsed = {"_raw": arguments}+ if not isinstance(parsed, dict):+ parsed = {"value": parsed}+ return {+ "id": call_id,+ "type": "function",+ "function": {"name": name, "arguments": arguments or "{}"},+ "arguments": parsed,+ }+++@dataclass(frozen = True)+class CodexRunContext:+ provider_id: str+ thread_id: str | None+ session_id: str | None+ messages: list[dict[str, Any]]+ model: str+ reasoning_effort: str | None+ response_format: dict[str, Any] | None = None+ tool_choice: Any = None+ continue_final_message: bool = False+++@dataclass(frozen = True)+class CodexToolPolicy:+ tools: list[dict[str, Any]]+ max_calls: int+ timeout: int+ permission_mode: str+ confirm_calls: bool+ bypass_permissions: bool+ rag_scope: dict[str, Any] | None+++async def stream_codex_with_studio_tools(+ client: OpenAICodexClient,+ *,+ run: CodexRunContext,+ policy: CodexToolPolicy,+ cancel_event: threading.Event,+) -> AsyncIterator[str]:+ """Stream Codex, execute requested Studio tools, and continue until a final answer."""+ conversation = [dict(message) for message in run.messages]+ remaining = policy.max_calls+ unlimited = remaining >= 9999+ provider_id = run.provider_id+ thread_id = run.thread_id+ session_id = run.session_id+ model = run.model+ reasoning_effort = run.reasoning_effort+ tools = policy.tools+ tool_choice = run.tool_choice if run.tool_choice is not None else "auto"+ allowed_tool_names = {+ name+ for tool in tools+ if isinstance(tool, dict)+ and isinstance(tool.get("function"), dict)+ and isinstance((name := tool["function"].get("name")), str)+ and name+ }+ tool_call_timeout = policy.timeout+ permission_mode = policy.permission_mode+ confirm_tool_calls = policy.confirm_calls+ bypass_permissions = policy.bypass_permissions+ rag_scope = policy.rag_scope++ skip_autoinject = run.continue_final_message or (+ confirm_tool_calls and not bypass_permissions and permission_mode not in ("auto", "off")+ )+ autoinject = (+ None+ if skip_autoinject+ else await asyncio.to_thread(build_rag_autoinject, conversation, rag_scope)+ )+ if autoinject:+ for event in autoinject["events"]:+ yield _sse(event)+ conversation.extend(autoinject["messages"])++ round_id = 0++ while not cancel_event.is_set():+ by_index: dict[int, dict[str, Any]] = {}+ assistant_text: list[str] = []+ reasoning_extra: dict[str, Any] | None = None+ finish_reason: str | None = None++ tools_available = tool_choice != "none" and (unlimited or remaining > 0)+ generator = client.stream(+ provider_id = provider_id,+ thread_id = thread_id,+ messages = conversation,+ model = model,+ max_tokens = None,+ reasoning_effort = reasoning_effort,+ response_format = run.response_format,+ tools = tools if tools_available else None,+ tool_choice = tool_choice if tools_available else "none",+ cancel_event = cancel_event,+ )+ async for line in generator:+ payload = _chunk_payload(line)+ if payload:+ choices = payload.get("choices")+ choice = choices[0] if isinstance(choices, list) and choices else {}+ if isinstance(choice, dict):+ delta = choice.get("delta")+ if isinstance(delta, dict):+ content = delta.get("content")+ if isinstance(content, str):+ assistant_text.append(content)+ extra = delta.get("extra_content")+ if isinstance(extra, dict):+ reasoning_extra = extra+ raw_calls = delta.get("tool_calls")+ if isinstance(raw_calls, list):+ for raw_call in raw_calls:+ if not isinstance(raw_call, dict):+ continue+ index = raw_call.get("index")+ if not isinstance(index, int):+ index = len(by_index)+ current = by_index.setdefault(+ index,+ {+ "id": "",+ "type": "function",+ "function": {"name": "", "arguments": ""},+ },+ )+ if isinstance(raw_call.get("id"), str):+ current["id"] = raw_call["id"]+ function = raw_call.get("function")+ if isinstance(function, dict):+ if isinstance(function.get("name"), str):+ current["function"]["name"] = function["name"]+ if isinstance(function.get("arguments"), str):+ current["function"]["arguments"] += function["arguments"]+ if isinstance(choice.get("finish_reason"), str):+ finish_reason = choice["finish_reason"]+ yield line++ calls = [+ normalized+ for _, call in sorted(by_index.items())+ if (normalized := _normalized_call(call)) is not None+ ]+ if finish_reason != "tool_calls" or not calls:+ return++ round_id += 1++ assistant_message: dict[str, Any] = {+ "role": "assistant",+ "content": "".join(assistant_text),+ "tool_calls": [+ {"id": call["id"], "type": "function", "function": call["function"]}+ for call in calls+ ],+ }+ if reasoning_extra:+ assistant_message["extra_content"] = reasoning_extra+ conversation.append(assistant_message)++ for call in calls:+ call_id = call["id"]+ name = call["function"]["name"]+ arguments = call["arguments"]+ allowed_call = tool_choice != "none" and name in allowed_tool_names+ has_budget = unlimited or remaining > 0+ within_budget = allowed_call and has_budget+ if within_budget and not unlimited:+ remaining -= 1+ needs_confirmation = (+ allowed_call+ and confirm_tool_calls+ and not bypass_permissions+ and permission_mode != "off"+ )+ if needs_confirmation and permission_mode == "auto":+ needs_confirmation = is_high_risk_tool_call(name, arguments)+ approval_id = new_approval_id() if needs_confirmation else ""+ decision_slot = (+ begin_tool_decision(session_id, approval_id)+ if needs_confirmation and within_budget+ else None+ )+ yield _sse(+ {+ "type": "tool_start",+ "tool_name": name,+ "tool_call_id": call_id,+ "arguments": arguments,+ "provenance": {"source": "local", "round_id": round_id},+ "approval_id": approval_id if within_budget else "",+ "awaiting_confirmation": needs_confirmation and within_budget,+ }+ )+ if not has_budget:+ result = _TOOL_BUDGET_EXHAUSTED+ elif not allowed_call:+ result = "Studio did not execute this tool call because the tool is disabled."+ else:+ try:+ decision = (+ await asyncio.to_thread(+ wait_tool_decision,+ decision_slot,+ approval_id,+ cancel_event = cancel_event,+ )+ if decision_slot is not None+ else None+ )+ if decision == "deny":+ decision_slot = None+ result = TOOL_REJECTED_MESSAGE+ else:+ decision_slot = None+ timeout = None if tool_call_timeout >= 9999 else tool_call_timeout+ try:+ result = await asyncio.to_thread(+ execute_tool,+ name,+ arguments,+ cancel_event = cancel_event,+ timeout = timeout,+ session_id = session_id,+ thread_id = thread_id,+ rag_scope = rag_scope,+ disable_sandbox = bypass_permissions,+ )+ except Exception as exc:+ if cancel_event.is_set():+ return+ result = f"Error: tool raised an exception: {exc}"+ finally:+ if decision_slot is not None:+ abort_tool_decision(decision_slot, approval_id)+ result_text = result if isinstance(result, str) else json.dumps(result)++ model_result = strip_result_for_model(result_text, name)+ yield _sse(+ {+ "type": "tool_end",+ "tool_name": name,+ "tool_call_id": call_id,+ "arguments": arguments,+ "result": result_text,+ "provenance": {"source": "local", "round_id": round_id},+ }+ )+ conversation.append(+ {+ "role": "tool",+ "tool_call_id": call_id,+ "name": name,+ "content": model_result,+ }+ )diff --git a/studio/backend/core/inference/openai_responses_shared.py b/studio/backend/core/inference/openai_responses_shared.pynew file mode 100644index 00000000000..d4c6dd79ec8--- /dev/null+++ b/studio/backend/core/inference/openai_responses_shared.py@@ -0,0 +1,114 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Shared OpenAI Responses request and SSE normalization helpers."""++from __future__ import annotations++from typing import Any+++def _normalize_schema_node(schema: Any) -> Any:+ if not isinstance(schema, dict):+ return schema++ normalized = dict(schema)+ for key in (+ "additionalProperties",+ "additionalItems",+ "contains",+ "contentSchema",+ "else",+ "if",+ "items",+ "not",+ "propertyNames",+ "then",+ "unevaluatedItems",+ "unevaluatedProperties",+ ):+ if key in normalized:+ value = normalized[key]+ if key == "items" and isinstance(value, list):+ normalized[key] = [_normalize_schema_node(item) for item in value]+ else:+ normalized[key] = _normalize_schema_node(value)++ for key in ("allOf", "anyOf", "oneOf", "prefixItems"):+ value = normalized.get(key)+ if isinstance(value, list):+ normalized[key] = [_normalize_schema_node(item) for item in value]++ for key in (+ "$defs",+ "definitions",+ "dependencies",+ "dependentSchemas",+ "patternProperties",+ "properties",+ ):+ value = normalized.get(key)+ if isinstance(value, dict):+ normalized[key] = {+ name: _normalize_schema_node(subschema) for name, subschema in value.items()+ }++ schema_type = normalized.get("type")+ if schema_type == "object" or (isinstance(schema_type, list) and "object" in schema_type):+ properties = normalized.get("properties")+ normalized["properties"] = properties if isinstance(properties, dict) else {}+ return normalized+++def normalize_function_schema(schema: Any) -> dict[str, Any]:+ """Ensure every object schema has properties, including nested combinators."""+ if not isinstance(schema, dict):+ return {"type": "object", "properties": {}}+ return _normalize_schema_node(schema)+++def responses_function_call(call_id: str, name: str, arguments: str) -> dict[str, Any]:+ return {+ "type": "function_call",+ "call_id": call_id,+ "name": name,+ "arguments": arguments,+ }+++def responses_function_output(call_id: str, output: str) -> dict[str, Any]:+ return {+ "type": "function_call_output",+ "call_id": call_id,+ "output": output,+ }+++def response_event_type(event: Any, event_name: str = "") -> str:+ """Return a validated Responses event type from JSON or the SSE event field."""+ if not isinstance(event, dict):+ raise ValueError("Responses event must be an object")+ value = event.get("type") or event_name+ if not isinstance(value, str) or not value:+ raise ValueError("Responses event type is missing")+ return value+++def responses_usage_to_chat(usage: Any) -> dict[str, Any] | None:+ """Translate Responses token usage into Chat Completions usage names."""+ if not isinstance(usage, dict):+ return None+ prompt_tokens = int(usage.get("input_tokens") or usage.get("prompt_tokens") or 0)+ completion_tokens = int(usage.get("output_tokens") or usage.get("completion_tokens") or 0)+ result: dict[str, Any] = {+ "prompt_tokens": prompt_tokens,+ "completion_tokens": completion_tokens,+ "total_tokens": int(usage.get("total_tokens") or prompt_tokens + completion_tokens),+ }+ input_details = usage.get("input_tokens_details")+ if isinstance(input_details, dict):+ result["prompt_tokens_details"] = dict(input_details)+ output_details = usage.get("output_tokens_details")+ if isinstance(output_details, dict):+ result["completion_tokens_details"] = dict(output_details)+ return resultdiff --git a/studio/backend/core/inference/providers.py b/studio/backend/core/inference/providers.pyindex 8a2e1029f98..199de1c9552 100644--- a/studio/backend/core/inference/providers.py+++ b/studio/backend/core/inference/providers.py@@ -12,6 +12,36 @@ import refrom typing import AnyPROVIDER_REGISTRY: dict[str, dict[str, Any]] = {+ "openai_codex": {+ "display_name": "ChatGPT / Codex subscription",+ "base_url": "https://chatgpt.com/backend-api",+ "default_models": [+ "gpt-5.3-codex-spark",+ "gpt-5.4",+ "gpt-5.4-mini",+ "gpt-5.5",+ "gpt-5.6-luna",+ "gpt-5.6-sol",+ "gpt-5.6-terra",+ ],+ "model_capabilities": {+ "gpt-5.3-codex-spark": {"vision": False, "studio_tools": True},+ "gpt-5.4": {"vision": True, "studio_tools": True},+ "gpt-5.4-mini": {"vision": True, "studio_tools": True},+ "gpt-5.5": {"vision": True, "studio_tools": True},+ "gpt-5.6-luna": {"vision": True, "studio_tools": True},+ "gpt-5.6-sol": {"vision": True, "studio_tools": True},+ "gpt-5.6-terra": {"vision": True, "studio_tools": True},+ },+ "supports_streaming": True,+ "supports_vision": True,+ "supports_tool_calling": True,+ "auth_kind": "chatgpt_oauth",+ "base_url_editable": False,+ "model_ids_editable": False,+ "model_list_mode": "curated",+ "notes": "Personal ChatGPT subscription via the Codex Responses endpoint.",+ },"openai": {"display_name": "OpenAI","base_url": "https://api.openai.com/v1",@@ -374,10 +404,14 @@ def list_available_providers() -> list[dict[str, Any]]:"display_name": info["display_name"],"base_url": info["base_url"],"default_models": info["default_models"],+ "model_capabilities": info.get("model_capabilities", {}),"supports_streaming": info["supports_streaming"],"supports_vision": info.get("supports_vision", False),"supports_tool_calling": info.get("supports_tool_calling", False),"model_list_mode": info.get("model_list_mode", "remote"),+ "auth_kind": info.get("auth_kind", "api_key"),+ "base_url_editable": info.get("base_url_editable", True),+ "model_ids_editable": info.get("model_ids_editable", True),})return resultdiff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.pyindex 1fe438fe793..409c6230836 100644--- a/studio/backend/core/research_runs.py+++ b/studio/backend/core/research_runs.py@@ -1143,6 +1143,9 @@ class ResearchSupervisor:"messages": messages,"stream": True,"stream_options": {"include_usage": True},+ # Keep every model hop in this durable run on one isolated Codex+ # prompt-cache session rather than sharing the transport fallback.+ "thread_id": f"research:{run['id']}",# Gathered page text lands in these prompts and research never reads tool calls# back, so this hop must stay out of the tool loop. Both opt-outs are needed:# --enable-tools overrides a per-request enable_tools, and an omitted@@ -1151,6 +1154,15 @@ class ResearchSupervisor:"enabled_tools": [],"temperature": inference.get("temperature", 0.2),}++ if inference.get("providerType") == "openai_codex":+ payload.update(+ {+ "provider_id": inference["providerId"],+ "provider_type": inference["providerType"],+ "external_model": inference["externalModel"],+ }+ )if inference.get("topP") is not None:payload["top_p"] = inference["topP"]if enable_thinking is not None:diff --git a/studio/backend/main.py b/studio/backend/main.pyindex c5398c7fde7..c0eb2de8196 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -300,6 +300,7 @@ from routes import (mcp_servers_router,models_router,providers_router,+ openai_codex_auth_router,rag_router,research_runs_router,training_history_router,@@ -764,6 +765,10 @@ async def lifespan(app: FastAPI):# Before any shutdown await: a warm finishing during one would still read the lifespan as current._stop_post_warm_thread()++ from core.inference.openai_codex_auth import shutdown_flows++ await shutdown_flows()try:from core.rag.folder_sync import stop_auto_syncstop_auto_sync()@@ -1379,6 +1384,9 @@ app.include_router(video_router, prefix = "/api/inference", tags = ["inference"]app.include_router(inference_router, prefix = "/v1", tags = ["openai-compat"])app.include_router(preview_router, prefix = "/p", tags = ["preview"])app.include_router(providers_router, prefix = "/api/providers", tags = ["providers"])++app.include_router(openai_codex_auth_router, prefix = "/api/providers", tags = ["providers"])+app.include_router(settings_router, prefix = "/api/settings", tags = ["settings"])app.include_router(mcp_servers_router, prefix = "/api/mcp/servers", tags = ["mcp"])app.include_router(prompts_router, prefix = "/api/prompts", tags = ["prompts"])diff --git a/studio/backend/models/providers.py b/studio/backend/models/providers.pyindex 84946802794..506b3ada0ba 100644--- a/studio/backend/models/providers.py+++ b/studio/backend/models/providers.py@@ -20,6 +20,8 @@ class ProviderRegistryEntry(BaseModel):default_models: list[str] = Field(default_factory = list, description = "Well-known model IDs for this provider")++ model_capabilities: dict[str, dict[str, bool]] = Field(default_factory = dict)supports_streaming: bool = Field(True, description = "Whether this provider supports SSE streaming")@@ -29,6 +31,10 @@ class ProviderRegistryEntry(BaseModel):supports_tool_calling: bool = Field(False, description = "Whether this provider supports tool/function calling")++ auth_kind: Literal["api_key", "chatgpt_oauth"] = "api_key"+ base_url_editable: bool = True+ model_ids_editable: bool = Truemodel_list_mode: Literal["remote", "curated"] = Field("remote",description = "remote = fetch /models; curated = huge catalogs — UI uses defaults + manual IDs only",@@ -104,6 +110,9 @@ class ProviderResponse(BaseModel):is_enabled: bool = Field(True, description = "Whether this provider is enabled")has_api_key: bool = Field(False, description = "Whether this caller has a saved API key")++ auth_kind: Literal["api_key", "chatgpt_oauth"] = "api_key"+ auth_status: Literal["disconnected", "connected", "reauthorization_required"] = "disconnected"models: list[str] = Field(default_factory = list,description = "Enabled model IDs for this connection",diff --git a/studio/backend/routes/__init__.py b/studio/backend/routes/__init__.pyindex ce00827fb17..c48b715af08 100644--- a/studio/backend/routes/__init__.py+++ b/studio/backend/routes/__init__.py@@ -17,6 +17,8 @@ from routes.export import router as export_routerfrom routes.training_history import router as training_history_routerfrom routes.chat_history import router as chat_history_routerfrom routes.providers import router as providers_router++from routes.openai_codex_auth import router as openai_codex_auth_routerfrom routes.mcp_servers import router as mcp_servers_routerfrom routes.rag import router as rag_routerfrom routes.research_runs import router as research_runs_router@@ -34,6 +36,7 @@ __all__ = ["training_history_router","chat_history_router","providers_router",+ "openai_codex_auth_router","mcp_servers_router","rag_router","research_runs_router",diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 4e1ee9ca67e..d18726304c1 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -10682,7 +10682,7 @@ def _build_external_messages(_native_gemini = _host == "generativelanguage.googleapis.com"except Exception:_native_gemini = False- emit_extra_content = _native_gemini+ emit_extra_content = _native_gemini or provider_type == "openai_codex"_SERVER_BUILTIN_TOOL_NAMES = frozenset({"web_search", "web_fetch", "code_execution", "image_generation"}@@ -10989,6 +10989,30 @@ async def _proxy_to_external_provider(detail = "Either provider_id or provider_type is required for external provider routing.",)+ codex_studio_tool_loop = (+ provider_type == "openai_codex" and _explicit_studio_tool_loop_requested(payload)+ )+ if (+ payload.confirm_tool_calls+ and not payload.bypass_permissions+ and not codex_studio_tool_loop+ and (+ payload.enable_tools is True+ or bool(payload.enabled_tools)+ or bool(payload.tools)+ or bool(payload.openai_code_exec_container_id)+ or bool(payload.anthropic_code_exec_container_id)+ )+ ):+ raise HTTPException(+ status_code = 400,+ detail = openai_error_body(+ "confirm_tool_calls is only supported for local streaming tools.",+ status = 400,+ code = "invalid_request_error",+ param = "confirm_tool_calls",+ ),+ )# Fall back to registry default base URLif not base_url:base_url = get_base_url(provider_type)@@ -10998,6 +11022,266 @@ async def _proxy_to_external_provider(detail = f"Unknown provider type: {provider_type}",)+ if provider_type == "openai_codex":+ from core.inference.openai_codex_auth import (+ OPENAI_CODEX_API_BASE,+ CodexAuthError,+ resolve_access,+ )+ from core.inference.openai_codex_client import (+ OpenAICodexClient,+ CodexTransportError,+ CodexQuotaError,+ CodexReauthorizationError,+ )++ api_key_token = _request_api_key_token(request)+ if api_key_token and not auth_storage.is_internal_api_key(api_key_token):+ raise HTTPException(+ status_code = 403,+ detail = "ChatGPT subscriptions are available only to Studio UI and internal workflows.",+ )+ if not payload.provider_id or payload.encrypted_api_key:+ raise HTTPException(+ status_code = 400, detail = "A saved ChatGPT subscription connection is required."+ )+ if base_url != OPENAI_CODEX_API_BASE:+ raise HTTPException(status_code = 400, detail = "ChatGPT subscription routing is fixed.")+ if payload.stream is not True:+ raise HTTPException(+ status_code = 400, detail = "ChatGPT subscription chat requires stream=true."+ )+ model = payload.external_model or payload.model+ from core.inference.providers import get_provider_info as _get_codex_provider_info++ info = _get_codex_provider_info("openai_codex") or {}+ if model not in info.get("default_models", []):+ raise HTTPException(status_code = 400, detail = "Choose a curated Codex model.")++ model_supports_vision = bool(+ info.get("model_capabilities", {}).get(model, {}).get("vision")+ )+ if not model_supports_vision:+ for message in payload.messages:+ if isinstance(message.content, list) and any(+ part.type == "image_url" for part in message.content+ ):+ raise HTTPException(+ status_code = 400,+ detail = f"{model} does not accept image input.",+ )+ try:+ access_token, account_id = await resolve_access(payload.provider_id)+ except CodexAuthError as exc:+ raise HTTPException(status_code = 401, detail = str(exc)) from exc+ chat_messages = _build_external_messages(+ payload.messages,+ model_supports_vision,+ provider_type = provider_type,+ base_url = base_url,+ )+ tool_payloads = [+ tool.model_dump(exclude_none = True) if hasattr(tool, "model_dump") else tool+ for tool in (payload.tools or [])+ ]++ studio_tool_payloads: list[dict] = []+ if _explicit_studio_tool_loop_requested(payload):+ studio_tool_payloads = await _select_request_tools(+ payload,+ tools_on = _effective_enable_tools(payload) is True,+ mcp_allowed = bool(payload.mcp_enabled),+ )+ # The Studio loop owns its schemas. Do not also expose a caller-supplied+ # catalog: Codex would return calls that this server is not authorized to run.+ tool_payloads = studio_tool_payloads+ cancel_event = threading.Event()+ cancel_keys = tuple(key for key in (payload.cancel_id, payload.session_id) if key)++ async def _codex_stream():+ current_access_token = access_token++ async def _refresh_codex_access() -> tuple[str, str]:+ nonlocal current_access_token+ current_access_token, refreshed_account_id = await resolve_access(+ payload.provider_id,+ force_refresh = True,+ expected_access_token = current_access_token,+ )+ return current_access_token, refreshed_account_id++ from core.inference.openai_codex_tool_loop import (+ CodexRunContext,+ CodexToolPolicy,+ stream_codex_with_studio_tools,+ )++ run = CodexRunContext(+ provider_id = payload.provider_id,+ thread_id = payload.thread_id,+ session_id = payload.session_id,+ messages = chat_messages,+ model = model,+ reasoning_effort = payload.reasoning_effort,+ response_format = _extract_response_format(payload),+ tool_choice = payload.tool_choice,+ continue_final_message = _continue_final_message(payload),+ )+ policy = (+ CodexToolPolicy(+ tools = studio_tool_payloads,+ max_calls = (+ payload.max_tool_calls_per_message+ if payload.max_tool_calls_per_message is not None+ else 25+ ),+ timeout = payload.tool_call_timeout or 300,+ permission_mode = payload.permission_mode or "auto",+ confirm_calls = _permission_mode_confirm(payload),+ bypass_permissions = bool(payload.bypass_permissions),+ rag_scope = payload.rag_scope,+ )+ if studio_tool_payloads+ else None+ )+ should_cancel = False+ with _CANCEL_LOCK:+ now = time.monotonic()+ _prune_pending(now)+ for key in cancel_keys:+ _CANCEL_REGISTRY.setdefault(key, set()).add(cancel_event)+ if payload.cancel_id and _PENDING_CANCELS.pop(payload.cancel_id, None) is not None:+ should_cancel = True+ if should_cancel:+ cancel_event.set()++ async def _watch_disconnect() -> None:+ while not cancel_event.is_set():+ if await request.is_disconnected():+ cancel_event.set()+ return+ await asyncio.sleep(0.1)++ disconnect_task = asyncio.create_task(_watch_disconnect())++ client = OpenAICodexClient(+ access_token,+ account_id,+ refresh_access = _refresh_codex_access,+ )+ try:+ # Closing the upstream response from the client's watcher makes+ # cancellation immediate even while no SSE line is arriving.+ generator = (+ stream_codex_with_studio_tools(+ client,+ run = run,+ policy = policy,+ cancel_event = cancel_event,+ )+ if policy+ else client.stream(+ provider_id = run.provider_id,+ thread_id = run.thread_id,+ messages = run.messages,+ model = run.model,+ max_tokens = _effective_max_tokens(payload),+ reasoning_effort = run.reasoning_effort,+ response_format = run.response_format,+ tools = tool_payloads,+ tool_choice = payload.tool_choice,+ cancel_event = cancel_event,+ )+ )+ async for line in generator:+ if cancel_event.is_set() or await request.is_disconnected():+ await generator.aclose()+ break+ yield f"{line}\n\n"+ yield "data: [DONE]\n\n"+ except asyncio.CancelledError:+ raise+ except CodexReauthorizationError as exc:+ from core.inference.openai_codex_auth import (+ mark_reauthorization_required,+ provider_oauth_write_guard,+ )++ async with provider_oauth_write_guard(payload.provider_id):+ mark_reauthorization_required(+ payload.provider_id,+ expected_access_token = exc.metadata.get("access_token"),+ )+ yield (+ "data: "+ + json.dumps({"error": {"message": str(exc), "type": "authentication_error"}})+ + "\n\n"+ )+ yield "data: [DONE]\n\n"+ except CodexQuotaError as exc:+ yield (+ "data: "+ + json.dumps(+ {+ "error": {+ "message": str(exc),+ "type": "rate_limit_error",+ "metadata": exc.metadata,+ }+ }+ )+ + "\n\n"+ )+ yield "data: [DONE]\n\n"++ except CodexTransportError as exc:+ logger.warning(+ "openai_codex.stream_failed",+ error_type = type(exc).__name__,+ status = exc.status,+ error = str(exc),+ )+ yield (+ "data: "+ + json.dumps({"error": {"message": str(exc), "type": "upstream_error"}})+ + "\n\n"+ )+ yield "data: [DONE]\n\n"++ except Exception as exc:+ logger.warning(+ "openai_codex.stream_failed",+ error_type = type(exc).__name__,+ status = getattr(exc, "status", None),+ error = str(exc),+ )+ yield (+ "data: "+ + json.dumps(+ {"error": {"message": _friendly_error(exc), "type": "server_error"}}+ )+ + "\n\n"+ )+ yield "data: [DONE]\n\n"+ finally:+ await client.close()+ disconnect_task.cancel()+ await asyncio.gather(disconnect_task, return_exceptions = True)++ with _CANCEL_LOCK:+ for key in cancel_keys:+ bucket = _CANCEL_REGISTRY.get(key)+ if bucket:+ bucket.discard(cancel_event)+ if not bucket:+ _CANCEL_REGISTRY.pop(key, None)++ return StreamingResponse(+ _codex_stream(),+ media_type = "text/event-stream",+ headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ )+api_key = resolve_provider_api_key_or_400(payload.provider_id,payload.encrypted_api_key,@@ -11434,28 +11718,6 @@ async def openai_chat_completions(from core.inference.llama_keepwarm import untrack_current_requestuntrack_current_request(request.scope)- # Bypass Permissions suppresses the confirm gate, so do not reject a- # request that sets both flags (effective confirm is then False).- if (- payload.confirm_tool_calls- and not payload.bypass_permissions- and (- payload.enable_tools is True- or bool(payload.enabled_tools)- or bool(payload.tools)- or bool(payload.openai_code_exec_container_id)- or bool(payload.anthropic_code_exec_container_id)- )- ):- raise HTTPException(- status_code = 400,- detail = openai_error_body(- "confirm_tool_calls is only supported for local streaming tools.",- status = 400,- code = "invalid_request_error",- param = "confirm_tool_calls",- ),- )if _wants_multiple_choices(payload):_raise_unsupported_n("external provider chat completions")return await _proxy_to_external_provider(payload, request, current_subject)diff --git a/studio/backend/routes/openai_codex_auth.py b/studio/backend/routes/openai_codex_auth.pynew file mode 100644index 00000000000..5f4e3d98cec--- /dev/null+++ b/studio/backend/routes/openai_codex_auth.py@@ -0,0 +1,164 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""UI-session-only lifecycle routes for ChatGPT/Codex subscription OAuth."""++import secrets+from typing import Literal++from fastapi import APIRouter, Depends, HTTPException+from pydantic import BaseModel, Field++from auth.authentication import authenticated_via_api_key, get_current_credential+from core.inference import openai_codex_auth as codex_auth+from routes.provider_credentials import current_credential_write, require_ui_session+from storage import providers_db++router = APIRouter()+++class OAuthStartRequest(BaseModel):+ method: Literal["browser", "device"]+++class OAuthCompleteRequest(BaseModel):+ callback_url: str = Field(..., min_length = 1, max_length = 8192)+++def _provider(provider_id: str) -> dict:+ row = providers_db.get_provider(provider_id)+ if row is None:+ raise HTTPException(status_code = 404, detail = "Provider not found")+ if row["provider_type"] != "openai_codex":+ raise HTTPException(+ status_code = 400, detail = "This provider does not use ChatGPT authorization."+ )+ return row+++def _safe_error(exc: Exception) -> HTTPException:+ if isinstance(exc, codex_auth.CodexAuthError):+ return HTTPException(status_code = 400, detail = str(exc))+ return HTTPException(status_code = 502, detail = "ChatGPT authorization failed. Please retry.")+++def _bundle_persister(credential: tuple, marker: str):+ async def persist(scope_id: str, bundle: dict) -> None:+ async with codex_auth.provider_oauth_write_guard(scope_id):+ with current_credential_write(credential):+ _provider(scope_id)+ if not codex_auth.oauth_flow_marker_matches(scope_id, marker):+ raise codex_auth.CodexAuthError("Authorization flow is no longer active.")+ codex_auth.save_oauth_bundle(scope_id, bundle)+ codex_auth.set_oauth_flow_marker_status(scope_id, marker, "connected")++ return persist++[email protected]("/{provider_id}/oauth/start")+async def start_oauth(+ provider_id: str,+ payload: OAuthStartRequest,+ credential: tuple = Depends(get_current_credential),+ via_api_key: bool = Depends(authenticated_via_api_key),+):+ require_ui_session(via_api_key)+ _provider(provider_id)+ codex_auth.credential_secrets.get_or_create_credential_encryption_key()+ marker = secrets.token_urlsafe(32)++ guarded_persist = _bundle_persister(credential, marker)+ flow = None+ try:+ async with codex_auth.provider_oauth_write_guard(provider_id):+ with current_credential_write(credential):+ codex_auth.save_oauth_flow_marker(provider_id, marker)+ flow = await codex_auth.start_flow(provider_id, payload.method, guarded_persist, marker)+ async with codex_auth.provider_oauth_write_guard(provider_id):+ with current_credential_write(credential):+ if codex_auth.oauth_flow_marker_matches(provider_id, marker):+ codex_auth.save_oauth_flow_marker(provider_id, marker, flow)+ return codex_auth.safe_flow(flow)+ except Exception as exc:+ if flow is not None:+ await codex_auth.cancel_flow(flow.id)+ try:+ async with codex_auth.provider_oauth_write_guard(provider_id):+ with current_credential_write(credential):+ codex_auth.delete_oauth_flow_marker(provider_id, marker)+ except codex_auth.CodexAuthError:+ pass+ raise _safe_error(exc) from exc++[email protected]("/{provider_id}/oauth/flows/{flow_id}")+async def oauth_status(+ provider_id: str,+ flow_id: str,+ _credential: tuple = Depends(get_current_credential),+ via_api_key: bool = Depends(authenticated_via_api_key),+):+ require_ui_session(via_api_key)+ _provider(provider_id)+ try:+ return codex_auth.safe_flow(codex_auth.get_flow(provider_id, flow_id))+ except Exception as exc:+ raise _safe_error(exc) from exc++[email protected]("/{provider_id}/oauth/flows/{flow_id}/complete")+async def complete_oauth(+ provider_id: str,+ flow_id: str,+ payload: OAuthCompleteRequest,+ credential: tuple = Depends(get_current_credential),+ via_api_key: bool = Depends(authenticated_via_api_key),+):+ require_ui_session(via_api_key)+ _provider(provider_id)+ try:+ flow = codex_auth.get_flow(provider_id, flow_id)+ if flow.persist_bundle is None:+ flow.persist_bundle = _bundle_persister(credential, flow.marker)+ flow = await codex_auth.complete_browser_flow(provider_id, flow_id, payload.callback_url)+ return codex_auth.safe_flow(flow)+ except Exception as exc:+ raise _safe_error(exc) from exc++[email protected]("/{provider_id}/oauth/flows/{flow_id}", status_code = 204)+async def cancel_oauth(+ provider_id: str,+ flow_id: str,+ credential: tuple = Depends(get_current_credential),+ via_api_key: bool = Depends(authenticated_via_api_key),+):+ require_ui_session(via_api_key)+ _provider(provider_id)+ try:+ flow = codex_auth.get_flow(provider_id, flow_id)+ # Closing a loopback server can wait for an in-flight callback. Do not+ # hold the credential guard while waiting for that handler to finish.+ await codex_auth.cancel_flow(flow.id)+ async with codex_auth.provider_oauth_write_guard(provider_id):+ with current_credential_write(credential):+ codex_auth.delete_oauth_flow_marker(provider_id, flow.marker)+ except Exception as exc:+ raise _safe_error(exc) from exc++[email protected]("/{provider_id}/oauth", status_code = 204)+async def delete_oauth(+ provider_id: str,+ credential: tuple = Depends(get_current_credential),+ via_api_key: bool = Depends(authenticated_via_api_key),+):+ require_ui_session(via_api_key)+ _provider(provider_id)+ codex_auth.credential_secrets.get_or_create_credential_encryption_key()++ await codex_auth.cancel_provider_flows(provider_id)+ async with codex_auth.provider_oauth_write_guard(provider_id):+ with current_credential_write(credential):+ codex_auth.delete_oauth_bundle(provider_id)+ codex_auth.delete_oauth_flow_marker(provider_id)diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.pyindex 9105b9d2cd0..0e91d1d5c83 100644--- a/studio/backend/routes/providers.py+++ b/studio/backend/routes/providers.py@@ -38,6 +38,8 @@ from core.inference.providers import ()from core.inference.pricing import pricing_snapshotfrom core.inference.external_provider import ExternalProviderClient++from core.inference import openai_codex_authfrom models.providers import (ProviderCreate,ProviderCredentialMigration,@@ -68,6 +70,18 @@ def _provider_response(row: dict) -> ProviderResponse:credential_secrets.PROVIDER_API_KEY_KIND,row["id"],),+ auth_kind = ("chatgpt_oauth" if row["provider_type"] == "openai_codex" else "api_key"),+ auth_status = (+ openai_codex_auth.auth_status(row["id"])+ if row["provider_type"] == "openai_codex"+ else (+ "connected"+ if credential_secrets.has_secret(+ credential_secrets.PROVIDER_API_KEY_KIND, row["id"]+ )+ else "disconnected"+ )+ ),models = row.get("models") or [],available_models = row.get("available_models") or [],created_at = row["created_at"],@@ -75,6 +89,25 @@ def _provider_response(row: dict) -> ProviderResponse:)+def _validate_provider_auth_contract(+ info: dict,+ *,+ encrypted_api_key: str | None,+ base_url: str | None,+ models: list[str] | None,+ updating: bool,+ clear_api_key: bool = False,+) -> None:+ if info.get("auth_kind") != "chatgpt_oauth":+ return+ if encrypted_api_key or clear_api_key:+ raise HTTPException(status_code = 400, detail = "ChatGPT subscriptions do not use API keys.")+ if base_url is not None and (not updating or base_url != info["base_url"]):+ raise HTTPException(status_code = 400, detail = "ChatGPT subscription routing is fixed.")+ if models is not None and (not models or not set(models).issubset(set(info["default_models"]))):+ raise HTTPException(status_code = 400, detail = "Choose only curated Codex models.")++# ── Public key for API key encryption ─────────────────────────────@@ -137,6 +170,14 @@ async def create_provider_config(f"Use GET /api/providers/registry to see available types.",)+ _validate_provider_auth_contract(+ info,+ encrypted_api_key = payload.encrypted_api_key,+ base_url = payload.base_url,+ models = payload.models,+ updating = False,+ )+api_key = resolve_provider_api_key_or_400(None, payload.encrypted_api_key)provider_id = uuid.uuid4().hex[:16]base_url = payload.base_url or info["base_url"]@@ -177,6 +218,16 @@ async def update_provider_config(if not existing:raise HTTPException(status_code = 404, detail = "Provider not found")+ existing_info = get_provider_info(existing["provider_type"]) or {}+ _validate_provider_auth_contract(+ existing_info,+ encrypted_api_key = payload.encrypted_api_key,+ base_url = payload.base_url,+ models = payload.models,+ updating = True,+ clear_api_key = payload.clear_api_key,+ )+if payload.clear_api_key and payload.encrypted_api_key:raise HTTPException(status_code = 400,@@ -264,23 +315,50 @@ async def delete_provider_config():"""Idempotently delete a saved provider and its installation credential."""require_ui_session(via_api_key)-- # Decryption must not open the auth DB after the generation guard locks it.+ await openai_codex_auth.cancel_provider_flows(provider_id)credential_secrets.get_or_create_credential_encryption_key()- with current_credential_write(credential):- existing_api_key = credential_secrets.get_provider_api_key(provider_id)- credential_secrets.delete_provider_api_key(provider_id)- try:- providers_db.delete_provider(provider_id)- except Exception:- if existing_api_key:++ async with openai_codex_auth.provider_oauth_write_guard(provider_id):+ with current_credential_write(credential):+ existing_api_key = credential_secrets.get_provider_api_key(provider_id)+ existing_oauth = credential_secrets.get_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_KIND, provider_id+ )++ existing_oauth_flow = credential_secrets.get_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_FLOW_KIND, provider_id+ )+ credential_secrets.delete_provider_api_key(provider_id)+ credential_secrets.delete_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_KIND, provider_id+ )+ credential_secrets.delete_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_FLOW_KIND, provider_id+ )+ try:+ providers_db.delete_provider(provider_id)+ except Exception:try:- credential_secrets.save_provider_api_key(provider_id, existing_api_key)+ if existing_api_key:+ credential_secrets.save_provider_api_key(provider_id, existing_api_key)+ if existing_oauth:+ credential_secrets.upsert_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_KIND,+ provider_id,+ existing_oauth,+ )++ if existing_oauth_flow:+ credential_secrets.upsert_secret(+ credential_secrets.OPENAI_CODEX_OAUTH_FLOW_KIND,+ provider_id,+ existing_oauth_flow,+ )except Exception:logger.exception("provider.delete_credential_rollback_failed", provider_id = provider_id)- raise+ raisedef _bind_saved_provider_target(payload):diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.pyindex f0e43ba5bd8..c8b3626acaf 100644--- a/studio/backend/routes/research_runs.py+++ b/studio/backend/routes/research_runs.py@@ -21,6 +21,7 @@ from auth.authentication import get_current_subjectfrom core.inference.message_content import content_to_textfrom core.inference.web_access_policy import normalize_website_policyfrom storage import research_runs_db as db+from storage import providers_dbfrom storage.studio_db import get_chat_message, get_chat_thread, upsert_chat_messagerouter = APIRouter()@@ -177,10 +178,13 @@ def _sanitize_config(payload: CreateResearchRun, thread: dict) -> dict:if any(key in request for key in ("baseUrl", "endpoint", "provider", "tools", "enabledTools")):raise HTTPException(status_code = 400,- detail = "Durable research currently supports only the selected local Studio model",+ detail = "Research inference routing cannot override endpoints or tool catalogs",)allowed = {"model",+ "providerId",+ "providerType",+ "externalModel","temperature","topP","maxTokens",@@ -193,6 +197,33 @@ def _sanitize_config(payload: CreateResearchRun, thread: dict) -> dict:status_code = 400,detail = f"Unsupported inferenceRequest fields: {', '.join(sorted(unknown))}",)+ provider_type = request.get("providerType")+ provider_id = request.get("providerId")+ external_model = request.get("externalModel")+ external_requested = any(+ value is not None for value in (provider_type, provider_id, external_model)+ )+ if external_requested:+ if (+ provider_type != "openai_codex"+ or not isinstance(provider_id, str)+ or not provider_id.strip()+ or not isinstance(external_model, str)+ or not external_model.strip()+ ):+ raise HTTPException(+ status_code = 400,+ detail = "Durable research supports only a saved ChatGPT/Codex connection",+ )+ provider = providers_db.get_provider(provider_id)+ if provider is None:+ raise HTTPException(status_code = 404, detail = "Provider config not found")+ if provider["provider_type"] != "openai_codex" or not provider["is_enabled"]:+ raise HTTPException(+ status_code = 400,+ detail = "Durable research requires an enabled ChatGPT/Codex connection",+ )+# Mirrors the ragScope guard below. Every allowed field is a scalar, but "model" is# stringified, so {"auth": "sk-..."} would slip past the sensitive-key scan (inner key# unlisted) into the durable config as the model id.diff --git a/studio/backend/storage/credential_secrets.py b/studio/backend/storage/credential_secrets.pyindex 62ca68dcc56..62de4acd4ec 100644--- a/studio/backend/storage/credential_secrets.py+++ b/studio/backend/storage/credential_secrets.py@@ -27,6 +27,10 @@ logger = logging.getLogger(__name__)HF_TOKEN_KIND = "hf_token"HF_TOKEN_SCOPE = "default"PROVIDER_API_KEY_KIND = "provider_api_key"++OPENAI_CODEX_OAUTH_KIND = "openai_codex_oauth"++OPENAI_CODEX_OAUTH_FLOW_KIND = "openai_codex_oauth_flow"_FORMAT_VERSION = 1_NONCE_BYTES = 12diff --git a/studio/backend/tests/test_openai_codex_subscription.py b/studio/backend/tests/test_openai_codex_subscription.pynew file mode 100644index 00000000000..a1a2bb8059c--- /dev/null+++ b/studio/backend/tests/test_openai_codex_subscription.py@@ -0,0 +1,1180 @@+# 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 base64++from contextlib import asynccontextmanager, contextmanager++import importlib.util++import inspect+from pathlib import Path+import sys++import threading+from types import ModuleType+import asyncio+import hashlib+import json+import time++import pytest++from core.inference import openai_codex_auth as codex_auth+++from core.inference.openai_codex_auth import (+ OPENAI_CODEX_API_BASE,+ OPENAI_CODEX_DEVICE_REDIRECT_URI,+ OPENAI_CODEX_CLIENT_ID,+ OAuthFlow,+ _validate_token_payload,+ create_pkce,+ extract_chatgpt_account_id,+ safe_flow,+)+from core.inference.openai_codex_client import (+ CodexReauthorizationError,+ CodexTransportError,+ OpenAICodexClient,+ _responses_input,+)++from core.inference.openai_responses_shared import normalize_function_schema+from core.inference.providers import get_provider_info, list_available_providers+++def _jwt(payload: dict) -> str:+ encoded = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")+ return f"header.{encoded}.signature"+++def test_protocol_constants_and_curated_provider_contract():+ assert OPENAI_CODEX_CLIENT_ID == "app_EMoamEEZ73f0CkXaXp7hrann"+ info = get_provider_info("openai_codex")+ assert info["base_url"] == OPENAI_CODEX_API_BASE+ assert info["auth_kind"] == "chatgpt_oauth"+ assert info["model_list_mode"] == "curated"+ assert info["base_url_editable"] is False+ assert info["model_ids_editable"] is False+ assert info["default_models"] == [+ "gpt-5.3-codex-spark",+ "gpt-5.4",+ "gpt-5.4-mini",+ "gpt-5.5",+ "gpt-5.6-luna",+ "gpt-5.6-sol",+ "gpt-5.6-terra",+ ]+ assert OPENAI_CODEX_DEVICE_REDIRECT_URI == ("https://auth.openai.com/deviceauth/callback")+ row = next(+ item for item in list_available_providers() if item["provider_type"] == "openai_codex"+ )+ assert row["auth_kind"] == "chatgpt_oauth"+++def test_provider_lock_can_release_from_another_executor_thread():+ lock = codex_auth._provider_file_lock("provider")+ assert lock.is_thread_local() is False+++def test_pkce_uses_s256_and_high_entropy_verifier():+ verifier, challenge = create_pkce()+ expected = (+ base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")+ )+ assert len(verifier) >= 43+ assert challenge == expected+ assert create_pkce()[0] != verifier+++def test_account_claim_and_token_response_are_validated_without_returning_raw_body():+ token = _jwt({"https://api.openai.com/auth": {"chatgpt_account_id": "acct-1"}})+ assert extract_chatgpt_account_id(token) == "acct-1"+ bundle = _validate_token_payload(+ {"access_token": token, "refresh_token": "refresh", "expires_in": 600}+ )+ assert bundle["account_id"] == "acct-1"+ assert bundle["expires_at"] > time.time()+ with pytest.raises(Exception, match = "invalid access token"):+ extract_chatgpt_account_id("not-a-jwt")+++def test_safe_flow_never_exposes_pkce_state_or_device_identifier():+ flow = OAuthFlow(+ id = "opaque",+ provider_id = "provider",+ method = "browser",+ created_at = 1,+ expires_at = 2,+ state = "secret-state",+ verifier = "secret-verifier",+ device_auth_id = "secret-device",+ authorization_url = "https://auth.openai.com/oauth/authorize",+ )+ serialized = json.dumps(safe_flow(flow))+ assert "opaque" in serialized+ assert "secret-state" not in serialized+ assert "secret-verifier" not in serialized+ assert "secret-device" not in serialized+++def test_responses_conversion_replays_only_opaque_reasoning_and_normalizes_tools():+ instructions, items = _responses_input(+ [+ {"role": "system", "content": "User system prompt"},+ {+ "role": "assistant",+ "content": "visible",+ "extra_content": {+ "openai_codex_reasoning": [+ {+ "type": "reasoning",+ "id": "r1",+ "encrypted_content": "opaque",+ "summary": [],+ },+ {"type": "reasoning", "id": "bad"},+ ]+ },+ },+ {"role": "user", "content": "next"},+ ]+ )+ assert "User system prompt" in instructions+ assert any(item.get("encrypted_content") == "opaque" for item in items)+ assert not any(item.get("id") == "bad" for item in items)+ user_item = next(item for item in items if item.get("role") == "user")+ assert user_item["content"] == [{"type": "input_text", "text": "next"}]+ assistant_item = next(item for item in items if item.get("type") == "message")+ assert assistant_item["content"] == [+ {"type": "output_text", "text": "visible", "annotations": []}+ ]+ schema = normalize_function_schema(+ {"type": "object", "properties": {"nested": {"type": "object"}}}+ )+ assert schema["properties"]["nested"]["properties"] == {}++ combinators = normalize_function_schema(+ {+ "type": "object",+ "$defs": {"row": {"type": "object"}},+ "properties": {+ "choice": {+ "anyOf": [+ {"type": "object"},+ {"type": "array", "items": {"type": "object"}},+ ]+ }+ },+ }+ )+ assert combinators["$defs"]["row"]["properties"] == {}+ assert combinators["properties"]["choice"]["anyOf"][0]["properties"] == {}+ assert combinators["properties"]["choice"]["anyOf"][1]["items"]["properties"] == {}+++def test_responses_conversion_stably_shortens_oversized_tool_call_ids():+ oversized = "call_" + "x" * 70+ _, items = _responses_input(+ [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": oversized,+ "type": "function",+ "function": {"name": "python", "arguments": "{}"},+ }+ ],+ },+ {"role": "tool", "tool_call_id": oversized, "content": "done"},+ ]+ )++ call = next(item for item in items if item.get("type") == "function_call")+ output = next(item for item in items if item.get("type") == "function_call_output")+ assert len(call["call_id"]) == 64+ assert call["call_id"] == output["call_id"]+ assert call["call_id"].startswith(oversized[:31] + "_")+++def test_cancelled_oauth_exchange_cannot_persist_credentials(monkeypatch):+ persisted = []+ flow = OAuthFlow(+ id = "flow-cancelled",+ provider_id = "provider",+ method = "browser",+ created_at = time.time(),+ expires_at = time.time() + 60,+ persist_bundle = lambda _provider, bundle: persisted.append(bundle),+ )+ token = _jwt({"https://api.openai.com/auth": {"chatgpt_account_id": "acct-1"}})++ async def token_request(_data):+ flow.status = "cancelled"+ return {"access_token": token, "refresh_token": "refresh", "expires_in": 600}++ monkeypatch.setattr(codex_auth, "_token_request", token_request)+ with pytest.raises(codex_auth.CodexAuthError, match = "cancelled"):+ asyncio.run(codex_auth._exchange_code(flow, "code"))+ assert persisted == []+++def test_successful_callback_does_not_wait_for_its_own_connection(monkeypatch):+ class Server:+ closed = False++ def close(self):+ self.closed = True++ async def wait_closed(self):+ raise AssertionError("callback must respond before active connections close")++ server = Server()+ persisted = []+ flow = OAuthFlow(+ id = "flow-success",+ provider_id = "provider",+ method = "browser",+ created_at = time.time(),+ expires_at = time.time() + 60,+ persist_bundle = lambda _provider, bundle: persisted.append(bundle),+ server = server,+ )+ token = _jwt({"https://api.openai.com/auth": {"chatgpt_account_id": "acct-1"}})++ async def token_request(_data):+ return {"access_token": token, "refresh_token": "refresh", "expires_in": 600}++ monkeypatch.setattr(codex_auth, "_token_request", token_request)+ asyncio.run(codex_auth._exchange_code(flow, "code"))++ assert flow.status == "connected"+ assert flow.server is None+ assert server.closed is True+ assert len(persisted) == 1+++def test_fixed_host_transport_sends_subscription_headers_and_normalizes_sse():+ captured = {}++ class FakeResponse:+ status_code = 200++ async def aiter_lines(self):+ yield 'data: {"type":"response.output_text.delta","delta":"hello"}'+ yield 'data: {"type":"response.completed","response":{"usage":{"input_tokens":2,"output_tokens":1}}}'+ yield "data: [DONE]"++ class FakeStream:+ async def __aenter__(self):+ return FakeResponse()++ async def __aexit__(self, *_args):+ return False++ class FakeClient:+ def stream(self, method, url, **kwargs):+ captured.update(method = method, url = url, **kwargs)+ return FakeStream()++ async def aclose(self):+ return None++ async def run():+ client = OpenAICodexClient("secret-token", "acct-1")+ await client._client.aclose()+ client._client = FakeClient()+ lines = [+ line+ async for line in client.stream(+ provider_id = "provider-1",+ thread_id = "thread-1",+ messages = [{"role": "user", "content": "hello"}],+ model = "gpt-5.4",+ max_tokens = 100,+ reasoning_effort = "none",+ tools = None,+ tool_choice = None,+ )+ ]+ await client.close()+ return lines++ lines = asyncio.run(run())+ assert captured["url"] == "https://chatgpt.com/backend-api/codex/responses"+ assert captured["headers"]["originator"] == "unsloth_studio"+ assert captured["headers"]["chatgpt-account-id"] == "acct-1"+ assert captured["headers"]["Authorization"] == "Bearer secret-token"+ assert captured["headers"]["session-id"]+ assert captured["json"]["store"] is False+ assert "max_output_tokens" not in captured["json"]++ assert captured["json"]["reasoning"] == {"effort": "none", "summary": "auto"}+ assert captured["json"]["include"] == ["reasoning.encrypted_content"]+ assert any("hello" in line for line in lines)+ assert not any("secret-token" in line for line in lines)+++def test_browser_state_mismatch_does_not_consume_flow(monkeypatch):+ persisted = []+ flow = OAuthFlow(+ id = "flow",+ provider_id = "provider",+ method = "browser",+ created_at = time.time(),+ expires_at = time.time() + 60,+ state = "expected-state",+ verifier = "secret-verifier",+ redirect_uri = "http://127.0.0.1:1455/auth/callback",+ persist_bundle = lambda _provider, bundle: persisted.append(bundle),+ )+ monkeypatch.setitem(codex_auth._flows, flow.id, flow)+ token = _jwt({"https://api.openai.com/auth": {"chatgpt_account_id": "acct-1"}})++ async def token_request(data):+ assert data["code_verifier"] == "secret-verifier"+ return {"access_token": token, "refresh_token": "refresh", "expires_in": 600}++ monkeypatch.setattr(codex_auth, "_token_request", token_request)+ with pytest.raises(codex_auth.CodexAuthError, match = "state"):+ asyncio.run(+ codex_auth.complete_browser_flow(+ "provider",+ "flow",+ "http://127.0.0.1:1455/auth/callback?code=bad&state=wrong",+ )+ )+ assert flow.status == "pending"+ assert flow.consumed is False++ asyncio.run(+ codex_auth.complete_browser_flow(+ "provider",+ "flow",+ "http://127.0.0.1:1455/auth/callback?code=good&state=expected-state",+ )+ )+ assert flow.status == "connected"+ assert len(persisted) == 1+ with pytest.raises(codex_auth.CodexAuthError, match = "no longer active"):+ asyncio.run(+ codex_auth.complete_browser_flow(+ "provider",+ "flow",+ "http://127.0.0.1:1455/auth/callback?code=replay&state=expected-state",+ )+ )+++def test_device_poll_shape_structured_pending_slow_down_and_exchange(monkeypatch):+ poll_bodies = []+ sleeps = []+ responses = [+ (400, {"error": {"code": "deviceauth_authorization_pending"}}),+ (400, {"error": "slow_down"}),+ (200, {"authorization_code": "auth-code", "code_verifier": "device-verifier"}),+ ]++ class FakeResponse:+ def __init__(self, status_code, body):+ self.status_code = status_code+ self._body = body++ def json(self):+ return self._body++ class FakeClient:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return False++ async def post(self, _url, *, json):+ poll_bodies.append(json)+ status, body = responses.pop(0)+ return FakeResponse(status, body)++ async def fake_sleep(delay):+ sleeps.append(delay)++ exchange_data = {}+ token = _jwt({"https://api.openai.com/auth": {"chatgpt_account_id": "acct-1"}})++ async def token_request(data):+ exchange_data.update(data)+ return {"access_token": token, "refresh_token": "refresh", "expires_in": 600}++ persisted = []+ flow = OAuthFlow(+ id = "device-flow",+ provider_id = "provider",+ method = "device",+ created_at = time.time(),+ expires_at = time.time() + 60,+ device_auth_id = "device-id",+ user_code = "USER-CODE",+ interval = 1,+ redirect_uri = OPENAI_CODEX_DEVICE_REDIRECT_URI,+ persist_bundle = lambda _provider, bundle: persisted.append(bundle),+ )+ monkeypatch.setattr(codex_auth.httpx, "AsyncClient", lambda **_kwargs: FakeClient())+ monkeypatch.setattr(codex_auth.asyncio, "sleep", fake_sleep)+ monkeypatch.setattr(codex_auth, "_token_request", token_request)++ asyncio.run(codex_auth._device_poll(flow))+ assert poll_bodies == [+ {"device_auth_id": "device-id", "user_code": "USER-CODE"},+ {"device_auth_id": "device-id", "user_code": "USER-CODE"},+ {"device_auth_id": "device-id", "user_code": "USER-CODE"},+ ]+ assert sleeps == [1, 1, 6]+ assert exchange_data["code"] == "auth-code"+ assert exchange_data["code_verifier"] == "device-verifier"+ assert exchange_data["redirect_uri"] == OPENAI_CODEX_DEVICE_REDIRECT_URI+ assert flow.status == "connected"+ assert len(persisted) == 1+++def test_device_poll_persists_terminal_error_for_other_workers(monkeypatch):+ record = {+ "marker": "marker",+ "flow_id": "device-error",+ "method": "device",+ "created_at": time.time(),+ "expires_at": time.time() + 60,+ "state": "secret-state",+ "verifier": "secret-verifier",+ "device_auth_id": "device-id",+ "user_code": "USER-CODE",+ "status": "pending",+ "message": "",+ }++ class FakeResponse:+ status_code = 400++ def json(self):+ return {"error": {"code": "access_denied"}}++ class FakeClient:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return False++ async def post(self, *_args, **_kwargs):+ return FakeResponse()++ async def fake_sleep(_delay):+ return None++ @asynccontextmanager+ async def oauth_guard(_provider_id):+ yield++ def upsert(_kind, _provider_id, value):+ record.clear()+ record.update(json.loads(value))++ flow = OAuthFlow(+ id = "device-error",+ provider_id = "provider",+ method = "device",+ created_at = record["created_at"],+ expires_at = record["expires_at"],+ device_auth_id = "device-id",+ user_code = "USER-CODE",+ interval = 1,+ marker = "marker",+ )+ monkeypatch.setattr(codex_auth.httpx, "AsyncClient", lambda **_kwargs: FakeClient())+ monkeypatch.setattr(codex_auth.asyncio, "sleep", fake_sleep)+ monkeypatch.setattr(codex_auth, "provider_oauth_write_guard", oauth_guard)+ monkeypatch.setattr(codex_auth, "_oauth_flow_record", lambda _provider: record.copy())+ monkeypatch.setattr(codex_auth.credential_secrets, "upsert_secret", upsert)++ asyncio.run(codex_auth._device_poll(flow))++ assert flow.status == "error"+ assert record["status"] == "error"+ assert record["message"] == flow.message+ assert all(not record[key] for key in ("state", "verifier", "device_auth_id", "user_code"))+ persisted = codex_auth._load_persisted_oauth_flow("provider", flow.id)+ assert persisted is not None+ assert persisted.status == "error"+ assert persisted.message == flow.message+++def test_expired_refreshable_bundle_stays_connected_and_reconnect_marker_is_sanitized(monkeypatch):+ bundle = {+ "access_token": "secret-access",+ "refresh_token": "secret-refresh",+ "expires_at": time.time() - 10,+ "account_id": "secret-account",+ }+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _provider: bundle)+ assert codex_auth.auth_status("provider") == "connected"+ bundle["reauthorization_required"] = True+ assert codex_auth.auth_status("provider") == "reauthorization_required"+ assert "secret" not in codex_auth.auth_status("provider")+++def test_oauth_start_captures_generation_guarded_persistence(monkeypatch):+ routes_package = ModuleType("routes")+ routes_package.__path__ = []+ provider_credentials = ModuleType("routes.provider_credentials")+ provider_credentials.current_credential_write = lambda _credential: contextmanager(+ lambda: (yield)+ )()+ provider_credentials.require_ui_session = lambda _via_api_key: None+ monkeypatch.setitem(sys.modules, "routes", routes_package)+ monkeypatch.setitem(sys.modules, "routes.provider_credentials", provider_credentials)+ route_path = Path(__file__).parents[1] / "routes" / "openai_codex_auth.py"+ spec = importlib.util.spec_from_file_location("codex_auth_route_under_test", route_path)+ assert spec is not None and spec.loader is not None+ auth_route = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(auth_route)++ seen = []+ markers = {}+ monkeypatch.setattr(+ auth_route, "_provider", lambda _provider: {"provider_type": "openai_codex"}+ )+ monkeypatch.setattr(+ codex_auth.credential_secrets,+ "get_or_create_credential_encryption_key",+ lambda: seen.append("warmed"),+ )++ @contextmanager+ def guard(credential):+ seen.append(("guard", credential))+ yield++ @asynccontextmanager+ async def oauth_guard(_provider_id):+ yield++ monkeypatch.setattr(auth_route, "current_credential_write", guard)+ monkeypatch.setattr(codex_auth, "provider_oauth_write_guard", oauth_guard)+ monkeypatch.setattr(+ codex_auth,+ "save_oauth_flow_marker",+ lambda scope, marker, _flow = None: markers.__setitem__(scope, marker),+ )++ monkeypatch.setattr(+ codex_auth,+ "set_oauth_flow_marker_status",+ lambda scope, marker, _status: markers.pop(scope, None)+ if markers.get(scope) == marker+ else None,+ )+ monkeypatch.setattr(+ codex_auth,+ "oauth_flow_marker_matches",+ lambda scope, marker: markers.get(scope) == marker,+ )+ monkeypatch.setattr(+ codex_auth,+ "delete_oauth_flow_marker",+ lambda scope, marker = None: markers.pop(scope, None)+ if marker is None or markers.get(scope) == marker+ else None,+ )+ monkeypatch.setattr(+ codex_auth,+ "save_oauth_bundle",+ lambda scope, bundle: seen.append((scope, bundle)),+ )++ async def fake_start(provider_id, method, persist, marker):+ assert seen[0] == "warmed"+ assert inspect.iscoroutinefunction(persist)++ assert markers[provider_id] == marker+ await persist(provider_id, {"access_token": "not-returned"})+ return OAuthFlow(+ id = "opaque",+ provider_id = provider_id,+ method = method,+ created_at = 1,+ expires_at = 2,+ marker = marker,+ )++ monkeypatch.setattr(codex_auth, "start_flow", fake_start)+ result = asyncio.run(+ auth_route.start_oauth(+ "provider",+ auth_route.OAuthStartRequest(method = "browser"),+ credential = ("alice", "generation-1"),+ via_api_key = False,+ )+ )+ assert result["flow_id"] == "opaque"+ assert ("guard", ("alice", "generation-1")) in seen+ assert any(item[0] == "provider" for item in seen if isinstance(item, tuple))+ assert markers == {}+ assert "not-returned" not in json.dumps(result)+++ "stream_lines",+ [+ ['data: {"type":"response.output_text.delta","delta":"partial"}'],+ ["data: {not-json}"],+ ['data: {"type":"response.output_text.delta","delta":42}'],+ ],+)+def test_malformed_or_truncated_stream_fails_without_token_leak(stream_lines):+ class FakeResponse:+ status_code = 200++ async def aiter_lines(self):+ for line in stream_lines:+ yield line++ class FakeStream:+ async def __aenter__(self):+ return FakeResponse()++ async def __aexit__(self, *_args):+ return False++ class FakeClient:+ def stream(self, *_args, **_kwargs):+ return FakeStream()++ async def aclose(self):+ return None++ async def run():+ client = OpenAICodexClient("super-secret-token", "acct-1")+ await client._client.aclose()+ client._client = FakeClient()+ try:+ return [+ line+ async for line in client.stream(+ provider_id = "provider",+ thread_id = "thread",+ messages = [{"role": "user", "content": "hello"}],+ model = "gpt-5.4",+ max_tokens = None,+ reasoning_effort = None,+ tools = None,+ tool_choice = None,+ )+ ]+ finally:+ await client.close()++ with pytest.raises(RuntimeError) as error:+ asyncio.run(run())+ assert "super-secret-token" not in str(error.value)+++def test_structured_upstream_error_is_actionable_and_bounded():+ class FakeStream:+ async def __aenter__(self):+ return __import__("httpx").Response(+ 400,+ json = {+ "error": {"code": "invalid_request", "message": "Unsupported request field."}+ },+ )++ async def __aexit__(self, *_args):+ return False++ class FakeClient:+ def stream(self, *_args, **_kwargs):+ return FakeStream()++ async def aclose(self):+ return None++ async def run():+ client = OpenAICodexClient("secret-token", "acct-1")+ await client._client.aclose()+ client._client = FakeClient()+ try:+ return [+ line+ async for line in client.stream(+ provider_id = "provider",+ thread_id = "thread",+ messages = [{"role": "user", "content": "hello"}],+ model = "gpt-5.4",+ max_tokens = None,+ reasoning_effort = None,+ tools = None,+ tool_choice = None,+ )+ ]+ finally:+ await client.close()++ with pytest.raises(CodexTransportError) as error:+ asyncio.run(run())+ assert error.value.status == 400+ assert "Unsupported request field" in str(error.value)+ assert "secret-token" not in str(error.value)+++def test_client_never_emits_done_marker_itself():+ # The route owns the one Chat-Completions [DONE] marker.+ assert not any("[DONE]" in line for line in asyncio.run(_successful_stream_lines()))+++async def _successful_stream_lines():+ class Response:+ status_code = 200++ async def aiter_lines(self):+ yield 'data: {"type":"response.completed","response":{}}'+ yield "data: [DONE]"++ class Stream:+ async def __aenter__(self):+ return Response()++ async def __aexit__(self, *_args):+ return False++ class Client:+ def stream(self, *_args, **_kwargs):+ return Stream()++ async def aclose(self):+ return None++ client = OpenAICodexClient("secret", "account")+ await client._client.aclose()+ client._client = Client()+ try:+ return [+ line+ async for line in client.stream(+ provider_id = "provider",+ thread_id = None,+ messages = [{"role": "user", "content": "hello"}],+ model = "gpt-5.4",+ max_tokens = None,+ reasoning_effort = None,+ tools = None,+ tool_choice = None,+ )+ ]+ finally:+ await client.close()+++def test_browser_no_bind_fallback_keeps_registered_manual_redirect(monkeypatch):+ attempted = []++ async def no_bind(_handler, host, port):+ attempted.append((host, port))+ raise OSError("busy")++ monkeypatch.setattr(codex_auth.asyncio, "start_server", no_bind)+ flow = asyncio.run(codex_auth._start_browser_flow("provider", lambda *_args: None))+ assert attempted == [("127.0.0.1", 1455)]+ assert flow.server is None+ assert flow.redirect_uri == "http://localhost:1455/auth/callback"+ assert "redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback" in (+ flow.authorization_url+ )+++def test_permanent_refresh_rejection_sets_only_sanitized_reconnect_marker(monkeypatch):+ bundle = {+ "access_token": "secret-access",+ "refresh_token": "secret-refresh",+ "expires_at": time.time() - 10,+ "account_id": "secret-account",+ }+ saved = []++ class Lock:+ def acquire(self):+ return None++ def release(self):+ return None++ async def rejected(_data):+ raise codex_auth.CodexReauthorizationRequired(+ "ChatGPT authorization is no longer valid. Please reconnect."+ )++ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _provider: bundle.copy())+ monkeypatch.setattr(+ codex_auth, "save_oauth_bundle", lambda _provider, value: saved.append(value)+ )+ monkeypatch.setattr(codex_auth, "FileLock", lambda *_args, **_kwargs: Lock())+ monkeypatch.setattr(codex_auth, "_token_request", rejected)+ codex_auth._refresh_locks.clear()++ with pytest.raises(codex_auth.CodexReauthorizationRequired) as error:+ asyncio.run(codex_auth.resolve_access("provider"))+ assert str(error.value) == "ChatGPT authorization is no longer valid. Please reconnect."+ assert saved and saved[-1]["reauthorization_required"] is True+ assert "secret-access" not in str(error.value)+ assert "secret-refresh" not in str(error.value)+++def test_stale_unauthorized_response_does_not_poison_reconnected_bundle(monkeypatch):+ bundle = {+ "access_token": "new-access",+ "refresh_token": "new-refresh",+ "expires_at": time.time() + 600,+ "account_id": "account",+ }+ saved = []+ monkeypatch.setattr(codex_auth, "load_oauth_bundle", lambda _provider: bundle.copy())+ monkeypatch.setattr(+ codex_auth,+ "save_oauth_bundle",+ lambda _provider, value: saved.append(value),+ )++ codex_auth.mark_reauthorization_required("provider", "old-access")+ assert saved == []+ codex_auth.mark_reauthorization_required("provider", "new-access")+ assert saved[-1]["reauthorization_required"] is True+++def test_expired_flow_is_removed_after_terminal_retention(monkeypatch):+ flow = OAuthFlow(+ id = "expired-flow",+ provider_id = "provider",+ method = "browser",+ created_at = time.time() - 10,+ expires_at = time.time() - 1,+ )+ codex_auth._flows[flow.id] = flow+ monkeypatch.setattr(codex_auth, "_FLOW_TERMINAL_RETENTION_SECONDS", 0)++ asyncio.run(codex_auth._expire_and_remove_flow(flow))++ assert flow.id not in codex_auth._flows+ assert flow.status == "cancelled"+++def test_cancellation_interrupts_request_before_response_headers():+ cancel_event = threading.Event()+ entered = asyncio.Event()+ enter_cancelled = asyncio.Event()++ class SlowStream:+ async def __aenter__(self):+ entered.set()+ try:+ await asyncio.Future()+ except asyncio.CancelledError:+ enter_cancelled.set()+ raise++ async def __aexit__(self, *_args):+ return False++ class FakeClient:+ def stream(self, *_args, **_kwargs):+ return SlowStream()++ async def aclose(self):+ return None++ async def run():+ client = OpenAICodexClient("secret", "account")+ await client._client.aclose()+ client._client = FakeClient()+ task = asyncio.create_task(_collect_codex_lines(client, cancel_event))+ await entered.wait()+ cancel_event.set()+ lines = await asyncio.wait_for(task, timeout = 1)+ await client.close()+ return lines++ assert asyncio.run(run()) == []+ assert enter_cancelled.is_set()+++async def _collect_codex_lines(client, cancel_event):+ return [+ line+ async for line in client.stream(+ provider_id = "provider",+ thread_id = "thread",+ messages = [{"role": "user", "content": "hello"}],+ model = "gpt-5.4",+ max_tokens = None,+ reasoning_effort = None,+ tools = None,+ tool_choice = None,+ cancel_event = cancel_event,+ )+ ]+++def test_transient_refresh_failure_does_not_require_reauthorization(monkeypatch):+ class FakeResponse:+ status_code = 401+ headers = {}++ async def aread(self):+ return b""++ def json(self):+ return {"error": {"message": "expired"}}++ class FakeStream:+ async def __aenter__(self):+ return FakeResponse()++ async def __aexit__(self, *_args):+ return False++ class FakeClient:+ def stream(self, *_args, **_kwargs):+ return FakeStream()++ async def aclose(self):+ return None++ async def transient_refresh():+ raise codex_auth.CodexAuthError("Could not reach ChatGPT authentication.")++ async def run():+ client = OpenAICodexClient("secret", "account", refresh_access = transient_refresh)+ await client._client.aclose()+ client._client = FakeClient()+ try:+ await _collect_codex_lines(client, threading.Event())+ finally:+ await client.close()++ with pytest.raises(CodexTransportError) as error:+ asyncio.run(run())+ assert not isinstance(error.value, CodexReauthorizationError)+++def test_codex_tool_loop_autoinjects_rag_before_first_model_call(monkeypatch):+ from core.inference import openai_codex_tool_loop as tool_loop++ class FakeCodexClient:+ def __init__(self):+ self.messages = []++ async def stream(self, **kwargs):+ self.messages.append(kwargs["messages"])+ yield 'data: {"choices":[{"delta":{"content":"from docs"},"finish_reason":"stop"}]}'++ injected_messages = [+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": "rag_auto_1",+ "type": "function",+ "function": {+ "name": "search_knowledge_base",+ "arguments": '{"query":"docs"}',+ },+ }+ ],+ },+ {+ "role": "tool",+ "name": "search_knowledge_base",+ "tool_call_id": "rag_auto_1",+ "content": "retrieved context",+ },+ ]+ monkeypatch.setattr(+ tool_loop,+ "build_rag_autoinject",+ lambda *_args: {+ "events": [{"type": "status", "text": "Searching documents"}],+ "messages": injected_messages,+ },+ raising = False,+ )+ client = FakeCodexClient()++ async def run():+ return [+ line+ async for line in tool_loop.stream_codex_with_studio_tools(+ client,+ run = tool_loop.CodexRunContext(+ provider_id = "provider",+ thread_id = "thread",+ session_id = "session",+ messages = [{"role": "user", "content": "docs"}],+ model = "gpt-5.6-sol",+ reasoning_effort = "medium",+ ),+ policy = tool_loop.CodexToolPolicy(+ tools = [{"type": "function", "function": {"name": "search_knowledge_base"}}],+ max_calls = 2,+ timeout = 30,+ permission_mode = "auto",+ confirm_calls = True,+ bypass_permissions = False,+ rag_scope = {"thread_id": "thread"},+ ),+ cancel_event = threading.Event(),+ )+ ]++ lines = asyncio.run(run())+ assert lines[0] == 'data: {"type":"status","text":"Searching documents"}'+ assert client.messages[0][-2:] == injected_messages+++def test_codex_studio_tool_loop_executes_and_continues(monkeypatch):+ from core.inference import openai_codex_tool_loop as tool_loop++ class FakeCodexClient:+ def __init__(self):+ self.messages = []++ async def stream(self, **kwargs):+ self.messages.append(kwargs["messages"])+ if len(self.messages) == 1:+ yield 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"python","arguments":"{\\"code\\":\\"print(6 * 7)\\"}"}}]},"finish_reason":null}]}'+ yield 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}'+ else:+ yield 'data: {"choices":[{"delta":{"content":"The result is 42."},"finish_reason":null}]}'+ yield 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}'++ executed = []+ monkeypatch.setattr(+ tool_loop,+ "execute_tool",+ lambda name, arguments, **kwargs: executed.append((name, arguments, kwargs)) or "42",+ )+ client = FakeCodexClient()++ async def run():+ return [+ line+ async for line in tool_loop.stream_codex_with_studio_tools(+ client,+ run = tool_loop.CodexRunContext(+ provider_id = "provider",+ thread_id = "thread",+ session_id = "sandbox",+ messages = [{"role": "user", "content": "calculate"}],+ model = "gpt-5.6-sol",+ reasoning_effort = "medium",+ ),+ policy = tool_loop.CodexToolPolicy(+ tools = [+ {+ "type": "function",+ "function": {+ "name": "python",+ "description": "Run Python",+ "parameters": {"type": "object"},+ },+ }+ ],+ max_calls = 2,+ timeout = 30,+ permission_mode = "off",+ confirm_calls = False,+ bypass_permissions = False,+ rag_scope = None,+ ),+ cancel_event = threading.Event(),+ )+ ]++ lines = asyncio.run(run())+ assert executed[0][0:2] == ("python", {"code": "print(6 * 7)"})+ assert any('"type":"tool_start"' in line for line in lines)+ assert any('"type":"tool_end"' in line and '"result":"42"' in line for line in lines)++ assert any(+ '"provenance":{"source":"local","round_id":1}' in line+ for line in lines+ if '"type":"tool_start"' in line or '"type":"tool_end"' in line+ )+ assert any("The result is 42." in line for line in lines)+ assert client.messages[1][-1] == {+ "role": "tool",+ "tool_call_id": "call_1",+ "name": "python",+ "content": "42",+ }+++def test_codex_tool_budget_resolves_parallel_overflow_without_executing_it(monkeypatch):+ from core.inference import openai_codex_tool_loop as tool_loop++ class FakeCodexClient:+ def __init__(self):+ self.requests = []++ async def stream(self, **kwargs):+ self.requests.append(kwargs)+ if len(self.requests) == 1:+ yield 'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"python","arguments":"{}"}},{"index":1,"id":"call_2","type":"function","function":{"name":"terminal","arguments":"{}"}}]},"finish_reason":null}]}'+ yield 'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}'+ else:+ yield 'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}'+ yield 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}'++ executed = []+ monkeypatch.setattr(+ tool_loop,+ "execute_tool",+ lambda name, arguments, **kwargs: executed.append(name) or "ok",+ )+ client = FakeCodexClient()++ async def run():+ return [+ line+ async for line in tool_loop.stream_codex_with_studio_tools(+ client,+ run = tool_loop.CodexRunContext(+ provider_id = "provider",+ thread_id = "thread",+ session_id = "session",+ messages = [{"role": "user", "content": "go"}],+ model = "gpt-5.6-sol",+ reasoning_effort = "medium",+ ),+ policy = tool_loop.CodexToolPolicy(+ tools = [{"type": "function", "function": {"name": "python"}}],+ max_calls = 1,+ timeout = 30,+ permission_mode = "off",+ confirm_calls = False,+ bypass_permissions = False,+ rag_scope = None,+ ),+ cancel_event = threading.Event(),+ )+ ]++ lines = asyncio.run(run())+ assert executed == ["python"]+ assert any("per-message tool-call limit" in line and "call_2" in line for line in lines)+ assert client.requests[1]["tools"] is None+ assert client.requests[1]["tool_choice"] == "none"+ assert [message["tool_call_id"] for message in client.requests[1]["messages"][-2:]] == [+ "call_1",+ "call_2",+ ]diff --git a/studio/backend/tests/test_openai_responses_translation.py b/studio/backend/tests/test_openai_responses_translation.pyindex 89d3409838a..59ae4ec9ed8 100644--- a/studio/backend/tests/test_openai_responses_translation.py+++ b/studio/backend/tests/test_openai_responses_translation.py@@ -264,7 +264,10 @@ def test_responses_function_call_output_translates_to_delta_tool_calls(monkeypatfinish_reason="tool_calls" (not "stop") so the frontend's accumulator runsthe function."""+ captured: dict = {}+def handler(request: httpx.Request) -> httpx.Response:+ captured["body"] = json.loads(request.content.decode("utf-8"))events = [{"type": "response.created"},{@@ -305,7 +308,10 @@ def test_responses_function_call_output_translates_to_delta_tool_calls(monkeypat"name": "get_weather","parameters": {"type": "object",- "properties": {"city": {"type": "string"}},+ "properties": {+ "city": {"type": "string"},+ "options": {"type": "object"},+ },},},}@@ -343,6 +349,9 @@ def test_responses_function_call_output_translates_to_delta_tool_calls(monkeypat)assert terminal["choices"][0]["finish_reason"] == "tool_calls", payloads+ parameters = captured["body"]["tools"][0]["parameters"]+ assert parameters["properties"]["options"]["properties"] == {}+def test_responses_parallel_function_calls_get_distinct_indices(monkeypatch):"""Round 13: parallel function_call items must land on distinctdiff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.pyindex 9ac15f61b8e..cad997b4439 100644--- a/studio/backend/tests/test_openai_tool_passthrough.py+++ b/studio/backend/tests/test_openai_tool_passthrough.py@@ -519,6 +519,35 @@ class TestChatCompletionRequestToolFields:assert body["error"]["param"] == "confirm_tool_calls"assert "only supported for local streaming tools" in body["error"]["message"]+ def test_confirm_tool_calls_allowed_for_codex_studio_tools(self, monkeypatch):+ from routes import inference as inference_route++ class _UnusedBackend:+ is_loaded = False++ client = self._v1_client(monkeypatch, _UnusedBackend())++ async def fake_proxy(*_args, **_kwargs):+ return {"ok": True}++ monkeypatch.setattr(inference_route, "_proxy_to_external_provider", fake_proxy)+ resp = client.post(+ "/v1/chat/completions",+ json = {+ "messages": [{"role": "user", "content": "search docs"}],+ "provider_type": "openai_codex",+ "external_model": "gpt-5.6-sol",+ "enable_tools": True,+ "enabled_tools": ["web_search"],+ "confirm_tool_calls": True,+ "permission_mode": "ask",+ "stream": True,+ },+ )++ assert resp.status_code == 200+ assert resp.json() == {"ok": True}+def test_logprobs_rejected_until_supported(self, monkeypatch):class _UnusedBackend:is_loaded = Falsediff --git a/studio/backend/tests/test_research_runs_hardening.py b/studio/backend/tests/test_research_runs_hardening.pyindex 9a5b71f130d..b81342d54fd 100644--- a/studio/backend/tests/test_research_runs_hardening.py+++ b/studio/backend/tests/test_research_runs_hardening.py@@ -807,6 +807,30 @@ def test_stream_completion_opts_out_of_the_tool_loop(monkeypatch):assert sent[0]["json"]["tool_choice"] == "none"assert sent[0]["json"]["enabled_tools"] == []+ assert sent[0]["json"]["thread_id"] == "research:run-1"+++def test_codex_research_hops_route_saved_provider_with_run_scoped_cache(monkeypatch):+ sent = _install_fake_client(monkeypatch, [_response(200, body = _stream_body())])+ supervisor = _make_supervisor(_noop_check_active)+ run = _waiting_run(30.0)+ run["config"]["inferenceRequest"] = {+ "model": "gpt-5.6-sol",+ "providerId": "provider-1",+ "providerType": "openai_codex",+ "externalModel": "gpt-5.6-sol",+ }++ assert asyncio.run(+ supervisor._stream_completion(run, [{"role": "user"}], report_progress = False)+ ) == ("report", "", "stop", None)+ body = sent[0]["json"]+ assert body["provider_id"] == "provider-1"+ assert body["provider_type"] == "openai_codex"+ assert body["external_model"] == "gpt-5.6-sol"+ assert body["thread_id"] == "research:run-1"+ assert body["tool_choice"] == "none" and body["enabled_tools"] == []+def _capture_backoff(monkeypatch) -> list:"""Record the delays the retry loop asks for and return control immediately."""diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex bb685336962..126dafbfdbe 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -4476,7 +4476,10 @@ const ComposerToolsMenu: FC<{const mcpDisabled = modelLoaded && !supportsTools;// Match Search and Code: allow pre-selection before a local model loads.const researchDisabled =- !researchAvailable || Boolean(externalSelection) || incognito;+ !researchAvailable ||+ (Boolean(externalSelection) &&+ selectedExternalProvider?.providerType !== "openai_codex") ||+ incognito;// Three most recently updated projects for the quick-access submenu.const { projects } = useChatProjects();const recentProjects = [...projects]diff --git a/studio/frontend/src/features/chat/api-provider-logo.tsx b/studio/frontend/src/features/chat/api-provider-logo.tsxindex 0eb85d5d3bd..6813163819b 100644--- a/studio/frontend/src/features/chat/api-provider-logo.tsx+++ b/studio/frontend/src/features/chat/api-provider-logo.tsx@@ -29,9 +29,10 @@ export function apiProviderLogoSrc(providerType: string | undefined | null,): string | undefined {if (!providerType) return undefined;- const ext = PROVIDER_LOGO_EXT[providerType];+ const logoProviderType = providerType === "openai_codex" ? "openai" : providerType;+ const ext = PROVIDER_LOGO_EXT[logoProviderType];if (!ext) return undefined;- return `${import.meta.env.BASE_URL}provider-logos/${providerType}.${ext}`;+ return `${import.meta.env.BASE_URL}provider-logos/${logoProviderType}.${ext}`;}interface ApiProviderLogoProps {@@ -40,7 +41,7 @@ interface ApiProviderLogoProps {title?: string;}-const DARK_INVERT_LOGOS = new Set(["openai", "ollama", "openrouter"]);+const DARK_INVERT_LOGOS = new Set(["openai", "openai_codex", "ollama", "openrouter"]);/** Provider logo from `public/provider-logos/`; monochrome ones invert in dark mode. */export function ApiProviderLogo({ providerType, className, title }: ApiProviderLogoProps) {diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 36f8bea2218..7275100838b 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -55,11 +55,30 @@ import {isPromptCacheTtl,loadExternalProviders,parseExternalModelId,- providerTypeSupportsVision,++ providerModelSupportsStudioTools,+ providerModelSupportsVision,supportsProviderPromptCacheTtl,supportsProviderPromptCaching,toExternalBackendProviderType,} from "../external-providers";++import {+ addCodexReasoning,++ codexLocalToolRoundId,+ codexReasoningForToolCalls,+ readCodexReasoning,++ shouldReplayAssistantReasoning,++ startsNewCodexToolRound,+ type CodexReasoningLedger,+} from "../codex-reasoning";++import { resolveToolCallPartId } from "../tool-call-id";++import { buildResearchInferenceRequest } from "../research-inference-request";import { pickFriendlyContainerName } from "../lib/friendly-names";import {reasoningCapsFromLoad,@@ -1152,6 +1171,21 @@ function collectAssistantTextThoughtSignature(return undefined;}+function setAssistantCodexReasoning(+ message: SerializedMessage,+ reasoning: unknown[] | undefined,+): void {+ if (!reasoning) return;+ const extra =+ message.extra_content &&+ typeof message.extra_content === "object" &&+ !Array.isArray(message.extra_content)+ ? (message.extra_content as Record<string, unknown>)+ : {};+ message.extra_content = { ...extra, openai_codex_reasoning: reasoning };+}++function attachAssistantThoughtSignature(messages: SerializedMessage[],thoughtSignature: string | undefined,@@ -1191,6 +1225,10 @@ function serializeAssistantReplayMessages(}const imageParts = collectImageParts(message);++ const codexReasoning = readCodexReasoning(+ (message as { metadata?: unknown }).metadata,+ );const messages: SerializedMessage[] = [];const pendingTextParts: string[] = [];const pendingReasoningParts: string[] = [];@@ -1198,6 +1236,8 @@ function serializeAssistantReplayMessages(let pendingToolResults: SerializedToolResult[] = [];let imagePartsPending = imageParts.length > 0;+ let pendingLocalToolRoundId: number | null = null;+const flushAssistantAndToolResults = (force = false): void => {const textContent = sanitizeAssistantReplayText(pendingTextParts.join("\n"),@@ -1206,13 +1246,16 @@ function serializeAssistantReplayMessages(const hasContent = textContent.length > 0 || includeImageParts.length > 0;const hasToolCalls = pendingToolCalls.length > 0;const reasoningContent = pendingReasoningParts.join("\n");- const reasoningOnlyTurnIsComplete =- message.status?.type !== "incomplete" &&- readIncompleteInfo((message as { metadata?: unknown }).metadata) === null;- const hasReasoningContent =- includeReasoningContent &&- reasoningContent.length > 0 &&- (hasContent || hasToolCalls || reasoningOnlyTurnIsComplete);+ const incomplete =+ message.status?.type === "incomplete" ||+ readIncompleteInfo((message as { metadata?: unknown }).metadata) !== null;+ const hasReasoningContent = shouldReplayAssistantReasoning({+ enabled: includeReasoningContent,+ reasoningContent,+ hasContent,+ hasToolCalls,+ incomplete,+ });if (!force && !hasContent && !hasToolCalls && !hasReasoningContent) {return;@@ -1237,6 +1280,16 @@ function serializeAssistantReplayMessages(assistantMessage.reasoning_content = reasoningContent;}+ if (hasToolCalls) {+ setAssistantCodexReasoning(+ assistantMessage,+ codexReasoningForToolCalls(+ codexReasoning,+ pendingToolCalls.map((call) => call.id),+ ),+ );+ }+messages.push(assistantMessage);if (pendingToolResults.length > 0) {messages.push(...pendingToolResults);@@ -1247,6 +1300,8 @@ function serializeAssistantReplayMessages(pendingToolCalls = [];pendingToolResults = [];imagePartsPending = false;++ pendingLocalToolRoundId = null;};for (const part of message.content ?? []) {@@ -1276,7 +1331,18 @@ function serializeAssistantReplayMessages(continue;}- const flushLocalPair = shouldFlushCompletedLocalToolPair(toolPart);++ const provenance = getToolReplayProvenance(toolPart);+ const localRoundId = codexLocalToolRoundId(provenance);+ if (+ pendingToolCalls.length > 0 &&+ startsNewCodexToolRound(pendingLocalToolRoundId, localRoundId)+ ) {+ flushAssistantAndToolResults();+ }+ if (localRoundId !== null) pendingLocalToolRoundId = localRoundId;+ const flushLocalPair =+ localRoundId === null && shouldFlushCompletedLocalToolPair(toolPart);if (flushLocalPair && pendingToolCalls.length > 0) {flushAssistantAndToolResults();}@@ -1297,6 +1363,13 @@ function serializeAssistantReplayMessages(messages,collectAssistantTextThoughtSignature(message),);++ const finalAssistant = [...messages]+ .reverse()+ .find((candidate) => candidate.role === "assistant");+ if (finalAssistant) {+ setAssistantCodexReasoning(finalAssistant, codexReasoning?.final);+ }return messages;}@@ -3545,53 +3618,43 @@ export function createOpenAIStreamAdapter(userMessageIndex > 0 ? messages[userMessageIndex - 1]!.id : null;const { params } = runtime;await persistResolvedQueuedModel(params.checkpoint);- const model = params.checkpoint.trim();- if (!model || parseExternalModelId(model)) {- throw new Error("Deep research requires a selected local model.");- }- const inferenceRequest: {- model: string;- temperature?: number;- topP?: number;- maxTokens?: number;- enableThinking?: boolean;- reasoningEffort?: string;- } = { model };+ const selectedCheckpoint = params.checkpoint.trim();+ const researchExternalSelection = parseExternalModelId(selectedCheckpoint);+ const researchExternalProvider = researchExternalSelection+ ? loadExternalProviders().find(+ (provider) => provider.id === researchExternalSelection.providerId,+ )+ : null;if (- Number.isFinite(params.temperature) &&- params.temperature >= 0 &&- params.temperature <= 2+ !selectedCheckpoint ||+ (researchExternalSelection &&+ researchExternalProvider?.providerType !== "openai_codex")) {- inferenceRequest.temperature = params.temperature;- }- if (Number.isFinite(params.topP) && params.topP > 0 && params.topP <= 1) {- inferenceRequest.topP = params.topP;- }- if (Number.isFinite(params.maxTokens) && params.maxTokens > 0) {- inferenceRequest.maxTokens = Math.min(8192, Math.floor(params.maxTokens));+ throw new Error(+ "Deep research requires a selected local model or ChatGPT/Codex subscription.",+ );}const reasoningRequested =runtime.reasoningAlwaysOn ||(runtime.reasoningEnabled && runtime.reasoningEffort !== "none");- if (- runtime.reasoningStyle === "enable_thinking" ||- runtime.reasoningStyle === "enable_thinking_effort"- ) {- inferenceRequest.enableThinking = reasoningRequested;- }- if (- reasoningRequested &&- (runtime.reasoningStyle === "reasoning_effort" ||- runtime.reasoningStyle === "enable_thinking_effort")- ) {- // Clamp like normal chat does. reasoningEffort is one shared persisted setting and- // the load paths refresh reasoningEffortLevels without re-clamping it, so a level- // this model lacks is dropped by llama.cpp and the run falls back to the default.- inferenceRequest.reasoningEffort = clampReasoningEffortToLevels(- runtime.reasoningEffort,- runtime.reasoningEffortLevels,- );- }+ const inferenceRequest = buildResearchInferenceRequest({+ checkpoint: selectedCheckpoint,+ external:+ researchExternalSelection && researchExternalProvider+ ? {+ providerId: researchExternalProvider.id,+ modelId: researchExternalSelection.modelId,+ }+ : undefined,+ temperature: params.temperature,+ topP: params.topP,+ maxTokens: params.maxTokens,+ reasoningRequested,+ reasoningStyle: runtime.reasoningStyle,+ reasoningEffort: runtime.reasoningEffort,+ reasoningEffortLevels: runtime.reasoningEffortLevels,+ clampReasoningEffort: clampReasoningEffortToLevels,+ });const researchProjectId = await resolveProjectId(resolvedThreadId,readThreadRecord,@@ -3937,6 +4000,16 @@ export function createOpenAIStreamAdapter((provider) => provider.id === externalSelection.providerId,): null;++ const externalUsesStudioTools =+ providerModelSupportsStudioTools(+ externalProvider?.providerType,+ externalSelection?.modelId,+ ) === true;++ const supportsStudioToolsForThisTurn = isExternalRequest+ ? externalUsesStudioTools+ : supportsTools;const selectedModelSummary = runtime.models.find((model) => model.id === params.checkpoint,);@@ -3961,10 +4034,15 @@ export function createOpenAIStreamAdapter(externalProvider.providerType === "gemini" &&isGeminiCustomOpenAICompatBase(externalProvider.baseUrl),);+ const externalProviderUsesOAuth =+ externalProvider?.authKind === "chatgpt_oauth";+if (isExternalRequest &&!externalApiKey &&!externalProvider?.hasApiKey &&++ !externalProviderUsesOAuth &&!externalProviderIsCustom &&!externalProviderIsGeminiCustomBase) {@@ -4254,8 +4332,9 @@ export function createOpenAIStreamAdapter(const imageGateReason = getImageInputUnavailableReason({activeModel,isExternalModel: isExternalRequest,- externalSupportsVision: providerTypeSupportsVision(+ externalSupportsVision: providerModelSupportsVision(externalProvider?.providerType,+ externalSelection?.modelId,),externalModelLabel: externalSelection?.modelId ?? null,loadedIsMultimodal: runtime.loadedIsMultimodal,@@ -4444,6 +4523,9 @@ export function createOpenAIStreamAdapter(// Every streamed yield carries the repaired text, not just the terminal ones:// assistant-ui drops whatever is yielded after an abort, so on Stop the last// STREAMED yield is what gets saved.+ let codexReasoningLedger: CodexReasoningLedger = { byToolCall: {} };+ let codexRoundToolCallIds: string[] = [];+const liveAssistantContent = () =>buildAssistantContent(mergeContinuation(cumulativeText));// Provisional reason on every streamed yield: an abort skips the terminal yields@@ -4451,6 +4533,7 @@ export function createOpenAIStreamAdapter(// lose why it was short. The terminal yields overwrite or clear it.const liveCustom = () => ({...reasoningDurationTracker.metadata(),+ openaiCodexReasoning: codexReasoningLedger,incomplete: { reason: "cancelled" as const },});// Why this turn stopped early. Drives the Continue affordance.@@ -4493,22 +4576,14 @@ export function createOpenAIStreamAdapter(// key is unique; every tool_start/output/args/end resolves the same id via// this map, dropped at tool_end.const toolPartIdByBackendId = new Map<string, string>();- const resolveToolPartId = (backendToolCallId: string): string => {- if (!backendToolCallId) {- return toolCallParts[toolCallParts.length - 1]?.toolCallId ?? "";- }- const confirmationId =- toolConfirmationIdsByBackendId.get(backendToolCallId);- if (confirmationId) {- return confirmationId;- }- let partId = toolPartIdByBackendId.get(backendToolCallId);- if (!partId) {- partId = `${backendToolCallId}:${crypto.randomUUID()}`;- toolPartIdByBackendId.set(backendToolCallId, partId);- }- return partId;- };+ const resolveToolPartId = (backendToolCallId: string): string =>+ resolveToolCallPartId(+ toolPartIdByBackendId,+ backendToolCallId,+ toolConfirmationIdsByBackendId.get(backendToolCallId),+ toolCallParts[toolCallParts.length - 1]?.toolCallId ?? "",+ () => `${backendToolCallId}:${crypto.randomUUID()}`,+ );// Latest Gemini text-part thoughtSignature; pinned onto the final// text MessagePart so next-turn replay carries it.let latestTextThoughtSignature: string | undefined;@@ -4728,11 +4803,10 @@ export function createOpenAIStreamAdapter(codeExecEnabledForThisTurn ||(!isExternalRequest && supportsTools && codeToolsEnabled),images: imageGenerationEnabledForThisTurn,- mcp: !isExternalRequest && supportsTools && mcpEnabledForChat,+ mcp:+ supportsStudioToolsForThisTurn && mcpEnabledForChat,docs:- !isExternalRequest &&- supportsTools &&- (ragEnabled || projectRagEnabled),+ supportsStudioToolsForThisTurn && (ragEnabled || projectRagEnabled),artifacts: renderHtmlToolEnabledForThisTurn,confirmToolCalls,bypassPermissions,@@ -4930,29 +5004,94 @@ export function createOpenAIStreamAdapter(externalSelection?.modelId,),),++ ...(externalUsesStudioTools && resolvedThreadId+ ? { thread_id: resolvedThreadId }+ : {}),// Forward only sampling knobs the provider accepts....(externalCapabilities?.topK ? { top_k: params.topK } : {}),...(externalCapabilities?.presencePenalty? { presence_penalty: params.presencePenalty }: {}),- // enabled_tools from active pills; backend maps each name- // to the provider's tool schema.- ...(webSearchEnabledForThisTurn ||- webFetchEnabledForThisTurn ||- codeExecEnabledForThisTurn ||- imageGenerationEnabledForThisTurn+ // ChatGPT/Codex function calls are executed by Studio. Other+ // external providers keep their provider-hosted tool envelope.+ ...(supportsStudioToolsForThisTurn &&+ (toolsEnabled ||+ codeToolsEnabled ||+ mcpEnabledForChat ||+ ragEnabled ||+ projectRagEnabled)? {enable_tools: true,enabled_tools: [- ...(webSearchEnabledForThisTurn ? ["web_search"] : []),- ...(webFetchEnabledForThisTurn ? ["web_fetch"] : []),- ...(codeExecEnabledForThisTurn ? ["code_execution"] : []),- ...(imageGenerationEnabledForThisTurn- ? ["image_generation"]+ ...(ragEnabled || projectRagEnabled+ ? ["search_knowledge_base"]: []),+ ...(toolsEnabled ? ["web_search"] : []),+ ...(codeToolsEnabled ? ["python", "terminal"] : []),],+ mcp_enabled: mcpEnabledForChat,+ permission_mode: permissionMode,+ ...(permissionMode === "auto"+ ? {}+ : { confirm_tool_calls: permissionMode === "ask" }),+ bypass_permissions: bypassPermissions,+ max_tool_calls_per_message: runtime.maxToolCallsPerMessage,+ tool_call_timeout:+ runtime.toolCallTimeout >= 9999+ ? 9999+ : runtime.toolCallTimeout * 60,+ ...(sandboxSessionId ? { session_id: sandboxSessionId } : {}),+ ...(resolvedThreadId ? { thread_id: resolvedThreadId } : {}),+ ...(ragEnabled || projectRagEnabled+ ? {+ rag_scope: {+ ...(ragEnabled && ragSource.type === "kb"+ ? { kb_id: ragSource.kbId }+ : {+ ...(ragEnabled && resolvedThreadId+ ? { thread_id: resolvedThreadId }+ : {}),+ ...(projectRagEnabled && ragProjectId+ ? { project_id: ragProjectId }+ : {}),+ }),+ default_top_k: ragTopK,+ mode: ragMode,+ autoinject: resolveAutoInject(+ ragAutoInject,+ params.checkpoint,+ ),+ autoinject_min_score: ragAutoInjectMinScore,+ ...(ragAutoInject === "off"+ ? { whole_doc: false }+ : {}),+ context_length:+ runtime.ggufContextLength ??+ params.maxSeqLength ??+ undefined,+ },+ }+ : {}),}- : {}),+ : webSearchEnabledForThisTurn ||+ webFetchEnabledForThisTurn ||+ codeExecEnabledForThisTurn ||+ imageGenerationEnabledForThisTurn+ ? {+ enable_tools: true,+ enabled_tools: [+ ...(webSearchEnabledForThisTurn ? ["web_search"] : []),+ ...(webFetchEnabledForThisTurn ? ["web_fetch"] : []),+ ...(codeExecEnabledForThisTurn+ ? ["code_execution"]+ : []),+ ...(imageGenerationEnabledForThisTurn+ ? ["image_generation"]+ : []),+ ],+ }+ : {}),provider_id: externalProvider.id,provider_type: externalBackendProviderType,external_model: externalSelection.modelId,@@ -5651,15 +5790,16 @@ export function createOpenAIStreamAdapter(continue;}- // OpenAI-standard usage chunk: choices=[], usage populated.- if (chunk.choices?.length === 0 && chunk.usage) {+ // OpenAI usage may arrive either in an empty trailing chunk or on+ // the terminal Codex chunk that also carries reasoning metadata.+ if (chunk.usage) {serverMetadata = {usage: chunk.usage,timings: (chunk as Record<string, unknown>).timings as| ServerTimings| undefined,};- continue;+ if (chunk.choices?.length === 0) continue;}totalChunks += 1;@@ -5702,15 +5842,26 @@ export function createOpenAIStreamAdapter(| undefined)?.extra_content;if (deltaExtraContent && typeof deltaExtraContent === "object") {- const eGoogle = (deltaExtraContent as Record<string, unknown>)- .google;+ const extraRecord = deltaExtraContent as Record<string, unknown>;+ const eGoogle = extraRecord.google;if (eGoogle && typeof eGoogle === "object") {- const sig = (eGoogle as Record<string, unknown>)- .thought_signature;+ const sig = (eGoogle as Record<string, unknown>).thought_signature;if (typeof sig === "string" && sig) {latestTextThoughtSignature = sig;}}+ const codexReasoning = extraRecord.openai_codex_reasoning;+ if (Array.isArray(codexReasoning) && codexReasoning.length > 0) {+ codexReasoningLedger = addCodexReasoning(+ codexReasoningLedger,+ codexReasoning,+ codexRoundToolCallIds,+ );+ }+ }++ if (chunk.choices?.[0]?.finish_reason) {+ codexRoundToolCallIds = [];}// Kimi / DeepSeek stream thinking via delta.reasoning_content;// wrap inline as <think>...</think> for parseAssistantContent.@@ -5762,12 +5913,26 @@ export function createOpenAIStreamAdapter(const idx =typeof call.index === "number" ? call.index : undefined;const stableId = call.id;- // Match an existing fragment by id first (canonical), then+ // Studio's local Codex loop follows the OpenAI tool-call delta with+ // tool_start/tool_end events. Resolve the backend id now so all three+ // event shapes update one run-unique card instead of leaving the raw+ // provisional card beside a second execution card.+ const stablePartId = stableId+ ? resolveToolPartId(stableId)+ : undefined;+ // Match an existing fragment by resolved id first (canonical), then// by index slot; fall back to a minted tool_call_<n> id// for streams that send neither.- let existing = stableId- ? toolCallParts.find((p) => p.toolCallId === stableId)+ let existing = stablePartId+ ? toolCallParts.find((p) => p.toolCallId === stablePartId): undefined;++ if (+ stablePartId &&+ !codexRoundToolCallIds.includes(stablePartId)+ ) {+ codexRoundToolCallIds.push(stablePartId);+ }if (!existing && idx !== undefined) {existing = toolCallParts.find((p) => (p as PositionedToolCallPart)._delta_index === idx,@@ -5811,7 +5976,11 @@ export function createOpenAIStreamAdapter(}} else {const callId =- stableId || `tool_call_${idx ?? toolCallParts.length}`;+ stablePartId || `tool_call_${idx ?? toolCallParts.length}`;++ if (!codexRoundToolCallIds.includes(callId)) {+ codexRoundToolCallIds.push(callId);+ }const argsText = argsFragment;let parsedArgs: ToolCallMessagePart["args"] = {};if (argsText) {@@ -6055,6 +6224,8 @@ export function createOpenAIStreamAdapter(custom: {...reasoningDurationTracker.metadata(),// Persisted so Continue survives a reload; cleared on a normal end.++ openaiCodexReasoning: codexReasoningLedger,incomplete: incompleteReason ? { reason: incompleteReason } : undefined,// Persisted refusal flag driving the two-pass prune.anthropicRefusal: anthropicRefusalSeen || undefined,diff --git a/studio/frontend/src/features/chat/api/providers-api.ts b/studio/frontend/src/features/chat/api/providers-api.tsindex 53f9254fcac..d4bb1b9ce60 100644--- a/studio/frontend/src/features/chat/api/providers-api.ts+++ b/studio/frontend/src/features/chat/api/providers-api.ts@@ -5,16 +5,29 @@ import forge from "node-forge";import { authFetch } from "@/features/auth/api";import { formatFastApiDetail } from "@/lib/format-fastapi-error";++export type ProviderAuthKind = "api_key" | "chatgpt_oauth";+export type ProviderAuthStatus =+ | "disconnected"+ | "connected"+ | "reauthorization_required";+export interface ProviderRegistryEntry {provider_type: string;display_name: string;base_url: string;default_models: string[];++ model_capabilities?: Record<string, { vision?: boolean; studio_tools?: boolean }>;supports_streaming: boolean;supports_vision: boolean;supports_tool_calling: boolean;/** remote = fetch /models; curated = huge catalogs — UI uses defaults + manual IDs only */model_list_mode?: "remote" | "curated";++ auth_kind?: ProviderAuthKind;+ base_url_editable?: boolean;+ model_ids_editable?: boolean;}export interface ProviderConfig {@@ -25,6 +38,9 @@ export interface ProviderConfig {is_enabled: boolean;has_api_key: boolean;++ auth_kind?: ProviderAuthKind;+ auth_status?: ProviderAuthStatus;models?: string[];available_models?: string[];created_at: string;@@ -279,3 +295,69 @@ export async function listProviderModels(payload: {return parseJsonOrThrow<ProviderModelInfo[]>(response);});}+++export interface CodexOAuthFlow {+ flow_id: string;+ method: "browser" | "device";+ status: "pending" | "connected" | "error" | "cancelled";+ expires_at: number;+ authorization_url?: string | null;+ verification_url?: string | null;+ user_code?: string | null;+ message?: string | null;+}++export async function startCodexOAuth(+ providerId: string,+ method: "browser" | "device",+): Promise<CodexOAuthFlow> {+ const response = await authFetch(`/api/providers/${providerId}/oauth/start`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ method }),+ });+ return parseJsonOrThrow<CodexOAuthFlow>(response);+}++export async function getCodexOAuthFlow(providerId: string, flowId: string): Promise<CodexOAuthFlow> {+ const response = await authFetch(`/api/providers/${providerId}/oauth/flows/${flowId}`);+ return parseJsonOrThrow<CodexOAuthFlow>(response);+}++export async function completeCodexOAuth(+ providerId: string,+ flowId: string,+ callbackUrl: string,+): Promise<CodexOAuthFlow> {+ const response = await authFetch(`/api/providers/${providerId}/oauth/flows/${flowId}/complete`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ callback_url: callbackUrl }),+ });+ return parseJsonOrThrow<CodexOAuthFlow>(response);+}++export async function cancelCodexOAuthFlow(+ providerId: string,+ flowId: string,+): Promise<void> {+ const response = await authFetch(+ `/api/providers/${providerId}/oauth/flows/${flowId}`,+ { method: "DELETE" },+ );+ if (!response.ok) {+ const body = await response.json().catch(() => null);+ throw new Error(parseErrorText(response.status, body));+ }+}++++export async function disconnectCodexOAuth(providerId: string): Promise<void> {+ const response = await authFetch(`/api/providers/${providerId}/oauth`, { method: "DELETE" });+ if (!response.ok) {+ const body = await response.json().catch(() => null);+ throw new Error(parseErrorText(response.status, body));+ }+}diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 0281f61f9dc..274a07bfa91 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -138,6 +138,8 @@ import {buildExternalModelId,isExternalModelId,parseExternalModelId,++ providerModelSupportsStudioTools,} from "./external-providers";import { useChatModelRuntime } from "./hooks/use-chat-model-runtime";import type { SelectedModelInput } from "./hooks/use-chat-model-runtime";@@ -2231,12 +2233,11 @@ export function ChatPage({: true: state.reasoningEnabled,supportsPreserveThinking: false,- // External models have no local tool runtime, so `supportsTools` is- // false. The `supportsBuiltin*` flags cover providers that run tools- // server-side: WebSearch lights the Search pill (OpenAI/Anthropic/- // OpenRouter/Kimi), CodeExecution the Code pill (Claude 4.x, gpt-5.5),- // ImageGeneration the Images pill (OpenAI cloud Responses-API only).- supportsTools: false,+ supportsTools:+ providerModelSupportsStudioTools(+ provider?.providerType,+ selection.modelId,+ ) === true,supportsBuiltinWebSearch,supportsBuiltinCodeExecution,supportsBuiltinImageGeneration,@@ -2785,11 +2786,11 @@ export function ChatPage({: true: store.reasoningEnabled,supportsPreserveThinking: false,- // External models have no local tool runtime → supportsTools false.- // The supportsBuiltin* flags carry server-side capability per pill:- // Search, Code (Claude 4.x + gpt-5.5), Images (OpenAI cloud- // Responses-API).- supportsTools: false,+ supportsTools:+ providerModelSupportsStudioTools(+ selectedProvider?.providerType,+ selectedExternal?.modelId,+ ) === true,supportsBuiltinWebSearch,supportsBuiltinCodeExecution,supportsBuiltinImageGeneration,diff --git a/studio/frontend/src/features/chat/chat-providers-dialog.tsx b/studio/frontend/src/features/chat/chat-providers-dialog.tsxindex 524f41d7923..4cc4d6b543e 100644--- a/studio/frontend/src/features/chat/chat-providers-dialog.tsx+++ b/studio/frontend/src/features/chat/chat-providers-dialog.tsx@@ -37,6 +37,8 @@ import { AnimatePresence, motion, useReducedMotion } from "motion/react";import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";import { ApiProviderLogo } from "./api-provider-logo";++import { OpenAICodexConnect } from "./openai-codex-connect";import {type ProviderRegistryEntry,createProviderConfig,@@ -61,7 +63,6 @@ import {LEGACY_CUSTOM_PROVIDER_TYPE,CUSTOM_PROVIDER_DISPLAY_NAME,removeExternalProviderApiKey,- supportsProviderPromptCaching,supportsProviderReasoningToggle,supportsRemoteModelCatalog,toExternalBackendProviderType,@@ -187,19 +188,28 @@ export function ChatProvidersSettings({const isCustomProvider = isCustomProviderType(providerType);// llama.cpp hides the key field. Ollama and vLLM show an optional key:// Ollama cloud and secured vLLM need one; local servers leave it empty.- const showApiKeyField = !customPresetSkipsApiKeyField(providerType);const showReasoningToggle = supportsProviderReasoningToggle(providerType);const registryByType = useMemo(() => new Map(registry.map((entry) => [entry.provider_type, entry])),[registry],);+ const selectedProviderContract = registryByType.get(+ toExternalBackendProviderType(providerType),+ );+ const usesOAuth = selectedProviderContract?.auth_kind === "chatgpt_oauth";++ const isCodexSubscription = usesOAuth;+ const modelIdsEditable =+ selectedProviderContract?.model_ids_editable !== false;+ const showApiKeyField =+ !usesOAuth && !customPresetSkipsApiKeyField(providerType);const isCuratedModelList = useMemo(() => {return registryByType.get(providerType)?.model_list_mode === "curated";}, [registryByType, providerType]);const isManualModelList =(isCustomProvider && !supportsRemoteModelCatalog(providerType)) ||- isCuratedModelList;+ (isCuratedModelList && modelIdsEditable);const modelsPanelKey = isCustomProvider? providerType || "custom"@@ -531,6 +541,63 @@ export function ChatProvidersSettings({}}+ async function ensureCodexProvider(): Promise<string> {+ if (editingProviderId) return editingProviderId;+ const backendProviderType = toExternalBackendProviderType(providerType);+ const entry = registryByType.get(backendProviderType);+ if (entry?.auth_kind !== "chatgpt_oauth") {+ throw new Error("This connection does not support ChatGPT authorization.");+ }++ setMutatingProvider(true);+ try {+ const models = pruneProviderModelIds(+ providerType,+ selectedModelIds.length > 0 ? selectedModelIds : entry.default_models,+ );+ const available = pruneProviderModelIds(providerType, [+ ...new Set([...availableModels, ...entry.default_models]),+ ]);+ const created = await createProviderConfig({+ providerType: backendProviderType,+ displayName: entry.display_name,+ baseUrl: null,+ models,+ availableModels: available,+ });+ const provider: ExternalProviderConfig = {+ id: created.id,+ providerType: created.provider_type,+ name: created.display_name,+ baseUrl: created.base_url ?? "",+ models,+ availableModels: available,+ hasApiKey: created.has_api_key,+ authKind: created.auth_kind,+ authStatus: created.auth_status,+ createdAt: Number.isFinite(Date.parse(created.created_at))+ ? Date.parse(created.created_at)+ : Date.now(),+ updatedAt: Number.isFinite(Date.parse(created.updated_at))+ ? Date.parse(created.updated_at)+ : Date.now(),+ };+ const nextProviders = [+ ...providersRef.current.filter((current) => current.id !== created.id),+ provider,+ ];+ providersRef.current = nextProviders;+ onProvidersChange(nextProviders);+ setSelectedModelIds(models);+ setAvailableModels(available);+ setEditingProviderId(created.id);+ return created.id;+ } finally {+ setMutatingProvider(false);+ }+ }++async function addProvider() {if (!providerType) {toast.error("Choose a connection first.");@@ -541,14 +608,18 @@ export function ChatProvidersSettings({const displayName = isCustomProvider? customProviderName.trim() || customProviderDisplayName(providerType): (selectedRegistryEntry?.display_name ?? providerType);- if (!isCustomProvider && !apiKey.trim()) {+ if (+ !isCustomProvider &&+ selectedRegistryEntry?.auth_kind !== "chatgpt_oauth" &&+ !apiKey.trim()+ ) {toast.error("API key is required.");return;}const curated = selectedRegistryEntry?.model_list_mode === "curated";const manualOnly =(isCustomProvider && !supportsRemoteModelCatalog(providerType)) ||- curated;+ (curated && selectedRegistryEntry?.model_ids_editable !== false);const remoteAllowsManual = allowsManualModelIdsWithCatalog(providerType);const manualIds = parseManualModelIds(manualModelIds);const allowManual = manualOnly || remoteAllowsManual;@@ -623,6 +694,9 @@ export function ChatProvidersSettings({: pruneProviderModelIds(providerType, availableModels),hasApiKey: created.has_api_key,++ authKind: created.auth_kind,+ authStatus: created.auth_status,isReasoningModel: supportsProviderReasoningToggle(uiProviderType)? isReasoningModel: undefined,@@ -663,7 +737,15 @@ export function ChatProvidersSettings({apiKey,clearApiKeyRequested,);- if (!isEditingCustomProvider && credentialEdit.action === "missing") {+ const editingContract = registryByType.get(+ toExternalBackendProviderType(existing.providerType),+ );+ const isEditingOAuthProvider = existing.authKind === "chatgpt_oauth";+ if (+ !isEditingCustomProvider &&+ !isEditingOAuthProvider &&+ credentialEdit.action === "missing"+ ) {toast.error("API key is required.");return;}@@ -672,7 +754,7 @@ export function ChatProvidersSettings({const manualOnly =(isEditingCustomProvider &&!supportsRemoteModelCatalog(existing.providerType)) ||- curated;+ (curated && editingContract?.model_ids_editable !== false);const remoteAllowsManual = allowsManualModelIdsWithCatalog(existing.providerType,);@@ -869,6 +951,16 @@ export function ChatProvidersSettings({}async function testProvider(provider: ExternalProviderConfig) {++ if (provider.authKind === "chatgpt_oauth") {+ if (provider.authStatus === "connected") {+ toast.success("ChatGPT subscription is connected.");+ } else {+ await editProvider(provider);+ toast.info("Authorize this ChatGPT subscription connection.");+ }+ return;+ }const savedKey = provider.hasApiKey? "": getExternalProviderApiKey(provider.id).trim();@@ -1133,7 +1225,8 @@ export function ChatProvidersSettings({</div>) : null}- {isCustomProvider ? (+ {isCustomProvider &&+ selectedProviderContract?.base_url_editable !== false ? (<div className="grid grid-cols-[minmax(140px,0.8fr)_minmax(0,1.2fr)] items-center gap-4 px-4 py-3 @max-[520px]:grid-cols-1"><div className="flex min-w-0 flex-col gap-0.5"><Label@@ -1183,6 +1276,20 @@ export function ChatProvidersSettings({</div></section>++ {isCodexSubscription ? (+ <OpenAICodexConnect+ providerId={editingProviderId}+ authStatus={providers.find((provider) => provider.id === editingProviderId)?.authStatus}+ ensureProvider={ensureCodexProvider}+ onChanged={async () => {+ const synced = await syncExternalProvidersFromBackend(providersRef.current);+ providersRef.current = synced;+ onProvidersChange(synced);+ }}+ />+ ) : null}+<section className="overflow-hidden rounded-[8px] border border-border/70 bg-muted/[0.12]"><AnimatePresence initial={false} mode="wait"><motion.div@@ -1332,24 +1439,24 @@ export function ChatProvidersSettings({</ul></div>) : null}- <div className="space-y-2">- <Label- htmlFor="provider-manual-models"- className="text-sm font-medium"- >- Model IDs (one per line or comma-separated)- </Label>- <Textarea- id="provider-manual-models"- value={manualModelIds}- onChange={(event) =>- setManualModelIds(event.target.value)- }- placeholder={"model-id-1\nmodel-id-2"}- rows={5}- className="min-h-[100px] resize-y font-mono text-sm"- />- </div>+ {modelIdsEditable ? (+ <div className="space-y-2">+ <Label+ htmlFor="provider-manual-models"+ className="text-sm font-medium"+ >+ Model IDs (one per line or comma-separated)+ </Label>+ <Textarea+ id="provider-manual-models"+ value={manualModelIds}+ onChange={(event) => setManualModelIds(event.target.value)}+ placeholder={"model-id-1\nmodel-id-2"}+ rows={5}+ className="min-h-[100px] resize-y font-mono text-sm"+ />+ </div>+ ) : null}</div>) : availableModels.length === 0 &&!allowsManualModelIdsWithCatalog(providerType) ? null : (diff --git a/studio/frontend/src/features/chat/codex-reasoning.ts b/studio/frontend/src/features/chat/codex-reasoning.tsnew file mode 100644index 00000000000..e40dc98793a--- /dev/null+++ b/studio/frontend/src/features/chat/codex-reasoning.ts@@ -0,0 +1,97 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export interface CodexReasoningLedger {+ byToolCall: Record<string, unknown[]>;+ final?: unknown[];+}+++export function codexLocalToolRoundId(provenance: unknown): number | null {+ if (!provenance || typeof provenance !== "object" || Array.isArray(provenance)) {+ return null;+ }+ const value = provenance as { source?: unknown; round_id?: unknown };+ return value.source === "local" && typeof value.round_id === "number"+ ? value.round_id+ : null;+}+++export function startsNewCodexToolRound(+ currentRoundId: number | null,+ nextRoundId: number | null,+): boolean {+ return (+ currentRoundId !== null &&+ nextRoundId !== null &&+ currentRoundId !== nextRoundId+ );+}++export function shouldReplayAssistantReasoning(input: {+ enabled: boolean;+ reasoningContent: string;+ hasContent: boolean;+ hasToolCalls: boolean;+ incomplete: boolean;+}): boolean {+ return (+ input.enabled &&+ input.reasoningContent.length > 0 &&+ (input.hasContent || input.hasToolCalls || !input.incomplete)+ );+}++export function addCodexReasoning(+ ledger: CodexReasoningLedger,+ items: unknown[],+ toolCallIds: string[],+): CodexReasoningLedger {+ if (items.length === 0) return ledger;+ const toolCallId = toolCallIds[0];+ if (!toolCallId) return { ...ledger, final: items };+ return {+ ...ledger,+ byToolCall: { ...ledger.byToolCall, [toolCallId]: items },+ };+}++export function readCodexReasoning(+ metadata: unknown,+): CodexReasoningLedger | undefined {+ if (!metadata || typeof metadata !== "object") return undefined;+ const custom = (metadata as { custom?: unknown }).custom;+ if (!custom || typeof custom !== "object") return undefined;+ const value = (custom as Record<string, unknown>).openaiCodexReasoning;+ if (Array.isArray(value)) {+ return value.length > 0 ? { byToolCall: {}, final: value } : undefined;+ }+ if (!value || typeof value !== "object") return undefined;+ const record = value as Record<string, unknown>;+ const byToolCall: Record<string, unknown[]> = {};+ const rawByToolCall = record.byToolCall;+ if (rawByToolCall && typeof rawByToolCall === "object") {+ for (const [id, items] of Object.entries(rawByToolCall)) {+ if (Array.isArray(items) && items.length > 0) byToolCall[id] = items;+ }+ }+ const final = Array.isArray(record.final) && record.final.length > 0+ ? record.final+ : undefined;+ return Object.keys(byToolCall).length > 0 || final+ ? { byToolCall, ...(final ? { final } : {}) }+ : undefined;+}++export function codexReasoningForToolCalls(+ ledger: CodexReasoningLedger | undefined,+ toolCallIds: string[],+): unknown[] | undefined {+ if (!ledger) return undefined;+ for (const id of toolCallIds) {+ const items = ledger.byToolCall[id];+ if (items) return items;+ }+ return undefined;+}diff --git a/studio/frontend/src/features/chat/external-providers.ts b/studio/frontend/src/features/chat/external-providers.tsindex 5b400f5164c..0c43fc3b5b3 100644--- a/studio/frontend/src/features/chat/external-providers.ts+++ b/studio/frontend/src/features/chat/external-providers.ts@@ -1,6 +1,11 @@// 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 type {+ ProviderAuthKind,+ ProviderAuthStatus,+} from "./api/providers-api";+export interface ExternalProviderConfig {id: string;/** Backend provider type (e.g. openai, mistral, gemini). */@@ -16,6 +21,10 @@ export interface ExternalProviderConfig {/** Whether the backend has an installation-saved key. */hasApiKey?: boolean;++ /** Sanitized backend-owned authorization state; never contains OAuth material. */+ authKind?: ProviderAuthKind;+ authStatus?: ProviderAuthStatus;/** Whether to ask supported hosted providers to use prompt caching. */enablePromptCaching?: boolean;/**@@ -107,6 +116,84 @@ export function providerTypeSupportsVision(return null;}++const REGISTRY_MODEL_CAPABILITIES = new Map<+ string,+ Record<string, { vision?: boolean; studio_tools?: boolean }>+>();++const REGISTRY_MODEL_CAPABILITIES_KEY =+ "unsloth_chat_provider_model_capabilities";+let registryCapabilitiesHydrated = false;++function hydrateProviderModelCapabilities(): void {+ if (registryCapabilitiesHydrated) return;+ registryCapabilitiesHydrated = true;+ if (!canUseStorage()) return;+ try {+ const parsed = JSON.parse(+ localStorage.getItem(REGISTRY_MODEL_CAPABILITIES_KEY) ?? "{}",+ ) as Record<+ string,+ Record<string, { vision?: boolean; studio_tools?: boolean }>+ >;+ for (const [providerType, capabilities] of Object.entries(parsed)) {+ if (capabilities && typeof capabilities === "object") {+ REGISTRY_MODEL_CAPABILITIES.set(providerType, capabilities);+ }+ }+ } catch {+ // Ignore invalid browser state; the backend registry will repopulate it.+ }+}++function persistProviderModelCapabilities(): void {+ if (!canUseStorage()) return;+ try {+ localStorage.setItem(+ REGISTRY_MODEL_CAPABILITIES_KEY,+ JSON.stringify(Object.fromEntries(REGISTRY_MODEL_CAPABILITIES)),+ );+ } catch {+ // Ignore storage failures; capabilities remain valid for this session.+ }+}++export function setProviderModelCapabilities(+ providerType: string,+ capabilities: Record<string, { vision?: boolean; studio_tools?: boolean }> | undefined,+): void {+ hydrateProviderModelCapabilities();+ if (capabilities) REGISTRY_MODEL_CAPABILITIES.set(providerType, capabilities);+ else REGISTRY_MODEL_CAPABILITIES.delete(providerType);+ persistProviderModelCapabilities();+}+++export function providerModelSupportsVision(+ providerType: string | null | undefined,+ modelId: string | null | undefined,+): boolean | null {++ hydrateProviderModelCapabilities();+ if (providerType && modelId) {+ const capability = REGISTRY_MODEL_CAPABILITIES.get(providerType)?.[modelId];+ if (typeof capability?.vision === "boolean") return capability.vision;+ }+ return providerTypeSupportsVision(providerType);+}+++export function providerModelSupportsStudioTools(+ providerType: string | null | undefined,+ modelId: string | null | undefined,+): boolean | null {+ if (!providerType || !modelId) return null;+ hydrateProviderModelCapabilities();+ const value = REGISTRY_MODEL_CAPABILITIES.get(providerType)?.[modelId]?.studio_tools;+ return typeof value === "boolean" ? value : null;+}+export const CUSTOM_BACKEND_PROVIDER_TYPE = "openai";export const LEGACY_CUSTOM_PROVIDER_TYPE = "custom";export const CUSTOM_PROVIDER_DISPLAY_NAME = "Custom";diff --git a/studio/frontend/src/features/chat/hooks/use-rag-tool-disabled.ts b/studio/frontend/src/features/chat/hooks/use-rag-tool-disabled.tsindex 4f0912e4351..5aacd99412e 100644--- a/studio/frontend/src/features/chat/hooks/use-rag-tool-disabled.ts+++ b/studio/frontend/src/features/chat/hooks/use-rag-tool-disabled.ts@@ -1,7 +1,11 @@// 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 { parseExternalModelId } from "../external-providers";+import {+ parseExternalModelId,+ providerModelSupportsStudioTools,+} from "../external-providers";+import { useExternalProvidersStore } from "../stores/external-providers-store";import { useChatRuntimeStore } from "../stores/chat-runtime-store";// Pre-select gate for the RAG toggle, mirroring Web search/Code/MCP: armable@@ -13,7 +17,16 @@ export function useRagToolDisabled(): boolean {);const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint);const supportsTools = useChatRuntimeStore((s) => s.supportsTools);- return (- modelLoaded && (parseExternalModelId(checkpoint) !== null || !supportsTools)- );+ const externalSelection = parseExternalModelId(checkpoint);+ const providers = useExternalProvidersStore((s) => s.providers);+ const externalProvider = externalSelection+ ? providers.find((provider) => provider.id === externalSelection.providerId)+ : undefined;+ const externalWithoutStudioTools =+ externalSelection !== null &&+ providerModelSupportsStudioTools(+ externalProvider?.providerType,+ externalSelection.modelId,+ ) !== true;+ return modelLoaded && (externalWithoutStudioTools || !supportsTools);}diff --git a/studio/frontend/src/features/chat/openai-codex-connect.tsx b/studio/frontend/src/features/chat/openai-codex-connect.tsxnew file mode 100644index 00000000000..8382d8a5bad--- /dev/null+++ b/studio/frontend/src/features/chat/openai-codex-connect.tsx@@ -0,0 +1,233 @@+// 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 { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { openLink } from "@/lib/open-link";+import { useEffect, useRef, useState } from "react";+import {+ cancelCodexOAuthFlow,+ completeCodexOAuth,+ disconnectCodexOAuth,+ getCodexOAuthFlow,+ startCodexOAuth,+ type CodexOAuthFlow,+ type ProviderAuthStatus,+} from "./api/providers-api";++export function isTrustedCodexAuthUrl(raw: string): boolean {+ try {+ const url = new URL(raw);+ return (+ url.origin === "https://auth.openai.com" &&+ (url.pathname === "/oauth/authorize" || url.pathname === "/codex/device") &&+ url.username === "" &&+ url.password === ""+ );+ } catch {+ return false;+ }+}++interface Props {+ providerId: string | null;+ authStatus?: ProviderAuthStatus;+ onChanged: () => void | Promise<void>;+ ensureProvider?: () => Promise<string>;+ initialFlow?: CodexOAuthFlow | null;+}++export function OpenAICodexConnect({+ providerId,+ authStatus,+ onChanged,+ ensureProvider,+ initialFlow = null,+}: Props) {+ const [flow, setFlow] = useState<CodexOAuthFlow | null>(initialFlow);+ const [callbackUrl, setCallbackUrl] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");++ const [activeProviderId, setActiveProviderId] = useState(providerId);+ const [locallyDisconnected, setLocallyDisconnected] = useState(false);+ const mounted = useRef(true);++ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);+ useEffect(() => {+ if (providerId) setActiveProviderId(providerId);+ }, [providerId]);+ useEffect(() => {+ if (!flow || flow.status !== "pending" || !activeProviderId) return;+ const delay = flow.method === "device" ? 2500 : 1500;+ const timer = window.setInterval(() => {+ if (Date.now() >= flow.expires_at * 1000) {+ setFlow((current) => current ? {+ ...current,+ status: "error",+ message: "Authorization expired. Start a new connection.",+ } : current);+ setError("Authorization expired. Start a new connection.");+ return;+ }+ void getCodexOAuthFlow(activeProviderId, flow.flow_id)+ .then((next) => {+ if (!mounted.current) return;+ setFlow(next);+ if (next.status === "connected") void onChanged();+ if (next.status === "error") setError(next.message || "Authorization failed.");+ })+ .catch((cause) => mounted.current && setError(cause instanceof Error ? cause.message : "Authorization failed."));+ }, delay);+ return () => window.clearInterval(timer);+ }, [flow, activeProviderId, onChanged]);++ async function start(method: "browser" | "device") {+ setBusy(true);+ setError("");++ setLocallyDisconnected(false);+ try {+ const resolvedProviderId = activeProviderId ?? await ensureProvider?.();+ if (!resolvedProviderId) {+ throw new Error("Could not create the ChatGPT connection.");+ }+ setActiveProviderId(resolvedProviderId);+ const next = await startCodexOAuth(resolvedProviderId, method);+ setFlow(next);+ const url = next.authorization_url || next.verification_url;+ if (url) {+ if (!isTrustedCodexAuthUrl(url)) throw new Error("The authorization URL was not trusted.");+ openLink(url);+ }+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Authorization failed.");+ } finally {+ setBusy(false);+ }+ }++ async function complete() {+ if (!flow || !activeProviderId || !callbackUrl.trim()) return;+ setBusy(true);+ setError("");+ try {+ const next = await completeCodexOAuth(activeProviderId, flow.flow_id, callbackUrl.trim());+ setFlow(next);++ setLocallyDisconnected(false);+ setCallbackUrl("");+ await onChanged();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Authorization failed.");+ } finally {+ setBusy(false);+ }+ }+ async function cancel() {+ if (!flow || !activeProviderId || flow.status !== "pending") return;+ setBusy(true);+ setError("");+ try {+ await cancelCodexOAuthFlow(activeProviderId, flow.flow_id);+ setFlow({ ...flow, status: "cancelled", message: "Authorization cancelled." });+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Cancellation failed.");+ } finally {+ setBusy(false);+ }+ }++++ async function disconnect() {+ if (!activeProviderId) return;+ setBusy(true);+ setError("");+ try {+ await disconnectCodexOAuth(activeProviderId);+ setFlow(null);++ setLocallyDisconnected(true);+ await onChanged();+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Disconnect failed.");+ } finally {+ setBusy(false);+ }+ }++ const connected =+ !locallyDisconnected &&+ (authStatus === "connected" || flow?.status === "connected");++ const visibleError = error || (flow?.status === "error" ? flow.message || "Authorization failed." : "");+ return (+ <section className="space-y-3 rounded-[8px] border border-border/70 bg-background/45 p-4">+ <div>+ <p className="text-sm font-medium">ChatGPT subscription</p>+ <p className="text-xs text-muted-foreground">+ {connected+ ? "Connected securely on this Studio installation."+ : authStatus === "reauthorization_required"+ ? "Your saved authorization is no longer valid. Reconnect to continue."+ : "Authorize in your system browser. Tokens never enter browser storage."}+ </p>+ </div>+ {flow?.method === "device" && flow.status === "pending" ? (+ <div className="space-y-2 text-sm">+ <p>Enter this code in ChatGPT:</p>+ <code className="block w-fit rounded bg-muted px-3 py-2 font-mono text-base">{flow.user_code}</code>+ <p className="text-xs text-muted-foreground">Device login may need to be enabled in ChatGPT security or workspace settings.</p>++ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => void navigator.clipboard.writeText(flow.user_code || "")}+ >+ Copy code+ </Button>++ <p className="text-xs text-muted-foreground">+ Expires {new Date(flow.expires_at * 1000).toLocaleTimeString()}.+ </p>+ </div>+ ) : null}+ {flow?.method === "browser" && flow.status === "pending" ? (+ <div className="space-y-2">+ <p className="text-xs text-muted-foreground">If the browser cannot return automatically, paste the complete localhost callback URL.</p>+ <div className="flex gap-2">+ <Input value={callbackUrl} onChange={(event) => setCallbackUrl(event.target.value)} placeholder="http://localhost:1455/auth/callback?..." />+ <Button type="button" variant="outline" disabled={busy || !callbackUrl.trim()} onClick={() => void complete()}>Complete</Button>+ </div>+ </div>+ ) : null}+ {flow?.status === "cancelled" ? (+ <p className="text-xs text-muted-foreground">Authorization cancelled.</p>+ ) : null}++ {visibleError ? <p role="alert" className="text-xs text-destructive">{visibleError}</p> : null}+ <div className="flex flex-wrap gap-2">+ {!connected ? (+ <>+ <Button type="button" size="sm" disabled={busy} onClick={() => void start("browser")}>+ {authStatus === "reauthorization_required" ? "Reconnect in browser" : "Connect in browser"}+ </Button>+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void start("device")}>Use device code</Button>+ {flow?.status === "pending" ? (+ <Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => void cancel()}>Cancel</Button>+ ) : null}+ </>+ ) : (+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => void disconnect()}>Disconnect locally</Button>+ )}+ </div>+ </section>+ );+}diff --git a/studio/frontend/src/features/chat/provider-capabilities.ts b/studio/frontend/src/features/chat/provider-capabilities.tsindex e7959294daf..986f58ebce5 100644--- a/studio/frontend/src/features/chat/provider-capabilities.ts+++ b/studio/frontend/src/features/chat/provider-capabilities.ts@@ -1,6 +1,8 @@// 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 { providerModelSupportsStudioTools } from "./external-providers";+/*** Per-provider sampling parameter capability matrix.*@@ -149,7 +151,11 @@ export function getExternalMaxOutputTokens(const effectiveProvider =providerType === "openrouter"? _inferProviderFromOpenrouterId(normalized) ?? providerType- : providerType;+ : providerType === "openai_codex"+ ? "openai_codex"+ : providerType;+ if (effectiveProvider === "openai_codex") return 128000;+for (const entry of EXTERNAL_MAX_OUTPUT_TOKENS_BY_MODEL) {if (entry.providerType !== effectiveProvider) continue;if (entry.prefixes.some((prefix) => stripped.startsWith(prefix))) {@@ -218,6 +224,10 @@ export function providerSupportsBuiltinWebSearch(}return true;}+ if (providerType === "openai_codex") {+ return providerModelSupportsStudioTools(providerType, modelId) === true;+ }+return (providerType === "openai" ||providerType === "anthropic" ||@@ -345,6 +355,10 @@ export function providerSupportsBuiltinCodeExecution(normalized.startsWith(prefix),);}+ if (providerType === "openai_codex") {+ return providerModelSupportsStudioTools(providerType, modelId) === true;+ }+if (providerType === "openai") {if (!isOpenAICloudBaseUrl(baseUrl)) return false;return OPENAI_CODE_EXECUTION_MODEL_PREFIXES.some((prefix) =>@@ -504,6 +518,15 @@ const PROVIDER_CAPABILITIES: Record<string, ProviderCapabilities> = {// models served via /v1/responses, which rejects temperature, top_p, and// presence/frequency penalty. See backend// external_provider._stream_openai_responses for the proxy.+ openai_codex: {+ temperature: false,+ topP: false,+ topK: false,+ minP: false,+ repetitionPenalty: false,+ presencePenalty: false,+ },+openai: {temperature: false,topP: false,@@ -953,7 +976,8 @@ export function getExternalReasoningCapabilities(? normalizedModel.split("/").at(-1) ?? normalizedModel: normalizedModel;- const isOpenAIProvider = normalizedProvider === "openai";+ const isOpenAIProvider =+ normalizedProvider === "openai" || normalizedProvider === "openai_codex";const isAnthropicProvider = normalizedProvider === "anthropic";const isKimiProvider = normalizedProvider === "kimi";const isMistralProvider = normalizedProvider === "mistral";diff --git a/studio/frontend/src/features/chat/research-inference-request.ts b/studio/frontend/src/features/chat/research-inference-request.tsnew file mode 100644index 00000000000..0fdc1c9bdfc--- /dev/null+++ b/studio/frontend/src/features/chat/research-inference-request.ts@@ -0,0 +1,78 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++type ReasoningEffort =+ | "none"+ | "minimal"+ | "low"+ | "medium"+ | "high"+ | "xhigh"+ | "max";+++export interface ResearchInferenceRequest {+ model: string;+ providerId?: string;+ providerType?: "openai_codex";+ externalModel?: string;+ temperature?: number;+ topP?: number;+ maxTokens?: number;+ enableThinking?: boolean;+ reasoningEffort?: string;+}++export function buildResearchInferenceRequest(input: {+ checkpoint: string;+ external?: { providerId: string; modelId: string };+ temperature: number;+ topP: number;+ maxTokens: number;+ reasoningRequested: boolean;+ reasoningStyle: string;+ reasoningEffort: ReasoningEffort;+ reasoningEffortLevels: readonly ReasoningEffort[];+ clampReasoningEffort: (+ effort: ReasoningEffort,+ levels: readonly ReasoningEffort[],+ ) => ReasoningEffort;+}): ResearchInferenceRequest {+ const model = input.external?.modelId ?? input.checkpoint;+ const request: ResearchInferenceRequest = {+ model,+ ...(input.external+ ? {+ providerId: input.external.providerId,+ providerType: "openai_codex" as const,+ externalModel: input.external.modelId,+ }+ : {}),+ };+ if (Number.isFinite(input.temperature) && input.temperature >= 0 && input.temperature <= 2) {+ request.temperature = input.temperature;+ }+ if (Number.isFinite(input.topP) && input.topP > 0 && input.topP <= 1) {+ request.topP = input.topP;+ }+ if (Number.isFinite(input.maxTokens) && input.maxTokens > 0) {+ request.maxTokens = Math.min(8192, Math.floor(input.maxTokens));+ }+ if (+ input.reasoningStyle === "enable_thinking" ||+ input.reasoningStyle === "enable_thinking_effort"+ ) {+ request.enableThinking = input.reasoningRequested;+ }+ if (+ input.reasoningRequested &&+ (input.reasoningStyle === "reasoning_effort" ||+ input.reasoningStyle === "enable_thinking_effort")+ ) {+ request.reasoningEffort = input.clampReasoningEffort(+ input.reasoningEffort,+ input.reasoningEffortLevels,+ );+ }+ return request;+}diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex 7ab9bd5c9b7..0443bdf71f2 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -50,7 +50,7 @@ import {loadConnectionsEnabled,loadExternalProviders,parseExternalModelId,- providerTypeSupportsVision,+ providerModelSupportsVision,} from "./external-providers";import {OPEN_DOCUMENT_SPREADSHEET_MIME,@@ -190,8 +190,9 @@ class VisionImageAdapter implements AttachmentAdapter {const provider = providers.find((p) => p.id === externalSelection.providerId,);- externalSupportsVision = providerTypeSupportsVision(+ externalSupportsVision = providerModelSupportsVision(provider?.providerType,+ externalSelection.modelId,);externalModelLabel = externalSelection.modelId;}diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex e055661fd31..86fb1322234 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -109,7 +109,9 @@ import { resolveFitMaxSeqLength, resolveManualAutoCtxPin } from "./presets/preseimport { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";import {parseExternalModelId,- providerTypeSupportsVision,+ providerModelSupportsVision,++ providerModelSupportsStudioTools,} from "./external-providers";import { compareModelDisplayName } from "./lib/external-model-label";import { useExternalProvidersStore } from "./stores/external-providers-store";@@ -658,8 +660,9 @@ export function SharedComposer({const imageUnavailableReason = getImageInputUnavailableReason({activeModel,isExternalModel,- externalSupportsVision: providerTypeSupportsVision(+ externalSupportsVision: providerModelSupportsVision(selectedExternalProvider?.providerType,+ externalSelection?.modelId,),externalModelLabel: externalSelection?.modelId ?? null,loadedIsMultimodal,@@ -785,11 +788,14 @@ export function SharedComposer({// Fetch pill: Anthropic-only (web_fetch_20250910 / web_fetch_20260209).const webFetchDisabled = !modelLoaded || !supportsBuiltinWebFetch;const showWebFetchPill = supportsBuiltinWebFetch;- // Docs (RAG) is local-only: search_knowledge_base needs the local runtime.- // Disable only when a loaded model can't run it; with no model the toggle- // can still be pre-selected, matching Web search/Code/MCP.- const ragDisabled = modelLoaded && (isExternalModel || !supportsTools);- const showRagPill = !isExternalModel;+ const externalUsesStudioTools =+ providerModelSupportsStudioTools(+ selectedExternalProvider?.providerType,+ externalSelection?.modelId,+ ) === true;+ const ragDisabled =+ modelLoaded && ((!externalUsesStudioTools && isExternalModel) || !supportsTools);+ const showRagPill = !isExternalModel || externalUsesStudioTools;// Above 4 pills, collapse to icons only. Compare, Search, Code, and// permissions always show; the rest are conditional. Narrow viewports// collapse too: the labelled row is wider than a phone-width composer.diff --git a/studio/frontend/src/features/chat/sync-external-providers.ts b/studio/frontend/src/features/chat/sync-external-providers.tsindex 6af78cfc063..41a2eda055c 100644--- a/studio/frontend/src/features/chat/sync-external-providers.ts+++ b/studio/frontend/src/features/chat/sync-external-providers.ts@@ -23,6 +23,8 @@ import {LEGACY_CUSTOM_PROVIDER_TYPE,pruneExternalProviderApiKeys,removeExternalProviderApiKey,++ setProviderModelCapabilities,supportsProviderPromptCaching,supportsProviderPromptCacheTtl,supportsProviderReasoningToggle,@@ -138,6 +140,10 @@ export async function syncExternalProvidersFromBackend(listProviderRegistry(),listProviderConfigs(),]);++ for (const entry of registryRows) {+ setProviderModelCapabilities(entry.provider_type, entry.model_capabilities);+ }const configRows = await reconcileLegacyProviderKeys(loadedConfigRows, {getLegacyKey: getExternalProviderApiKey,saveLegacyKey: migrateProviderApiKey,@@ -226,6 +232,9 @@ export async function syncExternalProvidersFromBackend(availableModels: resolvedAvailableModels,hasApiKey: config.has_api_key,++ authKind: config.auth_kind,+ authStatus: config.auth_status,enablePromptCaching: supportsProviderPromptCaching(uiProviderType)? (existing?.enablePromptCaching ?? true): undefined,diff --git a/studio/frontend/src/features/chat/tool-call-id.ts b/studio/frontend/src/features/chat/tool-call-id.tsnew file mode 100644index 00000000000..5bad56f89ad--- /dev/null+++ b/studio/frontend/src/features/chat/tool-call-id.ts@@ -0,0 +1,18 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export function resolveToolCallPartId(+ ids: Map<string, string>,+ backendId: string,+ confirmationId: string | undefined,+ lastPartId: string,+ createId: () => string,+): string {+ if (!backendId) return lastPartId;+ if (confirmationId) return confirmationId;+ const existing = ids.get(backendId);+ if (existing) return existing;+ const partId = createId();+ ids.set(backendId, partId);+ return partId;+}diff --git a/studio/frontend/tests/codex-reasoning.test.ts b/studio/frontend/tests/codex-reasoning.test.tsnew file mode 100644index 00000000000..345060f9117--- /dev/null+++ b/studio/frontend/tests/codex-reasoning.test.ts@@ -0,0 +1,31 @@+// 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 assert from "node:assert/strict";+import test from "node:test";++import {+ addCodexReasoning,+ codexReasoningForToolCalls,+ readCodexReasoning,++ type CodexReasoningLedger,+} from "../src/features/chat/codex-reasoning.ts";++test("Codex reasoning stays with each tool round and the final answer", () => {+ let ledger: CodexReasoningLedger = { byToolCall: {} };+ ledger = addCodexReasoning(ledger, ["round-one"], ["call-1"]);+ ledger = addCodexReasoning(ledger, ["round-two"], ["call-2"]);+ ledger = addCodexReasoning(ledger, ["final"], []);++ assert.deepEqual(codexReasoningForToolCalls(ledger, ["call-1"]), ["round-one"]);+ assert.deepEqual(codexReasoningForToolCalls(ledger, ["call-2"]), ["round-two"]);+ assert.deepEqual(ledger.final, ["final"]);+});++test("legacy reasoning metadata remains replayable", () => {+ assert.deepEqual(+ readCodexReasoning({ custom: { openaiCodexReasoning: ["legacy"] } }),+ { byToolCall: {}, final: ["legacy"] },+ );+});diff --git a/studio/frontend/tests/codex-tool-card-reconciliation.test.ts b/studio/frontend/tests/codex-tool-card-reconciliation.test.tsnew file mode 100644index 00000000000..019764eb883--- /dev/null+++ b/studio/frontend/tests/codex-tool-card-reconciliation.test.ts@@ -0,0 +1,33 @@+// 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 assert from "node:assert/strict";+import test from "node:test";++import { resolveToolCallPartId } from "../src/features/chat/tool-call-id.ts";++test("a Codex delta and execution events resolve to one card id", () => {+ const ids = new Map<string, string>();+ let sequence = 0;+ const createId = () => `call-1:run-${++sequence}`;++ const deltaId = resolveToolCallPartId(ids, "call-1", undefined, "", createId);+ const startId = resolveToolCallPartId(ids, "call-1", undefined, "", createId);+ const endId = resolveToolCallPartId(ids, "call-1", undefined, "", createId);++ assert.equal(deltaId, startId);+ assert.equal(startId, endId);+ assert.equal(sequence, 1);+});++test("confirmation ids and empty backend ids keep their existing identity", () => {+ const ids = new Map<string, string>();+ assert.equal(+ resolveToolCallPartId(ids, "call-1", "approval-1", "", () => "new"),+ "approval-1",+ );+ assert.equal(+ resolveToolCallPartId(ids, "", undefined, "last-card", () => "new"),+ "last-card",+ );+});diff --git a/studio/frontend/tests/local-reasoning-replay.test.ts b/studio/frontend/tests/local-reasoning-replay.test.tsindex 9e44c5a8f41..8081ae6b051 100644--- a/studio/frontend/tests/local-reasoning-replay.test.ts+++ b/studio/frontend/tests/local-reasoning-replay.test.ts@@ -2,227 +2,62 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";-import { readFileSync } from "node:fs";import test from "node:test";-import { fileURLToPath } from "node:url";-import ts from "typescript";--const adapterPath = fileURLToPath(- new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),-);-const source = readFileSync(adapterPath, "utf8");-const start = source.indexOf("function serializeAssistantReplayMessages(");-const end = source.indexOf("\nfunction toOpenAIMessages(", start);-assert.ok(- start >= 0 && end > start,- "assistant replay serializer was not found",-);-const declaration = source.slice(start, end);--const serializeAssistantReplayMessages = new Function(- "isAnthropicRefusalMessage",- "collectImageParts",- "sanitizeAssistantReplayText",- "buildReplayContent",- "serializeAssistantToolCallPart",- "serializeToolResultPart",- "canReplayToolCallWithoutRoleTool",- "shouldFlushCompletedLocalToolPair",- "attachAssistantThoughtSignature",- "collectAssistantTextThoughtSignature",- "readIncompleteInfo",- `${- ts.transpileModule(declaration, {- compilerOptions: { target: ts.ScriptTarget.ES2020 },- }).outputText- }; return serializeAssistantReplayMessages;`,-)(- () => false,- () => [],- (text: string) => text,- (text: string) => text,- (part: {- type?: string;- toolCallId?: string;- toolName?: string;- args?: unknown;- }) =>- part.type === "tool-call"- ? {- id: part.toolCallId,- type: "function",- function: {- name: part.toolName,- arguments: JSON.stringify(part.args ?? {}),- },- }- : null,- (part: {- type?: string;- toolCallId?: string;- toolName?: string;- result?: unknown;- }) =>- part.type === "tool-call" && part.result !== undefined- ? {- role: "tool",- content: String(part.result),- tool_call_id: part.toolCallId,- name: part.toolName,- }- : null,- () => false,- (part: { type?: string; result?: unknown }) =>- part.type === "tool-call" && part.result !== undefined,- () => undefined,- () => undefined,- (metadata: unknown) => {- const custom = (- metadata as { custom?: Record<string, unknown> } | undefined- )?.custom;- return custom?.incomplete ?? null;- },-) as (- message: {- role: "assistant";- status?: { type: string; reason?: string };- metadata?: { custom?: Record<string, unknown> };- content: Array<{- type: string;- text?: string;- toolCallId?: string;- toolName?: string;- args?: unknown;- result?: unknown;- }>;- },- includeReasoningContent?: boolean,-) => Array<Record<string, unknown>>;--const assistantTurn = {- role: "assistant" as const,- content: [- { type: "reasoning", text: "First inspect the premise." },- { type: "reasoning", text: "Then answer clearly." },- { type: "text", text: "Here is the answer." },- ],-};--test("local replay preserves structured assistant reasoning", () => {- assert.deepEqual(serializeAssistantReplayMessages(assistantTurn, true), [- {- role: "assistant",- content: "Here is the answer.",- reasoning_content: "First inspect the premise.\nThen answer clearly.",- },- ]);-});--test("external replay does not add the local reasoning extension", () => {- assert.deepEqual(serializeAssistantReplayMessages(assistantTurn, false), [- { role: "assistant", content: "Here is the answer." },- ]);-});--test("a completed reasoning-only turn preserves its answer", () => {- assert.deepEqual(- serializeAssistantReplayMessages(- {- role: "assistant",- status: { type: "complete" },- content: [{ type: "reasoning", text: "The answer is forty-two." }],- },- true,- ),- [- {- role: "assistant",- content: "",- reasoning_content: "The answer is forty-two.",- },- ],+import {+ codexLocalToolRoundId,+ shouldReplayAssistantReasoning,+ startsNewCodexToolRound,+} from "../src/features/chat/codex-reasoning.ts";++test("reasoning replay follows completion and provider policy", () => {+ const base = {+ reasoningContent: "A structured thought.",+ hasContent: false,+ hasToolCalls: false,+ };++ assert.equal(+ shouldReplayAssistantReasoning({ ...base, enabled: true, incomplete: false }),+ true,);-});--test("an incomplete reasoning-only turn remains an empty sentinel", () => {- assert.deepEqual(- serializeAssistantReplayMessages(- {- role: "assistant",- status: { type: "incomplete", reason: "cancelled" },- content: [{ type: "reasoning", text: "An unfinished thought." }],- },- true,- ),- [{ role: "assistant", content: "" }],+ assert.equal(+ shouldReplayAssistantReasoning({ ...base, enabled: true, incomplete: true }),+ false,);-});--test("a rehydrated incomplete reasoning-only turn remains an empty sentinel", () => {- assert.deepEqual(- serializeAssistantReplayMessages(- {- role: "assistant",- status: { type: "complete" },- metadata: {- custom: { incomplete: { reason: "cancelled" } },- },- content: [{ type: "reasoning", text: "An unfinished thought." }],- },- true,- ),- [{ role: "assistant", content: "" }],+ assert.equal(+ shouldReplayAssistantReasoning({+ ...base,+ enabled: true,+ incomplete: true,+ hasContent: true,+ }),+ true,+ );+ assert.equal(+ shouldReplayAssistantReasoning({ ...base, enabled: false, incomplete: false }),+ false,+ );+ assert.equal(+ shouldReplayAssistantReasoning({+ ...base,+ enabled: true,+ incomplete: false,+ reasoningContent: "",+ }),+ false,);});-test("reasoning stays with the assistant segment around a local tool call", () => {- assert.deepEqual(- serializeAssistantReplayMessages(- {- role: "assistant",- content: [- { type: "reasoning", text: "I should inspect the file." },- {- type: "tool-call",- toolCallId: "call-1",- toolName: "read_file",- args: { path: "notes.txt" },- result: "contents",- },- { type: "reasoning", text: "The file answers the question." },- { type: "text", text: "Here is the answer." },- ],- },- true,- ),- [- {- role: "assistant",- content: null,- reasoning_content: "I should inspect the file.",- tool_calls: [- {- id: "call-1",- type: "function",- function: {- name: "read_file",- arguments: '{"path":"notes.txt"}',- },- },- ],- },- {- role: "tool",- content: "contents",- tool_call_id: "call-1",- name: "read_file",- },- {- role: "assistant",- content: "Here is the answer.",- reasoning_content: "The file answers the question.",- },- ],- );+test("Codex local tool provenance preserves parallel calls and round boundaries", () => {+ const firstRound = { source: "local", round_id: 1 };+ const secondRound = { source: "local", round_id: 2 };++ assert.equal(codexLocalToolRoundId(firstRound), 1);+ assert.equal(codexLocalToolRoundId({ source: "external", round_id: 1 }), null);+ assert.equal(codexLocalToolRoundId({ source: "local", round_id: "1" }), null);++ assert.equal(startsNewCodexToolRound(null, 1), false);+ assert.equal(startsNewCodexToolRound(1, 1), false);+ assert.equal(startsNewCodexToolRound(1, codexLocalToolRoundId(secondRound)), true);});diff --git a/studio/frontend/tests/openai-codex-connect.test.ts b/studio/frontend/tests/openai-codex-connect.test.tsnew file mode 100644index 00000000000..73096bf4176--- /dev/null+++ b/studio/frontend/tests/openai-codex-connect.test.ts@@ -0,0 +1,118 @@+// 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 assert from "node:assert/strict";+import { after, before, test } from "node:test";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { createServer, type ViteDevServer } from "vite";++interface CodexOAuthFlow {+ flow_id: string;+ method: "browser" | "device";+ status: "pending" | "connected" | "error" | "cancelled";+ expires_at: number;+ authorization_url?: string | null;+ verification_url?: string | null;+ user_code?: string | null;+ message?: string | null;+}++interface ConnectProps {+ providerId: string | null;+ authStatus?: "disconnected" | "connected" | "reauthorization_required";+ onChanged: () => void;+ ensureProvider?: () => Promise<string>;+ initialFlow?: CodexOAuthFlow | null;+}++type ConnectComponent = (props: ConnectProps) => ReturnType<typeof createElement>;++let vite: ViteDevServer;+let OpenAICodexConnect: ConnectComponent;++before(async () => {+ vite = await createServer({+ appType: "custom",+ server: { middlewareMode: true },+ });+ const loaded = await vite.ssrLoadModule(+ "/src/features/chat/openai-codex-connect.tsx",+ );+ OpenAICodexConnect = loaded.OpenAICodexConnect as ConnectComponent;+});++after(async () => {+ await vite.close();+});++function render(props: Partial<ConnectProps> = {}): string {+ return renderToStaticMarkup(createElement(OpenAICodexConnect, {+ providerId: "provider-1",+ onChanged: () => undefined,+ ...props,+ }));+}++function flow(overrides: Partial<CodexOAuthFlow>): CodexOAuthFlow {+ return {+ flow_id: "flow-1",+ method: "browser",+ status: "pending",+ expires_at: 4_000_000_000,+ ...overrides,+ };+}++test("renders login options before the provider has been saved", () => {+ const markup = render({ providerId: null, ensureProvider: async () => "provider-1" });+ assert.match(markup, /Connect in browser/);+ assert.match(markup, /Use device code/);+});+++test("renders browser callback completion and cancellation controls", () => {+ const markup = render({ initialFlow: flow({ method: "browser" }) });+ assert.match(markup, /paste the complete localhost callback URL/i);+ assert.match(markup, /http:\/\/localhost:1455\/auth\/callback/);+ assert.match(markup, />Complete</);+ assert.match(markup, />Cancel</);+});++test("renders device-code instructions without exposing OAuth internals", () => {+ const markup = render({+ initialFlow: flow({ method: "device", user_code: "ABCD-EFGH" }),+ });+ assert.match(markup, /Enter this code in ChatGPT/);+ assert.match(markup, /ABCD-EFGH/);+ assert.match(markup, />Copy code</);+ assert.doesNotMatch(markup, /code_verifier|device_auth_id|secret-state/);+});+++test("renders an expired authorization error as an alert", () => {+ const markup = render({+ initialFlow: flow({+ status: "error",+ message: "Authorization expired. Start a new connection.",+ }),+ });+ assert.match(markup, /role="alert"/);+ assert.match(markup, /Authorization expired/);+ assert.match(markup, /Connect in browser/);+});++test("renders cancelled, reconnect-required, and connected states", () => {+ assert.match(+ render({ initialFlow: flow({ status: "cancelled" }) }),+ /Authorization cancelled/,+ );+ assert.match(+ render({ authStatus: "reauthorization_required" }),+ /Reconnect in browser/,+ );+ const connected = render({ authStatus: "connected" });+ assert.match(connected, /Connected securely/);+ assert.match(connected, /Disconnect locally/);+ assert.doesNotMatch(connected, /Connect in browser/);+});diff --git a/studio/frontend/tests/provider-capabilities-current-models.test.ts b/studio/frontend/tests/provider-capabilities-current-models.test.tsindex c55ae46a0d3..3b824385b0e 100644--- a/studio/frontend/tests/provider-capabilities-current-models.test.ts+++ b/studio/frontend/tests/provider-capabilities-current-models.test.ts@@ -12,9 +12,15 @@ const {getExternalMaxOutputTokens,getExternalReasoningCapabilities,providerSupportsBuiltinCodeExecution,++ providerSupportsBuiltinWebSearch,providerSupportsFastMode,} = await import("../src/features/chat/provider-capabilities.ts");+const { providerModelSupportsVision, setProviderModelCapabilities } = await import(+ "../src/features/chat/external-providers.ts"+);+// The picker's default_models list (backend core/inference/providers.py) grew a// Claude 5 / gpt-5.6 / gemini-3.6 generation. Every table here is prefix-based,// so an un-widened prefix silently drops the control instead of failing loudly:@@ -71,6 +77,38 @@ test("the gpt-5.6 family gets the gpt-5.5 reasoning ladder", () => {}});+test("ChatGPT subscription models expose Studio-owned search and code tools", () => {++ setProviderModelCapabilities("openai_codex", {+ "gpt-5.3-codex-spark": { vision: false, studio_tools: true },+ "gpt-5.4": { vision: true, studio_tools: true },+ "gpt-5.6-sol": { vision: true, studio_tools: true },+ });+ for (const model of ["gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.6-sol"]) {+ const caps = getExternalReasoningCapabilities("openai_codex", model);+ assert.equal(caps.supportsReasoning, true, model);+ assert.equal(caps.reasoningStyle, "reasoning_effort", model);+ assert.equal(getExternalMaxOutputTokens("openai_codex", model), 128000, model);+ assert.equal(providerSupportsBuiltinWebSearch("openai_codex", model), true, model);+ assert.equal(providerSupportsBuiltinCodeExecution("openai_codex", model), true, model);+ }+});+++test("ChatGPT subscription vision gating follows the curated model", () => {++ setProviderModelCapabilities("openai_codex", {+ "gpt-5.3-codex-spark": { vision: false, studio_tools: true },+ "gpt-5.6-sol": { vision: true, studio_tools: true },+ });+ assert.equal(+ providerModelSupportsVision("openai_codex", "gpt-5.3-codex-spark"),+ false,+ );+ assert.equal(providerModelSupportsVision("openai_codex", "gpt-5.6-sol"), true);+});++test("Gemini 3.x minors keep the thinkingLevel ladder", () => {// gemini-3.6-flash must not fall through to the 2.5 integer-budget branch.for (const model of ["gemini-3.6-flash", "gemini-3.5-flash-lite", "gemini-3-flash-preview"]) {diff --git a/studio/frontend/tests/research-inference-request.test.ts b/studio/frontend/tests/research-inference-request.test.tsnew file mode 100644index 00000000000..fb696efcf02--- /dev/null+++ b/studio/frontend/tests/research-inference-request.test.ts@@ -0,0 +1,54 @@+// 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 assert from "node:assert/strict";+import test from "node:test";++import { buildResearchInferenceRequest } from "../src/features/chat/research-inference-request.ts";++const clamp = (effort: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max") =>+ effort === "xhigh" ? "high" as const : effort;++test("Codex research keeps provider routing and clamps generation settings", () => {+ assert.deepEqual(+ buildResearchInferenceRequest({+ checkpoint: "external::provider::gpt-5.6-sol",+ external: { providerId: "provider", modelId: "gpt-5.6-sol" },+ temperature: 0.2,+ topP: 0.9,+ maxTokens: 20000,+ reasoningRequested: true,+ reasoningStyle: "reasoning_effort",+ reasoningEffort: "xhigh",+ reasoningEffortLevels: ["low", "medium", "high"],+ clampReasoningEffort: clamp,+ }),+ {+ model: "gpt-5.6-sol",+ providerId: "provider",+ providerType: "openai_codex",+ externalModel: "gpt-5.6-sol",+ temperature: 0.2,+ topP: 0.9,+ maxTokens: 8192,+ reasoningEffort: "high",+ },+ );+});++test("invalid optional settings do not leak into a local research request", () => {+ assert.deepEqual(+ buildResearchInferenceRequest({+ checkpoint: "local/model.gguf",+ temperature: 3,+ topP: 0,+ maxTokens: 0,+ reasoningRequested: false,+ reasoningStyle: "enable_thinking",+ reasoningEffort: "none",+ reasoningEffortLevels: ["none", "low"],+ clampReasoningEffort: clamp,+ }),+ { model: "local/model.gguf", enableThinking: false },+ );+});diff --git a/tests/studio/test_deep_research_frontend_contract.py b/tests/studio/test_deep_research_frontend_contract.pyindex c8c0b20d3ba..1dc861d8348 100644--- a/tests/studio/test_deep_research_frontend_contract.py+++ b/tests/studio/test_deep_research_frontend_contract.py@@ -44,6 +44,8 @@ def test_research_api_is_isolated_and_cursor_based() -> None:def test_research_mode_is_single_chat_and_detaches_without_cancel() -> None:adapter = source("features/chat/api/chat-adapter.ts")++ inference_request = source("features/chat/research-inference-request.ts")thread = source("components/assistant-ui/thread.tsx")assert "runtime.deepResearchEnabled" in adapterassert "!options.pairId" in adapter@@ -58,10 +60,10 @@ def test_research_mode_is_single_chat_and_detaches_without_cancel() -> None:assert "watchResearchRun(createdRun.id" in adapterassert "followResearchRun" not in adapterassert "inferenceRequest" in adapter- assert "Number.isFinite(params.temperature)" in adapter- assert "Number.isFinite(params.topP)" in adapter- assert "Number.isFinite(params.maxTokens)" in adapter- assert "Math.min(8192, Math.floor(params.maxTokens))" in adapter+ assert "Number.isFinite(input.temperature)" in inference_request+ assert "Number.isFinite(input.topP)" in inference_request+ assert "Number.isFinite(input.maxTokens)" in inference_request+ assert "Math.min(8192, Math.floor(input.maxTokens))" in inference_requestassert '{ type: "text" as const, text: report }' in adapter# yields are deduped by status, or every streamed delta drives an autosave the server rejects.assert "run.status === yieldedStatus" in adapter@@ -99,12 +101,11 @@ def test_research_reasoning_effort_is_clamped_to_the_loaded_model() -> None:# fall back to the template default. Must use the same helper and levels as normal local# chat so the two paths cannot drift apart again.adapter = source("features/chat/api/chat-adapter.ts")- branch = adapter.split("Deep research requires a selected local model.", 1)[1].split(- "createdRun = await createResearchRun({", 1- )[0]- assert "inferenceRequest.reasoningEffort = runtime.reasoningEffort;" not in branch- assert "inferenceRequest.reasoningEffort = clampReasoningEffortToLevels(" in branch- assert "runtime.reasoningEffortLevels," in branch+ inference_request = source("features/chat/research-inference-request.ts")+ assert "buildResearchInferenceRequest({" in adapter+ assert "request.reasoningEffort = input.reasoningEffort;" not in inference_request+ assert "request.reasoningEffort = input.clampReasoningEffort(" in inference_request+ assert "input.reasoningEffortLevels," in inference_requestassert "const localReasoningEffort = clampReasoningEffortToLevels(" in adapter