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: let Allow microphone recover from a saved "Don't allow" on Windows (#9006)
Michael Han6453075ccd6b
diff --git a/studio/frontend/src/features/chat/adapters/studio-web-speech-dictation-adapter.ts b/studio/frontend/src/features/chat/adapters/studio-web-speech-dictation-adapter.tsindex d03f63f559d..a8ff10e4778 100644--- a/studio/frontend/src/features/chat/adapters/studio-web-speech-dictation-adapter.ts+++ b/studio/frontend/src/features/chat/adapters/studio-web-speech-dictation-adapter.ts@@ -77,7 +77,10 @@ export const isMissingDeviceError = (error: unknown): boolean => {export const describeMediaError = (error: unknown): string => {const name = mediaErrorName(error);if (name === "NotAllowedError" || name === "SecurityError") {- return "Microphone access is blocked. Allow microphone access for this Unsloth page, then try again.";+ // The desktop WebView has no site-permission UI, so Settings is the only way back.+ return isTauri+ ? "Microphone access is blocked. Open Settings > Voice and click Allow microphone."+ : "Microphone access is blocked. Allow microphone access for this Unsloth page, then try again.";}if (name === "NotFoundError" || name === "OverconstrainedError") {return "No microphone was found for dictation.";diff --git a/studio/frontend/src/features/settings/api/microphone-permission.ts b/studio/frontend/src/features/settings/api/microphone-permission.tsnew file mode 100644index 00000000000..83120d5e42a--- /dev/null+++ b/studio/frontend/src/features/settings/api/microphone-permission.ts@@ -0,0 +1,24 @@+// 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";++/**+ * Forget a saved "Don't allow" so the next getUserMedia can prompt again.+ *+ * WebView2 keeps that answer in its profile and offers no site-settings UI, so without+ * this an accidental deny blocked dictation permanently (#9001). The command only clears+ * the stored answer; access still comes from the prompt.+ *+ * Best effort by design: a browser tab has no command to call, and an older WebView2+ * runtime has no permission API, but getUserMedia is still worth trying in both.+ */+export async function resetMicrophonePermission(): Promise<void> {+ if (!isTauri) return;+ try {+ const { invoke } = await import("@tauri-apps/api/core");+ await invoke("reset_microphone_permission");+ } catch (error) {+ console.warn("Could not reset the saved microphone permission:", error);+ }+}diff --git a/studio/frontend/src/features/settings/tabs/voice-tab.tsx b/studio/frontend/src/features/settings/tabs/voice-tab.tsxindex a555bfc33e6..497030c2bf8 100644--- a/studio/frontend/src/features/settings/tabs/voice-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/voice-tab.tsx@@ -48,6 +48,7 @@ import { Search01Icon, VolumeHighIcon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { SquareIcon } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { resetMicrophonePermission } from "../api/microphone-permission";import { DictationDictionaryView } from "../components/dictation-dictionary-view";import { RecentDictationsView } from "../components/recent-dictations-view";import { SettingsRow } from "../components/settings-row";@@ -347,6 +348,9 @@ function useAudioInputDevices() {toast.error(t("settings.voice.dictation.micAccessUnsupported"));return;}+ // Clear a saved deny first: this button is the only way back from one, and WebView2+ // would otherwise reject the request without ever prompting (#9001).+ await resetMicrophonePermission();try {const stream = await navigator.mediaDevices.getUserMedia({audio: true,@@ -356,7 +360,15 @@ function useAudioInputDevices() {}await refresh();} catch {- toast.error(t("settings.voice.dictation.micAccessBlocked"));+ // A browser keeps its own saved deny and resetMicrophonePermission cannot+ // touch it, so only the desktop build can promise another prompt.+ toast.error(+ t(+ isTauri+ ? "settings.voice.dictation.micAccessBlockedDesktop"+ : "settings.voice.dictation.micAccessBlocked",+ ),+ );}}, [refresh, t]);diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 6fbbca94366..73d7eb3345b 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -282,6 +282,8 @@ export const ar = {allowMicrophone: "السماح بالميكروفون",micAccessBlocked:"تم حظر الوصول إلى الميكروفون. اسمح بالوصول إلى الميكروفون لصفحة Unsloth هذه ثم أعد المحاولة.",+ micAccessBlockedDesktop:+ "تم حظر الوصول إلى الميكروفون. أعد المحاولة واختر السماح، أو مكّن الميكروفون من إعدادات الخصوصية في النظام.",micAccessUnsupported:"الوصول إلى الميكروفون غير مدعوم في هذا المتصفح أو السياق.",systemDefault: "الإعداد الافتراضي للنظام",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 927bc3d1d20..e1363138e01 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -291,6 +291,8 @@ export const de = {allowMicrophone: "Mikrofonzugriff erlauben",micAccessBlocked:"Der Mikrofonzugriff wurde blockiert. Erlauben Sie den Mikrofonzugriff für diese Unsloth-Seite und versuchen Sie es erneut.",+ micAccessBlockedDesktop:+ "Der Mikrofonzugriff wurde blockiert. Versuchen Sie es erneut und wählen Sie Zulassen, oder aktivieren Sie das Mikrofon in den Datenschutzeinstellungen des Systems.",micAccessUnsupported:"Der Mikrofonzugriff wird in diesem Browser oder Kontext nicht unterstützt.",systemDefault: "Systemstandard",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 0a031c29ec4..aca2b8714d4 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -283,6 +283,8 @@ export const en = {allowMicrophone: "Allow microphone",micAccessBlocked:"Microphone access was blocked. Allow microphone access for this Unsloth page, then try again.",+ micAccessBlockedDesktop:+ "Microphone access was blocked. Try again and choose Allow, or enable the microphone in your system privacy settings.",micAccessUnsupported:"Microphone access is not supported in this browser or context.",systemDefault: "System default",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex e93e57174f8..7a4cba1e32d 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -288,6 +288,8 @@ export const es = {allowMicrophone: "Permitir el acceso al micrófono",micAccessBlocked:"Se bloqueó el acceso al micrófono. Permite el acceso al micrófono para esta página de Unsloth e inténtalo de nuevo.",+ micAccessBlockedDesktop:+ "Se bloqueó el acceso al micrófono. Inténtalo de nuevo y elige Permitir, o activa el micrófono en la configuración de privacidad del sistema.",micAccessUnsupported:"El acceso al micrófono no es compatible con este navegador o contexto.",systemDefault: "Predeterminado del sistema",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex af4376f6971..ff3208f1c59 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -290,6 +290,8 @@ export const fr = {allowMicrophone: "Autoriser l’accès au microphone",micAccessBlocked:"L'accès au microphone a été bloqué. Autorisez l'accès au microphone pour cette page Unsloth, puis réessayez.",+ micAccessBlockedDesktop:+ "L'accès au microphone a été bloqué. Réessayez et choisissez Autoriser, ou activez le microphone dans les paramètres de confidentialité du système.",micAccessUnsupported:"L'accès au microphone n'est pas pris en charge dans ce navigateur ou ce contexte.",systemDefault: "Par défaut du système",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 053d017a3c6..84b2f7ae8b4 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -285,6 +285,8 @@ export const hi = {allowMicrophone: "माइक्रोफ़ोन की अनुमति दें",micAccessBlocked:"माइक्रोफ़ोन एक्सेस रोक दिया गया है। इस Unsloth पेज के लिए माइक्रोफ़ोन एक्सेस की अनुमति दें, फिर दोबारा कोशिश करें।",+ micAccessBlockedDesktop:+ "माइक्रोफ़ोन एक्सेस रोक दिया गया है। दोबारा कोशिश करें और अनुमति दें चुनें, या सिस्टम की प्राइवेसी सेटिंग में माइक्रोफ़ोन चालू करें।",micAccessUnsupported:"इस ब्राउज़र या संदर्भ में माइक्रोफ़ोन एक्सेस समर्थित नहीं है।",systemDefault: "सिस्टम डिफ़ॉल्ट",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 07857228e66..7527da45d9a 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -255,6 +255,8 @@ export const it = {allowMicrophone: "Consenti l'accesso al microfono",micAccessBlocked:"L'accesso al microfono è stato bloccato. Consenti l'accesso al microfono per questa pagina di Unsloth, poi riprova.",+ micAccessBlockedDesktop:+ "L'accesso al microfono è stato bloccato. Riprova e scegli Consenti, oppure abilita il microfono nelle impostazioni di privacy del sistema.",micAccessUnsupported:"L'accesso al microfono non è supportato in questo browser o contesto.",systemDefault: "Predefinito di sistema",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex e9af73a9416..1fbb7e86d27 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -285,6 +285,8 @@ export const ja = {allowMicrophone: "マイクへのアクセスを許可",micAccessBlocked:"マイクへのアクセスがブロックされました。この Unsloth のページでマイクへのアクセスを許可してから、もう一度お試しください。",+ micAccessBlockedDesktop:+ "マイクへのアクセスがブロックされました。もう一度お試しになり「許可」を選択するか、システムのプライバシー設定でマイクを有効にしてください。",micAccessUnsupported:"このブラウザーまたはコンテキストではマイクへのアクセスに対応していません。",systemDefault: "システムのデフォルト",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 697183e186d..9ec599111f1 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -282,6 +282,8 @@ export const ko = {allowMicrophone: "마이크 허용",micAccessBlocked:"마이크 접근이 차단되었습니다. 이 Unsloth 페이지에 마이크 접근을 허용한 뒤 다시 시도하세요.",+ micAccessBlockedDesktop:+ "마이크 접근이 차단되었습니다. 다시 시도하여 허용을 선택하거나 시스템 개인 정보 보호 설정에서 마이크를 켜세요.",micAccessUnsupported:"이 브라우저나 환경에서는 마이크 접근을 지원하지 않습니다.",systemDefault: "시스템 기본값",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 46dc1dea5ea..3646d5bc83d 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -286,6 +286,8 @@ export const ptBR = {allowMicrophone: "Permitir acesso ao microfone",micAccessBlocked:"O acesso ao microfone foi bloqueado. Permita o acesso ao microfone nesta página do Unsloth e tente novamente.",+ micAccessBlockedDesktop:+ "O acesso ao microfone foi bloqueado. Tente novamente e escolha Permitir, ou ative o microfone nas configurações de privacidade do sistema.",micAccessUnsupported:"O acesso ao microfone não é suportado neste navegador ou contexto.",systemDefault: "Padrão do sistema",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex b6c874d1bb7..ce5dff1c456 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -285,6 +285,8 @@ export const ru = {allowMicrophone: "Разрешить доступ к микрофону",micAccessBlocked:"Доступ к микрофону заблокирован. Разрешите доступ к микрофону для этой страницы Unsloth и повторите попытку.",+ micAccessBlockedDesktop:+ "Доступ к микрофону заблокирован. Повторите попытку и выберите «Разрешить» или включите микрофон в системных настройках конфиденциальности.",micAccessUnsupported:"Доступ к микрофону не поддерживается в этом браузере или контексте.",systemDefault: "По умолчанию в системе",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex 60a4eb223e6..b4a094696e8 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -279,6 +279,8 @@ export const zhCN = {allowMicrophone: "允许使用麦克风",micAccessBlocked:"麦克风访问已被阻止。请在浏览器中允许此 Unsloth 页面使用麦克风,然后重试。",+ micAccessBlockedDesktop:+ "麦克风访问已被阻止。请重试并选择允许,或在系统隐私设置中启用麦克风。",micAccessUnsupported: "此浏览器或环境不支持访问麦克风。",systemDefault: "系统默认",savedMicDisconnected: "已保存的麦克风(未连接)",diff --git a/studio/frontend/tests/helpers/tauri-core-resolver.mjs b/studio/frontend/tests/helpers/tauri-core-resolver.mjsnew file mode 100644index 00000000000..d2bd55aae7a--- /dev/null+++ b/studio/frontend/tests/helpers/tauri-core-resolver.mjs@@ -0,0 +1,47 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// bundler-resolver's two rules, plus the two this suite needs:+//+// 1. "@tauri-apps/api/core" -> a local stub, because the real package only resolves+// inside a Tauri webview.+// 2. A "?bust=N" query on the importer is copied onto every src module it pulls in.+// lib/api-base computes `isTauri` once, at module evaluation, so the only way to+// exercise both branches in one process is to evaluate the subgraph again.+import { existsSync } from "node:fs";+import { fileURLToPath, pathToFileURL } from "node:url";++const SRC = fileURLToPath(new URL("../../src/", import.meta.url));+const CORE_STUB = new URL("./tauri-core-stub.mjs", import.meta.url).href;++function firstExisting(base) {+ for (const candidate of [`${base}.ts`, `${base}/index.ts`, base]) {+ if (existsSync(candidate)) return pathToFileURL(candidate).href;+ }+ return null;+}++function bustOf(parentURL) {+ if (!parentURL) return "";+ const bust = new URL(parentURL).searchParams.get("bust");+ return bust ? `?bust=${bust}` : "";+}++export function resolve(specifier, context, next) {+ const suffix = bustOf(context.parentURL);++ 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);+ }+ if (specifier.startsWith(".") && context.parentURL?.startsWith("file:")) {+ const parent = new URL(context.parentURL);+ parent.search = "";+ const resolved = firstExisting(fileURLToPath(new URL(specifier, parent)));+ if (resolved) return next(resolved + suffix, context);+ }+ return next(specifier, context);+}diff --git a/studio/frontend/tests/helpers/tauri-core-stub.mjs b/studio/frontend/tests/helpers/tauri-core-stub.mjsnew file mode 100644index 00000000000..babfc98abef--- /dev/null+++ b/studio/frontend/tests/helpers/tauri-core-stub.mjs@@ -0,0 +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++// Stands in for @tauri-apps/api/core, which only resolves inside a Tauri webview.+// State lives on globalThis so it survives the "?bust=N" re-evaluation.+//+// mode "ok" -> invoke resolves+// mode "rejects" -> invoke rejects, as an older WebView2 runtime would++const control = (globalThis.__TAURI_CORE_STUB__ ??= { calls: [], mode: "ok" });++export async function invoke(command, args) {+ control.calls.push({ command, args });+ if (control.mode === "rejects") {+ throw new Error("command reset_microphone_permission not found");+ }+}diff --git a/studio/frontend/tests/microphone-permission-reset.test.ts b/studio/frontend/tests/microphone-permission-reset.test.tsnew file mode 100644index 00000000000..d56bf4cd38c--- /dev/null+++ b/studio/frontend/tests/microphone-permission-reset.test.ts@@ -0,0 +1,169 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Issue 9001: WebView2 saves "Don't allow" in its profile and has no site-settings UI, so+// one accidental deny blocked dictation for good. Allow microphone now clears that saved+// answer before asking, and the toast no longer sends desktop users to a padlock that does+// not exist. The reset is best effort: a browser tab has no command to call and an older+// runtime has no permission API, but getUserMedia must still be attempted in both.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { register } from "node:module";+import test from "node:test";+import { fileURLToPath } from "node:url";++register("./helpers/tauri-core-resolver.mjs", import.meta.url);++const MODULE = fileURLToPath(+ new URL("../src/features/settings/api/microphone-permission.ts", import.meta.url),+);++const VOICE_TAB = readFileSync(+ fileURLToPath(new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url)),+ "utf8",+);++const ADAPTER = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/chat/adapters/studio-web-speech-dictation-adapter.ts",+ import.meta.url,+ ),+ ),+ "utf8",+);++const MAIN_RS = readFileSync(+ fileURLToPath(new URL("../../src-tauri/src/main.rs", import.meta.url)),+ "utf8",+);++type StubControl = { calls: { command: string }[]; mode: "ok" | "rejects" };++let generation = 0;++/** Install the globals api-base reads, then import a fresh copy of the module. */+async function load(options: { tauri: boolean; mode?: "ok" | "rejects" }) {+ const control: StubControl = { calls: [], mode: options.mode ?? "ok" };+ Object.defineProperty(globalThis, "__TAURI_CORE_STUB__", {+ value: control,+ configurable: true,+ writable: true,+ });+ Object.defineProperty(globalThis, "window", {+ value: {+ location: { protocol: options.tauri ? "tauri:" : "https:" },+ ...(options.tauri ? { __TAURI_INTERNALS__: {} } : {}),+ },+ configurable: true,+ writable: true,+ });++ generation += 1;+ const module = (await import(`${MODULE}?bust=${generation}`)) as {+ resetMicrophonePermission: () => Promise<void>;+ };+ return { module, control };+}++test("the desktop app clears the saved answer before asking again", async () => {+ const { module, control } = await load({ tauri: true });++ await module.resetMicrophonePermission();++ assert.deepEqual(+ control.calls.map((call) => call.command),+ ["reset_microphone_permission"],+ "without this call WebView2 refuses the request from its stored deny and never prompts",+ );+});++test("a browser tab calls no command", async () => {+ const { module, control } = await load({ tauri: false });++ await module.resetMicrophonePermission();++ assert.deepEqual(control.calls, [], "invoke does not exist outside the desktop app");+});++test("a runtime without the permission API does not break the request", async () => {+ const { module, control } = await load({ tauri: true, mode: "rejects" });++ // Must not reject: the caller goes on to getUserMedia, which may still prompt.+ await module.resetMicrophonePermission();++ assert.equal(control.calls.length, 1);+});++test("Allow microphone resets before it requests", () => {+ const reset = VOICE_TAB.indexOf("resetMicrophonePermission()");+ const request = VOICE_TAB.indexOf("navigator.mediaDevices.getUserMedia");++ assert.ok(reset > 0, "voice-tab no longer clears the saved microphone answer");+ assert.ok(+ reset < request,+ "the reset runs after the request, so the stored deny still rejects it",+ );+});++test("the blocked message stops pointing desktop users at a padlock", () => {+ assert.ok(+ ADAPTER.includes("Open Settings > Voice and click Allow microphone"),+ "the desktop dictation error still names browser site permissions, which WebView2 has no UI for",+ );+ assert.ok(+ ADAPTER.includes("isTauri"),+ "the message must stay browser-accurate off the desktop app",+ );+});++test("the blocked toast only promises another prompt on the desktop", () => {+ // resetMicrophonePermission returns early off the desktop app, so a browser+ // tab keeps its saved deny and cannot be asked again by clicking the button.+ assert.match(+ VOICE_TAB,+ /isTauri\s*\?\s*"settings\.voice\.dictation\.micAccessBlockedDesktop"\s*:\s*"settings\.voice\.dictation\.micAccessBlocked"/,+ "the toast must pick the message for the platform it is running on",+ );+});++test("the browser message still points at the page permission", () => {+ const en = readFileSync(+ fileURLToPath(new URL("../src/i18n/locales/en.ts", import.meta.url)),+ "utf8",+ );+ const blocked = en.match(/micAccessBlocked:\s*\n?\s*"([^"]+)"/);+ assert.ok(blocked, "micAccessBlocked is missing");+ assert.match(blocked[1], /for this Unsloth page/);+});++test("every locale carries both blocked messages", () => {+ const locales = [+ "ar", "de", "en", "es", "fr", "hi",+ "it", "ja", "ko", "pt-br", "ru", "zh-CN",+ ];+ for (const locale of locales) {+ const source = readFileSync(+ fileURLToPath(new URL(`../src/i18n/locales/${locale}.ts`, import.meta.url)),+ "utf8",+ );+ // Strict parity is enforced in CI, so a key added to en only fails the build.+ assert.ok(+ source.includes("micAccessBlockedDesktop:"),+ `${locale} is missing micAccessBlockedDesktop`,+ );+ assert.ok(+ source.includes("micAccessBlocked:"),+ `${locale} is missing micAccessBlocked`,+ );+ }+});++test("the command is registered with the app", () => {+ // A command that is only defined is not callable; invoke fails at runtime instead.+ assert.ok(+ MAIN_RS.includes("webview_permissions::reset_microphone_permission"),+ "reset_microphone_permission is missing from the invoke handler",+ );+});diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rsindex 6faea846fb0..77d36a57343 100644--- a/studio/src-tauri/src/main.rs+++ b/studio/src-tauri/src/main.rs@@ -21,6 +21,7 @@ mod preflight;mod process;mod process_identity;mod update;+mod webview_permissions;mod windows_job;mod x11_threads;@@ -1868,6 +1869,7 @@ fn main() {native_intents::register_artifact_path,native_intents::reveal_path_token,native_intents::open_path_token,+ webview_permissions::reset_microphone_permission,has_saved_window_state,was_launched_hidden,mark_in_app_relaunch,diff --git a/studio/src-tauri/src/webview_permissions.rs b/studio/src-tauri/src/webview_permissions.rsnew file mode 100644index 00000000000..1e937719202--- /dev/null+++ b/studio/src-tauri/src/webview_permissions.rs@@ -0,0 +1,151 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++//! Clearing a saved microphone decision so the next request can ask again.+//!+//! WebView2 saves "Don't allow" in its profile and ships no site-settings UI, so on Windows+//! one accidental deny blocked dictation for good (#9001): the profile survives reinstalls,+//! and the request never reaches the OS, so Windows privacy settings never list the app to+//! toggle either. Resetting to DEFAULT erases the saved answer and nothing more, so the next+//! getUserMedia prompts exactly as the first one did.+//!+//! Only Windows has this trap. WKWebView defers to the system permission, which macOS+//! exposes in System Settings, and webkit2gtk asks per session, so both are no-ops here.++use std::sync::mpsc;+use std::time::Duration;++/// The reset is one profile write on the UI thread. Long enough to outlast a busy thread,+/// short enough that a stuck WebView cannot hang the settings button.+const RESET_TIMEOUT: Duration = Duration::from_secs(10);++type Reply = mpsc::Sender<Result<(), String>>;++/// Origin to key the permission on. None when the URL cannot have one, which+/// SetPermissionState rejects with E_INVALIDARG.+pub(crate) fn permission_origin(url: &tauri::Url) -> Option<String> {+ if !matches!(url.scheme(), "http" | "https") {+ return None;+ }+ url.host_str()?;+ let origin = url.origin().ascii_serialization();+ (origin != "null").then_some(origin)+}++/// Forget a saved microphone decision for this window's origin.+///+/// Never grants access: DEFAULT restores the unanswered state, so consent still comes from+/// the prompt the next request raises.+#[tauri::command]+pub async fn reset_microphone_permission(window: tauri::WebviewWindow) -> Result<(), String> {+ let url = window.url().map_err(|error| error.to_string())?;+ let origin =+ permission_origin(&url).ok_or_else(|| format!("no origin to reset in window URL {url}"))?;++ // with_webview hops to the UI thread and the platform call answers later still, so both+ // report back through this channel.+ let (tx, rx) = mpsc::channel();+ let failed = tx.clone();+ window+ .with_webview(move |webview| {+ if let Err(error) = clear_saved_answer(&webview, &origin, tx) {+ let _ = failed.send(Err(error));+ }+ })+ .map_err(|error| error.to_string())?;++ tokio::task::spawn_blocking(move || rx.recv_timeout(RESET_TIMEOUT))+ .await+ .map_err(|error| error.to_string())?+ .map_err(|_| "the WebView did not answer the microphone permission reset".to_string())?+}++#[cfg(windows)]+fn clear_saved_answer(+ webview: &tauri::webview::PlatformWebview,+ origin: &str,+ tx: Reply,+) -> Result<(), String> {+ use webview2_com::Microsoft::Web::WebView2::Win32::{+ ICoreWebView2Profile4, ICoreWebView2_13, COREWEBVIEW2_PERMISSION_KIND_MICROPHONE,+ COREWEBVIEW2_PERMISSION_STATE_DEFAULT,+ };+ use webview2_com::SetPermissionStateCompletedHandler;+ use windows_core::{Interface, HSTRING};++ unsafe {+ let core = webview+ .controller()+ .CoreWebView2()+ .map_err(|error| error.to_string())?;+ // Profile4 carries the permission APIs. A runtime without it also has no way to+ // undo the deny, so say so rather than fail silently.+ let profile = core+ .cast::<ICoreWebView2_13>()+ .and_then(|core| core.Profile())+ .and_then(|profile| profile.cast::<ICoreWebView2Profile4>())+ .map_err(|error| format!("this WebView2 runtime cannot reset permissions: {error}"))?;++ let handler = SetPermissionStateCompletedHandler::create(Box::new(move |result| {+ let _ = tx.send(result.map_err(|error| error.to_string()));+ Ok(())+ }));+ // Bound, not inlined: SetPermissionState reads the string during the call.+ let origin = HSTRING::from(origin);+ profile+ .SetPermissionState(+ COREWEBVIEW2_PERMISSION_KIND_MICROPHONE,+ &origin,+ COREWEBVIEW2_PERMISSION_STATE_DEFAULT,+ &handler,+ )+ .map_err(|error| error.to_string())+ }+}++#[cfg(not(windows))]+fn clear_saved_answer(+ _webview: &tauri::webview::PlatformWebview,+ _origin: &str,+ tx: Reply,+) -> Result<(), String> {+ // Nothing to forget: neither WKWebView nor webkit2gtk keeps a saved answer of its own.+ let _ = tx.send(Ok(()));+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::permission_origin;++ fn origin_of(url: &str) -> Option<String> {+ permission_origin(&tauri::Url::parse(url).expect("test URL"))+ }++ #[test]+ fn the_packaged_and_dev_pages_both_yield_an_origin() {+ // What the window actually loads: tauri.localhost when bundled, the vite port in+ // dev. The path is dropped, which is what SetPermissionState keys on.+ assert_eq!(+ origin_of("http://tauri.localhost/index.html"),+ Some("http://tauri.localhost".to_string())+ );+ assert_eq!(+ origin_of("https://tauri.localhost/"),+ Some("https://tauri.localhost".to_string())+ );+ assert_eq!(+ origin_of("http://localhost:5173/settings"),+ Some("http://localhost:5173".to_string())+ );+ }++ #[test]+ fn a_url_without_a_usable_origin_is_refused_rather_than_sent() {+ // SetPermissionState rejects these with E_INVALIDARG, so catching them here keeps+ // the failure readable instead of surfacing a bare HRESULT.+ assert_eq!(origin_of("file:///C:/index.html"), None);+ assert_eq!(origin_of("data:text/html,hi"), None);+ assert_eq!(origin_of("about:blank"), None);+ }+}