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: optional notification when a chat reply finishes in the background (#13554)

Daniel Han1e7d78415b93
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index 74916d4c2ab..fc80cc219c3 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -61,6 +61,7 @@ export {
} from "./chat-settings-sheet";
export { useChatRuntimeStore } from "./stores/chat-runtime-store";
export { openFolderAsProject, useOpeningFolder } from "./utils/open-folder-as-project";
+export { requestReplyFinishedPermission } from "./utils/reply-finished-notification";
export {
hydrateModelDisclaimerPreference,
refreshModelDisclaimerPreference,
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 6c15b527a36..d40b2369108 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -185,6 +185,10 @@ import { createGenerationToolRecovery } from "./utils/generation-tool-recovery";
import { providerCompactionConnectionKey } from "./utils/provider-compaction";
import { mergeContextTruncation } from "./utils/context-truncation";
import { registerLiveThreadView } from "./utils/live-thread-head";
+import {
+ cancelReplyFinishedNotification,
+ notifyReplyFinished,
+} from "./utils/reply-finished-notification";
import {
extractDeltaText,
parseAssistantContent,
@@ -2375,6 +2379,7 @@ function createPersistedRunAdapter(
return {
...adapter,
async *run(options) {
+ cancelReplyFinishedNotification();
const trackedRunStartThreadIds = runStartThreadIdsForMessages(
options.messages,
);
@@ -2436,9 +2441,12 @@ function createPersistedRunAdapter(
}
if (typeof result === "object" && Symbol.asyncIterator in result) {
yield* result;
- return;
+ } else {
+ yield await result;
+ }
+ if (!options.abortSignal?.aborted) {
+ notifyReplyFinished();
}
- yield await result;
},
};
}
diff --git a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
index 0c642a9a8b2..b676aff35c9 100644
--- a/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-preferences-store.ts
@@ -27,7 +27,8 @@ import {
// until its thinking block is opened, and has no effect while toolVisibility is "expanded".
// pastedTextMinChars: paste length that becomes a .txt attachment; 0 is off.
// showInlineEditResponse: on keeps Edit response in each response's action bar instead of its
-// More menu.
+// More menu. notifyWhenReplyFinishes: on sends a system notification when a reply ends while the
+// window is hidden or unfocused.
export interface ChatPreferencesState {
plainTextComposer: boolean;
setPlainTextComposer: (value: boolean) => void;
@@ -59,6 +60,8 @@ export interface ChatPreferencesState {
setAutoScrollWhileGenerating: (value: boolean) => void;
showScrollToBottomButton: boolean;
setShowScrollToBottomButton: (value: boolean) => void;
+ notifyWhenReplyFinishes: boolean;
+ setNotifyWhenReplyFinishes: (value: boolean) => void;
}
// A stale stored value would leave the dropdown blank and unfixable.
@@ -112,6 +115,10 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
showScrollToBottomButton: true,
setShowScrollToBottomButton: (showScrollToBottomButton) =>
set({ showScrollToBottomButton }),
+ // Off by default: it asks for notification permission, so it stays opt in.
+ notifyWhenReplyFinishes: false,
+ setNotifyWhenReplyFinishes: (notifyWhenReplyFinishes) =>
+ set({ notifyWhenReplyFinishes }),
}),
{
name: "unsloth_chat_preferences",
@@ -149,6 +156,7 @@ export const useChatPreferencesStore = create<ChatPreferencesState>()(
),
autoScrollWhileGenerating: saved?.autoScrollWhileGenerating ?? true,
showScrollToBottomButton: saved?.showScrollToBottomButton ?? true,
+ notifyWhenReplyFinishes: saved?.notifyWhenReplyFinishes === true,
};
},
},
diff --git a/studio/frontend/src/features/chat/utils/reply-finished-notification.ts b/studio/frontend/src/features/chat/utils/reply-finished-notification.ts
new file mode 100644
index 00000000000..2af921456eb
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/reply-finished-notification.ts
@@ -0,0 +1,113 @@
+// 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 { isTauri } from "@/lib/api-base";
+import {
+ notifyNative,
+ primeNativeNotificationPermission,
+} from "@/lib/native-notifications";
+import { useChatPreferencesStore } from "../stores/chat-preferences-store.ts";
+
+const TITLE = "Reply finished";
+const BODY = "Your reply in Unsloth is ready.";
+
+// A reply cut at Max Tokens resumes as a new run (auto-continue), and a queued prompt starts the
+// next one; any run starting cancels this wait, so one notification fires once replies settle.
+export const REPLY_SETTLE_MS = 3_000;
+
+let sequence = 0;
+let pending: ReturnType<typeof setTimeout> | null = null;
+
+function browserNotificationApi(): typeof Notification | null {
+ if (typeof window === "undefined" || !("Notification" in window)) {
+ return null;
+ }
+ return window.Notification;
+}
+
+function windowIsInBackground(): boolean {
+ if (typeof document === "undefined") {
+ return false;
+ }
+ return (
+ document.visibilityState !== "visible" ||
+ (typeof document.hasFocus === "function" && !document.hasFocus())
+ );
+}
+
+export function cancelReplyFinishedNotification(): void {
+ if (pending !== null) {
+ clearTimeout(pending);
+ pending = null;
+ }
+}
+
+export function notifyReplyFinished(): void {
+ if (!useChatPreferencesStore.getState().notifyWhenReplyFinishes) {
+ return;
+ }
+ cancelReplyFinishedNotification();
+ // A reply that finished in view was seen, even if the user looks away before the timer.
+ if (!windowIsInBackground()) {
+ return;
+ }
+ pending = setTimeout(() => {
+ pending = null;
+ sendReplyFinished();
+ }, REPLY_SETTLE_MS);
+}
+
+function sendReplyFinished(): void {
+ if (
+ !useChatPreferencesStore.getState().notifyWhenReplyFinishes ||
+ !windowIsInBackground()
+ ) {
+ return;
+ }
+ sequence += 1;
+ if (isTauri) {
+ notifyNative({
+ key: `reply-finished:${sequence}`,
+ title: TITLE,
+ body: BODY,
+ requestPermission: false,
+ }).catch(() => undefined);
+ return;
+ }
+ const api = browserNotificationApi();
+ if (api?.permission !== "granted") {
+ return;
+ }
+ try {
+ // No tag: a same-tag replacement alerts only with renotify, so a later reply would be silent.
+ const notification = new api(TITLE, { body: BODY });
+ notification.onclick = () => {
+ window.focus();
+ notification.close();
+ };
+ } catch {
+ // Some browsers only allow notifications from a service worker.
+ }
+}
+
+// Called from the settings switch (a user gesture, so the prompt can show); false reverts it.
+export async function requestReplyFinishedPermission(): Promise<boolean> {
+ if (isTauri) {
+ return primeNativeNotificationPermission();
+ }
+ const api = browserNotificationApi();
+ if (!api) {
+ return false;
+ }
+ if (api.permission === "granted") {
+ return true;
+ }
+ if (api.permission === "denied") {
+ return false;
+ }
+ try {
+ return (await api.requestPermission()) === "granted";
+ } catch {
+ return false;
+ }
+}
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 5403b05cf59..2c4e4d6da4a 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -130,6 +130,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
"settings.chat.toolResultLimit",
"settings.chat.autoScroll",
"settings.chat.scrollToBottomButton",
+ "settings.chat.replyNotification",
"settings.profile.greetingSloth",
"settings.chat.thinking.visibility",
"settings.chat.tools.visibility",
@@ -437,6 +438,7 @@ export const SETTINGS_SEARCH_KEYWORDS: Partial<
"settings.chat.tools.foldIntoThinking": "settings.chat.visibilityKeywords",
"settings.chat.autoScroll": "settings.chat.autoScrollKeywords",
"settings.chat.scrollToBottomButton": "settings.chat.scrollToBottomButtonKeywords",
+ "settings.chat.replyNotification": "settings.chat.replyNotificationKeywords",
// match protocol and agent names omitted from the title.
"settings.apiKeys.mcp.title": "settings.apiKeys.mcp.keywords",
// the intro names only some agents; every listed one has to find this page.
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index c6dddc4062e..f41afb3fded 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -16,6 +16,7 @@ import {
type PlusMenuItemId,
normaliseDisplayVisibility,
refreshModelDisclaimerPreference,
+ requestReplyFinishedPermission,
saveModelDisclaimerPreference,
useChatPreferencesStore,
useChatRuntimeStore,
@@ -329,6 +330,12 @@ export function ChatTab() {
const setShowScrollToBottomButton = useChatPreferencesStore(
(state) => state.setShowScrollToBottomButton,
);
+ const notifyWhenReplyFinishes = useChatPreferencesStore(
+ (state) => state.notifyWhenReplyFinishes,
+ );
+ const setNotifyWhenReplyFinishes = useChatPreferencesStore(
+ (state) => state.setNotifyWhenReplyFinishes,
+ );
const thinkingVisibility = useChatPreferencesStore(
(state) => state.thinkingVisibility,
);
@@ -534,6 +541,24 @@ export function ChatTab() {
onCheckedChange={setShowScrollToBottomButton}
/>
</SettingsRow>
+ <SettingsRow
+ label={t("settings.chat.replyNotification")}
+ description={t("settings.chat.replyNotificationDescription")}
+ >
+ <Switch
+ aria-label={t("settings.chat.replyNotification")}
+ checked={notifyWhenReplyFinishes}
+ onCheckedChange={(checked) => {
+ setNotifyWhenReplyFinishes(checked);
+ if (!checked) return;
+ void requestReplyFinishedPermission().then((granted) => {
+ if (granted) return;
+ setNotifyWhenReplyFinishes(false);
+ toast.error(t("settings.chat.replyNotificationBlocked"));
+ });
+ }}
+ />
+ </SettingsRow>
</SettingsSection>
<SettingsSection title={t("settings.chat.groups.conversations.title")}>
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 20453db34ab..5dcdc8b65b4 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -2595,6 +2595,13 @@ export const ar = {
"إظهار زر للعودة إلى أحدث رسالة بعد التمرير لأعلى.",
scrollToBottomButtonKeywords:
"تمرير أسفل أحدث سهم زر إخفاء scroll bottom button",
+ replyNotification: "الإشعار عند انتهاء الرد",
+ replyNotificationDescription:
+ "إظهار إشعار من النظام عند انتهاء الرد بينما يكون Unsloth مصغرًا أو في الخلفية.",
+ replyNotificationBlocked:
+ "الإشعارات محظورة. اسمح بها لـ Unsloth في إعدادات المتصفح أو النظام، ثم حاول مرة أخرى.",
+ replyNotificationKeywords:
+ "إشعار تنبيه انتهى اكتمل جاهز رد خلفية مصغر notify notification alert done finished reply background",
showResponseModel: "إظهار نموذج الاستجابة",
showResponseModelDescription:
"إظهار البيانات الوصفية للنموذج في ردود المساعد.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 009ef8a64a1..08b1aaa7bfa 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -2634,6 +2634,13 @@ export const de = {
"Eine Schaltfläche anzeigen, um nach dem Hochscrollen zur neuesten Nachricht zurückzuspringen.",
scrollToBottomButtonKeywords:
"scrollen unten springen neueste Pfeil Schaltfläche ausblenden scroll bottom button",
+ replyNotification: "Benachrichtigen, wenn eine Antwort fertig ist",
+ replyNotificationDescription:
+ "Zeigt eine Systembenachrichtigung, wenn eine Antwort fertig ist, während Unsloth minimiert oder im Hintergrund ist.",
+ replyNotificationBlocked:
+ "Benachrichtigungen sind blockiert. Erlaube sie für Unsloth in den Browser- oder Systemeinstellungen und versuche es erneut.",
+ replyNotificationKeywords:
+ "Benachrichtigung benachrichtigen Hinweis fertig abgeschlossen bereit Antwort Hintergrund minimiert notify notification alert done finished reply background",
showResponseModel: "Antwortmodell anzeigen",
showResponseModelDescription:
"Modellmetadaten in Antworten des Assistenten anzeigen.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 4052a8d91d2..52326170585 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -2635,6 +2635,13 @@ export const en = {
"Show a button to jump back to the latest message after you scroll up.",
scrollToBottomButtonKeywords:
"scroll bottom jump latest newest arrow down button floating hide show",
+ replyNotification: "Notify when a reply finishes",
+ replyNotificationDescription:
+ "Show a system notification when a reply finishes while Unsloth is minimized or in the background.",
+ replyNotificationBlocked:
+ "Notifications are blocked. Allow them for Unsloth in your browser or system settings, then try again.",
+ replyNotificationKeywords:
+ "notify notification alert done finished complete ready response reply background minimized desktop sound",
showResponseModel: "Response model",
showResponseModelDescription:
"Show model details in assistant responses.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index ed69380c147..f488fd5a51e 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -2625,6 +2625,13 @@ export const es = {
"Muestra un botón para volver al último mensaje después de desplazarte hacia arriba.",
scrollToBottomButtonKeywords:
"desplazar final abajo saltar último flecha botón ocultar scroll bottom button",
+ replyNotification: "Avisar cuando termine una respuesta",
+ replyNotificationDescription:
+ "Muestra una notificación del sistema cuando termina una respuesta mientras Unsloth está minimizado o en segundo plano.",
+ replyNotificationBlocked:
+ "Las notificaciones están bloqueadas. Permítelas para Unsloth en la configuración del navegador o del sistema y vuelve a intentarlo.",
+ replyNotificationKeywords:
+ "notificación avisar alerta terminado completado listo respuesta segundo plano minimizado notify notification alert done finished reply background",
showResponseModel: "Mostrar el modelo de respuesta",
showResponseModelDescription:
"Muestra los metadatos del modelo en las respuestas del asistente.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index d5c2512bedd..b095e82bd50 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -2631,6 +2631,13 @@ export const fr = {
"Afficher un bouton pour revenir au dernier message après avoir fait défiler vers le haut.",
scrollToBottomButtonKeywords:
"défiler bas sauter dernier flèche bouton masquer scroll bottom button",
+ replyNotification: "Notifier quand une réponse est terminée",
+ replyNotificationDescription:
+ "Affiche une notification système quand une réponse se termine alors qu'Unsloth est réduit ou en arrière-plan.",
+ replyNotificationBlocked:
+ "Les notifications sont bloquées. Autorisez-les pour Unsloth dans les réglages du navigateur ou du système, puis réessayez.",
+ replyNotificationKeywords:
+ "notification notifier alerte terminé fini prêt réponse arrière-plan réduit notify notification alert done finished reply background",
showResponseModel: "Afficher le modèle de réponse",
showResponseModelDescription:
"Afficher les métadonnées du modèle dans les réponses de l’assistant.",
diff --git a/studio/frontend/src/i18n/locales/he.ts b/studio/frontend/src/i18n/locales/he.ts
index 21809cd8483..bd1218157c1 100644
--- a/studio/frontend/src/i18n/locales/he.ts
+++ b/studio/frontend/src/i18n/locales/he.ts
@@ -2699,6 +2699,13 @@ export const he = {
"הצג לחצן לקפיצה חזרה להודעה האחרונה לאחר גלילה למעלה.",
scrollToBottomButtonKeywords:
"scroll bottom jump latest newest arrow down button floating hide show גלילה תחתית לחצן חץ",
+ replyNotification: "התראה כשתשובה מסתיימת",
+ replyNotificationDescription:
+ "הצגת התראת מערכת כשתשובה מסתיימת בזמן ש-Unsloth ממוזער או ברקע.",
+ replyNotificationBlocked:
+ "ההתראות חסומות. יש לאפשר אותן ל-Unsloth בהגדרות הדפדפן או המערכת ולנסות שוב.",
+ replyNotificationKeywords:
+ "notify notification alert done finished reply background minimized התראה הודעה הסתיים מוכן תשובה רקע ממוזער",
showResponseModel: "מודל המענה",
showResponseModelDescription: "הצג פרטי מודל בתשובות העוזר.",
inlineEditResponse: "עריכת תגובה על גבי התגובות",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index 54a3b26a528..9eeb1d9dc31 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -2602,6 +2602,13 @@ export const hi = {
"ऊपर स्क्रॉल करने के बाद नवीनतम संदेश पर वापस जाने के लिए बटन दिखाएँ।",
scrollToBottomButtonKeywords:
"स्क्रॉल नीचे नवीनतम तीर बटन छिपाएँ scroll bottom button",
+ replyNotification: "जवाब पूरा होने पर सूचना दें",
+ replyNotificationDescription:
+ "जब Unsloth छोटा किया हुआ हो या बैकग्राउंड में हो, तब जवाब पूरा होने पर सिस्टम सूचना दिखाएँ।",
+ replyNotificationBlocked:
+ "सूचनाएँ ब्लॉक हैं। ब्राउज़र या सिस्टम सेटिंग्स में Unsloth के लिए इन्हें अनुमति दें, फिर दोबारा कोशिश करें।",
+ replyNotificationKeywords:
+ "सूचना अलर्ट पूरा तैयार जवाब बैकग्राउंड notify notification alert done finished reply background",
showResponseModel: "जवाब देने वाला मॉडल दिखाएँ",
showResponseModelDescription:
"असिस्टेंट के जवाबों में मॉडल का मेटाडेटा दिखाएँ।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 23690a18f68..b2a48d7773b 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -2542,6 +2542,13 @@ export const it = {
"Mostra un pulsante per tornare all'ultimo messaggio dopo aver scorso verso l'alto.",
scrollToBottomButtonKeywords:
"scorrere fondo saltare ultimo freccia pulsante nascondere scroll bottom button",
+ replyNotification: "Avvisa quando una risposta è finita",
+ replyNotificationDescription:
+ "Mostra una notifica di sistema quando una risposta finisce mentre Unsloth è ridotto a icona o in background.",
+ replyNotificationBlocked:
+ "Le notifiche sono bloccate. Consentile per Unsloth nelle impostazioni del browser o del sistema, poi riprova.",
+ replyNotificationKeywords:
+ "notifica avvisare avviso finito completato pronto risposta background ridotto notify notification alert done finished reply background",
showResponseModel: "Mostra il modello della risposta",
showResponseModelDescription:
"Mostra i metadati del modello nelle risposte dell'assistente.",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index a6e86ac81de..3e835bfdc2e 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -2579,6 +2579,13 @@ export const ja = {
"上にスクロールしたときに、最新のメッセージへ戻るボタンを表示します。",
scrollToBottomButtonKeywords:
"スクロール 一番下 最新 矢印 ボタン 非表示 scroll bottom button",
+ replyNotification: "応答完了時に通知",
+ replyNotificationDescription:
+ "Unsloth が最小化またはバックグラウンドにあるときに応答が完了すると、システム通知を表示します。",
+ replyNotificationBlocked:
+ "通知がブロックされています。ブラウザーまたはシステムの設定で Unsloth の通知を許可してから、もう一度お試しください。",
+ replyNotificationKeywords:
+ "通知 アラート 完了 終了 準備完了 応答 バックグラウンド 最小化 notify notification alert done finished reply background",
showResponseModel: "応答モデルを表示",
showResponseModelDescription:
"アシスタントの応答にモデルのメタデータを表示します。",
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 17cacc8b314..c851b96bed9 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -2588,6 +2588,13 @@ export const ko = {
"위로 스크롤한 뒤 최신 메시지로 돌아가는 버튼을 표시합니다.",
scrollToBottomButtonKeywords:
"스크롤 맨 아래 최신 화살표 버튼 숨기기 scroll bottom button",
+ replyNotification: "응답이 끝나면 알림",
+ replyNotificationDescription:
+ "Unsloth가 최소화되었거나 백그라운드에 있을 때 응답이 끝나면 시스템 알림을 표시합니다.",
+ replyNotificationBlocked:
+ "알림이 차단되어 있습니다. 브라우저 또는 시스템 설정에서 Unsloth의 알림을 허용한 후 다시 시도하세요.",
+ replyNotificationKeywords:
+ "알림 통지 완료 끝 준비 응답 백그라운드 최소화 notify notification alert done finished reply background",
showResponseModel: "응답 모델 표시",
showResponseModelDescription:
"어시스턴트 응답에 모델 메타데이터를 표시합니다.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index 65cf737a373..0ff9748fb53 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -2612,6 +2612,13 @@ export const ptBR = {
"Mostra um botão para voltar à mensagem mais recente depois de rolar para cima.",
scrollToBottomButtonKeywords:
"rolar final baixo pular recente seta botão ocultar scroll bottom button",
+ replyNotification: "Avisar quando uma resposta terminar",
+ replyNotificationDescription:
+ "Mostra uma notificação do sistema quando uma resposta termina enquanto o Unsloth está minimizado ou em segundo plano.",
+ replyNotificationBlocked:
+ "As notificações estão bloqueadas. Permita-as para o Unsloth nas configurações do navegador ou do sistema e tente novamente.",
+ replyNotificationKeywords:
+ "notificação avisar alerta terminou concluído pronto resposta segundo plano minimizado notify notification alert done finished reply background",
showResponseModel: "Mostrar o modelo da resposta",
showResponseModelDescription:
"Mostra os metadados do modelo nas respostas do assistente.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index f626ad958a2..da74aa307a0 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -2608,6 +2608,13 @@ export const ru = {
"Показывать кнопку для возврата к последнему сообщению после прокрутки вверх.",
scrollToBottomButtonKeywords:
"прокрутка вниз последнее стрелка кнопка скрыть scroll bottom button",
+ replyNotification: "Уведомлять о готовом ответе",
+ replyNotificationDescription:
+ "Показывать системное уведомление, когда ответ готов, а Unsloth свернут или в фоне.",
+ replyNotificationBlocked:
+ "Уведомления заблокированы. Разрешите их для Unsloth в настройках браузера или системы и попробуйте снова.",
+ replyNotificationKeywords:
+ "уведомление оповещение готово завершено ответ фон свернут notify notification alert done finished reply background",
showResponseModel: "Показывать модель в ответах",
showResponseModelDescription:
"Показывать метаданные модели в ответах ассистента.",
diff --git a/studio/frontend/src/i18n/locales/sv.ts b/studio/frontend/src/i18n/locales/sv.ts
index d1dbe97b016..94a971bca6f 100644
--- a/studio/frontend/src/i18n/locales/sv.ts
+++ b/studio/frontend/src/i18n/locales/sv.ts
@@ -2780,6 +2780,13 @@ export const sv = {
"Visa en knapp för att hoppa tillbaka till senaste meddelandet efter att du har rullat uppåt.",
scrollToBottomButtonKeywords:
"rulla botten hoppa senaste nyaste pil ner knapp flytande dölj visa scroll bottom jump latest newest arrow down button floating hide show",
+ replyNotification: "Avisera när ett svar är klart",
+ replyNotificationDescription:
+ "Visa en systemavisering när ett svar blir klart medan Unsloth är minimerat eller i bakgrunden.",
+ replyNotificationBlocked:
+ "Aviseringar är blockerade. Tillåt dem för Unsloth i webbläsarens eller systemets inställningar och försök igen.",
+ replyNotificationKeywords:
+ "avisering notis meddelande klar färdig svar bakgrund minimerad notify notification alert done finished reply background",
showResponseModel: "Svarsmodell",
showResponseModelDescription:
"Visa modellinformation i assistentens svar.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index ba95827df3b..08e9d887949 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -2556,6 +2556,13 @@ export const zhCN = {
"向上滚动后显示一个按钮,用于跳回最新消息。",
scrollToBottomButtonKeywords:
"滚动 底部 跳转 最新 箭头 按钮 隐藏 scroll bottom button",
+ replyNotification: "回复完成时通知",
+ replyNotificationDescription:
+ "当 Unsloth 最小化或在后台时,回复完成后显示系统通知。",
+ replyNotificationBlocked:
+ "通知已被阻止。请在浏览器或系统设置中允许 Unsloth 发送通知,然后重试。",
+ replyNotificationKeywords:
+ "通知 提醒 完成 结束 就绪 回复 后台 最小化 notify notification alert done finished reply background",
showResponseModel: "显示回复模型",
showResponseModelDescription: "在助手回复中显示模型元数据。",
inlineEditResponse: "在回复上显示编辑回复",
diff --git a/studio/frontend/src/lib/native-notifications.ts b/studio/frontend/src/lib/native-notifications.ts
index 9cbe5ddd9e0..bfe6e11aed7 100644
--- a/studio/frontend/src/lib/native-notifications.ts
+++ b/studio/frontend/src/lib/native-notifications.ts
@@ -61,6 +61,17 @@ function rememberSentKey(key: string): void {
}
}
+// The plugin's webview shim reports "denied" on Windows although the desktop backend grants
+// (tauri-apps/plugins-workspace#3512), so the backend answers before a shim "denied" is trusted.
+async function backendGrantsPermission(): Promise<boolean> {
+ try {
+ const { invoke } = await import("@tauri-apps/api/core");
+ return (await invoke("plugin:notification|is_permission_granted")) === true;
+ } catch {
+ return false;
+ }
+}
+
async function checkNativePermission(allowRequest: boolean): Promise<boolean> {
const notification = getBrowserNotificationApi();
if (notification?.permission === "granted") {
@@ -68,6 +79,11 @@ async function checkNativePermission(allowRequest: boolean): Promise<boolean> {
return true;
}
+ if (await backendGrantsPermission()) {
+ permissionState = "granted";
+ return true;
+ }
+
if (notification?.permission === "denied") {
permissionState = "denied";
return false;
@@ -119,9 +135,12 @@ async function ensurePermission(allowRequest: boolean): Promise<boolean> {
return checkNativePermission(allowRequest);
}
-export async function primeNativeNotificationPermission(): Promise<void> {
- if (!isTauri || permissionState !== "unknown") {
- return;
+export async function primeNativeNotificationPermission(): Promise<boolean> {
+ if (!isTauri) {
+ return false;
+ }
+ if (permissionState !== "unknown") {
+ return hasGrantedPermission();
}
if (!permissionPrimeInFlight) {
@@ -133,6 +152,7 @@ export async function primeNativeNotificationPermission(): Promise<void> {
}
await permissionPrimeInFlight;
+ return hasGrantedPermission();
}
export async function notifyNative(
diff --git a/studio/frontend/tests/helpers/notification-resolver.mjs b/studio/frontend/tests/helpers/notification-resolver.mjs
index 428da18ef77..2c7742bc5b6 100644
--- a/studio/frontend/tests/helpers/notification-resolver.mjs
+++ b/studio/frontend/tests/helpers/notification-resolver.mjs
@@ -3,8 +3,8 @@
// clipboard-resolver.mjs's two rules, for the notification plugin:
//
-// 1. "@tauri-apps/plugin-notification" -> a local stub; the real package only
-// resolves inside a Tauri webview.
+// 1. "@tauri-apps/plugin-notification" and "@tauri-apps/api/core" -> local stubs;
+// the real packages only resolve inside a Tauri webview.
// 2. A "?bust=N" query on the importer is copied onto every src module it pulls
// in. api-base computes `isTauri` once at module evaluation, and
// native-notifications caches the grant and its sent-key set in module scope,
@@ -15,6 +15,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
const SRC = fileURLToPath(new URL("../../src/", import.meta.url));
const NOTIFICATION_STUB = new URL("./tauri-notification-stub.mjs", import.meta.url)
.href;
+const CORE_STUB = new URL("./tauri-notification-core-stub.mjs", import.meta.url).href;
function firstExisting(base) {
for (const candidate of [`${base}.ts`, `${base}/index.ts`, base]) {
@@ -35,6 +36,9 @@ export function resolve(specifier, context, next) {
if (specifier === "@tauri-apps/plugin-notification") {
return next(NOTIFICATION_STUB + suffix, context);
}
+ if (specifier === "@tauri-apps/api/core") {
+ return next(CORE_STUB + suffix, context);
+ }
if (specifier.startsWith("@/")) {
const resolved = firstExisting(SRC + specifier.slice(2));
return next(resolved ? resolved + suffix : specifier, context);
diff --git a/studio/frontend/tests/helpers/tauri-notification-core-stub.mjs b/studio/frontend/tests/helpers/tauri-notification-core-stub.mjs
new file mode 100644
index 00000000000..0b632a4bb59
--- /dev/null
+++ b/studio/frontend/tests/helpers/tauri-notification-core-stub.mjs
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Stands in for @tauri-apps/api/core beside tauri-notification-stub.mjs, sharing its
+// control object. `backend` is what the plugin's desktop backend answers to
+// is_permission_granted; left unset, invoke throws, as it does outside a Tauri webview.
+const control = (globalThis.__TAURI_NOTIFICATION_STUB__ ??= {
+ sent: [],
+ granted: false,
+ mode: "ok",
+ requests: 0,
+});
+
+export async function invoke(command) {
+ if (command === "plugin:notification|is_permission_granted" && control.backend !== undefined) {
+ return control.backend;
+ }
+ throw new Error(`invoke ${command}: no Tauri backend`);
+}
diff --git a/studio/frontend/tests/model-load-native-notifications.test.ts b/studio/frontend/tests/model-load-native-notifications.test.ts
index d344d7fc8c7..bd3c9df42f8 100644
--- a/studio/frontend/tests/model-load-native-notifications.test.ts
+++ b/studio/frontend/tests/model-load-native-notifications.test.ts
@@ -50,6 +50,8 @@ type EnvOptions = {
/** What Notification.requestPermission() resolves to once the user answers. */
answer?: "granted" | "denied";
stub?: StubMode;
+ /** What the plugin's desktop backend answers to is_permission_granted; unset = no backend. */
+ backend?: boolean;
};
type Control = {
@@ -57,6 +59,7 @@ type Control = {
granted: boolean;
mode: StubMode;
requests: number;
+ backend?: boolean;
};
let generation = 0;
@@ -81,6 +84,7 @@ async function load(options: EnvOptions) {
pluginGranted = false,
answer = "granted",
stub = "ok",
+ backend,
} = options;
const webviewRequests = { count: 0 };
@@ -111,6 +115,7 @@ async function load(options: EnvOptions) {
control.granted = pluginGranted;
control.mode = stub;
control.requests = 0;
+ control.backend = backend;
const mod = (await import(`${MODULE}?bust=${generation}`)) as {
notifyNative: (options: {
@@ -275,22 +280,23 @@ test("a denied grant sends nothing and does not reject", async () => {
// these are the shim's states, not hypothetical browser ones: Linux and macOS
// report "granted" with no prompt (desktop request_permission is hardcoded to
// Granted), Windows reports "denied" because the shim short-circuits its own
-// bootstrap (tauri-apps/plugins-workspace#3512). Either way, moving the prime
-// off the chat path must not change what training does.
+// bootstrap (tauri-apps/plugins-workspace#3512) while the backend still grants,
+// so the backend's answer wins. Moving the prime off the chat path must not
+// change what training does.
test("each desktop platform's shim state behaves the same with and without a chat prime", async () => {
const platforms = [
{ name: "linux/macOS", webview: "granted" as const, expected: ["Training finished"] },
- { name: "windows", webview: "denied" as const, expected: [] },
+ { name: "windows", webview: "denied" as const, expected: ["Training finished"] },
];
for (const platform of platforms) {
// A chat-side prime first, as the app behaved before the split.
- const primedByChat = await load({ tauri: true, webview: platform.webview });
+ const primedByChat = await load({ tauri: true, webview: platform.webview, backend: true });
await primedByChat.primeNativeNotificationPermission();
await trainingFinished(primedByChat);
// Training on its own, as it behaves now.
- const trainingOnly = await load({ tauri: true, webview: platform.webview });
+ const trainingOnly = await load({ tauri: true, webview: platform.webview, backend: true });
await trainingOnly.primeNativeNotificationPermission();
await trainingFinished(trainingOnly);
diff --git a/studio/frontend/tests/persisted-run-steering.test.ts b/studio/frontend/tests/persisted-run-steering.test.ts
index fac7ff7666f..a0c63f91e80 100644
--- a/studio/frontend/tests/persisted-run-steering.test.ts
+++ b/studio/frontend/tests/persisted-run-steering.test.ts
@@ -34,6 +34,8 @@ function pendingRun(hasReservation = true) {
let cancelled = false;
let released = 0;
let calls = 0;
+ let notified = 0;
+ let cancels = 0;
let resolve!: (id: string) => void;
let reject!: (error: Error) => void;
const preflight = new Promise<string>((yes, no) => {
@@ -56,6 +58,12 @@ function pendingRun(hasReservation = true) {
requestPromptQueueStop: (ids: string[]) => stops.push(ids),
notifyPromptQueueRunFailed: (id: string) => failures.push(id),
adoptPreStreamRunReservation: () => {},
+ notifyReplyFinished: () => {
+ notified += 1;
+ },
+ cancelReplyFinishedNotification: () => {
+ cancels += 1;
+ },
};
const factory = new Function(
...Object.keys(deps),
@@ -84,6 +92,8 @@ function pendingRun(hasReservation = true) {
},
released: () => released,
calls: () => calls,
+ notified: () => notified,
+ cancels: () => cancels,
};
}
@@ -144,6 +154,26 @@ test("successful history persistence starts the adapter once", async () => {
assert.deepEqual(await next, { value: { content: "answer" }, done: false });
assert.equal((await w.run.next()).done, true);
assert.equal(w.calls(), 1);
+ assert.equal(w.cancels(), 1, "a starting run cancels a pending reply notification");
+ assert.equal(w.notified(), 1);
assert.deepEqual(w.stops, []);
assert.deepEqual(w.failures, []);
});
+
+test("a reply the user stopped mid-stream sends no reply notification", async () => {
+ const w = pendingRun();
+ const next = w.run.next();
+ w.resolve("chat");
+ assert.deepEqual(await next, { value: { content: "answer" }, done: false });
+ w.controller.abort();
+ assert.equal((await w.run.next()).done, true);
+ assert.equal(w.notified(), 0);
+});
+
+test("a failed history write sends no reply notification", async () => {
+ const w = pendingRun();
+ const next = w.run.next();
+ w.reject(new Error("history write failed"));
+ await assert.rejects(next, /history write failed/);
+ assert.equal(w.notified(), 0);
+});
diff --git a/studio/frontend/tests/reply-finished-notification.test.ts b/studio/frontend/tests/reply-finished-notification.test.ts
new file mode 100644
index 00000000000..3a5b801dd07
--- /dev/null
+++ b/studio/frontend/tests/reply-finished-notification.test.ts
@@ -0,0 +1,379 @@
+// 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 reply notification is opt in and only fires while the window is in the background.
+// runtime-provider.tsx and chat-tab.tsx are .tsx, which node's type stripping cannot import,
+// so their wiring is pinned from source.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test, { mock } from "node:test";
+
+import { readSrc } from "./helpers/kit.ts";
+
+// Same "?bust=N" resolver as model-load-native-notifications.test.ts: api-base reads `isTauri`
+// at evaluation, so each case re-evaluates the module graph under its own globals.
+register("./helpers/notification-resolver.mjs", import.meta.url);
+
+const MODULE = new URL(
+ "../src/features/chat/utils/reply-finished-notification.ts",
+ import.meta.url,
+).href;
+const STORE = new URL(
+ "../src/features/chat/stores/chat-preferences-store.ts",
+ import.meta.url,
+).href;
+
+type Env = {
+ tauri: boolean;
+ enabled: boolean;
+ hidden?: boolean;
+ focused?: boolean;
+ permission?: "absent" | "default" | "granted" | "denied";
+ answer?: "granted" | "denied";
+ pluginGranted?: boolean;
+ backend?: boolean;
+};
+
+type Control = {
+ sent: { title: string; body?: string }[];
+ granted: boolean;
+ mode: string;
+ requests: number;
+ backend?: boolean;
+};
+
+let generation = 0;
+
+function memoryStorage(): Storage {
+ const items = new Map<string, string>();
+ return {
+ get length() {
+ return items.size;
+ },
+ clear: () => items.clear(),
+ getItem: (key) => items.get(key) ?? null,
+ key: (index) => [...items.keys()][index] ?? null,
+ removeItem: (key) => void items.delete(key),
+ setItem: (key, value) => void items.set(key, String(value)),
+ };
+}
+
+function define(name: string, value: unknown) {
+ Object.defineProperty(globalThis, name, {
+ value,
+ configurable: true,
+ writable: true,
+ });
+}
+
+async function load(env: Env) {
+ const {
+ tauri,
+ enabled,
+ hidden = true,
+ focused = !hidden,
+ permission = "absent",
+ answer = "granted",
+ pluginGranted = false,
+ backend,
+ } = env;
+ const created: { title: string; options?: NotificationOptions }[] = [];
+ const storage = memoryStorage();
+ define("localStorage", storage);
+ const windowStub: Record<string, unknown> = {
+ location: { protocol: tauri ? "tauri:" : "http:" },
+ localStorage: storage,
+ focus() {},
+ };
+ if (tauri) {
+ windowStub.__TAURI_INTERNALS__ = {};
+ }
+ if (permission !== "absent") {
+ const api = function (title: string, options?: NotificationOptions) {
+ created.push({ title, options });
+ return { close() {}, onclick: null };
+ } as unknown as {
+ permission: string;
+ requestPermission: () => Promise<string>;
+ };
+ api.permission = permission;
+ api.requestPermission = async () => {
+ api.permission = answer;
+ return answer;
+ };
+ windowStub.Notification = api;
+ }
+ define("window", windowStub);
+ define("document", {
+ visibilityState: hidden ? "hidden" : "visible",
+ hasFocus: () => focused,
+ });
+
+ const control = ((globalThis as Record<string, unknown>)
+ .__TAURI_NOTIFICATION_STUB__ ??= {}) as Control;
+ control.sent = [];
+ control.granted = pluginGranted;
+ control.mode = "ok";
+ control.requests = 0;
+ control.backend = backend;
+
+ generation += 1;
+ const store = await import(`${STORE}?bust=${generation}`);
+ store.useChatPreferencesStore.setState({ notifyWhenReplyFinishes: enabled });
+ const mod = (await import(`${MODULE}?bust=${generation}`)) as {
+ notifyReplyFinished: () => void;
+ cancelReplyFinishedNotification: () => void;
+ requestReplyFinishedPermission: () => Promise<boolean>;
+ REPLY_SETTLE_MS: number;
+ };
+ return { mod, control, created };
+}
+
+mock.timers.enable({ apis: ["setTimeout"] });
+
+// Past the settle window, then until `expected` sends land: notifyNative resolves its plugin
+// through dynamic imports, which take a variable number of turns. A case expecting none still
+// waits out a short window, so a send that should not happen has time to show up.
+async function settle(sent: () => number = () => 0, expected = 0) {
+ mock.timers.tick(3_000);
+ const deadline = Date.now() + (expected === 0 ? 1_000 : 10_000);
+ while (sent() < Math.max(expected, 1) && Date.now() < deadline) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+}
+
+test("off by default, including installs that never saw the setting", async () => {
+ const { useChatPreferencesStore } = await import(
+ `${STORE}?bust=default`
+ );
+ assert.equal(
+ useChatPreferencesStore.getInitialState().notifyWhenReplyFinishes,
+ false,
+ );
+ assert.match(
+ readSrc("features/chat/stores/chat-preferences-store.ts"),
+ /notifyWhenReplyFinishes: saved\?\.notifyWhenReplyFinishes === true/,
+ );
+});
+
+test("a finished reply notifies nothing while the setting is off", async () => {
+ for (const tauri of [true, false]) {
+ const { mod, control, created } = await load({
+ tauri,
+ enabled: false,
+ permission: "granted",
+ pluginGranted: true,
+ });
+ mod.notifyReplyFinished();
+ await settle(() => control.sent.length, 0);
+ assert.equal(control.sent.length, 0);
+ assert.equal(created.length, 0);
+ }
+});
+
+test("Desktop sends one native notification per reply finished in the background", async () => {
+ const { mod, control } = await load({
+ tauri: true,
+ enabled: true,
+ pluginGranted: true,
+ });
+ mod.notifyReplyFinished();
+ await settle(() => control.sent.length, 1);
+ mod.notifyReplyFinished();
+ await settle(() => control.sent.length, 2);
+ assert.equal(control.sent.length, 2, "one per settled reply");
+ assert.equal(control.sent[0].title, "Reply finished");
+ assert.equal(control.requests, 0, "a finished reply never prompts");
+});
+
+test("nothing fires until the settle window passes", async () => {
+ const { mod, control } = await load({
+ tauri: true,
+ enabled: true,
+ pluginGranted: true,
+ });
+ assert.equal(mod.REPLY_SETTLE_MS, 3_000);
+ mod.notifyReplyFinished();
+ mock.timers.tick(2_999);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(control.sent.length, 0);
+ await settle(() => control.sent.length, 1);
+ assert.equal(control.sent.length, 1);
+});
+
+test("a run starting inside the window, like auto-continue after Max Tokens, cancels it", async () => {
+ const { mod, control } = await load({
+ tauri: true,
+ enabled: true,
+ pluginGranted: true,
+ });
+ mod.notifyReplyFinished();
+ mock.timers.tick(1_000);
+ mod.cancelReplyFinishedNotification();
+ await settle(() => control.sent.length, 0);
+ assert.equal(control.sent.length, 0, "the cut reply never notifies");
+ mod.notifyReplyFinished();
+ await settle(() => control.sent.length, 1);
+ assert.equal(control.sent.length, 1, "the continuation that settles does");
+});
+
+test("replies finishing together send one notification", async () => {
+ const { mod, control } = await load({
+ tauri: true,
+ enabled: true,
+ pluginGranted: true,
+ });
+ mod.notifyReplyFinished();
+ mock.timers.tick(500);
+ mod.notifyReplyFinished();
+ await settle(() => control.sent.length, 1);
+ assert.equal(control.sent.length, 1);
+});
+
+test("Windows Desktop: the switch turns on and notifies although the plugin shim says denied", async () => {
+ // tauri-apps/plugins-workspace#3512: the shim stamps "denied" at startup on Windows while
+ // the desktop backend grants.
+ const { mod, control } = await load({
+ tauri: true,
+ enabled: true,
+ permission: "denied",
+ backend: true,
+ });
+ assert.equal(await mod.requestReplyFinishedPermission(), true);
+ mod.notifyReplyFinished();
+ await settle(() => control.sent.length, 1);
+ assert.equal(control.sent.length, 1);
+});
+
+test("a reply that finished in view never notifies, even if the user looks away before the timer", async () => {
+ const env = await load({
+ tauri: true,
+ enabled: true,
+ hidden: false,
+ focused: true,
+ pluginGranted: true,
+ });
+ env.mod.notifyReplyFinished();
+ Object.defineProperty(globalThis, "document", {
+ value: { visibilityState: "hidden", hasFocus: () => false },
+ configurable: true,
+ writable: true,
+ });
+ await settle(() => env.control.sent.length, 0);
+ assert.equal(env.control.sent.length, 0);
+});
+
+test("an unfocused but visible window still counts as the background", async () => {
+ const { mod, control } = await load({
+ tauri: true,
+ enabled: true,
+ hidden: false,
+ focused: false,
+ pluginGranted: true,
+ });
+ mod.notifyReplyFinished();
+ await settle(() => control.sent.length, 1);
+ assert.equal(control.sent.length, 1);
+});
+
+test("nothing fires while the user is looking at the window", async () => {
+ for (const tauri of [true, false]) {
+ const { mod, control, created } = await load({
+ tauri,
+ enabled: true,
+ hidden: false,
+ focused: true,
+ permission: "granted",
+ pluginGranted: true,
+ });
+ mod.notifyReplyFinished();
+ await settle(() => control.sent.length, 0);
+ assert.equal(control.sent.length, 0);
+ assert.equal(created.length, 0);
+ }
+});
+
+test("the browser notifies only with permission already granted", async () => {
+ const granted = await load({
+ tauri: false,
+ enabled: true,
+ permission: "granted",
+ });
+ granted.mod.notifyReplyFinished();
+ await settle(() => granted.created.length, 1);
+ assert.equal(granted.created.length, 1);
+ assert.equal(granted.created[0].title, "Reply finished");
+ assert.equal(
+ granted.created[0].options?.tag,
+ undefined,
+ "a tagged replacement would arrive silently while the earlier one is showing",
+ );
+
+ for (const permission of ["default", "denied", "absent"] as const) {
+ const env = await load({ tauri: false, enabled: true, permission });
+ env.mod.notifyReplyFinished();
+ await settle(() => env.created.length, 0);
+ assert.equal(env.created.length, 0, permission);
+ }
+});
+
+test("turning the switch on asks for permission and reports the answer", async () => {
+ const asked = await load({
+ tauri: false,
+ enabled: true,
+ permission: "default",
+ answer: "granted",
+ });
+ assert.equal(await asked.mod.requestReplyFinishedPermission(), true);
+
+ const refused = await load({
+ tauri: false,
+ enabled: true,
+ permission: "default",
+ answer: "denied",
+ });
+ assert.equal(await refused.mod.requestReplyFinishedPermission(), false);
+
+ for (const permission of ["denied", "absent"] as const) {
+ const env = await load({ tauri: false, enabled: true, permission });
+ assert.equal(await env.mod.requestReplyFinishedPermission(), false);
+ }
+
+ const desktop = await load({
+ tauri: true,
+ enabled: true,
+ pluginGranted: true,
+ });
+ assert.equal(await desktop.mod.requestReplyFinishedPermission(), true);
+});
+
+test("the run adapter cancels on start and notifies once after the stream ends, never on a stop", () => {
+ const source = readSrc("features/chat/runtime-provider.tsx");
+ const start = source.indexOf("function createPersistedRunAdapter(");
+ assert.notEqual(start, -1, "createPersistedRunAdapter is gone");
+ const body = source.slice(start, source.indexOf("\nfunction ", start + 1));
+ assert.match(
+ body,
+ /yield\* result;\n\s*\} else \{\n\s*yield await result;\n\s*\}\n\s*if \(!options\.abortSignal\?\.aborted\) \{\n\s*notifyReplyFinished\(\);/,
+ );
+ assert.equal(body.match(/notifyReplyFinished\(\)/g)?.length, 1);
+ assert.match(body, /async \*run\(options\) \{\n\s*cancelReplyFinishedNotification\(\);/);
+});
+
+test("the setting is a searchable switch in Chat settings that reverts when refused", async () => {
+ const tab = readSrc("features/settings/tabs/chat-tab.tsx");
+ const at = tab.indexOf('label={t("settings.chat.replyNotification")}');
+ assert.notEqual(at, -1);
+ const row = tab.slice(at, tab.indexOf("</SettingsRow>", at));
+ assert.match(row, /checked=\{notifyWhenReplyFinishes\}/);
+ assert.match(row, /requestReplyFinishedPermission\(\)/);
+ assert.match(row, /setNotifyWhenReplyFinishes\(false\)/);
+ const { SETTINGS_SEARCH_INDEX } = await import(
+ new URL("../src/features/settings/settings-search.ts", import.meta.url)
+ .href
+ );
+ assert.ok(
+ SETTINGS_SEARCH_INDEX.chat.includes("settings.chat.replyNotification"),
+ );
+});