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
tests: follow the remote-connection contract through its refactor (#8467)
Daniel Han620b9fa29e77
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex 999afab61b3..7a359ef7ed5 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -1428,12 +1428,21 @@ function GgufVariantExpander({}return recommended;}, [variantGroups, preferredByGroup, totalBudgetGb, budgetKnown, getGgufFit]);- // Flattened, for readers with no row to ask about (the footprint representative- // below). A ROW asks its own group, or it lights the other group's pick too.- const effectiveRecommended = useMemo(- () => new Set(effectiveRecommendedByGroup.values()),- [effectiveRecommendedByGroup],- );+ // The same recommendations, reachable from a row. `effectiveRecommendedByGroup`+ // is keyed by PRESENTATION group ("quantizations", "text-frames",+ // "reference-media"); the footprint pass below buckets by the backend's+ // dependency_key ("flux.2-klein:<digest>"). Those are different key spaces,+ // so that pass has to ask through the variant itself, which is the object+ // the presentation grouping already placed.+ const recommendedQuantForVariant = useMemo(() => {+ const byVariant = new Map<GgufVariantDetail, string>();+ for (const group of variantGroups) {+ const recommended = effectiveRecommendedByGroup.get(group.key);+ if (recommended === undefined) continue;+ for (const variant of group.variants) byVariant.set(variant, recommended);+ }+ return byVariant;+ }, [variantGroups, effectiveRecommendedByGroup]);const sortedVariants = useMemo(() => {if (!variants) return variants;@@ -1509,16 +1518,21 @@ function GgufVariantExpander({continue;}// The recommended quant is the representative of its own group when it- // has one; otherwise the group's first row stands.+ // has one; otherwise the group's first row stands. Asked per variant, not+ // of a flattened set: two families in one neutral repo can share quant+ // names, so global membership would let the other group's pick stand in+ // here and resolve companions against the wrong base repo.+ const recommended = recommendedQuantForVariant.get(variant);if (- !effectiveRecommended.has(current.quant) &&- effectiveRecommended.has(variant.quant)+ recommended !== undefined &&+ current.quant !== recommended &&+ variant.quant === recommended) {byKey.set(key, variant);}}return Array.from(byKey.values());- }, [displayVariants, effectiveRecommended]);+ }, [displayVariants, recommendedQuantForVariant]);const [companionBytesByKey, setCompanionBytesByKey] = useState<Map<string, number>>(() => new Map());diff --git a/studio/frontend/tests/credential-persistence.test.ts b/studio/frontend/tests/credential-persistence.test.tsindex e44770086b4..9fd839cd524 100644--- a/studio/frontend/tests/credential-persistence.test.ts+++ b/studio/frontend/tests/credential-persistence.test.ts@@ -150,6 +150,30 @@ test("superseded provider backfills are not launched", async () => {});+test("provider backfills are finished, not merely started, when the batch resolves", async () => {+ // The credential bootstrap gate releases app content on this promise, so a batch that is+ // only started leaves the writes racing an immediate close. Timer-backed tasks are the+ // only way to tell "awaited" from "fired and forgotten": a task that counts synchronously+ // is already done by the time the helper returns either way.+ const finished: string[] = [];+ const delayed = (name: string, ms: number) => () =>+ new Promise((resolve) => {+ setTimeout(() => {+ finished.push(name);+ resolve(null);+ }, ms);+ });++ // The rejection in the middle must not sink the two around it, which is why the batch+ // settles rather than rejecting on the first failure.+ await settleTasksIfCurrent(+ [delayed("first", 20), () => Promise.reject(new Error("backfill failed")), delayed("last", 40)],+ () => true,+ );+ assert.deepEqual(finished, ["first", "last"]);+});++test("authoritative provider cleanup removes only orphaned legacy keys", async () => {const { store } = installLocalStorageFake();store.set(diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 185bdf14a17..1a5a5cf3090 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -1693,14 +1693,43 @@ def test_a_lost_generate_post_must_prove_it_reached_the_backend():fn = src[src.index("async function settleLostGeneration") :]fn = fn[: fn.index("\n}\n")]assert "sawActive" in fn+ assert "did not reach the server" in fn# The proof used to be an inline knownIds set; it is now a baseline handed# to hasUnknownRecord in lib/gallery-flags.ts. Same proof, named helper, so# the assertion follows it rather than pinning the old spelling.assert "hasUnknownRecord(" in fn- assert "baseline" in fn- assert "did not reach the server" in fn+ assert "hasUnknownRecord(\n baseline," in fn+ # The caller still snapshots the ids BEFORE the POST and passes THAT SET in.+ # Pin the argument, not the mere presence of the snapshot expression: with a+ # fresh `new Set()` in the knownIds slot the snapshot still exists, is still+ # taken before the POST and `probeBaseline` still reaches the probe, yet every+ # record already on the page reads as unknown and a POST that never landed is+ # reported as a finished image. Whitespace is normalised first, so reformatting+ # the call cannot break the pin.+ snapshot_pattern = (+ r"const (\w+) = new Set\(galleryCache\.images\.map\(\(image\) => image\.id\)\);"+ )+ assert len(re.findall(snapshot_pattern, src)) == 1, "the pre-POST id snapshot is not unique"+ snapshot = re.search(snapshot_pattern, src)+ known_ids = snapshot.group(1)+ flat = " ".join(src.split())+ call = re.search(r"const probeBaseline = newRecordProbeBaseline\(\s*(.*?)\s*\);", flat)+ assert call, "probeBaseline is no longer built by newRecordProbeBaseline"+ args = [arg.strip() for arg in call.group(1).split(",") if arg.strip()]+ assert args == ["galleryCache.images", "galleryCache.hasMore", known_ids], args+ baseline = src.index("const probeBaseline = newRecordProbeBaseline(")+ # Snapshot, then baseline, then the POST -- in that order.+ assert snapshot.start() < baseline+ assert baseline < src.index("await generateDiffusionImage(", baseline)+ assert "settleLostGeneration(() => isMounted.current, probeBaseline)" in src+flags = _read("lib/gallery-flags.ts")assert "export async function hasUnknownRecord" in flags+ # An unknown row is the proof, and only an unpinned one counts.+ assert "return !baseline.knownIds.has(record.id);" in flags+ # Inconclusive listings must refuse to claim proof, else a submission that+ # never landed reads as a finished image, which is the bug this guards.+ assert "if (!baseline.canJudgeUnpinned) return false;" in flagsdef test_parallel_slots_setting_wired_end_to_end():@@ -2108,7 +2137,7 @@ def test_vulkan_inference_devices_are_the_pickable_set():# The Vulkan inventory is authoritative even while its probe is temporarily# empty. Falling through would expose physical CUDA/ROCm IDs in an ordinal# picker and make DiffusionGemma offer a selection the route rejects.- assert "const inference = data?.inference_gpu; " 'if (inference?.backend === "vulkan") {' in src+ assert 'const inference = data?.inference_gpu; if (inference?.backend === "vulkan") {' in src# A confirmed-Vulkan backend with no enumerated devices yet must return no# devices, not fall through to the torch/CUDA inventory below.assert "if (!(inference.devices ?? []).length) return [];" in src@@ -3363,15 +3392,37 @@ def test_the_gguf_footprint_is_resolved_per_dependency_group_not_per_repo():)# Representatives are derived per key, not once for the listing.group = src.split("const footprintVariants = useMemo(", 1)[1]- group = group.split("}, [displayVariants, effectiveRecommended]);", 1)[0]+ group = group.split("}, [displayVariants, recommendedQuantForVariant]);", 1)[0]assert "new Map<string, GgufVariantDetail>()" in groupassert 'const key = variant.dependency_key ?? "";' in group- # The recommended quant still wins, but only inside its own group.- # effectiveRecommended went from a single quant to a SET of them, so the- # representative test is membership rather than equality. The contract is- # unchanged: the recommended quant represents its own group when it has one.- assert "effectiveRecommended.has(variant.quant)" in group- assert "!effectiveRecommended.has(current.quant)" in group+ # The recommended quant still wins, and only inside its own group. Main+ # tracked the source through effectiveRecommended becoming a SET and+ # asserted membership in it; but that set is flattened across groups, so it+ # blesses the other group's pick when two families in one repo share quant+ # names.+ #+ # Group-scoping it is right, but this block buckets by the BACKEND's+ # dependency_key ("flux.2-klein:<digest>") while the recommendation map is+ # keyed by PRESENTATION group ("quantizations", "text-frames",+ # "reference-media"). Joining those two key spaces makes every lookup+ # undefined and the recommended-quant branch dead, leaving whichever row+ # tier ordering put first to speak for the group. So ask through the+ # variant, and pin that neither the flattened set nor the crossed-key+ # lookup is what stands here.+ assert "const recommended = recommendedQuantForVariant.get(variant);" in group+ assert "variant.quant === recommended" in group+ assert "current.quant !== recommended" in group+ assert "recommended !== undefined" in group+ assert "effectiveRecommended.has(" not in group+ assert "effectiveRecommendedByGroup.get(key)" not in group++ # And the map it asks is built from the presentation groups, keyed by the+ # variant objects those groups hold.+ builder = src.split("const recommendedQuantForVariant = useMemo(", 1)[1]+ builder = builder.split("}, [variantGroups, effectiveRecommendedByGroup]);", 1)[0]+ assert "new Map<GgufVariantDetail, string>()" in builder+ assert "effectiveRecommendedByGroup.get(group.key)" in builder+ assert "byVariant.set(variant, recommended)" in builderdef test_every_footprint_group_gets_its_own_resolve_call():diff --git a/tests/studio/test_provider_backfill_awaits_batch.py b/tests/studio/test_provider_backfill_awaits_batch.pynew file mode 100644index 00000000000..38bc3c4e0b5--- /dev/null+++ b/tests/studio/test_provider_backfill_awaits_batch.py@@ -0,0 +1,149 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The provider model backfill must be finished before the sync resolves (#7281).++``syncExternalProvidersFromBackend`` is what the credential bootstrap gate awaits before it+releases app content, so the backfill writes have to be complete when it returns. Two hops+carry that: the ``await`` on ``settleTasksIfCurrent`` at the call site, and the ``await`` on+``Promise.allSettled`` inside the helper. Drop either and the sync resolves while the writes+are still in flight, so an immediate close or a session transition loses them.++A string contract cannot hold this. ``await`` is one token in a source file; asserting it is+present is defeated by any reformat, and asserting the call is present says nothing about+whether it is awaited. So both hops are run for real instead: the helper and the call-site+tail are sliced VERBATIM out of the studio sources into a node harness (see+``_node_harness``) and driven with tasks that only finish on a timer. If either ``await``+goes, the tail resolves with the timers still pending and the recorded order is empty.++The same run pins the other half of the contract, that the batch SETTLES rather than+rejecting on the first failure: one task rejects immediately, and the two that resolve later+must still be recorded. Under ``Promise.all`` the tail would reject instead.+"""++from __future__ import annotations++import textwrap++import pytest++from _node_harness import (+ WORKDIR,+ read,+ require_node,+ run_harness,+ slice_between,+ source_path,+)++RECONCILIATION = source_path("studio/frontend/src/features/credentials/reconciliation.ts")+SYNC_PROVIDERS = source_path("studio/frontend/src/features/chat/sync-external-providers.ts")++SOURCES = (RECONCILIATION, SYNC_PROVIDERS)++TEMP = WORKDIR / "temp" / "provider_backfill_awaits_batch"++# The end of syncExternalProvidersFromBackend, which is where the backfill batch is awaited.+# Anchored on the unique return and walked BACK to the staleness guard, so the slice is taken+# without matching on the word being tested.+TAIL_END = "\n return syncedProviders;\n}"+TAIL_START = "if (isCurrent && !isCurrent()) return existingProviders;"+++def _helper_source() -> str:+ """settleTasksIfCurrent, verbatim."""+ text = read(RECONCILIATION)+ assert text.count("export async function settleTasksIfCurrent") == 1+ return slice_between(text, "export async function settleTasksIfCurrent", "\nexport ")+++def _tail_source() -> str:+ """The awaiting tail of syncExternalProvidersFromBackend, verbatim."""+ text = read(SYNC_PROVIDERS)+ assert text.count(TAIL_END) == 1, "the sync no longer ends in a single return"+ end = text.index(TAIL_END) + len(TAIL_END) - len("\n}")+ start = text.rindex(TAIL_START, 0, end)+ return text[start:end]+++def _harness_source() -> str:+ return (+ textwrap.dedent(+ """+ // @ts-nocheck+ // ---- PRELUDE: the sliced tail reads only through its parameters ----+ // ---- PRELUDE ENDS: verbatim studio source follows ----+ """+ )+ + _helper_source()+ + textwrap.dedent(+ """+ export async function syncBackfillTail(+ backfillTasks,+ isCurrent,+ existingProviders,+ syncedProviders,+ ) {+ """+ )+ + " "+ + _tail_source()+ + "\n}\n"+ )+++SCRIPT = """+// @ts-nocheck+import { settleTasksIfCurrent, syncBackfillTail } from "./harness.ts";++const finished = [];+const delayed = (name, ms) => () =>+ new Promise((resolve) => {+ setTimeout(() => {+ finished.push(name);+ resolve(null);+ }, ms);+ });++// One immediate rejection between two timer-backed writes: the tail must wait for both and+// must not be sunk by the failure in between.+const returned = await syncBackfillTail(+ [delayed("first", 40), () => Promise.reject(new Error("backfill failed")), delayed("last", 80)],+ () => true,+ ["existing"],+ ["synced"],+);+const finishedWhenSyncResolved = [...finished];++// A session that moved on skips the batch entirely, and must not run a task.+const stale = [];+await settleTasksIfCurrent(+ [+ () => {+ stale.push("ran");+ return Promise.resolve();+ },+ ],+ () => false,+);++console.log(JSON.stringify({ finishedWhenSyncResolved, returned, stale }));+"""++[email protected](scope = "module")+def result() -> dict:+ require_node(SOURCES)+ return run_harness(TEMP, _harness_source(), SCRIPT)+++def test_the_backfill_batch_is_complete_when_the_sync_resolves(result: dict):+ assert result["finishedWhenSyncResolved"] == ["first", "last"], (+ "the sync resolved with backfill writes still in flight, so a close or a session "+ "transition right after startup would lose them"+ )+ assert result["returned"] == ["synced"]+++def test_a_stale_session_runs_no_backfill(result: dict):+ assert result["stale"] == []diff --git a/tests/studio/test_remote_connection_models_contract.py b/tests/studio/test_remote_connection_models_contract.pyindex 1f0ee4e6905..f19e7133b7d 100644--- a/tests/studio/test_remote_connection_models_contract.py+++ b/tests/studio/test_remote_connection_models_contract.py@@ -11,6 +11,7 @@ FRONTEND = REPO / "studio/frontend/src"PROVIDERS_API = FRONTEND / "features/chat/api/providers-api.ts"SYNC_PROVIDERS = FRONTEND / "features/chat/sync-external-providers.ts"CHAT_PAGE = FRONTEND / "features/chat/chat-page.tsx"+RECONCILIATION = FRONTEND / "features/credentials/reconciliation.ts"CREDENTIAL_BOOTSTRAP = FRONTEND / "features/credentials/bootstrap.ts"ROOT_ROUTE = FRONTEND / "app/routes/__root.tsx"PROVIDERS_DB = REPO / "studio/backend/storage/providers_db.py"@@ -46,11 +47,25 @@ def test_frontend_sync_backfills_local_models_to_backend():# settleTasksIfCurrent in features/credentials/reconciliation.ts, which# allSettles them AND drops the result when the auth session has moved on.# Same guarantee through a named helper, so the assertion follows it.- assert "settleTasksIfCurrent(backfillTasks" in source- helper = (FRONTEND / "features/credentials/reconciliation.ts").read_text(encoding = "utf-8")+ #+ # Wiring only. That BOTH hops are awaited -- the call below and the+ # allSettled inside the helper -- is not something a source string can hold,+ # since `await` is one token that any reformat moves; that half is run for+ # real in test_provider_backfill_awaits_batch.py. Whitespace is normalised+ # here so prettier wrapping the argument list does not fail the wiring check+ # either.+ flat = " ".join(source.split()).replace("( ", "(")+ assert "settleTasksIfCurrent(backfillTasks" in flat+ helper = RECONCILIATION.read_text(encoding = "utf-8")assert "export async function settleTasksIfCurrent" in helper+ # Scoped to the helper's own body. The module also allSettles in+ # runCredentialBootstrap, so a module-wide search stays green when+ # settleTasksIfCurrent is regressed to Promise.all -- which is exactly the+ # first-failure-sinks-the-rest bug this contract exists to catch.+ body = helper.split("export async function settleTasksIfCurrent", 1)[1]+ body = body.split("\nexport ", 1)[0]assert (- "allSettled" in helper+ "Promise.allSettled(tasks.map(" in body), "the batch must still settle rather than reject on the first failure"@@ -71,13 +86,20 @@ def test_connections_are_hydrated_on_startup():into the app rather than only on the chat page. Asserting the old locationwould fail on a change that improved the thing being asserted, so theassertion follows the call to where it went and pins both halves -- the- bootstrap wires the sync, and something actually runs the bootstrap."""+ bootstrap wires the sync, and something actually runs the bootstrap.++ Both halves match CALL sites, not bare names: an import survives deleting+ the call it feeds, so a name-only assertion passes on a startup that+ hydrates nothing."""bootstrap = CREDENTIAL_BOOTSTRAP.read_text(encoding = "utf-8")- assert "syncExternalProvidersFromBackend" in bootstrap+ assert "syncExternalProvidersFromBackend(providers" in bootstraproot = ROOT_ROUTE.read_text(encoding = "utf-8")assert (- "bootstrapPersistedCredentials" in root+ "bootstrapPersistedCredentials()" in root), "nothing calls the credential bootstrap, so no page hydrates connections"+ # The call lives inside CredentialBootstrapGate, so the gate has to be+ # rendered too: dropping it stops hydration while the call still exists.+ assert "<CredentialBootstrapGate>" in root# The chat page still hydrates its own persisted settings.assert "hydratePersistedSettings()" in CHAT_PAGE.read_text(encoding = "utf-8")