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
Studio: let the owner share a connection with every account (#14365)
Daniel Han0a930d47e3bd
diff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.pyindex 89db426d090..f339a3b09c7 100644--- a/studio/backend/hub/services/models/account_access.py+++ b/studio/backend/hub/services/models/account_access.py@@ -826,6 +826,39 @@ def model_allowed(repo_id: str) -> bool:return any(fnmatchcase(repo_id, pattern) for pattern in allowlist)+def connection_model_allowed(model_id: str) -> bool:+ allowlist = model_allowlist()+ if allowlist is None:+ return True+ model_id = (model_id or "").strip().lower()+ untagged = model_id.split(":", 1)[0]+ # OpenRouter's "latest" aliases carry a leading "~", which an allowlist entry cannot.+ candidates = {model_id, untagged, untagged.lstrip("~")}+ return any(fnmatchcase(candidate, pattern) for candidate in candidates for pattern in allowlist)+++def shared_connection_view(row: dict) -> dict | None:+ view = {**row, "shared": True, "shared_by_owner": True}+ models = row.get("models") or []+ if not models:+ from core.inference.providers import get_provider_info+ models = list(+ (get_provider_info(row.get("provider_type") or "") or {}).get("default_models") or []+ )+ view["models"] = [model for model in models if connection_model_allowed(model)]+ view["available_models"] = [+ model for model in row.get("available_models") or [] if model in view["models"]+ ]+ return view if view["models"] else None+++def require_connection_model_allowed(config: dict | None, model) -> None:+ if not config or not config.get("shared_by_owner"):+ return+ if not isinstance(model, str) or model not in (config.get("models") or []):+ raise HTTPException(status_code = 403, detail = MODEL_NOT_ALLOWED)++def _reference_repo_id(reference: str) -> str | None:path = Path(reference).expanduser()if path.is_absolute() or reference.startswith(("./", "../", "~")) or path.exists():diff --git a/studio/backend/models/providers.py b/studio/backend/models/providers.pyindex 492c4036e2d..c55fc6103cc 100644--- a/studio/backend/models/providers.py+++ b/studio/backend/models/providers.py@@ -114,6 +114,10 @@ class ProviderCreate(BaseModel):None,description = "Optional RSA-encrypted API key to persist for this connection",)+ shared: bool = Field(+ False,+ description = "Let every account on this installation use this connection (owner only)",+ )class ProviderUpdate(BaseModel):@@ -146,6 +150,10 @@ class ProviderUpdate(BaseModel):False,description = "Explicitly remove the saved API key",)+ shared: Optional[bool] = Field(+ None,+ description = "Let every account on this installation use this connection (owner only)",+ )class ProviderCredentialMigration(BaseModel):@@ -186,6 +194,11 @@ class ProviderResponse(BaseModel):None,description = "Configured maximum Max Tokens cap for this connection",)+ shared: bool = Field(False, description = "Whether every account on this installation can use it")+ shared_by_owner: bool = Field(+ False,+ description = "The installation owner shared this connection; this account can use but not edit it",+ )created_at: str = Field(..., description = "ISO 8601 creation timestamp")updated_at: str = Field(..., description = "ISO 8601 last-update timestamp")diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 0ec3774ce65..2f7a9e5c7bf 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -25852,6 +25852,7 @@ async def _external_tts_speech(body: AudioSpeechRequest, request: Request) -> Reconfig = await asyncio.to_thread(providers_db.get_provider, provider_id)if config is None:raise HTTPException(status_code = 404, detail = f"Provider config not found: {provider_id}")+ account_access.require_connection_model_allowed(config, external_model)_refuse_decision_connection(config["provider_type"], config.get("api_type"))if not config["is_enabled"]:raise HTTPException(@@ -25865,7 +25866,9 @@ async def _external_tts_speech(body: AudioSpeechRequest, request: Request) -> Rebase_url = validate_provider_base_url(base_url)except ValueError as exc:raise HTTPException(status_code = 400, detail = str(exc)) from None- async with provider_config_guard(provider_id):+ async with provider_config_guard(+ provider_id, shared_by_owner = bool(config.get("shared_by_owner"))+ ):current = await asyncio.to_thread(providers_db.get_provider, provider_id)routing_fields = ("provider_type", "base_url", "is_enabled")if current is None or any(@@ -25875,6 +25878,7 @@ async def _external_tts_speech(body: AudioSpeechRequest, request: Request) -> Restatus_code = 409,detail = "Provider changed while the request was starting; retry.",)+ account_access.require_connection_model_allowed(current, external_model)if body.encrypted_api_key and body.provider_base_url != current.get("base_url"):# The browser encrypted a legacy key for the connection it rendered. A# same-id edit may have replaced both its destination and saved key while@@ -26102,6 +26106,7 @@ async def _external_stt_transcription(config = await asyncio.to_thread(providers_db.get_provider, provider_id)if config is None:raise HTTPException(status_code = 404, detail = f"Provider config not found: {provider_id}")+ account_access.require_connection_model_allowed(config, external_model)_refuse_decision_connection(config["provider_type"], config.get("api_type"))if not config["is_enabled"]:raise HTTPException(@@ -26116,7 +26121,9 @@ async def _external_stt_transcription(except ValueError as exc:raise HTTPException(status_code = 400, detail = str(exc)) from None- async with provider_config_guard(provider_id):+ async with provider_config_guard(+ provider_id, shared_by_owner = bool(config.get("shared_by_owner"))+ ):current = await asyncio.to_thread(providers_db.get_provider, provider_id)routing_fields = ("provider_type", "base_url", "is_enabled")if current is None or any(@@ -26126,6 +26133,7 @@ async def _external_stt_transcription(status_code = 409,detail = "Provider changed while the request was starting; retry.",)+ account_access.require_connection_model_allowed(current, external_model)api_key = await asyncio.to_thread(resolve_provider_api_key_or_400,provider_id,@@ -30267,6 +30275,9 @@ async def _proxy_to_external_provider(# A saved credential is scoped to this saved provider. Never pair it with# request-controlled routing metadata.saved_provider_snapshot = config+ account_access.require_connection_model_allowed(+ config, payload.external_model or payload.model+ )provider_type = config["provider_type"]base_url = config["base_url"]api_type = config.get("api_type", "chat_completions")@@ -30832,7 +30843,10 @@ async def _proxy_to_external_provider(if managed is not None:api_key = managed.api_keyelif saved_provider_snapshot is not None:- async with provider_config_guard(payload.provider_id):+ async with provider_config_guard(+ payload.provider_id,+ shared_by_owner = bool(saved_provider_snapshot.get("shared_by_owner")),+ ):current = await asyncio.to_thread(providers_db.get_provider, payload.provider_id)routing_fields = ("provider_type",@@ -30848,6 +30862,9 @@ async def _proxy_to_external_provider(status_code = 409,detail = "Provider changed while the request was starting; retry.",)+ account_access.require_connection_model_allowed(+ current, payload.external_model or payload.model+ )api_key = await asyncio.to_thread(resolve_provider_api_key_or_400,payload.provider_id,@@ -31807,6 +31824,11 @@ def _resolve_openai_cloud_client(status_code = 400,detail = "OpenAI container management requires a saved OpenAI provider.",)+ if config.get("shared_by_owner"):+ raise HTTPException(+ status_code = 403,+ detail = "OpenAI containers are not available on a connection shared by the owner.",+ )if not config["is_enabled"]:raise HTTPException(@@ -51991,6 +52013,7 @@ async def _external_image_generation(config = await asyncio.to_thread(providers_db.get_provider, provider_id)if config is None:raise HTTPException(status_code = 404, detail = f"Provider config not found: {provider_id}")+ account_access.require_connection_model_allowed(config, external_model)_refuse_decision_connection(config["provider_type"], config.get("api_type"))if not config["is_enabled"]:raise HTTPException(@@ -52005,7 +52028,9 @@ async def _external_image_generation(except ValueError as exc:raise HTTPException(status_code = 400, detail = str(exc)) from None- async with provider_config_guard(provider_id):+ async with provider_config_guard(+ provider_id, shared_by_owner = bool(config.get("shared_by_owner"))+ ):current = await asyncio.to_thread(providers_db.get_provider, provider_id)routing_fields = ("provider_type", "base_url", "is_enabled")if current is None or any(@@ -52015,6 +52040,7 @@ async def _external_image_generation(status_code = 409,detail = "Provider changed while the request was starting; retry.",)+ account_access.require_connection_model_allowed(current, external_model)api_key = await asyncio.to_thread(resolve_provider_api_key_or_400,provider_id,diff --git a/studio/backend/routes/provider_credentials.py b/studio/backend/routes/provider_credentials.pyindex 2d8f8177d57..8cb0bc62b97 100644--- a/studio/backend/routes/provider_credentials.py+++ b/studio/backend/routes/provider_credentials.py@@ -19,7 +19,7 @@ from fastapi import HTTPExceptionfrom storage import credential_secretsfrom hub.services.models import account_access-from utils.account_context import current_account_id+from utils.account_context import OWNER, current_account_id, run_aslogger = structlog.get_logger(__name__)@@ -28,15 +28,21 @@ _provider_config_locks: WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, a)-def provider_config_guard(provider_id: str) -> asyncio.Lock:+def _guard_key(provider_id: str):+ if account_access.account_scope() is None:+ return provider_id+ return (current_account_id(), provider_id)+++def provider_config_guard(provider_id: str, *, shared_by_owner: bool = False) -> asyncio.Lock:"""Serialize one provider's routing metadata and installation credential."""loop = asyncio.get_running_loop()locks = _provider_config_locks.setdefault(loop, {})- key = (- (current_account_id(), provider_id)- if account_access.account_scope() is not None- else provider_id- )+ key = _guard_key(provider_id)+ # Runs on the event loop: the caller passes the flag, never read the store here.+ if shared_by_owner and account_access.managed_account():+ # Readers queue behind the owner's edit of a shared row.+ key = run_as(OWNER, _guard_key, provider_id)return locks.setdefault(key, asyncio.Lock())diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.pyindex 6d920fd53c1..ef1ff6f6cec 100644--- a/studio/backend/routes/providers.py+++ b/studio/backend/routes/providers.py@@ -79,7 +79,11 @@ _MAX_RESPONSES_CONNECTIVITY_MODELS = 5_PROVIDER_CONNECTIVITY_TIMEOUT_SECONDS = 15.0+_SHARED_READ_ONLY = "This connection is shared by the installation owner. Only they can change it."++def _provider_response(row: dict) -> ProviderResponse:+ has_api_key = credential_secrets.provider_api_key_saved(row["id"])return ProviderResponse(id = row["id"],provider_type = row["provider_type"],@@ -88,30 +92,55 @@ def _provider_response(row: dict) -> ProviderResponse:api_type = row.get("api_type", "chat_completions"),reasoning_config = row.get("reasoning_config"),is_enabled = bool(row["is_enabled"]),- has_api_key = credential_secrets.has_secret(- credential_secrets.PROVIDER_API_KEY_KIND,- row["id"],- ),+ has_api_key = has_api_key,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"- )+ else ("connected" if has_api_key else "disconnected")),models = row.get("models") or [],available_models = row.get("available_models") or [],max_output_tokens = row.get("max_output_tokens"),+ shared = bool(row.get("shared")),+ shared_by_owner = bool(row.get("shared_by_owner")),created_at = row["created_at"],updated_at = row["updated_at"],)+def _validate_share_request(+ shared: bool | None,+ provider_type: str,+ base_url: str | None = None,+) -> None:+ if not shared:+ return+ if account_access.managed_account():+ raise HTTPException(+ status_code = 403, detail = "Only the installation owner can share connections."+ )+ if provider_type == "openai_codex":+ raise HTTPException(+ status_code = 400, detail = "A ChatGPT subscription connection cannot be shared."+ )+ if providers_db.base_url_carries_credential(base_url):+ # Other accounts are shown the base URL, so a credential inside it would be shared too.+ raise HTTPException(+ status_code = 400,+ detail = "Move the credential in this base URL into the API key field to share it.",+ )+++def _own_provider_or_error(provider_id: str) -> dict:+ existing = providers_db.get_own_provider(provider_id)+ if existing is not None:+ return existing+ if providers_db.is_owner_shared_provider(provider_id):+ raise HTTPException(status_code = 403, detail = _SHARED_READ_ONLY)+ raise HTTPException(status_code = 404, detail = "Provider not found")++def _validate_provider_auth_contract(info: dict,*,@@ -260,6 +289,7 @@ async def create_provider_config()base_url = payload.base_url or info["base_url"]+ _validate_share_request(payload.shared, payload.provider_type, base_url)# An empty base URL stays allowed (custom/vLLM entries carry none until the# user fills one in); anything present is checked before a key is decrypted.if base_url:@@ -284,6 +314,7 @@ async def create_provider_config(max_output_tokens = payload.max_output_tokens,api_type = payload.api_type,reasoning_config = payload.reasoning_config,+ shared = payload.shared,)try:if api_key:@@ -307,9 +338,12 @@ async def update_provider_config("""Update a saved provider configuration."""require_ui_session(via_api_key)- existing = providers_db.get_provider(provider_id)- if not existing:- raise HTTPException(status_code = 404, detail = "Provider not found")+ existing = _own_provider_or_error(provider_id)+ _validate_share_request(+ payload.shared if payload.shared is not None else existing.get("shared"),+ existing["provider_type"],+ payload.base_url or existing["base_url"],+ )reasoning_config_requested = "reasoning_config" in payload.model_fields_seteffective_reasoning_config = (@@ -389,6 +423,7 @@ async def update_provider_config("max_output_tokens","api_type","reasoning_config",+ "shared",}metadata_requested = bool(payload.model_fields_set & metadata_fields)@@ -420,6 +455,7 @@ async def update_provider_config(models = payload.models,available_models = payload.available_models,api_type = payload.api_type,+ shared = payload.shared,)if max_output_tokens_requested:metadata_updates["max_output_tokens"] = payload.max_output_tokens@@ -440,12 +476,13 @@ async def update_provider_config(max_output_tokens = existing.get("max_output_tokens"),api_type = existing.get("api_type", "chat_completions"),reasoning_config = existing.get("reasoning_config"),+ shared = bool(existing.get("shared")),)def _current_matches(current: dict, field: str, written) -> bool:"""Does the row still hold what this request wrote into that column?"""- if field == "is_enabled":- return bool(current.get("is_enabled")) == bool(written)+ if field in ("is_enabled", "shared"):+ return bool(current.get(field)) == bool(written)return current.get(field) == writtendef _restore_metadata() -> None:@@ -538,8 +575,7 @@ async def migrate_provider_api_key():"""Insert a browser legacy key only when this provider has no saved key."""require_ui_session(via_api_key)- if providers_db.get_provider(provider_id) is None:- raise HTTPException(status_code = 404, detail = "Provider not found")+ _own_provider_or_error(provider_id)api_key = resolve_provider_api_key_or_400(None, payload.encrypted_api_key, allow_saved_key = False)@@ -559,8 +595,11 @@ async def delete_provider_config(via_api_key: bool = Depends(authenticated_via_api_key),):"""Idempotently delete a saved provider and its installation credential."""- if account_access.managed_account() and providers_db.get_provider(provider_id) is None:- raise HTTPException(status_code = 404, detail = "Provider config not found")+ if providers_db.get_own_provider(provider_id) is None:+ if providers_db.is_owner_shared_provider(provider_id):+ raise HTTPException(status_code = 403, detail = _SHARED_READ_ONLY)+ if account_access.managed_account():+ raise HTTPException(status_code = 404, detail = "Provider config not found")require_ui_session(via_api_key)await openai_codex_auth.cancel_provider_flows(provider_id)credential_secrets.get_or_create_credential_encryption_key()@@ -615,6 +654,20 @@ async def delete_provider_config(openai_codex_client.forget_subscription_models(provider_id)+def _is_shared_saved_target(payload) -> bool:+ return bool(+ payload.provider_id+ and not payload.encrypted_api_key+ and providers_db.is_owner_shared_provider(payload.provider_id)+ )+++def _shared_target_models(payload) -> set[str] | None:+ if not _is_shared_saved_target(payload):+ return None+ return set((providers_db.get_provider(payload.provider_id) or {}).get("models") or [])++def _bind_saved_provider_target(payload):"""Use the saved provider's endpoint whenever its saved credential may be used."""if not payload.provider_id or payload.encrypted_api_key:@@ -836,6 +889,7 @@ async def test_provider(saved provider key."""+ shared = _is_shared_saved_target(payload)payload = _bind_saved_provider_target(payload)info = get_connectable_provider_info(payload.provider_type)if info is None:@@ -875,6 +929,25 @@ async def test_provider(timeout = _PROVIDER_CONNECTIVITY_TIMEOUT_SECONDS,)+ if shared:+ # Others learn only reachability: no model probe, no upstream error text (it can quote the URL).+ try:+ if answers_decisions_only(payload.provider_type, payload.api_type):+ await client.list_decision_models()+ else:+ await client.list_models()+ except Exception:+ return ProviderTestResult(+ success = False,+ message = "Connection failed. Ask the owner to check this connection.",+ models_count = None,+ )+ finally:+ await client.close()+ return ProviderTestResult(+ success = True, message = "Connected successfully.", models_count = None+ )+try:if answers_decisions_only(payload.provider_type, payload.api_type):return await _test_decision_connectivity(client, (payload.model_id or "").strip())@@ -995,6 +1068,14 @@ async def list_provider_model_capabilities(_current_subject: str = Depends(get_current_subject),via_api_key: bool = Depends(authenticated_via_api_key),):+ shared_models = _shared_target_models(payload)+ capabilities = await _list_model_capabilities(payload, via_api_key)+ if shared_models is not None:+ capabilities = [entry for entry in capabilities if entry.get("id", "") in shared_models]+ return capabilities+++async def _list_model_capabilities(payload: ProviderModelsRequest, via_api_key: bool):payload = _bind_saved_provider_target(payload)info = get_connectable_provider_info(payload.provider_type)if info is None:@@ -1068,6 +1149,7 @@ async def list_provider_models(An explicit encrypted key takes precedence over the saved provider key."""+ shared_models = _shared_target_models(payload)payload = _bind_saved_provider_target(payload)info = get_connectable_provider_info(payload.provider_type)if info is None:@@ -1091,6 +1173,7 @@ async def list_provider_models(owned_by = None,)for m in info.get("default_models", [])+ if shared_models is None or m in shared_models]base_url = payload.base_url or info["base_url"]@@ -1129,7 +1212,9 @@ async def list_provider_models(except ValueError:ids = []return [- ProviderModelInfo(id = m, display_name = m, context_length = None, owned_by = None) for m in ids+ ProviderModelInfo(id = m, display_name = m, context_length = None, owned_by = None)+ for m in ids+ if shared_models is None or m in shared_models]try:@@ -1171,6 +1256,8 @@ async def list_provider_models(models = [m for m in models if not denylist.search(m.get("id", ""))]# Optional cap after filtering to keep large catalogs picker-sized. Unsorted, so "first N matches"; pair with# default_models for flagships.+ if shared_models is not None:+ models = [m for m in models if m.get("id", "") in shared_models]limit = info.get("model_id_limit")if isinstance(limit, int) and limit > 0:models = models[:limit]diff --git a/studio/backend/routes/research_runs.py b/studio/backend/routes/research_runs.pyindex dfebf8e121d..67c4bce4ec2 100644--- a/studio/backend/routes/research_runs.py+++ b/studio/backend/routes/research_runs.py@@ -26,6 +26,7 @@ from core.inference.providers import answers_decisions_only, provider_runs_localfrom models.providers import MAX_JSON_SAFE_INTEGERfrom state import run_subscribers, unattended_runsfrom state.tool_policy import get_tool_policy+from hub.services.models import account_accessfrom storage import mcp_servers_db, providers_dbfrom storage.studio_db import get_chat_message, get_chat_thread, upsert_chat_messagefrom utils.current_date_prompt_settings import current_date_prompt_line@@ -358,6 +359,7 @@ def _sanitize_config(provider = providers_db.get_provider(provider_id)if provider is None:raise HTTPException(status_code = 404, detail = "Provider config not found")+ account_access.require_connection_model_allowed(provider, external_model)# The saved row is the source of truth for routing, so validate against it rather than the type the client# sent: a self-hosted connection is stored under the backend "openai" type but surfaced as "custom" / "vllm" /# "ollama" / "llama_cpp", so comparing the two for equality 400s exactly the connections this path serves.diff --git a/studio/backend/storage/credential_secrets.py b/studio/backend/storage/credential_secrets.pyindex 9568f91e3f4..fa556792b99 100644--- a/studio/backend/storage/credential_secrets.py+++ b/studio/backend/storage/credential_secrets.py@@ -302,7 +302,33 @@ def delete_hf_token() -> bool:def get_provider_api_key(provider_id: str) -> Optional[str]:- return get_secret(PROVIDER_API_KEY_KIND, provider_id)+ key = get_secret(PROVIDER_API_KEY_KIND, provider_id)+ if key is None and _owner_shared_provider(provider_id):+ from utils.account_context import OWNER, run_as++ # Server-side only: no route returns a saved key.+ key = run_as(OWNER, get_secret, PROVIDER_API_KEY_KIND, provider_id)+ return key+++def provider_api_key_saved(provider_id: str) -> bool:+ if has_secret(PROVIDER_API_KEY_KIND, provider_id):+ return True+ if not _owner_shared_provider(provider_id):+ return False+ from utils.account_context import OWNER, run_as++ return run_as(OWNER, has_secret, PROVIDER_API_KEY_KIND, provider_id)+++def _owner_shared_provider(provider_id: str) -> bool:+ from utils.account_context import is_owner_context++ if is_owner_context() or not provider_id:+ return False+ from storage import providers_db++ return providers_db.is_owner_shared_provider(provider_id)def save_provider_api_key(diff --git a/studio/backend/storage/providers_db.py b/studio/backend/storage/providers_db.pyindex 3a2f7d0b806..e35018ec566 100644--- a/studio/backend/storage/providers_db.py+++ b/studio/backend/storage/providers_db.py@@ -153,6 +153,8 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:conn.execute("ALTER TABLE llm_providers ADD COLUMN max_output_tokens INTEGER")if "reasoning_config_json" not in existing_cols:conn.execute("ALTER TABLE llm_providers ADD COLUMN reasoning_config_json TEXT")+ if "shared" not in existing_cols:+ conn.execute("ALTER TABLE llm_providers ADD COLUMN shared INTEGER NOT NULL DEFAULT 0")# ALTER TABLE persists independently in SQLite, but its one-time data migration does not.conn.commit()@@ -215,6 +217,7 @@ def create_provider(max_output_tokens: Optional[int] = None,api_type: str = "chat_completions",reasoning_config: Optional[dict] = None,+ shared: bool = False,) -> None:"""Insert a new provider configuration."""reasoning_json = _encode_reasoning_config(reasoning_config)@@ -226,9 +229,9 @@ def create_provider(INSERT INTO llm_providers (id, provider_type, display_name, base_url,models_json, available_models_json, max_output_tokens, api_type,- reasoning_config_json, created_at, updated_at+ reasoning_config_json, shared, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",(id,@@ -240,6 +243,7 @@ def create_provider(max_output_tokens,api_type,reasoning_json,+ 1 if shared else 0,now,now,),@@ -261,6 +265,7 @@ def update_provider(connection: sqlite3.Connection | None = None,api_type: str | None = None,reasoning_config: dict | None | object = _UNSET,+ shared: bool | None = None,) -> bool:"""Update fields on an existing provider. Returns True if a row was updated."""updates = []@@ -289,6 +294,9 @@ def update_provider(if reasoning_config is not _UNSET:updates.append("reasoning_config_json = ?")params.append(_encode_reasoning_config(reasoning_config))+ if shared is not None:+ updates.append("shared = ?")+ params.append(1 if shared else 0)if not updates:return Falseupdates.append("updated_at = ?")@@ -321,38 +329,83 @@ def delete_provider(id: str) -> bool:conn.close()-def get_provider(id: str) -> Optional[dict]:- """Fetch a single provider by ID."""+def _row_to_provider(row: sqlite3.Row) -> dict:+ data = dict(row)+ data["reasoning_config"] = _decode_reasoning_config(data.pop("reasoning_config_json", None))+ models, available_models = _row_models(row)+ data["models"] = models+ data["available_models"] = available_models+ data["shared"] = bool(data.get("shared"))+ return data+++def _own_rows(where: str = "", params: tuple = ()) -> list[dict]:conn = get_connection()try:- row = conn.execute("SELECT * FROM llm_providers WHERE id = ?", (id,)).fetchone()- if not row:- return None- data = dict(row)- data["reasoning_config"] = _decode_reasoning_config(data.pop("reasoning_config_json", None))- models, available_models = _row_models(row)- data["models"] = models- data["available_models"] = available_models- return data+ rows = conn.execute(+ f"SELECT * FROM llm_providers {where} ORDER BY created_at", params+ ).fetchall()+ return [_row_to_provider(row) for row in rows]finally:conn.close()-def list_providers() -> list[dict]:- """List all provider configurations, ordered by creation time."""- conn = get_connection()+def base_url_carries_credential(base_url: Optional[str]) -> bool:try:- rows = conn.execute("SELECT * FROM llm_providers ORDER BY created_at").fetchall()- providers: list[dict] = []- for row in rows:- data = dict(row)- data["reasoning_config"] = _decode_reasoning_config(- data.pop("reasoning_config_json", None)- )- models, available_models = _row_models(row)- data["models"] = models- data["available_models"] = available_models- providers.append(data)- return providers- finally:- conn.close()+ parts = urlparse(base_url or "")+ return bool(parts.username or parts.password or parts.query)+ except ValueError:+ return True+++def _owner_shared_rows(provider_id: Optional[str] = None) -> list[dict]:+ # A ChatGPT subscription is never shared: it is one person's sign-in, not an API key.+ from utils.account_context import OWNER, is_owner_context, run_as++ if is_owner_context():+ return []+ where = "WHERE shared = 1 AND provider_type != 'openai_codex'"+ params: tuple = ()+ if provider_id is not None:+ where += " AND id = ?"+ params = (provider_id,)++ def _read() -> list[dict]:+ # Reading must never create the owner's database.+ if not studio_db_path().exists():+ return []+ return _own_rows(where, params)++ try:+ rows = run_as(OWNER, _read)+ except Exception: # noqa: BLE001 - an unreadable owner store shares nothing+ logger.warning("Could not read the owner's shared connections", exc_info = True)+ return []+ from hub.services.models.account_access import shared_connection_view++ # Re-checked on read: an older build can edit the URL of a row it does not know is shared.+ rows = [row for row in rows if not base_url_carries_credential(row.get("base_url"))]+ return [view for view in (shared_connection_view(row) for row in rows) if view is not None]+++def is_owner_shared_provider(id: str) -> bool:+ return not _own_rows("WHERE id = ?", (id,)) and bool(_owner_shared_rows(id))+++def get_own_provider(id: str) -> Optional[dict]:+ rows = _own_rows("WHERE id = ?", (id,))+ return rows[0] if rows else None+++def get_provider(id: str) -> Optional[dict]:+ own = get_own_provider(id)+ if own is not None:+ return own+ shared = _owner_shared_rows(id)+ return shared[0] if shared else None+++def list_providers() -> list[dict]:+ own = _own_rows()+ own_ids = {row["id"] for row in own}+ return own + [row for row in _owner_shared_rows() if row["id"] not in own_ids]diff --git a/studio/backend/tests/test_account_shared_connections.py b/studio/backend/tests/test_account_shared_connections.pynew file mode 100644index 00000000000..2ab94fbc137--- /dev/null+++ b/studio/backend/tests/test_account_shared_connections.py@@ -0,0 +1,436 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+++import asyncio+import http.server+import json+import sqlite3+import threading+from contextlib import nullcontext++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient++from auth import policy+from auth.authentication import (+ authenticated_via_api_key,+ get_current_credential,+ get_current_subject,+)+from core.inference import providers as providers_core+from hub.services.models import account_access as access+from routes import provider_credentials, providers+from storage import credential_secrets, providers_db, studio_db+from utils import managed_provider_url_settings as mpu+from utils.account_context import (+ OWNER,+ AccountContext,+ arun_as,+ bind_account,+ reset_account,+ run_as,+)+from utils.paths import studio_db_path++ALICE = AccountContext("a" * 32, "alice")+BOB = AccountContext("b" * 32, "bob")+UPSTREAM_MODELS = ["unsloth/Qwen3-8B-GGUF", "unsloth/gemma-3-4b-it-GGUF", "other/private-model"]++[email protected](autouse = True)+def isolated(monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.delenv(providers_core._BLOCK_PRIVATE_ENV, raising = False)+ mpu.forget_cached_setting()+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ for module in (credential_secrets, providers_db, studio_db):+ monkeypatch.setattr(module, "_schema_ready", set(), raising = False)+ monkeypatch.setattr(+ credential_secrets, "get_or_create_credential_encryption_key", lambda: b"k" * 32+ )+ monkeypatch.setattr(providers, "current_credential_write", lambda credential: nullcontext())+ monkeypatch.setattr(access, "_allowlists", {})+ providers_core._dns_cache.clear()+ yield+ providers_core._dns_cache.clear()+++def upstream():+ seen = []++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ seen.append(self.headers.get("Authorization"))+ body = json.dumps({"data": [{"id": model} for model in UPSTREAM_MODELS]}).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_POST(self):+ seen.append(f"POST {self.path}")+ self.send_response(404)+ self.send_header("Content-Length", "0")+ self.end_headers()++ def log_message(self, *args):+ pass++ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target = server.serve_forever, daemon = True).start()+ try:+ yield f"http://127.0.0.1:{server.server_address[1]}/v1", seen+ finally:+ server.shutdown()+ server.server_close()+++def client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.dependency_overrides[get_current_credential] = lambda: (account.username, None)+ app.dependency_overrides[authenticated_via_api_key] = lambda: False+ app.include_router(providers.router, prefix = "/providers")+ return TestClient(app)+++def owner_connection(+ base_url = "https://api.example.com/v1",+ *,+ shared = True,+ models = None,+ available_models = None,+):+ with client_for(OWNER) as client:+ created = client.post(+ "/providers/",+ json = {+ "provider_type": "custom",+ "display_name": "Household Gufo",+ "base_url": base_url,+ "models": models if models is not None else UPSTREAM_MODELS[:2],+ "available_models": available_models or [],+ "shared": shared,+ },+ )+ assert created.status_code == 201, created.text+ provider_id = created.json()["id"]+ run_as(OWNER, credential_secrets.save_provider_api_key, provider_id, "owner-secret")+ return provider_id+++def allow_only(monkeypatch, *patterns):+ allowlist = tuple(pattern.lower() for pattern in patterns)+ monkeypatch.setattr(+ access, "model_allowlist", lambda: None if access.is_owner_context() else allowlist+ )+++def listed(account):+ with client_for(account) as client:+ response = client.get("/providers/")+ assert response.status_code == 200, response.text+ return response.json()+++def test_a_shared_connection_reaches_every_account_with_the_owner_key():+ provider_id = owner_connection()+ for account in (ALICE, BOB):+ [row] = listed(account)+ assert row["id"] == provider_id+ assert row["shared"] is True and row["shared_by_owner"] is True+ assert row["has_api_key"] is True and row["auth_status"] == "connected"+ assert "owner-secret" not in json.dumps(row)+ assert (+ run_as(account, provider_credentials.resolve_provider_api_key_or_400, provider_id, None)+ == "owner-secret"+ )+ [owner_row] = listed(OWNER)+ assert owner_row["shared"] is True and owner_row["shared_by_owner"] is False+++def test_an_unshared_connection_stays_private_and_unsharing_revokes():+ private_id = owner_connection(shared = False)+ assert listed(ALICE) == []+ assert run_as(ALICE, credential_secrets.get_provider_api_key, private_id) is None++ shared_id = owner_connection()+ assert [row["id"] for row in listed(ALICE)] == [shared_id]+ with client_for(OWNER) as client:+ assert client.put(f"/providers/{shared_id}", json = {"shared": False}).status_code == 200+ assert listed(ALICE) == []+ assert run_as(ALICE, credential_secrets.get_provider_api_key, shared_id) is None+ assert run_as(ALICE, providers_db.get_provider, shared_id) is None+++def test_a_base_url_carrying_a_credential_cannot_be_shared():+ provider_id = owner_connection(shared = False)+ run_as(OWNER, providers_db.update_provider, provider_id, base_url = "https://user:pass@[bad/v1")+ with client_for(OWNER) as client:+ assert client.put(f"/providers/{provider_id}", json = {"shared": True}).status_code == 400+ for base_url in ("https://user:[email protected]/v1", "https://gw.example.com/v1?key=s"):+ with client_for(OWNER) as client:+ refused = client.post(+ "/providers/",+ json = {+ "provider_type": "custom",+ "display_name": "Gateway",+ "base_url": base_url,+ "shared": True,+ },+ )+ assert refused.status_code == 400, base_url+ provider_id = owner_connection()+ with client_for(OWNER) as client:+ moved = client.put(+ f"/providers/{provider_id}", json = {"base_url": "https://gw.example.com/v1?key=s"}+ )+ assert moved.status_code == 400+ unshared = client.put(+ f"/providers/{provider_id}",+ json = {"base_url": "https://gw.example.com/v1?key=s", "shared": False},+ )+ assert unshared.status_code == 200+ assert listed(ALICE) == []+++def test_other_accounts_can_use_but_never_change_a_shared_connection():+ provider_id = owner_connection()+ with client_for(ALICE) as client:+ assert (+ client.put(f"/providers/{provider_id}", json = {"display_name": "mine"}).status_code+ == 403+ )+ assert (+ client.put(+ f"/providers/{provider_id}/api-key/migrate", json = {"encrypted_api_key": "x"}+ ).status_code+ == 403+ )+ assert client.delete(f"/providers/{provider_id}").status_code == 403+ [row] = listed(OWNER)+ assert row["display_name"] == "Household Gufo"+ assert run_as(OWNER, credential_secrets.get_provider_api_key, provider_id) == "owner-secret"+++def test_only_the_owner_can_share_and_never_a_chatgpt_subscription():+ with client_for(ALICE) as client:+ refused = client.post(+ "/providers/",+ json = {"provider_type": "openai", "display_name": "Mine", "shared": True},+ )+ assert refused.status_code == 403+ own = client.post("/providers/", json = {"provider_type": "openai", "display_name": "Mine"})+ assert own.status_code == 201+ own_id = own.json()["id"]+ assert client.put(f"/providers/{own_id}", json = {"shared": True}).status_code == 403+ assert listed(BOB) == []+ with client_for(OWNER) as client:+ codex = client.post(+ "/providers/",+ json = {"provider_type": "openai_codex", "display_name": "ChatGPT", "shared": True},+ )+ assert codex.status_code == 400+++def test_an_accounts_own_connections_come_first_and_keep_their_own_keys():+ shared_id = owner_connection()+ with client_for(ALICE) as client:+ own = client.post("/providers/", json = {"provider_type": "openai", "display_name": "Mine"})+ own_id = own.json()["id"]+ run_as(ALICE, credential_secrets.save_provider_api_key, own_id, "alice-secret")+ assert [row["id"] for row in listed(ALICE)] == [own_id, shared_id]+ assert run_as(ALICE, credential_secrets.get_provider_api_key, own_id) == "alice-secret"+ assert run_as(OWNER, credential_secrets.get_provider_api_key, own_id) is None+++def test_model_access_limits_the_models_of_a_shared_connection(monkeypatch):+ provider_id = owner_connection()+ allow_only(monkeypatch, "unsloth/qwen3-*")+ [row] = listed(ALICE)+ assert row["models"] == ["unsloth/Qwen3-8B-GGUF"]+ config = run_as(ALICE, providers_db.get_provider, provider_id)+ run_as(ALICE, access.require_connection_model_allowed, config, "unsloth/Qwen3-8B-GGUF")+ with pytest.raises(HTTPException) as refused:+ run_as(ALICE, access.require_connection_model_allowed, config, "unsloth/gemma-3-4b-it-GGUF")+ assert refused.value.status_code == 403+ owner_config = run_as(OWNER, providers_db.get_provider, provider_id)+ run_as(OWNER, access.require_connection_model_allowed, owner_config, "other/private-model")+ run_as(ALICE, access.require_connection_model_allowed, {"id": "own"}, "other/private-model")+ allow_only(monkeypatch, "google/*")+ assert run_as(ALICE, access.connection_model_allowed, "~google/gemini-pro-latest")+ assert run_as(ALICE, access.connection_model_allowed, "google/gemma-3:latest")+++def test_only_the_models_the_owner_enabled_are_shared():+ provider_id = owner_connection(models = UPSTREAM_MODELS[:1])+ config = run_as(ALICE, providers_db.get_provider, provider_id)+ run_as(ALICE, access.require_connection_model_allowed, config, UPSTREAM_MODELS[0])+ with pytest.raises(HTTPException) as refused:+ run_as(ALICE, access.require_connection_model_allowed, config, "other/private-model")+ assert refused.value.status_code == 403+++def test_a_shared_row_whose_url_gained_a_credential_elsewhere_is_withdrawn():+ provider_id = owner_connection()+ run_as(+ OWNER, providers_db.update_provider, provider_id, base_url = "https://gw.example.com/v1?key=s"+ )+ assert listed(ALICE) == []+ assert run_as(ALICE, credential_secrets.get_provider_api_key, provider_id) is None+++def test_a_shared_connection_with_no_allowed_model_is_hidden(monkeypatch):+ owner_connection()+ allow_only(monkeypatch, "someone/else")+ assert listed(ALICE) == []+++def test_listing_models_through_a_shared_lan_connection(monkeypatch, upstream):+ base_url, seen = upstream+ provider_id = owner_connection(base_url)+ mpu.set_managed_private_provider_urls_allowed(True)+ allow_only(monkeypatch, "unsloth/*")+ with client_for(ALICE) as client:+ response = client.post(+ "/providers/models", json = {"provider_type": "custom", "provider_id": provider_id}+ )+ assert response.status_code == 200, response.text+ assert [model["id"] for model in response.json()] == UPSTREAM_MODELS[:2]+ assert seen == ["Bearer owner-secret"]+++def test_listing_a_shared_connection_shows_only_the_models_the_owner_enabled(upstream):+ base_url, _ = upstream+ provider_id = owner_connection(+ base_url, models = UPSTREAM_MODELS[:1], available_models = UPSTREAM_MODELS+ )+ mpu.set_managed_private_provider_urls_allowed(True)+ [row] = listed(ALICE)+ assert row["available_models"] == UPSTREAM_MODELS[:1]+ with client_for(ALICE) as client:+ response = client.post(+ "/providers/models", json = {"provider_type": "custom", "provider_id": provider_id}+ )+ assert response.status_code == 200, response.text+ assert [model["id"] for model in response.json()] == UPSTREAM_MODELS[:1]+ with client_for(OWNER) as client:+ response = client.post(+ "/providers/models", json = {"provider_type": "custom", "provider_id": provider_id}+ )+ assert [model["id"] for model in response.json()] == UPSTREAM_MODELS+++def test_a_shared_reader_queues_on_the_owner_lock_without_reading_the_store(monkeypatch):+ provider_id = owner_connection()+ config = run_as(ALICE, providers_db.get_provider, provider_id)++ async def guard(**kwargs):+ return provider_credentials.provider_config_guard(provider_id, **kwargs)++ def no_store_read(*args, **kwargs):+ raise AssertionError("provider store read on the event loop")++ async def check():+ owner_lock = await arun_as(OWNER, guard())+ monkeypatch.setattr(providers_db, "get_connection", no_store_read)+ assert await arun_as(ALICE, guard()) is not owner_lock+ reader = await arun_as(ALICE, guard(shared_by_owner = config["shared_by_owner"]))+ assert reader is owner_lock++ asyncio.run(check())+++def test_a_shared_lan_connection_still_needs_the_private_address_switch(upstream):+ base_url, seen = upstream+ provider_id = owner_connection(base_url)+ with client_for(ALICE) as client:+ response = client.post(+ "/providers/models", json = {"provider_type": "custom", "provider_id": provider_id}+ )+ assert response.status_code == 400+ assert seen == []+++def test_a_store_from_before_sharing_upgrades_with_nothing_shared(tmp_path):+ db = run_as(OWNER, studio_db_path)+ db.parent.mkdir(parents = True, exist_ok = True)+ with sqlite3.connect(db) as conn:+ conn.execute(+ "CREATE TABLE llm_providers (id TEXT NOT NULL PRIMARY KEY, provider_type TEXT NOT NULL, "+ "display_name TEXT NOT NULL, base_url TEXT NOT NULL, is_enabled INTEGER NOT NULL DEFAULT 1, "+ "created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"+ )+ conn.execute(+ "INSERT INTO llm_providers VALUES ('old', 'openai', 'Old', '', 1, '2026-01-01', '2026-01-01')"+ )+ [row] = run_as(OWNER, providers_db.list_providers)+ assert row["id"] == "old" and row["shared"] is False+ assert listed(ALICE) == []+++def test_the_owner_openai_project_containers_stay_off_limits():+ from models.inference import OpenAIContainerRequest+ from routes import inference++ with client_for(OWNER) as client:+ created = client.post(+ "/providers/",+ json = {"provider_type": "openai", "display_name": "OpenAI", "shared": True},+ )+ provider_id = created.json()["id"]+ run_as(OWNER, credential_secrets.save_provider_api_key, provider_id, "owner-secret")+ body = OpenAIContainerRequest(provider_id = provider_id)+ with pytest.raises(HTTPException) as refused:+ run_as(ALICE, inference._resolve_openai_cloud_client, body, allow_saved_key = True)+ assert refused.value.status_code == 403+ assert run_as(OWNER, inference._resolve_openai_cloud_client, body, allow_saved_key = True)+++def test_checking_a_shared_connection_probes_no_model_and_quotes_no_upstream_error(+ monkeypatch, upstream+):+ base_url, seen = upstream+ mpu.set_managed_private_provider_urls_allowed(True)+ provider_id = owner_connection(base_url)+ allow_only(monkeypatch, "unsloth/qwen3-*")+ with client_for(ALICE) as client:+ response = client.post(+ "/providers/test",+ json = {+ "provider_type": "custom",+ "provider_id": provider_id,+ "model_id": "unsloth/gemma-3-4b-it-GGUF",+ },+ )+ assert response.status_code == 200+ assert response.json()["success"] is True+ assert len(seen) == 1 and not seen[0].startswith("POST")++ run_as(+ OWNER,+ providers_db.update_provider,+ provider_id,+ base_url = "http://127.0.0.1:9/v1",+ )+ with client_for(ALICE) as client:+ failed = client.post(+ "/providers/test", json = {"provider_type": "custom", "provider_id": provider_id}+ )+ assert failed.json() == {+ "success": False,+ "message": "Connection failed. Ask the owner to check this connection.",+ "models_count": None,+ }diff --git a/studio/backend/tests/test_config_mutations_on_event_loop.py b/studio/backend/tests/test_config_mutations_on_event_loop.pyindex 8d50a026e24..b0d0ec10f0a 100644--- a/studio/backend/tests/test_config_mutations_on_event_loop.py+++ b/studio/backend/tests/test_config_mutations_on_event_loop.py@@ -74,7 +74,7 @@ _MUTATIONS = {{"display_name": "renamed"},provider_routes,"providers_db",- "get_provider",+ "get_own_provider",None,404,),@@ -84,7 +84,7 @@ _MUTATIONS = {{"encrypted_api_key": "k"},provider_routes,"providers_db",- "get_provider",+ "get_own_provider",None,404,),diff --git a/studio/backend/tests/test_provider_lookup_off_event_loop.py b/studio/backend/tests/test_provider_lookup_off_event_loop.pyindex 9df2a306bdb..2e90a38dda1 100644--- a/studio/backend/tests/test_provider_lookup_off_event_loop.py+++ b/studio/backend/tests/test_provider_lookup_off_event_loop.py@@ -121,6 +121,41 @@ def test_the_saved_provider_target_and_key_are_one_snapshot(monkeypatch):assert state["key"] == "new-secret"+def test_a_model_the_owner_disabled_while_the_request_waited_is_refused(monkeypatch):+ rows = [+ {+ "id": "saved-1",+ "provider_type": "openai",+ "display_name": "Shared",+ "base_url": "https://owner.example/v1",+ "is_enabled": True,+ "shared_by_owner": True,+ "models": models,+ }+ for models in (["kept", "dropped"], ["kept"])+ ]+ observed = []++ def _get_provider(_provider_id):+ return dict(rows.pop(0) if len(rows) > 1 else rows[0])++ def _resolve_key(*_args, **_kwargs):+ observed.append("key")+ return "owner-secret"++ monkeypatch.setattr(inference_routes.providers_db, "get_provider", _get_provider)+ monkeypatch.setattr(inference_routes, "resolve_provider_api_key_or_400", _resolve_key)++ with pytest.raises(HTTPException) as excinfo:+ asyncio.run(+ inference_routes._proxy_to_external_provider(+ _payload(external_model = "dropped"), _request(), current_subject = "t"+ )+ )+ assert excinfo.value.status_code == 403+ assert observed == []++@pytest.mark.parametrize("handler",[diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex 76d80b88eda..6c42d217dd4 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -333,8 +333,11 @@ export const BUDGET = {// Picking a preset forgetting a model's remembered sampling (#14128) keeps its preset marks in the eager chat// runtime store, about 1,860 B raw / 440 B transfer: merged with main at acb31d909b the build measures// 6,876,062 B raw / 2,070,545 B transfer (Node 24, 97 chunks). Raised to that plus the same margin.- transferBytes: 2_070_734,- rawBytes: 6_876_222,+ // Sharing a connection with every account adds the shared flags to the eager provider mapping: 180 B raw /+ // 20 B transfer (6,862,624 -> 6,862,804 B raw, 2,066,394 -> 2,066,414 B transfer against 723a43b02, one+ // machine and build, Node 22, 96 chunks); the share switch itself is in the lazy Connections tab. Raised by that.+ transferBytes: 2_070_754,+ rawBytes: 6_876_402,};// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering thediff --git a/studio/frontend/src/features/chat/api/providers-api.ts b/studio/frontend/src/features/chat/api/providers-api.tsindex d5f03bb5954..c596ef2c150 100644--- a/studio/frontend/src/features/chat/api/providers-api.ts+++ b/studio/frontend/src/features/chat/api/providers-api.ts@@ -55,6 +55,8 @@ export interface ProviderConfig {available_models?: string[];max_output_tokens?: number | null;reasoning_config?: CustomReasoningConfig | null;+ shared?: boolean;+ shared_by_owner?: boolean;created_at: string;updated_at: string;}@@ -217,6 +219,7 @@ export async function createProviderConfig(payload: {availableModels?: string[];maxOutputTokens?: number | null;reasoningConfig?: CustomReasoningConfig | null;+ shared?: boolean;apiKey?: string;}): Promise<ProviderConfig> {return withApiKeyEncryptionRetry(payload.apiKey ?? "", async (encryptedApiKey) => {@@ -236,6 +239,7 @@ export async function createProviderConfig(payload: {...(payload.reasoningConfig === undefined? {}: { reasoning_config: payload.reasoningConfig }),+ ...(payload.shared === undefined ? {} : { shared: payload.shared }),encrypted_api_key: encryptedApiKey,}),});@@ -269,6 +273,7 @@ export async function updateProviderConfig(availableModels?: string[];maxOutputTokens?: number | null;reasoningConfig?: CustomReasoningConfig | null;+ shared?: boolean;apiKey?: string;clearApiKey?: boolean;},@@ -292,6 +297,7 @@ export async function updateProviderConfig(...(payload.reasoningConfig === undefined? {}: { reasoning_config: payload.reasoningConfig }),+ ...(payload.shared === undefined ? {} : { shared: payload.shared }),...(payload.apiKey === undefined ? {} : { encrypted_api_key: encryptedApiKey }),...(payload.clearApiKey === undefined ? {} : { clear_api_key: payload.clearApiKey }),}),diff --git a/studio/frontend/src/features/chat/chat-providers-dialog.tsx b/studio/frontend/src/features/chat/chat-providers-dialog.tsxindex 899499804ed..6b4c9adfcbb 100644--- a/studio/frontend/src/features/chat/chat-providers-dialog.tsx+++ b/studio/frontend/src/features/chat/chat-providers-dialog.tsx@@ -40,6 +40,7 @@ import {import { AnimatePresence, motion, useReducedMotion } from "motion/react";import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";+import { useIsAccountOwner, useLoginMode } from "@/features/auth";import { useSettingsDialogStore } from "@/features/settings";import { useT } from "@/i18n";import { ApiProviderLogo } from "./api-provider-logo";@@ -320,6 +321,9 @@ export function ChatProvidersSettings({const [isReasoningModel, setIsReasoningModel] = useState(false);const [reasoningConfig, setReasoningConfig] = useState<CustomReasoningConfig | null>(null);const [autoReloadModels, setAutoReloadModels] = useState(false);+ const [sharedDraft, setSharedDraft] = useState(false);+ const isAccountOwner = useIsAccountOwner();+ const loginMode = useLoginMode();const modelFieldsAtOpenRef = useRef<string | null>(null);const reduceMotion = useReducedMotion();const connectionsEnabled = useExternalProvidersStore(@@ -420,6 +424,10 @@ export function ChatProvidersSettings({? providers.find((provider) => provider.id === editingProviderId): undefined;const editingProviderHasSavedKey = Boolean(editingProvider?.hasApiKey);+ const showShareToggle =+ isAccountOwner &&+ !usesOAuth &&+ (loginMode === "multi" || editingProvider?.shared === true);const selectedProviderLabel = isCustomProviderType(providerType)? customProviderDisplayName(providerType): selectedProviderContract?.display_name;@@ -619,6 +627,7 @@ export function ChatProvidersSettings({setCustomProviderName(customProviderDisplayName(providerType));setIsReasoningModel(false);setAutoReloadModels(false);+ setSharedDraft(false);modelFieldsAtOpenRef.current = null;}@@ -976,6 +985,7 @@ export function ChatProvidersSettings({reasoningConfig: isCustomReasoningConnection? (showCustomReasoning ? reasoningConfig : null): undefined,+ ...(showShareToggle && sharedDraft ? { shared: true } : {}),apiKey: apiKey.trim(),});@@ -1006,6 +1016,7 @@ export function ChatProvidersSettings({: undefined,hasApiKey: created.has_api_key,+ shared: created.shared === true,authKind: created.auth_kind,authStatus: created.auth_status,@@ -1154,6 +1165,9 @@ export function ChatProvidersSettings({reasoningConfig: isCustomReasoningConnection? (showCustomReasoning ? reasoningConfig : null): undefined,+ ...(showShareToggle && sharedDraft !== (existing.shared === true)+ ? { shared: sharedDraft }+ : {}),...(credentialEdit.action === "replace"? { apiKey: credentialEdit.apiKey }: credentialEdit.action === "clear"@@ -1188,6 +1202,7 @@ export function ChatProvidersSettings({: undefined,hasApiKey: updated.has_api_key,+ shared: updated.shared === true,autoReloadModels:existing.providerType === "llama_cpp" ? autoReloadModels : undefined,isReasoningModel: supportsProviderReasoningToggle(@@ -1276,6 +1291,10 @@ export function ChatProvidersSettings({}async function editProvider(provider: ExternalProviderConfig) {+ if (provider.sharedByOwner) {+ toast.info("This connection is shared by the owner. Only they can change it.");+ return;+ }// Switching connections retires an in-flight catalog request, including on the branches// below that never reach applyCodexSubscriptionModels.codexCatalogRequestRef.current += 1;@@ -1295,6 +1314,7 @@ export function ChatProvidersSettings({setShowApiKey(false);setBaseUrlDraft(provider.baseUrl);setAutoReloadModels(provider.autoReloadModels === true);+ setSharedDraft(provider.shared === true);modelFieldsAtOpenRef.current = null;setApiType(provider.decisionsOnly ? "systemone" : (provider.apiType ?? "chat_completions"),@@ -1845,6 +1865,33 @@ export function ChatProvidersSettings({/></div>) : null}+ {showShareToggle ? (+ <div className="flex items-center justify-between gap-4 px-4 py-3">+ <div className="space-y-1">+ <Label+ htmlFor="provider-shared"+ className="text-sm font-medium"+ >+ Share with all accounts+ </Label>+ <p+ id="provider-shared-help"+ className="text-xs text-muted-foreground"+ >+ Other accounts can chat with its models using your saved+ key, but cannot see the key or change the connection. Model+ access in Settings > Accounts limits which models each+ account sees.+ </p>+ </div>+ <Switch+ id="provider-shared"+ checked={sharedDraft}+ onCheckedChange={setSharedDraft}+ aria-describedby="provider-shared-help"+ />+ </div>+ ) : null}{showCustomReasoning ? (<><div className="grid grid-cols-[minmax(140px,0.8fr)_minmax(0,1.2fr)] items-start gap-4 px-4 py-3 @max-[520px]:grid-cols-1">@@ -2401,6 +2448,11 @@ export function ChatProvidersSettings({{t("settings.apiKeys.decisionApi.title")}</span>) : null}+ {provider.shared ? (+ <span className="shrink-0 rounded-full border border-border/70 px-1.5 py-0.5 text-ui-10 leading-none text-muted-foreground">+ {provider.sharedByOwner ? "Shared by owner" : "Shared"}+ </span>+ ) : null}</div><div className="mt-0.5 truncate text-xs text-muted-foreground"><span>{providerLabel}</span>@@ -2420,6 +2472,7 @@ export function ChatProvidersSettings({</div></div><div className="flex shrink-0 items-center justify-end gap-0.5 text-muted-foreground">+ {provider.sharedByOwner ? null : (<Buttontype="button"size="icon-sm"@@ -2432,6 +2485,7 @@ export function ChatProvidersSettings({><HugeiconsIcon icon={Edit03Icon} className="size-4" /></Button>+ )}<Buttontype="button"size="icon-sm"@@ -2444,6 +2498,7 @@ export function ChatProvidersSettings({><HugeiconsIcon icon={Wifi02Icon} className="size-4" /></Button>+ {provider.sharedByOwner ? null : (<Buttontype="button"size="icon-sm"@@ -2456,6 +2511,7 @@ export function ChatProvidersSettings({><HugeiconsIcon icon={Delete02Icon} className="size-4" /></Button>+ )}</div></div>);diff --git a/studio/frontend/src/features/chat/external-providers.ts b/studio/frontend/src/features/chat/external-providers.tsindex 94e9bfab387..d6e9d54fae3 100644--- a/studio/frontend/src/features/chat/external-providers.ts+++ b/studio/frontend/src/features/chat/external-providers.ts@@ -37,6 +37,8 @@ export interface ExternalProviderConfig {/** Whether the backend has an installation-saved key. */hasApiKey?: boolean;+ shared?: boolean;+ sharedByOwner?: boolean;/** Sanitized backend-owned authorization state; never contains OAuth material. */authKind?: ProviderAuthKind;diff --git a/studio/frontend/src/features/chat/llama-cpp-auto-reload.ts b/studio/frontend/src/features/chat/llama-cpp-auto-reload.tsindex 042a1b13e1e..e80c014d0dd 100644--- a/studio/frontend/src/features/chat/llama-cpp-auto-reload.ts+++ b/studio/frontend/src/features/chat/llama-cpp-auto-reload.ts@@ -38,7 +38,7 @@ function autoReloadConnections(): ExternalProviderConfig[] {const { providers, connectionsEnabled } = useExternalProvidersStore.getState();if (!connectionsEnabled) return [];return providers.filter(- (p) => p.providerType === "llama_cpp" && p.autoReloadModels === true,+ (p) => p.providerType === "llama_cpp" && p.autoReloadModels === true && !p.sharedByOwner,);}diff --git a/studio/frontend/src/features/chat/sync-external-providers.ts b/studio/frontend/src/features/chat/sync-external-providers.tsindex 75110db2cd5..d195e6185ea 100644--- a/studio/frontend/src/features/chat/sync-external-providers.ts+++ b/studio/frontend/src/features/chat/sync-external-providers.ts@@ -299,7 +299,7 @@ export async function syncExternalProvidersFromBackend(serverModels.length === 0 && savedModels.length > 0;const needsAvailableBackfill =serverAvailableModels.length === 0 && savedAvailableModels.length > 0;- if (needsModelBackfill || needsAvailableBackfill) {+ if (!config.shared_by_owner && (needsModelBackfill || needsAvailableBackfill)) {backfillTasks.push(() =>updateProviderConfig(config.id, {models: resolvedModels,@@ -326,6 +326,8 @@ export async function syncExternalProvidersFromBackend(: undefined,hasApiKey: config.has_api_key,+ shared: config.shared === true,+ sharedByOwner: config.shared_by_owner === true,authKind: config.auth_kind,authStatus: config.auth_status,diff --git a/studio/frontend/tests/connections-shared-by-owner.test.ts b/studio/frontend/tests/connections-shared-by-owner.test.tsnew file mode 100644index 00000000000..5568c5ef8f3--- /dev/null+++ b/studio/frontend/tests/connections-shared-by-owner.test.ts@@ -0,0 +1,40 @@+// 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 { readSrc } from "./helpers/kit.ts";++const dialog = readSrc("features/chat/chat-providers-dialog.tsx");+const sync = readSrc("features/chat/sync-external-providers.ts");+const autoReload = readSrc("features/chat/llama-cpp-auto-reload.ts");++test("only the owner sees the share toggle, and only with another account or a shared row", () => {+ assert.match(+ dialog,+ /const showShareToggle =\s*isAccountOwner &&\s*!usesOAuth &&\s*\(loginMode === "multi" \|\| editingProvider\?\.shared === true\);/,+ );+ assert.match(dialog, /\{showShareToggle \? \(/);+});++test("a single-account save sends no shared field", () => {+ assert.match(dialog, /\.\.\.\(showShareToggle && sharedDraft \? \{ shared: true \} : \{\}\),/);+ assert.match(+ dialog,+ /\.\.\.\(showShareToggle && sharedDraft !== \(existing\.shared === true\)\s*\? \{ shared: sharedDraft \}\s*: \{\}\),/,+ );+});++test("a row shared by the owner has no edit or delete action", () => {+ assert.equal([...dialog.matchAll(/\{provider\.sharedByOwner \? null : \(/g)].length, 2);+ assert.match(dialog, /if \(provider\.sharedByOwner\) \{\s*toast\.info\(/);+});++test("sync maps the flags and never writes back to a row shared by the owner", () => {+ assert.match(sync, /shared: config\.shared === true,/);+ assert.match(sync, /sharedByOwner: config\.shared_by_owner === true,/);+ assert.match(sync, /if \(!config\.shared_by_owner && \(needsModelBackfill \|\| needsAvailableBackfill\)\)/);+ assert.match(autoReload, /p\.autoReloadModels === true && !p\.sharedByOwner/);+});