Skip to content

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.

Studio: save idle auto-unload seconds on Enter (#16501)

Nilayf5b6181e6494
diff --git a/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx b/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx
index 68b47e59f5f..3dba1a4a02f 100644
--- a/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx
+++ b/studio/frontend/src/features/settings/components/model-auto-switch-section.tsx
@@ -5,7 +5,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { useT } from "@/i18n";
-import { useEffect, useState } from "react";
+import { type KeyboardEvent, useEffect, useState } from "react";
import {
type OpenAIAutoSwitchSettings,
type OpenAIAutoSwitchUpdate,
@@ -18,7 +18,6 @@ import { SettingsSection } from "./settings-section";
// Mirrors MIN_AUTO_UNLOAD_IDLE_SECONDS in the backend settings store.
export const MIN_IDLE_SECONDS = 60;
-// Parse an idle-seconds draft: 0 (off) or >= MIN_IDLE_SECONDS; else null.
export const parseIdleSeconds = (draft: string): number | null => {
if (!draft.trim()) {
return null;
@@ -30,8 +29,15 @@ export const parseIdleSeconds = (draft: string): number | null => {
return parsed === 0 || parsed >= MIN_IDLE_SECONDS ? parsed : null;
};
-// The image/video TTL, shown under Model memory: no enable toggle gates it, so
-// it lives beside the other memory settings rather than the chat TTL.
+// Chromium still delivers keydown to a focused input once it turns disabled.
+const saveOnEnter =
+ (save: () => void, disabled: boolean) =>
+ (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === "Enter" && !event.nativeEvent.isComposing && !disabled) {
+ save();
+ }
+ };
+
export function MediaIdleUnloadRow({
draftSeconds,
onDraftChange,
@@ -49,7 +55,6 @@ export function MediaIdleUnloadRow({
}) {
const t = useT();
const disabled = !settings || isSaving;
- // A saved TTL held off by a residency veto; the number alone would not say so.
const paused =
settings !== null &&
settings.mediaAutoUnloadIdleSeconds > 0 &&
@@ -82,6 +87,7 @@ export function MediaIdleUnloadRow({
)}
disabled={disabled}
onChange={(event) => onDraftChange(event.target.value)}
+ onKeyDown={saveOnEnter(onSave, disabled)}
className="h-control w-24"
/>
<span className="text-xs font-medium text-muted-foreground">s</span>
@@ -99,8 +105,6 @@ export function MediaIdleUnloadRow({
);
}
-// Saves the media TTL alone, with no `enabled`, so a stale chat toggle is never
-// written back. Re-reads when residency changes: that decides the paused note.
export function MediaIdleUnloadSetting({
residencyKey,
}: { residencyKey?: unknown }) {
@@ -281,8 +285,7 @@ export function ModelAutoSwitchSection() {
};
}, [t]);
- // syncDraft only for a write the chat idle-seconds input owns; every other row
- // leaves that draft alone so a save elsewhere cannot discard what is typed there.
+ // Other rows must preserve the unsaved idle-seconds draft.
const persist = async (
update: OpenAIAutoSwitchUpdate,
{ syncDraft = false }: { syncDraft?: boolean } = {},
@@ -307,7 +310,6 @@ export function ModelAutoSwitchSection() {
}
};
- // Toggling off keeps the saved seconds; the backend gates unloading on the enabled flag.
const handleToggle = (enabled: boolean) => {
const savedIdleSeconds = settings?.autoUnloadIdleSeconds ?? 0;
if (!enabled) {
@@ -362,6 +364,8 @@ export function ModelAutoSwitchSection() {
void persist({ enabled: settings.enabled, autoUnloadApiOnly: apiOnly });
};
+ const idleDisabled = !settings?.enabled || isSaving;
+
return (
<SettingsSection title={t("settings.general.modelAutoSwitch.sectionTitle")}>
<SettingsRow
@@ -404,6 +408,13 @@ export function ModelAutoSwitchSection() {
<span className="max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs text-muted-foreground">
{t("settings.general.modelAutoSwitch.idleNeedsEnable")}
</span>
+ ) : settings &&
+ !isSaving &&
+ parseIdleSeconds(draftIdleSeconds) !==
+ settings.autoUnloadIdleSeconds ? (
+ <span className="max-w-[calc(260px*var(--ui-space-scale,1))] text-right text-xs text-muted-foreground">
+ {t("settings.general.modelAutoSwitch.idleUnsaved")}
+ </span>
) : null
}
>
@@ -417,8 +428,9 @@ export function ModelAutoSwitchSection() {
aria-label={t(
"settings.general.modelAutoSwitch.idleSecondsAriaLabel",
)}
- disabled={!settings?.enabled || isSaving}
+ disabled={idleDisabled}
onChange={(event) => setDraftIdleSeconds(event.target.value)}
+ onKeyDown={saveOnEnter(handleSaveIdle, idleDisabled)}
className="h-control w-24"
/>
<span className="text-xs font-medium text-muted-foreground">s</span>
@@ -426,7 +438,7 @@ export function ModelAutoSwitchSection() {
<Button
variant="outline"
size="sm"
- disabled={!settings?.enabled || isSaving}
+ disabled={idleDisabled}
onClick={handleSaveIdle}
>
{isSaving ? t("common.saving") : t("common.save")}
@@ -445,7 +457,6 @@ export function ModelAutoSwitchSection() {
onCheckedChange={handleMediaAutoSwitchToggle}
/>
</SettingsRow>
- {/* Ungated: the KV save also runs before an image or video model takes the GPU. */}
<SettingsRow
label={t("settings.general.modelAutoSwitch.keepKv")}
description={t("settings.general.modelAutoSwitch.keepKvDescription")}
@@ -457,8 +468,6 @@ export function ModelAutoSwitchSection() {
onCheckedChange={handleKeepKvToggle}
/>
</SettingsRow>
- {/* Also whenever a media TTL is saved: this switch decides which media models that
- TTL may free, so it has to be reachable without re-enabling chat unloading first. */}
{settings &&
(settings.idleUnloadActive || settings.mediaAutoUnloadIdleSeconds > 0) ? (
<SettingsRow
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 801601d9fba..3044b8f0974 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1924,6 +1924,7 @@ export const ar = {
loadError: "فشل تحميل إعدادات التبديل التلقائي للنموذج.",
saveError: "فشل حفظ إعدادات التبديل التلقائي للنموذج.",
idleError: "أدخل 0 لإبقاء النموذج محمَّلاً، أو 60 ثانية على الأقل.",
+ idleUnsaved: "لم يُحفظ بعد.",
autoDownload: "تنزيل النماذج غير المنزَّلة",
autoDownloadDescription:
"يجلب ملف GGUF المذكور في طلب واجهة API إذا لم يكن منزَّلًا بعد. عندئذٍ يمكن لأي شخص لديه مفتاح API استهلاك مساحة القرص وعرض النطاق.",
diff --git a/studio/frontend/src/i18n/locales/cs.ts b/studio/frontend/src/i18n/locales/cs.ts
index 817711ea25c..266bdc83df1 100644
--- a/studio/frontend/src/i18n/locales/cs.ts
+++ b/studio/frontend/src/i18n/locales/cs.ts
@@ -2119,6 +2119,7 @@ export const cs = {
"Nastavení automatického přepínání modelu se nepodařilo uložit.",
idleError:
"Zadejte 0, chcete-li model ponechat načtený, nebo alespoň 60 sekund.",
+ idleUnsaved: "Zatím neuloženo.",
keepKv: "Zachovat kontext chatu i po uvolnění",
keepKvDescription:
"Uložit mezipaměť KV před uvolněním při nečinnosti nebo před tím, než GPU převezme model obrázků či videa, aby obnovené chaty nemusely znovu číst historii. Až 10 GB na disku.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index ca5f912cc3a..a087f0bdae4 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1941,6 +1941,7 @@ export const de = {
saveError:
"Einstellungen für automatischen Modellwechsel konnten nicht gespeichert werden.",
idleError: "Geben Sie 0 ein, um das Modell geladen zu halten, oder mindestens 60 Sekunden.",
+ idleUnsaved: "Noch nicht gespeichert.",
autoDownload: "Fehlende Modelle herunterladen",
autoDownloadDescription:
"Lädt ein in einer API-Anfrage genanntes GGUF herunter, das noch nicht vorhanden ist. Wer einen API-Schlüssel hat, kann dann Speicherplatz und Bandbreite verbrauchen.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index fea04856439..7001d630df8 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1939,6 +1939,7 @@ export const en = {
loadError: "Failed to load model auto-switch settings.",
saveError: "Failed to save model auto-switch settings.",
idleError: "Enter 0 to keep the model loaded, or at least 60 seconds.",
+ idleUnsaved: "Not saved yet.",
keepKv: "Keep chat context across unloads",
keepKvDescription:
"Save the KV cache before an idle unload, or before an image or video model takes the GPU, so resumed chats skip re-reading history. Up to 10 GB on disk.",
diff --git a/studio/frontend/src/i18n/locales/es-419.ts b/studio/frontend/src/i18n/locales/es-419.ts
index 6cd91171e09..44ab304fab2 100644
--- a/studio/frontend/src/i18n/locales/es-419.ts
+++ b/studio/frontend/src/i18n/locales/es-419.ts
@@ -2132,6 +2132,7 @@ export const es419 = {
"No se pudo guardar la configuración de cambio automático de modelo.",
idleError:
"Ingresa 0 para mantener el modelo cargado, o al menos 60 segundos.",
+ idleUnsaved: "Aún no se guardó.",
keepKv: "Conservar el contexto del chat entre descargas de memoria",
keepKvDescription:
"Guarda la caché KV antes de liberar el modelo por inactividad, o antes de que un modelo de imagen o video ocupe la GPU, para que los chats reanudados no tengan que volver a leer el historial. Hasta 10 GB en disco.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 26c136b7da6..cdca2fd482d 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1937,6 +1937,7 @@ export const es = {
saveError:
"No se pudo guardar la configuración de cambio automático de modelo.",
idleError: "Introduce 0 para mantener el modelo cargado, o al menos 60 segundos.",
+ idleUnsaved: "Aún no se ha guardado.",
autoDownload: "Descargar los modelos que falten",
autoDownloadDescription:
"Descarga un GGUF que se indique en una solicitud de la API y que aún no esté descargado. Cualquiera con una clave de API podría así consumir disco y ancho de banda.",
diff --git a/studio/frontend/src/i18n/locales/fa.ts b/studio/frontend/src/i18n/locales/fa.ts
index faa73e3e64b..8e562892193 100644
--- a/studio/frontend/src/i18n/locales/fa.ts
+++ b/studio/frontend/src/i18n/locales/fa.ts
@@ -2095,6 +2095,7 @@ export const fa = {
loadError: "بارگذاری تنظیمات تعویض خودکار مدل ناموفق بود.",
saveError: "ذخیرهٔ تنظیمات تعویض خودکار مدل ناموفق بود.",
idleError: "برای بارگذاری‌شده ماندن مدل 0 یا دست‌کم 60 ثانیه وارد کنید.",
+ idleUnsaved: "هنوز ذخیره نشده است.",
keepKv: "حفظ زمینهٔ گفتگو در میان تخلیه‌ها",
keepKvDescription:
"کش KV پیش از تخلیه در حالت بیکاری، یا پیش از آنکه مدل تصویر یا ویدیو GPU را بگیرد، ذخیره می‌شود تا گفتگوهای ازسرگرفته‌شده بازخوانی تاریخچه را رد کنند. حداکثر 10 GB روی دیسک.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 3134867d847..6939d25d6f7 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1939,6 +1939,7 @@ export const fr = {
saveError:
"Échec de l'enregistrement des paramètres de changement automatique de modèle.",
idleError: "Saisissez 0 pour garder le modèle chargé, ou au moins 60 secondes.",
+ idleUnsaved: "Pas encore enregistré.",
autoDownload: "Télécharger les modèles manquants",
autoDownloadDescription:
"Récupérer un GGUF indiqué dans une requête API qui n'est pas encore téléchargé. Toute personne disposant d'une clé API peut alors consommer de l'espace disque et de la bande passante.",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index b19a4da404d..874d28f3d59 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -1982,6 +1982,7 @@ export const he = {
loadError: "טעינת הגדרות ההחלפה האוטומטית של מודלים נכשלה.",
saveError: "שמירת הגדרות ההחלפה האוטומטית של מודלים נכשלה.",
idleError: "הזן 0 כדי לשמור את המודל טעון, או לפחות 60 שניות.",
+ idleUnsaved: "עדיין לא נשמר.",
keepKv: "שמור הקשר צ'אט על פני פריקות",
keepKvDescription:
"שמור את מטמון ה-KV לפני פריקה בחוסר פעילות, או לפני שמודל תמונה או וידאו תופס את ה-GPU, כדי שצ'אטים שיחודשו ידלגו על קריאה מחדש של ההיסטוריה. עד 10 GB בדיסק.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 44fc0a23df1..e56d34c9118 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1928,6 +1928,7 @@ export const hi = {
loadError: "मॉडल ऑटो-स्विच सेटिंग्स लोड करने में विफल।",
saveError: "मॉडल ऑटो-स्विच सेटिंग्स सहेजने में विफल।",
idleError: "मॉडल को लोड रखने के लिए 0 दर्ज करें, या कम से कम 60 सेकंड।",
+ idleUnsaved: "अभी सहेजा नहीं गया।",
autoDownload: "अनुपलब्ध मॉडल डाउनलोड करें",
autoDownloadDescription:
"API अनुरोध में बताया गया ऐसा GGUF लाता है जो अभी डाउनलोड नहीं हुआ है। इसके बाद API key रखने वाला कोई भी व्यक्ति डिस्क और बैंडविड्थ खर्च कर सकता है।",
diff --git a/studio/frontend/src/i18n/locales/id.ts b/studio/frontend/src/i18n/locales/id.ts
index ca5317c4529..cdded327a55 100644
--- a/studio/frontend/src/i18n/locales/id.ts
+++ b/studio/frontend/src/i18n/locales/id.ts
@@ -2105,6 +2105,7 @@ export const id = {
loadError: "Gagal memuat pengaturan peralihan model otomatis.",
saveError: "Gagal menyimpan pengaturan peralihan model otomatis.",
idleError: "Masukkan 0 agar model tetap dimuat, atau minimal 60 detik.",
+ idleUnsaved: "Belum disimpan.",
keepKv: "Pertahankan konteks chat saat model dilepas",
keepKvDescription:
"Simpan cache KV sebelum pelepasan karena tidak aktif, atau sebelum model gambar atau video mengambil alih GPU, agar chat yang dilanjutkan tidak perlu membaca ulang riwayat. Hingga 10 GB di disk.",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index b5cc5540e06..848755b63e5 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1844,6 +1844,7 @@ export const it = {
"Salvataggio delle impostazioni di cambio automatico del modello non riuscito.",
idleError:
"Inserisci 0 per mantenere il modello in memoria, oppure almeno 60 secondi.",
+ idleUnsaved: "Non ancora salvato.",
keepKv:
"Mantieni il contesto della chat tra gli scaricamenti",
keepKvDescription:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 35c408429ea..a121602e96a 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1916,6 +1916,7 @@ export const ja = {
loadError: "モデル自動切り替え設定の読み込みに失敗しました。",
saveError: "モデル自動切り替え設定の保存に失敗しました。",
idleError: "モデルを読み込んだままにするには 0 を、それ以外は 60 秒以上を入力してください。",
+ idleUnsaved: "まだ保存されていません。",
autoDownload: "不足しているモデルをダウンロード",
autoDownloadDescription:
"API リクエストで指定された未ダウンロードの GGUF を取得します。API キーを持つ人なら誰でもディスクと帯域を消費できるようになります。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 3641e5d9a6a..2ff866143ce 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1921,6 +1921,7 @@ export const ko = {
loadError: "모델 자동 전환 설정을 불러오지 못했습니다.",
saveError: "모델 자동 전환 설정을 저장하지 못했습니다.",
idleError: "모델을 로드 상태로 유지하려면 0을, 그렇지 않으면 60초 이상을 입력하세요.",
+ idleUnsaved: "아직 저장되지 않았습니다.",
autoDownload: "아직 받지 않은 모델 다운로드",
autoDownloadDescription:
"API 요청에 지정된 GGUF 모델이 아직 다운로드되어 있지 않으면 해당 모델을 자동으로 다운로드합니다. 이 기능을 사용하면 API 키를 가진 사용자가 디스크 공간과 네트워크 대역폭을 사용할 수 있습니다.",
diff --git a/studio/frontend/src/i18n/locales/nl.ts b/studio/frontend/src/i18n/locales/nl.ts
index bec1babe7e1..d7e0f131381 100644
--- a/studio/frontend/src/i18n/locales/nl.ts
+++ b/studio/frontend/src/i18n/locales/nl.ts
@@ -2137,6 +2137,7 @@ export const nl = {
"Kan de instellingen voor automatisch van model wisselen niet opslaan.",
idleError:
"Voer 0 in om het model geladen te houden, of minimaal 60 seconden.",
+ idleUnsaved: "Nog niet opgeslagen.",
keepKv: "Chatcontext behouden bij ontladen",
keepKvDescription:
"De KV-cache opslaan vóór het ontladen bij inactiviteit, of voordat een afbeeldings- of videomodel de GPU overneemt, zodat hervatte chats de geschiedenis niet opnieuw hoeven te lezen. Tot 10 GB op schijf.",
diff --git a/studio/frontend/src/i18n/locales/pl.ts b/studio/frontend/src/i18n/locales/pl.ts
index b8441fe6c52..cce88b5901f 100644
--- a/studio/frontend/src/i18n/locales/pl.ts
+++ b/studio/frontend/src/i18n/locales/pl.ts
@@ -2131,6 +2131,7 @@ export const pl = {
"Nie udało się zapisać ustawień automatycznego przełączania modelu.",
idleError:
"Wpisz 0, aby utrzymać model wczytany, lub co najmniej 60 sekund.",
+ idleUnsaved: "Jeszcze nie zapisano.",
keepKv: "Zachowuj kontekst czatu po zwolnieniu",
keepKvDescription:
"Zapisuj pamięć podręczną KV przed zwolnieniem z powodu bezczynności lub przed zajęciem GPU przez model obrazów lub wideo, aby wznowione czaty nie musiały ponownie wczytywać historii. Do 10 GB na dysku.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index e6ee33a5404..903e21b9b4d 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1930,6 +1930,7 @@ export const ptBR = {
loadError: "Falha ao carregar as configurações de troca automática de modelo.",
saveError: "Falha ao salvar as configurações de troca automática de modelo.",
idleError: "Insira 0 para manter o modelo carregado, ou pelo menos 60 segundos.",
+ idleUnsaved: "Ainda não salvo.",
autoDownload: "Baixar modelos ausentes",
autoDownloadDescription:
"Busca um GGUF indicado em uma requisição da API que ainda não foi baixado. Com isso, qualquer pessoa com uma chave de API pode consumir disco e largura de banda.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 254d4334336..24316834c17 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1927,6 +1927,7 @@ export const ru = {
loadError: "Не удалось загрузить настройки автопереключения модели.",
saveError: "Не удалось сохранить настройки автопереключения модели.",
idleError: "Введите 0, чтобы модель оставалась загруженной, или не менее 60 секунд.",
+ idleUnsaved: "Ещё не сохранено.",
autoDownload: "Скачивать недостающие модели",
autoDownloadDescription:
"Скачивает GGUF, указанный в запросе к API, если его ещё нет. Тогда любой, у кого есть ключ API, сможет расходовать место на диске и трафик.",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index ae8f749ec76..24b0813c491 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -2038,6 +2038,7 @@ export const sv = {
"Det gick inte att spara inställningarna för automatiskt modellbyte.",
idleError:
"Ange 0 för att behålla modellen inläst, eller minst 60 sekunder.",
+ idleUnsaved: "Inte sparat ännu.",
keepKv: "Behåll chattkontext mellan avlastningar",
keepKvDescription:
"Spara KV-cachen före en avlastning efter inaktivitet, eller innan en bild- eller videomodell tar över GPU:n, så att återupptagna chattar slipper läsa historiken igen. Upp till 10 GB på disk.",
diff --git a/studio/frontend/src/i18n/locales/th.ts b/studio/frontend/src/i18n/locales/th.ts
index 78c8d931b96..a9d9630ed1d 100644
--- a/studio/frontend/src/i18n/locales/th.ts
+++ b/studio/frontend/src/i18n/locales/th.ts
@@ -2008,6 +2008,7 @@ export const th = {
loadError: "โหลดการตั้งค่าการสลับโมเดลอัตโนมัติไม่สำเร็จ",
saveError: "บันทึกการตั้งค่าการสลับโมเดลอัตโนมัติไม่สำเร็จ",
idleError: "ป้อน 0 เพื่อโหลดโมเดลค้างไว้ หรืออย่างน้อย 60 วินาที",
+ idleUnsaved: "ยังไม่ได้บันทึก",
keepKv: "เก็บบริบทแชทไว้เมื่อยกเลิกการโหลด",
keepKvDescription:
"บันทึกแคช KV ก่อนยกเลิกการโหลดเมื่อไม่ได้ใช้งาน หรือก่อนที่โมเดลรูปภาพหรือวิดีโอจะใช้ GPU เพื่อให้แชทที่กลับมาทำต่อไม่ต้องอ่านประวัติซ้ำ ใช้ดิสก์ได้สูงสุด 10 GB",
diff --git a/studio/frontend/src/i18n/locales/tr.ts b/studio/frontend/src/i18n/locales/tr.ts
index 7ea86bdffaa..882eda294ab 100644
--- a/studio/frontend/src/i18n/locales/tr.ts
+++ b/studio/frontend/src/i18n/locales/tr.ts
@@ -2100,6 +2100,7 @@ export const tr = {
loadError: "Otomatik model değiştirme ayarları yüklenemedi.",
saveError: "Otomatik model değiştirme ayarları kaydedilemedi.",
idleError: "Modeli yüklü tutmak için 0 veya en az 60 saniye girin.",
+ idleUnsaved: "Henüz kaydedilmedi.",
keepKv: "Bellekten kaldırmalar arasında sohbet bağlamını koru",
keepKvDescription:
"Boşta bellekten kaldırmadan veya bir görüntü ya da video modeli GPU'yu almadan önce KV önbelleğini kaydedin; böylece devam ettirilen sohbetler geçmişi yeniden okumaz. Diskte en fazla 10 GB.",
diff --git a/studio/frontend/src/i18n/locales/uk.ts b/studio/frontend/src/i18n/locales/uk.ts
index 507931e85ee..44dde615faa 100644
--- a/studio/frontend/src/i18n/locales/uk.ts
+++ b/studio/frontend/src/i18n/locales/uk.ts
@@ -2122,6 +2122,7 @@ export const uk = {
saveError: "Не вдалося зберегти налаштування автоперемикання моделей.",
idleError:
"Введіть 0, щоб модель залишалася завантаженою, або щонайменше 60 секунд.",
+ idleUnsaved: "Ще не збережено.",
keepKv: "Зберігати контекст чату між вивантаженнями",
keepKvDescription:
"Зберігати KV-кеш перед вивантаженням через простій або перед тим, як модель зображень чи відео займе GPU, щоб відновлені чати не перечитували історію. До 10 GB на диску.",
diff --git a/studio/frontend/src/i18n/locales/vi.ts b/studio/frontend/src/i18n/locales/vi.ts
index 034559afd26..bd7ab632800 100644
--- a/studio/frontend/src/i18n/locales/vi.ts
+++ b/studio/frontend/src/i18n/locales/vi.ts
@@ -2111,6 +2111,7 @@ export const vi = {
loadError: "Không thể tải cài đặt tự động chuyển mô hình.",
saveError: "Không thể lưu cài đặt tự động chuyển mô hình.",
idleError: "Nhập 0 để giữ mô hình được nạp, hoặc ít nhất 60 giây.",
+ idleUnsaved: "Chưa được lưu.",
keepKv: "Giữ ngữ cảnh trò chuyện qua các lần gỡ",
keepKvDescription:
"Lưu KV cache trước khi gỡ do không hoạt động, hoặc trước khi một mô hình hình ảnh hay video chiếm GPU, để các cuộc trò chuyện được tiếp tục không phải đọc lại lịch sử. Tối đa 10 GB trên ổ đĩa.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index c4ce3daf614..cae81f05929 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1905,6 +1905,7 @@ export const zhCN = {
loadError: "加载模型自动切换设置失败。",
saveError: "保存模型自动切换设置失败。",
idleError: "输入 0 保持模型加载,或输入至少 60 秒。",
+ idleUnsaved: "尚未保存。",
autoDownload: "下载缺失的模型",
autoDownloadDescription:
"获取 API 请求中指定但尚未下载的 GGUF。开启后,任何持有 API 密钥的人都可以占用你的磁盘空间和带宽。",
diff --git a/studio/frontend/src/i18n/locales/zh-TW.ts b/studio/frontend/src/i18n/locales/zh-TW.ts
index d33f1a7b885..6f42130d6f5 100644
--- a/studio/frontend/src/i18n/locales/zh-TW.ts
+++ b/studio/frontend/src/i18n/locales/zh-TW.ts
@@ -1995,6 +1995,7 @@ export const zhTW = {
loadError: "無法載入模型自動切換設定。",
saveError: "無法儲存模型自動切換設定。",
idleError: "輸入 0 以保持模型載入,或輸入至少 60 秒。",
+ idleUnsaved: "尚未儲存。",
keepKv: "卸載後保留聊天上下文",
keepKvDescription:
"在閒置卸載前,或在圖片或影片模型佔用 GPU 前儲存 KV 快取,讓恢復的聊天不必重新讀取記錄。最多佔用 10 GB 磁碟空間。",
diff --git a/studio/frontend/tests/idle-seconds-enter-save.test.ts b/studio/frontend/tests/idle-seconds-enter-save.test.ts
new file mode 100644
index 00000000000..e8846f3cb0f
--- /dev/null
+++ b/studio/frontend/tests/idle-seconds-enter-save.test.ts
@@ -0,0 +1,206 @@
+// 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 type * as SectionModule from "../src/features/settings/components/model-auto-switch-section.tsx";
+import { type StubElement, loadWithStubs, stubJsxRuntime } from "./helpers/module-stubs.ts";
+
+const UNSAVED = "settings.general.modelAutoSwitch.idleUnsaved";
+const IDLE_ERROR = "settings.general.modelAutoSwitch.idleError";
+
+Object.assign(globalThis, { window: new EventTarget() });
+
+const Input = () => null;
+let slots: { value: unknown }[] = [];
+let cursor = 0;
+let mounting = false;
+let puts: Record<string, unknown>[] = [];
+let stored: Record<string, unknown> = {};
+let hold: Promise<void> | null = null;
+
+const react = {
+ useState<T>(initial: T) {
+ const slot = (slots[cursor++] ??= { value: initial });
+ return [slot.value, (next: T) => { slot.value = next; }];
+ },
+ useEffect(effect: () => void) {
+ if (mounting) effect();
+ },
+};
+
+const section = loadWithStubs<typeof SectionModule>(
+ new URL("../src/features/settings/components/model-auto-switch-section.tsx", import.meta.url),
+ {
+ react,
+ "react/jsx-runtime": stubJsxRuntime(),
+ "@/components/ui/button": { Button: () => null },
+ "@/components/ui/input": { Input },
+ "@/components/ui/switch": { Switch: () => null },
+ "@/i18n": { useT: () => (key: string) => key },
+ "../api/openai-auto-switch": {
+ loadOpenAIAutoSwitchSettings: async () => ({ ...stored }),
+ updateOpenAIAutoSwitchSettings: async (update: Record<string, unknown>) => {
+ puts.push(update);
+ await hold;
+ stored = { ...stored, ...update };
+ return { ...stored };
+ },
+ },
+ "./settings-row": { SettingsRow: () => null },
+ "./settings-section": { SettingsSection: () => null },
+ },
+);
+
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+function walk(node: unknown, found: StubElement[] = []): StubElement[] {
+ if (Array.isArray(node)) {
+ for (const child of node) walk(child, found);
+ } else if (node && typeof node === "object" && "props" in node) {
+ const element = node as StubElement;
+ found.push(element);
+ walk(element.props.children, found);
+ walk(element.props.below, found);
+ }
+ return found;
+}
+
+function mount(component: (props: Record<string, never>) => unknown) {
+ slots = [];
+ const render = () => {
+ cursor = 0;
+ return walk(component({}));
+ };
+ mounting = true;
+ render();
+ mounting = false;
+ return {
+ input() {
+ const element = render().find((node) => node.type === Input);
+ assert.ok(element);
+ return element.props as {
+ value: string;
+ onChange: (event: { target: { value: string } }) => void;
+ onKeyDown?: (event: { key: string; nativeEvent: { isComposing: boolean } }) => void;
+ };
+ },
+ shows: (text: string) => render().some((node) => node.props.children === text),
+ };
+}
+
+function type(view: ReturnType<typeof mount>, value: string) {
+ view.input().onChange({ target: { value } });
+}
+
+function press(view: ReturnType<typeof mount>, key = "Enter", isComposing = false) {
+ view.input().onKeyDown?.({ key, nativeEvent: { isComposing } });
+}
+
+async function chat(seconds: number) {
+ puts = [];
+ hold = null;
+ stored = { enabled: true, autoUnloadIdleSeconds: seconds, mediaAutoUnloadIdleSeconds: 0 };
+ const view = mount(section.ModelAutoSwitchSection);
+ await flush();
+ return view;
+}
+
+test("Enter saves the chat idle field", async () => {
+ const view = await chat(60);
+ type(view, "0");
+ press(view);
+ await flush();
+ assert.deepEqual(puts, [{ enabled: true, autoUnloadIdleSeconds: 0 }]);
+ assert.equal(view.input().value, "0");
+ assert.equal(view.shows(UNSAVED), false);
+});
+
+test("Enter on an invalid value shows the error and writes nothing", async () => {
+ const view = await chat(60);
+ type(view, "30");
+ press(view);
+ await flush();
+ assert.deepEqual(puts, []);
+ assert.equal(view.shows(IDLE_ERROR), true);
+});
+
+test("Enter that confirms an IME composition saves nothing", async () => {
+ const view = await chat(60);
+ type(view, "0");
+ press(view, "Enter", true);
+ await flush();
+ assert.deepEqual(puts, []);
+});
+
+test("other keys save nothing", async () => {
+ const view = await chat(60);
+ type(view, "0");
+ press(view, "Tab");
+ await flush();
+ assert.deepEqual(puts, []);
+});
+
+test("the row says when the typed value is not the saved one", async () => {
+ const view = await chat(60);
+ assert.equal(view.shows(UNSAVED), false);
+ type(view, "0");
+ assert.equal(view.shows(UNSAVED), true);
+ type(view, "060");
+ assert.equal(view.shows(UNSAVED), false);
+});
+
+test("the unsaved note stays away while the save is running", async () => {
+ const view = await chat(60);
+ let release = () => {};
+ hold = new Promise((resolve) => { release = resolve; });
+ type(view, "0");
+ press(view);
+ assert.equal(view.shows(UNSAVED), false);
+ release();
+ await flush();
+ assert.equal(view.shows(UNSAVED), false);
+});
+
+test("Enter while a save is running writes nothing more", async () => {
+ const view = await chat(60);
+ let release = () => {};
+ hold = new Promise((resolve) => { release = resolve; });
+ type(view, "0");
+ press(view);
+ press(view);
+ press(view);
+ release();
+ await flush();
+ assert.equal(puts.length, 1);
+});
+
+test("Enter in a field that is off writes nothing", async () => {
+ await chat(60);
+ stored.enabled = false;
+ const off = mount(section.ModelAutoSwitchSection);
+ await flush();
+ type(off, "0");
+ press(off);
+ await flush();
+ assert.deepEqual(puts, []);
+});
+
+test("Enter saves the media idle field alone", async () => {
+ puts = [];
+ hold = null;
+ stored = { enabled: true, autoUnloadIdleSeconds: 60, mediaAutoUnloadIdleSeconds: 120 };
+ const Row = section.MediaIdleUnloadRow;
+ const view = mount((props) => {
+ const element = section.MediaIdleUnloadSetting(props) as unknown as StubElement;
+ assert.equal(element.type, Row);
+ return Row(element.props as Parameters<typeof Row>[0]);
+ });
+ await flush();
+ assert.equal(view.input().value, "120");
+ type(view, "0");
+ press(view);
+ await flush();
+ assert.deepEqual(puts, [{ mediaAutoUnloadIdleSeconds: 0 }]);
+});