Skip to content

fix(studio): persist connection model selections for remote clients - #7298

Merged
danielhanchen merged 8 commits into
unslothai:mainfrom
Souravrajvi0:fix/7281-remote-connection-models-persist
Jul 24, 2026
Merged

danielhanchen merged 8 commits into
unslothai:mainfrom
Souravrajvi0:fix/7281-remote-connection-models-persist

Conversation

@Souravrajvi0

Copy link
Copy Markdown
Contributor

Problem

On remote Studio sessions (different browser, hostname, or device), saved external connections appeared in Settings → Connections but were unusable in chat. Connection metadata (name, base URL, type) synced from the server, while enabled model IDs and discovered catalogs lived only in browser localStorage. A remote client therefore saw an empty model list even though the connection row existed.

Reported in #7281.

Fix

Persist models and available_models in llm_providers (models_json / available_models_json) and expose them through the providers API. The Connections UI now writes model selections on create/update and prefers server-stored models during backend sync when the local overlay is empty.

API keys remain browser-local by design; this PR does not change key storage.

Verification

  • npm run typecheck (studio/frontend)
  • pytest tests/studio/test_remote_connection_models_contract.py
  • studio/backend/tests/test_providers_db_models.py (runs in Studio Backend CI with backend deps)
  • Manual (not run here): create an Ollama connection on host A with enabled models → open Studio from host B → models appear under Connected without re-selecting

Compatibility

Backend schema migration adds two nullable JSON columns with ALTER TABLE defaults. Existing connections keep working; model lists backfill on the next edit. Frontend-only clients on an older backend ignore the new fields safely.

Fixes #7281

Remote Studio clients could see saved connections but not their enabled
model lists because models lived only in browser localStorage.

Store models and available_models in llm_providers and sync them through
the providers API so alternate clients inherit the same catalog state.

