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: laya download confirm (#12196)
Nilay7402079aa603
diff --git a/studio/backend/core/systemone/laya_runtime.py b/studio/backend/core/systemone/laya_runtime.pyindex c33031cca91..b0bdd6f8faf 100644--- a/studio/backend/core/systemone/laya_runtime.py+++ b/studio/backend/core/systemone/laya_runtime.py@@ -848,12 +848,16 @@ def status() -> dict[str, Any]:}-def unload() -> bool:- global _agent, _loaded, _device_name, _failure+def ensure_can_unload() -> None:with _state_lock:# _loading: a load claimed but not yet started would otherwise land after this unload.if _loading is not None or (_loader is not None and _loader.is_alive()):raise Unavailable(409, "model_loading", "Wait for the load to finish before unloading")+++def unload() -> bool:+ global _agent, _loaded, _device_name, _failure+ ensure_can_unload()with _run_lock:was_loaded = _agent is not None_agent = _loaded = _device_name = Nonediff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex db40dfa23d5..bcb9c860a97 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -652,6 +652,8 @@ class SystemOneSettingsPayload(BaseModel):enabled: Optional[bool] = Nonemodel: Optional[str] = Nonedevice: Optional[str] = None+ expected_enabled: Optional[bool] = None+ expected_model: Optional[str] = Noneclass SystemOneDownloadPlan(BaseModel):@@ -1399,6 +1401,37 @@ def _systemone_response() -> SystemOneSettingsResponse:)+_SYSTEMONE_SETTINGS_LOCK = threading.Lock()+++def _systemone_values(payload: SystemOneSettingsPayload) -> dict[str, Any]:+ try:+ return systemone_settings.validate(+ **payload.model_dump(include = {"enabled", "model", "device"}, exclude_none = True)+ )+ except ValueError as exc:+ raise log_and_http_error(+ exc,+ 400,+ safe_curated_detail(exc, fallback = "Invalid Decision API setting."),+ event = "settings.update_systemone_failed",+ log = logger,+ ) from exc+++def _check_systemone_expectations(payload: SystemOneSettingsPayload) -> None:+ from core.systemone import catalog+ changed = (+ payload.expected_enabled is not None+ and systemone_settings.get_enabled() != payload.expected_enabled+ ) or (+ payload.expected_model is not None+ and catalog.default_checkpoint().name != payload.expected_model+ )+ if changed:+ raise HTTPException(status_code = 409, detail = "Decision API settings changed. Try again.")++@_shared_settings_router.get("/systemone", response_model = SystemOneSettingsResponse)def get_systemone_settings(current_subject: str = Depends(get_current_subject),@@ -1411,33 +1444,44 @@ def update_systemone_settings(payload: SystemOneSettingsPayload, current_subject: str = Depends(get_current_subject)) -> SystemOneSettingsResponse:from core.systemone import laya_runtime-- try:- values = systemone_settings.validate(**payload.model_dump(exclude_none = True))- except ValueError as exc:- raise log_and_http_error(- exc,- 400,- safe_curated_detail(exc, fallback = "Invalid Decision API setting."),- event = "settings.update_systemone_failed",- log = logger,- ) from exc- if values:- # The resident model was built from the old settings; drop it so the next request uses the new ones.- try:- laya_runtime.unload()- except laya_runtime.Unavailable as exc:- raise HTTPException(status_code = 409, detail = exc.message) from None- systemone_settings.save(values)+ with _SYSTEMONE_SETTINGS_LOCK:+ _check_systemone_expectations(payload)+ values = _systemone_values(payload)+ if values:+ # The resident model was built from the old settings; drop it so the next request uses the new ones.+ try:+ laya_runtime.unload()+ except laya_runtime.Unavailable as exc:+ raise HTTPException(status_code = 409, detail = exc.message) from None+ systemone_settings.save(values)return _systemone_response()+@_owner_settings_router.post("/systemone/validate", status_code = 204)+def validate_systemone_settings(+ payload: SystemOneSettingsPayload, current_subject: str = Depends(get_current_subject)+) -> None:+ from core.systemone import laya_runtime+ with _SYSTEMONE_SETTINGS_LOCK:+ _check_systemone_expectations(payload)+ values = _systemone_values(payload)+ if values:+ try:+ laya_runtime.ensure_can_unload()+ except laya_runtime.Unavailable as exc:+ raise HTTPException(status_code = 409, detail = exc.message) from None++@_owner_settings_router.get("/systemone/resolve", response_model = SystemOneDownloadPlan)def resolve_systemone_download(- current_subject: str = Depends(get_current_subject),+ model: Optional[str] = None, current_subject: str = Depends(get_current_subject)) -> SystemOneDownloadPlan:from core.systemone import catalog, laya_runtime- return SystemOneDownloadPlan(**laya_runtime.download_plan(catalog.default_checkpoint()))++ checkpoint = catalog.default_checkpoint() if model is None else catalog.resolve(model)+ if checkpoint is None:+ raise HTTPException(status_code = 400, detail = "Unknown Decision API model.")+ return SystemOneDownloadPlan(**laya_runtime.download_plan(checkpoint))@_owner_settings_router.post("/systemone/unload", response_model = SystemOneSettingsResponse)diff --git a/studio/backend/tests/test_systemone.py b/studio/backend/tests/test_systemone.pyindex 64304e967c1..b37f28e09d4 100644--- a/studio/backend/tests/test_systemone.py+++ b/studio/backend/tests/test_systemone.py@@ -396,6 +396,45 @@ def test_invalid_settings_are_refused_without_evicting_the_model(client, payloadassert client.get("/api/settings/systemone").json()["loaded_model"] == "laya-multilingual"+def test_settings_update_refuses_a_stale_consent_snapshot(client):+ response = client.put(+ "/api/settings/systemone",+ json = {+ "model": "laya-english",+ "expected_enabled": False,+ "expected_model": "laya-multilingual",+ },+ )+ assert response.status_code == 409+ assert response.json()["detail"] == "Decision API settings changed. Try again."+ assert client.get("/api/settings/systemone").json()["model"] == "laya-multilingual"+++def test_settings_validation_checks_the_snapshot_without_saving(client):+ response = client.post(+ "/api/settings/systemone/validate",+ json = {+ "model": "laya-english",+ "expected_enabled": True,+ "expected_model": "laya-multilingual",+ },+ )+ assert response.status_code == 204+ settings = client.get("/api/settings/systemone").json()+ assert settings["enabled"] is True+ assert settings["model"] == "laya-multilingual"+ updated = client.put(+ "/api/settings/systemone",+ json = {+ "model": "laya-english",+ "expected_enabled": True,+ "expected_model": "laya-multilingual",+ },+ )+ assert updated.status_code == 200+ assert updated.json()["model"] == "laya-english"++def test_env_model_is_locked(client, monkeypatch, tmp_path):monkeypatch.setenv("UNSLOTH_SYSTEMONE_MODEL", "laya-english")settings = client.get("/api/settings/systemone").json()@@ -406,6 +445,21 @@ def test_env_model_is_locked(client, monkeypatch, tmp_path):)+def test_stale_check_uses_the_display_name_for_a_local_env_model(client, monkeypatch, tmp_path):+ monkeypatch.setenv("UNSLOTH_SYSTEMONE_MODEL", str(tmp_path))+ settings = client.get("/api/settings/systemone").json()+ assert settings["model"] == "laya-local"+ response = client.post(+ "/api/settings/systemone/validate",+ json = {+ "enabled": True,+ "expected_enabled": True,+ "expected_model": "laya-local",+ },+ )+ assert response.status_code == 204++def test_settings_change_waits_for_a_running_load(client, monkeypatch):release = threading.Event()@@ -416,6 +470,17 @@ def test_settings_change_waits_for_a_running_load(client, monkeypatch):monkeypatch.setattr(laya_runtime, "_load_checkpoint", slow)monkeypatch.setattr(laya_runtime, "LOAD_WAIT_S", 0.05)assert _post(client).status_code == 503+ assert (+ client.post(+ "/api/settings/systemone/validate",+ json = {+ "model": "laya-english",+ "expected_enabled": True,+ "expected_model": "laya-multilingual",+ },+ ).status_code+ == 409+ )assert client.put("/api/settings/systemone", json = {"model": "laya-english"}).status_code == 409assert client.get("/api/settings/systemone").json()["model"] == "laya-multilingual"release.set()@@ -498,6 +563,31 @@ def test_download_plan_lists_exact_subfolder_files(client, monkeypatch):}+def test_download_plan_can_preview_a_model_without_changing_the_setting(client, monkeypatch):+ import huggingface_hub++ seen = []++ def list_tree(self, repo, **kwargs):+ seen.append((repo, kwargs))+ return []++ monkeypatch.setattr(laya_runtime, "is_cached", lambda checkpoint: False)+ monkeypatch.setattr(huggingface_hub.HfApi, "list_repo_tree", list_tree)+ plan = client.get("/api/settings/systemone/resolve?model=laya-english")+ assert plan.status_code == 200+ assert plan.json()["repo"] == catalog.LAYA_REPO+ assert plan.json()["size_bytes"] == catalog.CHECKPOINTS["laya-english"].download_bytes+ assert client.get("/api/settings/systemone").json()["model"] == "laya-multilingual"+ assert seen == [(catalog.LAYA_REPO, {"recursive": True})]+++def test_download_plan_refuses_an_unknown_preview_model(client):+ response = client.get("/api/settings/systemone/resolve?model=not-a-model")+ assert response.status_code == 400+ assert response.json()["detail"] == "Unknown Decision API model."++def test_download_plan_for_a_cached_model_skips_the_hub(client, monkeypatch):import huggingface_hub@@ -781,6 +871,17 @@ def test_decision_api_cannot_be_enabled_where_laya_is_not_installed(client, monkmonkeypatch.setattr(studio_db, "upsert_app_settings", settings.update)reason = "The Decision API needs PyTorch, which this Studio install does not include."monkeypatch.setattr(systemone_settings, "runtime_unavailable_reason", lambda: reason)+ preview = client.post(+ "/api/settings/systemone/validate",+ json = {+ "enabled": True,+ "expected_enabled": False,+ "expected_model": "laya-multilingual",+ },+ )+ assert preview.status_code == 400+ assert preview.json()["detail"] == reason+ assert settings == {}response = client.put("/api/settings/systemone", json = {"enabled": True})assert response.status_code == 400assert response.json()["detail"] == reasondiff --git a/studio/frontend/src/features/settings/api/systemone.ts b/studio/frontend/src/features/settings/api/systemone.tsindex ba22639c640..5821fa55796 100644--- a/studio/frontend/src/features/settings/api/systemone.ts+++ b/studio/frontend/src/features/settings/api/systemone.ts@@ -36,6 +36,14 @@ export type SystemOneDownloadPlan = {error: string | null;};+export type SystemOneSettingsPatch = {+ enabled?: boolean;+ model?: string;+ device?: SystemOneDevice;+ expectedEnabled?: boolean;+ expectedModel?: string;+};+type ApiSystemOneSettings = {enabled: boolean;// biome-ignore lint/style/useNamingConvention: API schema@@ -71,6 +79,17 @@ type ApiSystemOneDownloadPlan = {const SETTINGS_PATH = "/api/settings/systemone";+function toApiPatch(patch: SystemOneSettingsPatch) {+ const { expectedEnabled, expectedModel, ...settings } = patch;+ return {+ ...settings,+ ...(expectedEnabled !== undefined && {+ expected_enabled: expectedEnabled,+ }),+ ...(expectedModel !== undefined && { expected_model: expectedModel }),+ };+}+function fromApi(settings: ApiSystemOneSettings): SystemOneSettings {return {enabled: settings.enabled,@@ -107,21 +126,37 @@ export async function loadSystemOneSettings(): Promise<SystemOneSettings> {);}-export async function updateSystemOneSettings(patch: {- enabled?: boolean;- model?: string;- device?: SystemOneDevice;-}): Promise<SystemOneSettings> {+export async function updateSystemOneSettings(+ patch: SystemOneSettingsPatch,+): Promise<SystemOneSettings> {return readSettings(await authFetch(SETTINGS_PATH, {method: "PUT",headers: { "Content-Type": "application/json" },- body: JSON.stringify(patch),+ body: JSON.stringify(toApiPatch(patch)),}),"Failed to save Decision API settings",);}+export async function validateSystemOneSettings(+ patch: SystemOneSettingsPatch,+): Promise<void> {+ const res = await authFetch(`${SETTINGS_PATH}/validate`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(toApiPatch(patch)),+ });+ if (!res.ok) {+ throw new Error(+ await readFastApiError(+ res,+ "Couldn't validate the Decision API setting.",+ ),+ );+ }+}+export async function unloadSystemOneModel(): Promise<SystemOneSettings> {return readSettings(await authFetch(`${SETTINGS_PATH}/unload`, { method: "POST" }),@@ -129,8 +164,11 @@ export async function unloadSystemOneModel(): Promise<SystemOneSettings> {);}-export async function resolveSystemOneDownload(): Promise<SystemOneDownloadPlan> {- const res = await authFetch(`${SETTINGS_PATH}/resolve`);+export async function resolveSystemOneDownload(+ model?: string,+): Promise<SystemOneDownloadPlan> {+ const query = model ? `?${new URLSearchParams({ model })}` : "";+ const res = await authFetch(`${SETTINGS_PATH}/resolve${query}`);if (!res.ok) {throw new Error(await readFastApiError(res, "Failed to check the Decision API model"),diff --git a/studio/frontend/src/features/settings/components/decision-api-section.tsx b/studio/frontend/src/features/settings/components/decision-api-section.tsxindex 6ccde0db870..168d907ed60 100644--- a/studio/frontend/src/features/settings/components/decision-api-section.tsx+++ b/studio/frontend/src/features/settings/components/decision-api-section.tsx@@ -1,6 +1,17 @@// 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 {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogMedia,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";import {Select,@@ -33,6 +44,7 @@ import {resolveSystemOneDownload,unloadSystemOneModel,updateSystemOneSettings,+ validateSystemOneSettings,} from "../api/systemone";import { SettingsRow } from "./settings-row";@@ -63,6 +75,11 @@ export function DecisionApiSection(): ReactElement | null {model: string;plan: SystemOneDownloadPlan;} | null>(null);+ const [confirm, setConfirm] = useState<{+ plan: SystemOneDownloadPlan;+ patch: Parameters<typeof updateSystemOneSettings>[0];+ model: string;+ } | null>(null);const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);@@ -108,7 +125,7 @@ export function DecisionApiSection(): ReactElement | null {useEffect(() => {if (!enabled || !model) return;let live = true;- resolveSystemOneDownload().then(+ resolveSystemOneDownload(model).then((next) => live && setPlanState({ model, plan: next }),(err) => live && setError(errorMessage(err)),);@@ -120,8 +137,25 @@ export function DecisionApiSection(): ReactElement | null {const modelLabel = (name: string) =>MODEL_LABELS[name] ? t(MODEL_LABELS[name]) : name;+ const resyncSettingsAfterError = async (message: string) => {+ try {+ setSettings(await loadSystemOneSettings());+ } catch (refreshError) {+ console.warn(+ "Couldn't refresh Decision API settings after a rejected change.",+ refreshError,+ );+ }+ setError(message);+ };+const startDownload = async (next: SystemOneDownloadPlan) => {- if (!next.repo || next.cached || next.files.length === 0) return;+ if (!next.repo || next.cached || next.files.length === 0) return false;+ const downloadKey = jobKeyOf(+ DOWNLOAD_KIND.MODEL,+ next.repo,+ scopedVariant(DOWNLOAD_SCOPE),+ );try {const outcome = await downloadManager.requestStart({kind: DOWNLOAD_KIND.MODEL,@@ -132,9 +166,17 @@ export function DecisionApiSection(): ReactElement | null {inventoryKind: "model",expectedBytes: next.sizeBytes,});- if (outcome === "started") return;+ if (outcome === "started") {+ const acceptedState =+ useDownloadManagerStore.getState().jobs[downloadKey]?.state;+ if (acceptedState === "running" || acceptedState === "complete") {+ return true;+ }+ }if (outcome === "conflict" || outcome === "busy") {toast.info(t("settings.apiKeys.decisionApi.downloadBusy"));+ } else if (outcome === "started") {+ toast.info(t("settings.apiKeys.decisionApi.downloadBusy"));} else {toast.error(t("settings.apiKeys.decisionApi.downloadFailed"));}@@ -143,6 +185,7 @@ export function DecisionApiSection(): ReactElement | null {description: errorMessage(err) ?? undefined,});}+ return false;};const apply = async (@@ -152,16 +195,62 @@ export function DecisionApiSection(): ReactElement | null {setBusy(true);setError(null);try {- const next = await updateSystemOneSettings(patch);+ // Offer the download on the switch, not on the first request: a first API call should not sit behind a 700 MB transfer.+ const nextEnabled = patch.enabled ?? settings?.enabled;+ const nextModel = patch.model ?? settings?.model;+ const settingsPatch =+ downloadAfter && settings+ ? {+ ...patch,+ expectedEnabled: settings.enabled,+ expectedModel: settings.model,+ }+ : patch;+ let resolvedPlan: { model: string; plan: SystemOneDownloadPlan } | null =+ null;+ if (nextEnabled && nextModel && downloadAfter) {+ const nextPlan = await resolveSystemOneDownload(nextModel);+ if (!nextPlan.cached) {+ if (nextPlan.error || !nextPlan.repo || nextPlan.files.length === 0) {+ throw new Error(+ nextPlan.error ??+ t("settings.apiKeys.decisionApi.downloadFailed"),+ );+ }+ setConfirm({+ plan: nextPlan,+ patch: settingsPatch,+ model: nextModel,+ });+ return;+ }+ resolvedPlan = { model: nextModel, plan: nextPlan };+ }+ const next = await updateSystemOneSettings(settingsPatch);setSettings(next);- // Download on the switch, not on the first request: a first API call should not sit behind a 700 MB transfer.- if (next.enabled && downloadAfter) {- const nextPlan = await resolveSystemOneDownload();- setPlanState({ model: next.model, plan: nextPlan });- await startDownload(nextPlan);+ if (resolvedPlan?.model === next.model) setPlanState(resolvedPlan);+ } catch (err) {+ await resyncSettingsAfterError(+ errorMessage(err) ?? t("settings.apiKeys.decisionApi.saveFailed"),+ );+ } finally {+ setBusy(false);+ }+ };++ const acceptDownload = async (accepted: NonNullable<typeof confirm>) => {+ setBusy(true);+ setError(null);+ try {+ await validateSystemOneSettings(accepted.patch);+ if (!(await startDownload(accepted.plan))) return;+ const next = await updateSystemOneSettings(accepted.patch);+ setSettings(next);+ if (next.model === accepted.model) {+ setPlanState({ model: accepted.model, plan: accepted.plan });}} catch (err) {- setError(+ await resyncSettingsAfterError(errorMessage(err) ?? t("settings.apiKeys.decisionApi.saveFailed"),);} finally {@@ -419,6 +508,46 @@ export function DecisionApiSection(): ReactElement | null {</Select></SettingsRow></div>++ <AlertDialog+ open={confirm !== null}+ onOpenChange={(open) => {+ if (!open && confirm) {+ setConfirm(null);+ }+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogMedia>+ <HugeiconsIcon icon={TaskDone01Icon} strokeWidth={1.75} />+ </AlertDialogMedia>+ <AlertDialogTitle>+ {t("settings.apiKeys.decisionApi.downloadConfirmTitle", {+ model: modelLabel(confirm?.model ?? settings.model),+ })}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t("settings.apiKeys.decisionApi.downloadConfirmBody", {+ size: formatBytes(confirm?.plan.sizeBytes || sizeBytes),+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel>+ <AlertDialogAction+ onClick={(event) => {+ event.preventDefault();+ const accepted = confirm;+ setConfirm(null);+ if (accepted) void acceptDownload(accepted);+ }}+ >+ {t("settings.apiKeys.decisionApi.download")}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></section>);}diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 0eb064fd346..9211c1b7578 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -2198,6 +2198,9 @@ export const ar = {loading: "جارٍ التحميل…",loadedOn: "مُحمَّل على {device}",download: "تنزيل",+ downloadConfirmTitle: "هل تريد تنزيل Laya {model}؟",+ downloadConfirmBody:+ "تحتاج واجهة API للقرارات إلى هذا النموذج للرد على الطلبات. حجمه نحو {size}، ويُنزَّل مرة واحدة إلى ذاكرة Hugging Face المؤقتة.",unload: "إلغاء التحميل",downloadBusy: "يجري بالفعل تنزيل نموذج لواجهة القرارات.",downloadFailed: "تعذّر بدء التنزيل.",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 5c392a85420..36fb761497f 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -2242,6 +2242,9 @@ export const de = {loading: "Wird geladen…",loadedOn: "Geladen auf {device}",download: "Herunterladen",+ downloadConfirmTitle: "Laya {model} herunterladen?",+ downloadConfirmBody:+ "Die Entscheidungs-API braucht dieses Modell, um Anfragen zu beantworten. Etwa {size}, einmalig in deinen Hugging-Face-Cache geladen.",unload: "Entladen",downloadBusy: "Ein Modell der Entscheidungs-API wird bereits heruntergeladen.",downloadFailed: "Der Download konnte nicht gestartet werden.",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 1b1d4b11336..cba74d80e92 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -2193,6 +2193,9 @@ export const en = {loading: "Loading…",loadedOn: "Loaded on {device}",download: "Download",+ downloadConfirmTitle: "Download Laya {model}?",+ downloadConfirmBody:+ "The Decision API needs this model to answer requests. About {size}, fetched once into your Hugging Face cache.",unload: "Unload",downloadBusy: "A Decision API model is already downloading.",downloadFailed: "Couldn't start the download.",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 91a51f119dd..119440b0437 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -2233,6 +2233,9 @@ export const es = {loading: "Cargando…",loadedOn: "Cargado en {device}",download: "Descargar",+ downloadConfirmTitle: "¿Descargar Laya {model}?",+ downloadConfirmBody:+ "La API de decisiones necesita este modelo para responder solicitudes. Unos {size}, se descarga una vez en tu caché de Hugging Face.",unload: "Descargar de memoria",downloadBusy: "Ya se está descargando un modelo de la API de decisiones.",downloadFailed: "No se pudo iniciar la descarga.",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 4820d732201..673f7931960 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -2243,6 +2243,9 @@ export const fr = {loading: "Chargement…",loadedOn: "Chargé sur {device}",download: "Télécharger",+ downloadConfirmTitle: "Télécharger Laya {model} ?",+ downloadConfirmBody:+ "L'API de décision a besoin de ce modèle pour répondre aux requêtes. Environ {size}, téléchargé une seule fois dans votre cache Hugging Face.",unload: "Décharger",downloadBusy: "Un modèle de l'API de décision est déjà en cours de téléchargement.",downloadFailed: "Impossible de lancer le téléchargement.",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 5d092ce307d..87b4da83a44 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -2204,6 +2204,9 @@ export const hi = {loading: "लोड हो रहा है…",loadedOn: "{device} पर लोड हुआ",download: "डाउनलोड करें",+ downloadConfirmTitle: "Laya {model} डाउनलोड करें?",+ downloadConfirmBody:+ "Decision API को अनुरोधों का जवाब देने के लिए इस मॉडल की ज़रूरत है। लगभग {size}, आपके Hugging Face कैश में एक बार डाउनलोड होता है।",unload: "अनलोड करें",downloadBusy: "निर्णय API का एक मॉडल पहले से डाउनलोड हो रहा है।",downloadFailed: "डाउनलोड शुरू नहीं हो सका।",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex daacd57f9aa..9480c0941d1 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -2203,6 +2203,9 @@ export const it = {loading: "Caricamento…",loadedOn: "Caricato su {device}",download: "Scarica",+ downloadConfirmTitle: "Scaricare Laya {model}?",+ downloadConfirmBody:+ "L'API decisionale ha bisogno di questo modello per rispondere alle richieste. Circa {size}, scaricato una sola volta nella cache di Hugging Face.",unload: "Rimuovi dalla memoria",downloadBusy: "Un modello dell'API decisionale è già in download.",downloadFailed: "Impossibile avviare il download.",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex a1b9bce5f83..4f6ac3f3333 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -2168,6 +2168,9 @@ export const ja = {loading: "読み込み中…",loadedOn: "{device} に読み込み済み",download: "ダウンロード",+ downloadConfirmTitle: "Laya {model} をダウンロードしますか?",+ downloadConfirmBody:+ "Decision API がリクエストに応答するにはこのモデルが必要です。約 {size}、Hugging Face キャッシュに一度だけダウンロードされます。",unload: "アンロード",downloadBusy: "判定 API のモデルはすでにダウンロード中です。",downloadFailed: "ダウンロードを開始できませんでした。",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 380a722270f..0b0194a8233 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -2191,6 +2191,9 @@ export const ko = {loading: "로드 중…",loadedOn: "{device}에 로드됨",download: "다운로드",+ downloadConfirmTitle: "Laya {model}을(를) 다운로드할까요?",+ downloadConfirmBody:+ "Decision API가 요청에 응답하려면 이 모델이 필요합니다. 약 {size}이며 Hugging Face 캐시에 한 번만 다운로드됩니다.",unload: "언로드",downloadBusy: "판단 API 모델이 이미 다운로드 중입니다.",downloadFailed: "다운로드를 시작하지 못했습니다.",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 2ca775e5a50..3aab2852e37 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -2214,6 +2214,9 @@ export const ptBR = {loading: "Carregando…",loadedOn: "Carregado em {device}",download: "Baixar",+ downloadConfirmTitle: "Baixar Laya {model}?",+ downloadConfirmBody:+ "A API de decisão precisa deste modelo para responder às solicitações. Cerca de {size}, baixado uma única vez no seu cache do Hugging Face.",unload: "Descarregar",downloadBusy: "Um modelo da API de decisões já está sendo baixado.",downloadFailed: "Não foi possível iniciar o download.",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 1116cedb955..400b9bc921b 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -2210,6 +2210,9 @@ export const ru = {loading: "Загрузка…",loadedOn: "Загружена на {device}",download: "Скачать",+ downloadConfirmTitle: "Скачать Laya {model}?",+ downloadConfirmBody:+ "API решений нужна эта модель, чтобы отвечать на запросы. Около {size}, загружается один раз в кэш Hugging Face.",unload: "Выгрузить",downloadBusy: "Модель API решений уже скачивается.",downloadFailed: "Не удалось начать скачивание.",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex a37851b9c7b..c5e07729855 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -2148,6 +2148,9 @@ export const zhCN = {loading: "正在加载…",loadedOn: "已加载到 {device}",download: "下载",+ downloadConfirmTitle: "下载 Laya {model}?",+ downloadConfirmBody:+ "决策 API 需要此模型来响应请求。约 {size},只需下载一次到你的 Hugging Face 缓存。",unload: "卸载",downloadBusy: "已有一个决策 API 模型正在下载。",downloadFailed: "无法开始下载。",diff --git a/studio/frontend/tests/decision-api-section.test.ts b/studio/frontend/tests/decision-api-section.test.tsindex 039560e0a58..2660b16449c 100644--- a/studio/frontend/tests/decision-api-section.test.ts+++ b/studio/frontend/tests/decision-api-section.test.ts@@ -6,8 +6,8 @@ import { readFileSync } from "node:fs";import test from "node:test";import { fileURLToPath } from "node:url";-import { en } from "../src/i18n/locales/en.ts";import { SETTINGS_SEARCH_INDEX } from "../src/features/settings/settings-search.ts";+import { en } from "../src/i18n/locales/en.ts";function read(path: string): string {return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf-8");@@ -50,11 +50,57 @@ test("turning it on or picking a model downloads, the device does not", () => {);});+test("a download waits for confirmation before changing the setting", () => {+ const apply = SECTION.slice(+ SECTION.indexOf("const apply = async"),+ SECTION.indexOf("const acceptDownload = async"),+ );+ assert.doesNotMatch(apply, /startDownload\(/);+ assert.ok(+ apply.indexOf("resolveSystemOneDownload(nextModel)") <+ apply.indexOf("updateSystemOneSettings(settingsPatch)"),+ );+ assert.match(apply, /expectedEnabled: settings\.enabled/);+ assert.match(apply, /expectedModel: settings\.model/);+ assert.match(+ apply,+ /setConfirm\(\{\s*plan: nextPlan,\s*patch: settingsPatch,\s*model: nextModel,?\s*\}\);\s*return;/,+ );+ assert.doesNotMatch(+ apply.slice(0, apply.indexOf("setConfirm")),+ /setPlanState/,+ );+ const accept = SECTION.slice(+ SECTION.indexOf("const acceptDownload = async"),+ SECTION.indexOf("const unload = async"),+ );+ assert.ok(+ accept.indexOf("validateSystemOneSettings(accepted.patch)") <+ accept.indexOf("startDownload(accepted.plan)"),+ );+ assert.ok(+ accept.indexOf("startDownload(accepted.plan)") <+ accept.indexOf("updateSystemOneSettings(accepted.patch)"),+ );+ assert.match(+ SECTION,+ /<AlertDialogAction[\s\S]*?acceptDownload\(accepted\)[\s\S]*?<\/AlertDialogAction>/,+ );+ assert.doesNotMatch(SECTION, /apply\(confirm\./);+ assert.match(en.settings.apiKeys.decisionApi.downloadConfirmBody, /\{size\}/);+});+test("the download goes through the manager with the exact files and one scope", () => {assert.match(SECTION, /const DOWNLOAD_SCOPE = "systemone";/);assert.match(SECTION, /scopeId: DOWNLOAD_SCOPE,/);assert.match(SECTION, /files: next\.files,/);assert.match(SECTION, /expectedBytes: next\.sizeBytes,/);+ assert.match(+ SECTION,+ /acceptedState === "running" \|\| acceptedState === "complete"/,+ );+ assert.match(SECTION, /resolveSystemOneDownload\(model\)\.then/);+ assert.match(SECTION, /await resyncSettingsAfterError/);});test("environment overrides lock their control and say why", () => {@@ -91,7 +137,10 @@ test("the copy stays plain", () => {test("the client talks to the settings routes and maps the schema", () => {assert.match(API, /const SETTINGS_PATH = "\/api\/settings\/systemone";/);assert.match(API, /`\$\{SETTINGS_PATH\}\/unload`/);- assert.match(API, /`\$\{SETTINGS_PATH\}\/resolve`/);+ assert.match(API, /`\$\{SETTINGS_PATH\}\/validate`/);+ assert.match(API, /`\$\{SETTINGS_PATH\}\/resolve\$\{query\}`/);+ assert.match(API, /expected_enabled: expectedEnabled/);+ assert.match(API, /expected_model: expectedModel/);for (const [camel, snake] of [["enabledLocked", "enabled_locked"],["gpuAvailable", "gpu_available"],