Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(desktop): voice input on/off switch in Settings, off by default (MUL-9274) (#10607)
Jiayuan Zhang79d32e639420
diff --git a/packages/core/voice/store.ts b/packages/core/voice/store.tsindex 2513e1bedf..760f5c8984 100644--- a/packages/core/voice/store.ts+++ b/packages/core/voice/store.ts@@ -24,6 +24,8 @@ export const MAX_VOCABULARY_WORDS = 40;export const MAX_VOCABULARY_WORD_LENGTH = 40;export interface VoiceSettings {+ /** Show the mic in composers and listen for the voice shortcut. Off until the user turns it on. */+ enabled: boolean;activation: VoiceActivation;language: VoiceLanguage;/** Input device id; null follows the system default. */@@ -38,6 +40,7 @@ export interface VoiceSettings {}export const DEFAULT_VOICE_SETTINGS: VoiceSettings = {+ enabled: false,activation: "auto",language: "auto",deviceId: null,@@ -60,6 +63,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {/** Keep what is valid from storage and fall back to defaults for the rest. */export function sanitizeVoiceSettings(value: unknown): VoiceSettings {const raw = isRecord(value) ? value : {};+ const enabled = typeof raw.enabled === "boolean" ? raw.enabled : DEFAULT_VOICE_SETTINGS.enabled;const activation = ["auto", "toggle", "hold"].includes(raw.activation as string)? (raw.activation as VoiceActivation): DEFAULT_VOICE_SETTINGS.activation;@@ -76,7 +80,7 @@ export function sanitizeVoiceSettings(value: unknown): VoiceSettings {const keepHistory = (VOICE_HISTORY_RETENTIONS as readonly string[]).includes(raw.keepHistory as string)? (raw.keepHistory as VoiceHistoryRetention): DEFAULT_VOICE_SETTINGS.keepHistory;- return { activation, language, deviceId, removeFillers, vocabulary, modelId, keepHistory };+ return { enabled, activation, language, deviceId, removeFillers, vocabulary, modelId, keepHistory };}function normalizeVocabulary(words: readonly string[]): string[] {@@ -115,6 +119,7 @@ export const useVoiceSettingsStore = create<VoiceSettingsState>()(function pickSettings(state: VoiceSettings): VoiceSettings {return {+ enabled: state.enabled,activation: state.activation,language: state.language,deviceId: state.deviceId,diff --git a/packages/core/voice/voice.test.ts b/packages/core/voice/voice.test.tsindex ea86731930..3a6173049e 100644--- a/packages/core/voice/voice.test.ts+++ b/packages/core/voice/voice.test.ts@@ -66,13 +66,25 @@ describe("sanitizeVoiceSettings", () => {it("falls back to defaults for junk", () => {expect(sanitizeVoiceSettings(null)).toEqual(DEFAULT_VOICE_SETTINGS);expect(- sanitizeVoiceSettings({ activation: "shout", language: "xx", deviceId: 3, removeFillers: "yes" }),+ sanitizeVoiceSettings({+ enabled: "on",+ activation: "shout",+ language: "xx",+ deviceId: 3,+ removeFillers: "yes",+ }),).toEqual(DEFAULT_VOICE_SETTINGS);});+ it("is off until the user turns it on", () => {+ expect(DEFAULT_VOICE_SETTINGS.enabled).toBe(false);+ expect(sanitizeVoiceSettings({ activation: "hold" }).enabled).toBe(false);+ });+it("keeps valid values and dedupes the vocabulary", () => {const words = Array.from({ length: MAX_VOCABULARY_WORDS + 5 }, (_, i) => `w${i}`);const settings = sanitizeVoiceSettings({+ enabled: true,activation: "hold",language: "zh",deviceId: "mic-1",@@ -80,6 +92,7 @@ describe("sanitizeVoiceSettings", () => {vocabulary: ["Multica", "multica", " ", 7, ...words],modelId: "sensevoice-small",});+ expect(settings.enabled).toBe(true);expect(settings.activation).toBe("hold");expect(settings.language).toBe("zh");expect(settings.deviceId).toBe("mic-1");diff --git a/packages/views/issues/components/annotation-composer.test.tsx b/packages/views/issues/components/annotation-composer.test.tsxindex a7b656d7a4..26703ab7e6 100644--- a/packages/views/issues/components/annotation-composer.test.tsx+++ b/packages/views/issues/components/annotation-composer.test.tsx@@ -3,11 +3,13 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import {+ DEFAULT_VOICE_SETTINGS,cancelVoice,connectVoiceRuntime,getVoiceState,stopVoice,useVoiceModelsStore,+ useVoiceSettingsStore,} from "@multica/core/voice";import type { ReplyAnnotation } from "@multica/core/drafts/reply-annotation";import { renderWithI18n } from "../../test/i18n";@@ -46,10 +48,12 @@ beforeEach(() => {models: [{ id: "m", name: "M", author: "A", licenseUrl: "https://example.com", languages: ["zh"],languageHint: true, sizeBytes: 1, status: "ready", receivedBytes: 1 }],}));+ act(() => useVoiceSettingsStore.getState().update({ enabled: true }));});afterEach(() => {act(() => cancelVoice());+ act(() => useVoiceSettingsStore.getState().update(DEFAULT_VOICE_SETTINGS));cleanup();});diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 92c207d86f..3ddf6d193a 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1893,6 +1893,10 @@"model_title": "Speech model","model_hint": "Models run on this computer. Download one, or switch between the ones you have.","engine_unavailable": "On-device transcription isn't available for this computer.",+ "enabled": {+ "title": "Voice input",+ "hint": "Show the mic in chat, comments and replies, and turn on the voice shortcut."+ },"input_title": "Input","shortcut": {"title": "Shortcut",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex bac8590c10..264e549776 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -1893,6 +1893,10 @@"model_title": "Modelo de voz","model_hint": "Los modelos se ejecutan en este ordenador. Descarga uno o cambia entre los que tienes.","engine_unavailable": "La transcripción en el dispositivo no está disponible en este ordenador.",+ "enabled": {+ "title": "Entrada de voz",+ "hint": "Muestra el micrófono en el chat, los comentarios y las respuestas, y activa el atajo de voz."+ },"input_title": "Entrada","shortcut": {"title": "Atajo",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 11ad64b1eb..254e799369 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -1893,6 +1893,10 @@"model_title": "Modèle vocal","model_hint": "Les modèles s’exécutent sur cet ordinateur. Téléchargez-en un, ou passez de l’un à l’autre.","engine_unavailable": "La transcription sur l’appareil n’est pas disponible sur cet ordinateur.",+ "enabled": {+ "title": "Saisie vocale",+ "hint": "Affiche le micro dans le chat, les commentaires et les réponses, et active le raccourci vocal."+ },"input_title": "Saisie","shortcut": {"title": "Raccourci",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 60a00d62b7..bd2e1206fd 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1872,6 +1872,10 @@"model_title": "音声モデル","model_hint": "モデルはこのコンピューター上で動作します。ダウンロードするか、ダウンロード済みのモデルを切り替えます。","engine_unavailable": "このコンピューターではオンデバイスの文字起こしを利用できません。",+ "enabled": {+ "title": "音声入力",+ "hint": "チャット、コメント、返信にマイクボタンを表示し、音声入力のショートカットを有効にします。"+ },"input_title": "入力","shortcut": {"title": "ショートカット",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex e2efdea354..92494c85ff 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -1872,6 +1872,10 @@"model_title": "음성 모델","model_hint": "모델은 이 컴퓨터에서 실행됩니다. 하나를 다운로드하거나 받은 모델 사이에서 전환하세요.","engine_unavailable": "이 컴퓨터에서는 기기 내 받아쓰기를 사용할 수 없습니다.",+ "enabled": {+ "title": "음성 입력",+ "hint": "채팅, 댓글, 답글에 마이크 버튼을 표시하고 음성 입력 단축키를 켭니다."+ },"input_title": "입력","shortcut": {"title": "단축키",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 9944a731dc..f17d80db04 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -1934,6 +1934,10 @@"model_title": "Речевая модель","model_hint": "Модели работают на этом компьютере. Скачайте модель или переключайтесь между скачанными.","engine_unavailable": "Расшифровка на устройстве недоступна на этом компьютере.",+ "enabled": {+ "title": "Голосовой ввод",+ "hint": "Показывать микрофон в чате, комментариях и ответах и включить голосовую комбинацию клавиш."+ },"input_title": "Ввод","shortcut": {"title": "Сочетание клавиш",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 7870d7b962..5767127b97 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1872,6 +1872,10 @@"model_title": "语音模型","model_hint": "模型在这台电脑上运行。下载一个,或在已下载的模型之间切换。","engine_unavailable": "这台电脑暂不支持本地语音转写。",+ "enabled": {+ "title": "语音输入",+ "hint": "在对话、评论和回复中显示麦克风按钮,并启用语音快捷键。"+ },"input_title": "输入","shortcut": {"title": "快捷键",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex cd428ea706..0ee7c06fdf 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -1872,6 +1872,10 @@"model_title": "語音模型","model_hint": "模型在這台電腦上執行。下載一個,或在已下載的模型之間切換。","engine_unavailable": "這台電腦暫不支援本機語音轉寫。",+ "enabled": {+ "title": "語音輸入",+ "hint": "在對話、留言和回覆中顯示麥克風按鈕,並啟用語音快捷鍵。"+ },"input_title": "輸入","shortcut": {"title": "快捷鍵",diff --git a/packages/views/settings/components/use-settings-search-index.ts b/packages/views/settings/components/use-settings-search-index.tsindex 17d4b85d90..aca96105cb 100644--- a/packages/views/settings/components/use-settings-search-index.ts+++ b/packages/views/settings/components/use-settings-search-index.ts@@ -218,6 +218,12 @@ export function useSettingsSearchIndex(title: t(($) => $.page.tabs.voice_input),description: t(($) => $.voice_input.description),},+ {+ tab: "voice-input",+ anchor: "voice-enabled",+ title: t(($) => $.voice_input.enabled.title),+ description: t(($) => $.voice_input.enabled.hint),+ },{tab: "voice-input",anchor: "voice-model",diff --git a/packages/views/settings/components/voice-input-tab.test.tsx b/packages/views/settings/components/voice-input-tab.test.tsxnew file mode 100644index 0000000000..e2dfd29986--- /dev/null+++ b/packages/views/settings/components/voice-input-tab.test.tsx@@ -0,0 +1,57 @@+import type { ReactNode } from "react";+import { screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { DEFAULT_VOICE_SETTINGS, useVoiceModelsStore, useVoiceSettingsStore } from "@multica/core/voice";+import { renderWithI18n } from "../../test/i18n";+import { VoiceInputTab } from "./voice-input-tab";++vi.mock("../../navigation", () => ({+ AppLink: ({ href, children, ...props }: { href: string; children?: ReactNode }) => (+ <a href={href} {...props}>+ {children}+ </a>+ ),+ useOptionalNavigation: () => null,+}));+vi.mock("../../voice/engine", async () => {+ const { useVoiceModelsStore } = await import("@multica/core/voice");+ return { useVoiceModels: () => useVoiceModelsStore((s) => s.models) };+});++beforeEach(() => {+ useVoiceSettingsStore.getState().update(DEFAULT_VOICE_SETTINGS);+ useVoiceModelsStore.getState().setModels({ engineAvailable: true, models: [] });+ (window as unknown as { desktopAPI: unknown }).desktopAPI = {+ voice: {+ listModels: vi.fn(),+ onModelsChanged: vi.fn(),+ transcribe: vi.fn(),+ history: {+ list: vi.fn(async () => []),+ onChanged: vi.fn(() => () => {}),+ setRetention: vi.fn(async () => {}),+ },+ },+ };+});++afterEach(() => {+ delete (window as unknown as { desktopAPI?: unknown }).desktopAPI;+});++describe("VoiceInputTab", () => {+ it("starts off with only the switch and history, and turning it on shows the rest", async () => {+ renderWithI18n(<VoiceInputTab />);+ const toggle = screen.getByRole("switch", { name: "Voice input" });+ expect(toggle).not.toBeChecked();+ expect(screen.queryByText("Speech model")).not.toBeInTheDocument();+ expect(screen.queryByText("Microphone")).not.toBeInTheDocument();+ expect(screen.getByText("History")).toBeInTheDocument();++ await userEvent.click(toggle);+ expect(useVoiceSettingsStore.getState().enabled).toBe(true);+ expect(screen.getByRole("switch", { name: "Voice input" })).toBeChecked();+ expect(screen.getByText("Speech model")).toBeInTheDocument();+ });+});diff --git a/packages/views/settings/components/voice-input-tab.tsx b/packages/views/settings/components/voice-input-tab.tsxindex 962265bfd3..3322542ce9 100644--- a/packages/views/settings/components/voice-input-tab.tsx+++ b/packages/views/settings/components/voice-input-tab.tsx@@ -42,56 +42,87 @@ import {export function VoiceInputTab() {const { t } = useT("settings");const engineAvailable = useVoiceModels()?.engineAvailable;+ const enabled = useVoiceSettingsStore((state) => state.enabled);return (<SettingsTabtitle={t(($) => $.page.tabs.voice_input)}description={t(($) => $.voice_input.description)}scope="device">- <SettingsSection- title={t(($) => $.voice_input.model_title)}- description={- engineAvailable === false- ? t(($) => $.voice_input.engine_unavailable)- : t(($) => $.voice_input.model_hint)- }- anchor="voice-model"- >- {engineAvailable && (- <SettingsCard>- <VoiceModelRows manage />- </SettingsCard>- )}- </SettingsSection>- <SettingsSection title={t(($) => $.voice_input.input_title)} anchor="voice-input">+ <SettingsSection><SettingsCard>- <ShortcutRow />- <ActivationRow />- </SettingsCard>- </SettingsSection>- <SettingsSection- title={t(($) => $.voice_input.recognition_title)}- anchor="voice-recognition"- >- <SettingsCard>- <LanguageRow />- <FillersRow />- <VocabularyRow />- </SettingsCard>- </SettingsSection>- <SettingsSection- title={t(($) => $.voice_input.microphone_title)}- anchor="voice-microphone"- >- <SettingsCard>- <MicrophoneRows />+ <EnabledRow /></SettingsCard></SettingsSection>+ {enabled && (+ <>+ <SettingsSection+ title={t(($) => $.voice_input.model_title)}+ description={+ engineAvailable === false+ ? t(($) => $.voice_input.engine_unavailable)+ : t(($) => $.voice_input.model_hint)+ }+ anchor="voice-model"+ >+ {engineAvailable && (+ <SettingsCard>+ <VoiceModelRows manage />+ </SettingsCard>+ )}+ </SettingsSection>+ <SettingsSection title={t(($) => $.voice_input.input_title)} anchor="voice-input">+ <SettingsCard>+ <ShortcutRow />+ <ActivationRow />+ </SettingsCard>+ </SettingsSection>+ <SettingsSection+ title={t(($) => $.voice_input.recognition_title)}+ anchor="voice-recognition"+ >+ <SettingsCard>+ <LanguageRow />+ <FillersRow />+ <VocabularyRow />+ </SettingsCard>+ </SettingsSection>+ <SettingsSection+ title={t(($) => $.voice_input.microphone_title)}+ anchor="voice-microphone"+ >+ <SettingsCard>+ <MicrophoneRows />+ </SettingsCard>+ </SettingsSection>+ </>+ )}+ {/* Recordings already on this computer stay reachable while voice input is off. */}<VoiceHistorySection /></SettingsTab>);}+function EnabledRow() {+ const { t } = useT("settings");+ const enabled = useVoiceSettingsStore((state) => state.enabled);+ const update = useVoiceSettingsStore((state) => state.update);+ const label = t(($) => $.voice_input.enabled.title);+ return (+ <SettingsRow+ anchor="voice-enabled"+ label={label}+ description={t(($) => $.voice_input.enabled.hint)}+ >+ <Switch+ checked={enabled}+ onCheckedChange={(checked) => update({ enabled: checked })}+ aria-label={label}+ />+ </SettingsRow>+ );+}+function ShortcutRow() {const { t } = useT("settings");const shortcut = useShortcut("voiceInput");diff --git a/packages/views/voice/use-composer-voice.test.tsx b/packages/views/voice/use-composer-voice.test.tsxindex 42e70cfa46..834896f72c 100644--- a/packages/views/voice/use-composer-voice.test.tsx+++ b/packages/views/voice/use-composer-voice.test.tsx@@ -1,6 +1,7 @@import { act, cleanup, render, renderHook, waitFor } from "@testing-library/react";import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import {+ DEFAULT_VOICE_SETTINGS,cancelVoice,connectVoiceRuntime,getVoiceState,@@ -8,6 +9,7 @@ import {releaseVoice,stopVoice,useVoiceModelsStore,+ useVoiceSettingsStore,type VoiceModels,} from "@multica/core/voice";import { createShortcutChord, useShortcutStore } from "@multica/core/shortcuts";@@ -58,12 +60,14 @@ beforeEach(() => {engine.started = 0;engine.transcribe.mockReset();act(() => useVoiceModelsStore.getState().setModels(INSTALLED));+ act(() => useVoiceSettingsStore.getState().update({ enabled: true }));useShortcutStore.getState().setShortcut("voiceInput", createShortcutChord("Space", { alt: true }));});afterEach(() => {useShortcutStore.getState().resetShortcut("voiceInput");act(() => cancelVoice());+ act(() => useVoiceSettingsStore.getState().update(DEFAULT_VOICE_SETTINGS));cleanup();});@@ -119,6 +123,25 @@ describe("useComposerVoice", () => {await waitFor(() => expect(insert).toHaveBeenCalledWith("still here"));});+ it("hides the mic and ignores the shortcut until voice input is turned on, and turning it off cancels a recording", async () => {+ act(() => useVoiceSettingsStore.getState().update({ enabled: false }));+ const hook = renderHook((options: ComposerVoiceOptions) => useComposerVoice(options), {+ initialProps: { insert: () => true },+ });+ expect(hook.result.current.available).toBe(false);+ await act(async () => shortcut());+ expect(getVoiceState().phase).toBe("idle");+ expect(engine.started).toBe(0);++ act(() => useVoiceSettingsStore.getState().update({ enabled: true }));+ expect(hook.result.current.available).toBe(true);+ await act(async () => shortcut());+ expect(getVoiceState().phase).toBe("recording");++ act(() => useVoiceSettingsStore.getState().update({ enabled: false }));+ expect(getVoiceState().phase).toBe("idle");+ });+it("does not listen while hidden, and hiding cancels a recording", async () => {const hook = renderHook((options: ComposerVoiceOptions) => useComposerVoice(options), {initialProps: { insert: () => true, hidden: true },diff --git a/packages/views/voice/use-composer-voice.ts b/packages/views/voice/use-composer-voice.tsindex 3bcec13acd..e303533468 100644--- a/packages/views/voice/use-composer-voice.ts+++ b/packages/views/voice/use-composer-voice.ts@@ -1,5 +1,11 @@import { useCallback, useEffect, useId, useRef, useSyncExternalStore } from "react";-import { noteVoiceFocus, registerVoiceTarget, useVoiceState, type VoiceState } from "@multica/core/voice";+import {+ noteVoiceFocus,+ registerVoiceTarget,+ useVoiceSettingsStore,+ useVoiceState,+ type VoiceState,+} from "@multica/core/voice";import { useVoiceModels } from "./engine";import { voiceInputSupported } from "./recorder";@@ -23,7 +29,7 @@ export interface ComposerVoiceOptions {export interface ComposerVoice {id: string;- /** Show the mic: this app has a speech engine and can record. */+ /** Show the mic: voice input is on, and this app has a speech engine and can record. */available: boolean;/** The session, when this composer owns it. */session: VoiceState | null;@@ -61,9 +67,10 @@ export function useComposerVoice({disabled = false,}: ComposerVoiceOptions): ComposerVoice {const id = useId();+ const enabled = useVoiceSettingsStore((s) => s.enabled);const engineAvailable = useVoiceModels()?.engineAvailable ?? false;const supported = useSyncExternalStore(noSubscribe, voiceInputSupported, () => false);- const available = engineAvailable && supported && !disabled;+ const available = enabled && engineAvailable && supported && !disabled;const listening = available && !hidden;const callbacks = useRef({ insert, submit, activate });