Fixes unslothai#7281

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces server-side persistence for enabled and available model configurations of LLM providers, updating the database schema, backend API models, and frontend synchronization logic. The review feedback highlights several opportunities for improvement, including simplifying database row parsing, updating the main table creation schema, removing redundant frontend model pruning calls, and refactoring contract tests to dynamically inspect schemas and models rather than asserting on fragile source code strings.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +47 to +53
def _row_models(row: sqlite3.Row) -> tuple[list[str], list[str]]:
return (
_decode_models_json(row["models_json"] if "models_json" in row.keys() else None),
_decode_models_json(
row["available_models_json"] if "available_models_json" in row.keys() else None
),
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The check "models_json" in row.keys() is redundant and adds unnecessary overhead. Since _ensure_schema is guaranteed to run and apply migrations before any queries are executed, and the queries use SELECT *, these columns will always exist in the sqlite3.Row object. We can simplify this by accessing the columns directly.

def _row_models(row: sqlite3.Row) -> tuple[list[str], list[str]]:
    return (
        _decode_models_json(row["models_json"]),
        _decode_models_json(row["available_models_json"]),
    )

Comment on lines +72 to +78
existing_cols = {row[1] for row in conn.execute("PRAGMA table_info(llm_providers)").fetchall()}
if "models_json" not in existing_cols:
conn.execute("ALTER TABLE llm_providers ADD COLUMN models_json TEXT NOT NULL DEFAULT '[]'")
if "available_models_json" not in existing_cols:
conn.execute(
"ALTER TABLE llm_providers ADD COLUMN available_models_json TEXT NOT NULL DEFAULT '[]'"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While these ALTER TABLE statements are necessary for migrating existing databases, it is highly recommended to also update the main CREATE TABLE statement (lines 61-70) to include models_json and available_models_json by default. This ensures that new installations create the table with the correct schema in a single operation, rather than creating it and immediately altering it.

Comment on lines 418 to 433
const existingModels = pruneProviderModelIds(
uiProviderType,
savedModels.length > 0 ? savedModels : defaultModels,
serverModels.length > 0
? serverModels
: savedModels.length > 0
? savedModels
: defaultModels,
);
const existingAvailableModels = pruneProviderModelIds(
uiProviderType,
savedAvailableModels.length > 0 ? savedAvailableModels : defaultModels,
serverAvailableModels.length > 0
? serverAvailableModels
: savedAvailableModels.length > 0
? savedAvailableModels
: defaultModels,
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The lists serverModels, savedModels, and defaultModels are already pruned using pruneProviderModelIds earlier in the function. Calling pruneProviderModelIds again on the final selected list is redundant. We can simplify this by removing the outer pruneProviderModelIds calls.

            const existingModels = serverModels.length > 0
              ? serverModels
              : savedModels.length > 0
                ? savedModels
                : defaultModels;
            const existingAvailableModels = serverAvailableModels.length > 0
              ? serverAvailableModels
              : savedAvailableModels.length > 0
                ? savedAvailableModels
                : defaultModels;

Comment on lines +17 to +21
def test_providers_db_stores_model_json_columns():
source = PROVIDERS_DB.read_text(encoding = "utf-8")
assert "models_json" in source
assert "available_models_json" in source
assert "ALTER TABLE llm_providers ADD COLUMN models_json" in source

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Asserting on exact source code strings is fragile and can easily break due to minor formatting changes (e.g., single vs double quotes, spacing, or line breaks). It is much more robust to test the database schema dynamically by running _ensure_schema on an in-memory or temporary database and inspecting the columns.

Suggested change
def test_providers_db_stores_model_json_columns():
source = PROVIDERS_DB.read_text(encoding = "utf-8")
assert "models_json" in source
assert "available_models_json" in source
assert "ALTER TABLE llm_providers ADD COLUMN models_json" in source
def test_providers_db_stores_model_json_columns(tmp_path):
import sqlite3
from storage.providers_db import _ensure_schema
db_path = tmp_path / "studio.db"
conn = sqlite3.connect(str(db_path))
_ensure_schema(conn)
columns = {row[1] for row in conn.execute("PRAGMA table_info(llm_providers)").fetchall()}
assert "models_json" in columns
assert "available_models_json" in columns
conn.close()

Comment on lines +24 to +27
def test_provider_api_schemas_expose_models():
source = PROVIDERS_MODELS.read_text(encoding = "utf-8")
assert "models: list[str]" in source
assert "available_models: list[str]" in source

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instead of reading and asserting on the raw Python source code of the models file, we can import the Pydantic models directly and inspect their fields. This is much more robust and immune to formatting changes.

Suggested change
def test_provider_api_schemas_expose_models():
source = PROVIDERS_MODELS.read_text(encoding = "utf-8")
assert "models: list[str]" in source
assert "available_models: list[str]" in source
def test_provider_api_schemas_expose_models():
from models.providers import ProviderCreate, ProviderUpdate, ProviderResponse
for model in [ProviderCreate, ProviderUpdate, ProviderResponse]:
fields = model.model_fields if hasattr(model, "model_fields") else model.__fields__
assert "models" in fields
assert "available_models" in fields

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c3d7141569

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +408 to +410
const serverModels = pruneProviderModelIds(
uiProviderType,
config.models ?? [],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Hydrate connections before building the model picker

When a fresh remote browser opens chat without first visiting Settings → Connections, this new backend model sync never runs because it is scoped to ChatProvidersSettings; the chat page still builds externalModels only from useExternalProvidersStore/localStorage, so server-persisted config.models are not available in the Connected picker until the settings tab is mounted. Please move or duplicate this provider-config hydration into app/store startup so persisted model selections are loaded before the picker renders.

Useful? React with 👍 / 👎.

Extract provider sync logic into sync-external-providers.ts and call it
from chat-page on mount so persisted model selections appear in the
Connected picker without opening Settings → Connections first.
@Souravrajvi0

Copy link
Copy Markdown
Contributor Author

Fixed in f7f19f1.

P2 — Hydrate connections before building the model picker: Valid. Server-persisted config.models / config.available_models were only synced when ChatProvidersSettings mounted (Settings → Connections), so a fresh remote browser opening chat directly built externalModels from localStorage-only state and missed persisted model selections.

Fix: Extracted the provider hydration logic into sync-external-providers.ts (syncExternalProvidersFromBackend, shared pruneProviderModelIds / resolveUiProviderTypeFromConfig). chat-providers-dialog.tsx now reuses that helper for its existing sync + focus re-sync. chat-page.tsx calls it on mount alongside hydratePersistedSettings() so the Connected picker is populated before first render without visiting Connections.

Tests: tests/studio/test_remote_connection_models_contract.py (5 passed) + npm run typecheck.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f7f19f1826

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +137 to +140
serverModels.length > 0
? serverModels
: savedModels.length > 0
? savedModels

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Backfill legacy saved model selections to the backend

For upgraded connections whose backend rows get the new models_json default of [], this fallback keeps the current browser using savedModels from localStorage but never writes those IDs back to /api/providers. A fresh remote client still receives config.models: [] (and custom/vLLM/Ollama have no registry defaults), so the Connected picker remains empty until the original browser manually re-saves each connection; when this branch uses savedModels, please backfill models/availableModels to the backend.

Useful? React with 👍 / 👎.

const synced = await syncExternalProvidersFromBackend(
useExternalProvidersStore.getState().providers,
);
setExternalProviders(synced);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve local provider options during startup sync

When ChatPage mounts after a user saved provider-local options such as Anthropic promptCacheTtl: "1h" or OpenAI openaiContainerTtlMinutes in localStorage, this new startup sync replaces the store with reconstructed provider objects. syncExternalProvidersFromBackend only carries over enablePromptCaching/isReasoningModel, so setExternalProviders persists a stripped array and later external requests fall back to the default TTL settings even though the user did not change them; please carry all local-only provider fields through the sync.

Useful? React with 👍 / 👎.

@Souravrajvi0
Souravrajvi0 marked this pull request as draft July 23, 2026 07:34
…nslothai#7298)

Address Codex P2 on remote connection persistence:
- Backfill localStorage model selections to /api/providers when backend
  rows still have empty models_json (legacy upgrades)
- Carry promptCacheTtl and openaiContainerTtlMinutes through startup sync
- Await hydratePersistedSettings before syncing on ChatPage mount

Contract tests: 7 passed; npm run typecheck passed.
@Souravrajvi0
Souravrajvi0 marked this pull request as ready for review July 23, 2026 09:46
@Souravrajvi0

Copy link
Copy Markdown
Contributor Author

Ready for review / merge

Addressed the remaining Codex P2 items on e5a76f2b1:

1. Backfill legacy saved model selections to the backend
When a connection row still has empty models_json / available_models_json but the browser has local selections, syncExternalProvidersFromBackend now PUTs those IDs back via updateProviderConfig so a fresh remote client sees them without re-saving in Connections.

2. Preserve local provider options during startup sync
Added mergeLocalProviderOptions so startup sync keeps browser-local knobs (promptCacheTtl, openaiContainerTtlMinutes, etc.) instead of rebuilding a stripped provider object.

Also: ChatPage now await hydratePersistedSettings() before syncing, so localStorage is loaded before the backend merge/backfill runs.

Verified locally

  • pytest tests/studio/test_remote_connection_models_contract.py — 7 passed
  • npm run typecheck — passed

CI note: Core HF/TRL matrix failures on prior runs were the unrelated unsloth_zoo MLX flake (test_mlx_cce_kernel.py), not this Studio change.

Undrafted and ready for maintainer review.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: d28af008c6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: b19b7c704f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member

Reviewed and verified. Remote clients previously lost their per connection model selection on reload. This persists the selection correctly and remaps MLX optimizer labels on Apple Silicon so the control stays truthful. Ran the studio backend and frontend tests, simulated the remote reconnect flow, and confirmed the fix holds on Linux and Mac. Codex review converged with no open items. Good to merge.

@danielhanchen
danielhanchen merged commit b448fb5 into unslothai:main Jul 24, 2026
40 of 45 checks passed
danielhanchen added a commit to mahiatlinux/unsloth that referenced this pull request Sep 29, 2026
Suppressing it for every llama.cpp row stopped legacy local-only catalogs from
reaching the backend, which remote clients read (unslothai#7298). Only auto-reloading
rows need their catalog written by the queued refresh instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Connections don't show properly on remote systems

2 participants