Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat: integrate Pi Voice local speech-to-text into PI-Desktop

vastsa3c1356d67164
diff --git a/apps/desktop/electron/main/audio-backend.ts b/apps/desktop/electron/main/audio-backend.ts
new file mode 100644
index 000000000..4f5f4c6bc
--- /dev/null
+++ b/apps/desktop/electron/main/audio-backend.ts
@@ -0,0 +1,205 @@
+/**
+ * PvRecorder-based audio capture backend.
+ * Implements AudioCaptureFactory from @pi-desktop/voice-runtime.
+ *
+ * Also serves as the real backend for the pi.audio plugin capture APIs,
+ * replacing the previous UNSUPPORTED stubs.
+ */
+
+import { systemPreferences } from "electron";
+import type {
+ AudioCapture,
+ AudioCaptureFactory,
+ AudioInputDevice,
+} from "@pi-desktop/voice-runtime";
+import {
+ CAPTURE_SAMPLE_RATE,
+ FRAME_LENGTH,
+ convertFrames,
+ computeRms,
+} from "@pi-desktop/voice-runtime";
+
+/** Lazily loaded PvRecorder module. */
+let PvRecorderModule: typeof import("@picovoice/pvrecorder-node") | null = null;
+
+async function loadPvRecorder() {
+ if (!PvRecorderModule) {
+ PvRecorderModule = await import("@picovoice/pvrecorder-node");
+ }
+ return PvRecorderModule;
+}
+
+// ---------------------------------------------------------------------------
+// macOS Microphone Permission
+// ---------------------------------------------------------------------------
+
+export async function checkMicrophonePermission(): Promise<
+ "granted" | "denied" | "undetermined"
+> {
+ if (process.platform !== "darwin") return "granted";
+
+ const status = systemPreferences.getMediaAccessStatus("microphone");
+ switch (status) {
+ case "granted":
+ return "granted";
+ case "denied":
+ case "restricted":
+ return "denied";
+ case "not-determined":
+ return "undetermined";
+ default:
+ return "undetermined";
+ }
+}
+
+export async function requestMicrophonePermission(): Promise<boolean> {
+ if (process.platform !== "darwin") return true;
+ return systemPreferences.askForMediaAccess("microphone");
+}
+
+// ---------------------------------------------------------------------------
+// PvRecorderCapture — single recording session
+// ---------------------------------------------------------------------------
+
+class PvRecorderCapture implements AudioCapture {
+ private recorder: InstanceType<
+ (typeof import("@picovoice/pvrecorder-node"))["PvRecorder"]
+ > | null = null;
+ private frameCallback: ((frame: Int16Array) => void) | null = null;
+ private frames: Int16Array[] = [];
+ private readLoop: Promise<void> | undefined;
+ private stopping = false;
+ private readError: Error | undefined;
+
+ constructor(private readonly deviceIndex: number) {}
+
+ get isActive(): boolean {
+ return this.recorder !== null && !this.stopping;
+ }
+
+ onFrame(cb: (frame: Int16Array) => void): void {
+ this.frameCallback = cb;
+ }
+
+ async start(): Promise<void> {
+ if (this.recorder) throw new Error("Capture already active");
+
+ const { PvRecorder } = await loadPvRecorder();
+ const recorder = new PvRecorder(FRAME_LENGTH, this.deviceIndex);
+
+ try {
+ if (recorder.sampleRate !== CAPTURE_SAMPLE_RATE) {
+ throw new Error(
+ `PvRecorder reported ${recorder.sampleRate} Hz; expected ${CAPTURE_SAMPLE_RATE} Hz`,
+ );
+ }
+
+ this.frames = [];
+ this.stopping = false;
+ this.readError = undefined;
+ recorder.start();
+ this.recorder = recorder;
+ this.readLoop = this.readFrames(recorder);
+ } catch (error) {
+ recorder.release();
+ throw error;
+ }
+ }
+
+ async stop(): Promise<Float32Array> {
+ const recorder = this.recorder;
+ if (!recorder) throw new Error("Capture not active");
+
+ this.stopping = true;
+ let stopError: Error | undefined;
+
+ try {
+ if (recorder.isRecording) recorder.stop();
+ } catch (error) {
+ stopError = error instanceof Error ? error : new Error(String(error));
+ }
+
+ try {
+ await this.readLoop;
+ } finally {
+ recorder.release();
+ this.recorder = null;
+ this.readLoop = undefined;
+ }
+
+ if (stopError) throw stopError;
+ if (this.readError) throw this.readError;
+
+ return convertFrames(this.frames);
+ }
+
+ cancel(): void {
+ this.stopping = true;
+ try {
+ if (this.recorder?.isRecording) this.recorder.stop();
+ } catch {
+ // Best-effort
+ }
+ try {
+ this.recorder?.release();
+ } catch {
+ // Best-effort
+ }
+ this.recorder = null;
+ this.frames = [];
+ }
+
+ private async readFrames(
+ recorder: InstanceType<
+ (typeof import("@picovoice/pvrecorder-node"))["PvRecorder"]
+ >,
+ ): Promise<void> {
+ try {
+ while (!this.stopping && recorder.isRecording) {
+ const frame: Int16Array = await recorder.read();
+ if (this.stopping) continue;
+ this.frames.push(frame);
+ try {
+ this.frameCallback?.(frame);
+ } catch {
+ // Frame callback errors must not fail the recording
+ }
+ }
+ } catch (error) {
+ if (!this.stopping) {
+ this.readError =
+ error instanceof Error ? error : new Error(String(error));
+ }
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// PvRecorderBackend — AudioCaptureFactory implementation
+// ---------------------------------------------------------------------------
+
+export class PvRecorderBackend implements AudioCaptureFactory {
+ async getDevices(): Promise<AudioInputDevice[]> {
+ const { PvRecorder } = await loadPvRecorder();
+ const names: string[] = PvRecorder.getAvailableDevices();
+
+ return names.map((label, index) => ({
+ deviceId: String(index),
+ label,
+ isDefault: index === 0,
+ }));
+ }
+
+ create(deviceId: string | null): AudioCapture {
+ const index = deviceId !== null ? parseInt(deviceId, 10) : -1;
+ return new PvRecorderCapture(isNaN(index) ? -1 : index);
+ }
+
+ async checkPermission(): Promise<"granted" | "denied" | "undetermined"> {
+ return checkMicrophonePermission();
+ }
+
+ async requestPermission(): Promise<boolean> {
+ return requestMicrophonePermission();
+ }
+}
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index f346f35ac..de108674d 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -114,6 +114,7 @@ import { registerWindowIpc } from "./ipc/window-ipc";
import { registerPullsIpc } from "./ipc/pulls-ipc";
import { registerAgentIpc } from "./ipc/agent-ipc";
import { registerIpcHandlers } from "./ipc/register";
+import { VoiceService } from "./voice-service";
import {
type WindowLifecycleState,
} from "./bootstrap/window";
@@ -1246,6 +1247,13 @@ runtimeLifecycle = createRuntimeLifecycle({
});
const { bootHostStatus, runtimeArch, bootBackends } = runtimeLifecycle;
+// Voice service — created lazily on first use, disposed on quit.
+const voiceService = new VoiceService(
+ dataDir + "/voice-models",
+ () => mainWindow,
+);
+app.once("before-quit", () => voiceService.dispose());
+
function registerIpc() {
return registerIpcHandlers({
traySessions: applicationLifecycle!.traySessions,
@@ -1337,6 +1345,7 @@ function registerIpc() {
getPluginPanelTheme: () => pluginPanelTheme,
isDeveloperMode: () => developerMode,
sendToRenderer,
+ voiceService,
});
}
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index b48a03528..09a147eff 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -31,6 +31,7 @@ import { registerWindowIpc } from "./window-ipc";
import { createComposerTemplateLoader, registerWorkspaceIpc } from "./workspace-ipc";
import { registerComposerIpc } from "./composer-ipc";
import { registerSpeechIpc } from "./speech-ipc";
+import { registerVoiceIpc } from "./voice-ipc";
import type { IpcRegistrar } from "./types";
import type { createTraySessions } from "../tray-sessions";
@@ -153,6 +154,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
getPluginPanelTheme,
isDeveloperMode,
sendToRenderer,
+ voiceService,
} = dependencies;
@@ -447,6 +449,10 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
registerSpeechIpc({ registrar, speech });
+ if (voiceService) {
+ registerVoiceIpc({ registrar, voiceService });
+ }
+
registerRemoteHostIpc({ registrar });
registerMarketIpc({
diff --git a/apps/desktop/electron/main/ipc/voice-ipc.ts b/apps/desktop/electron/main/ipc/voice-ipc.ts
new file mode 100644
index 000000000..f511c7204
--- /dev/null
+++ b/apps/desktop/electron/main/ipc/voice-ipc.ts
@@ -0,0 +1,57 @@
+/**
+ * Voice IPC handler registration.
+ * Follows the same pattern as speech-ipc.ts and other IPC modules.
+ */
+
+import { IPC } from "@pi-desktop/shared";
+import type { IpcRegistrar } from "./types";
+import type { VoiceService } from "../voice-service";
+
+export function registerVoiceIpc({
+ registrar,
+ voiceService,
+}: {
+ registrar: IpcRegistrar;
+ voiceService: VoiceService;
+}): void {
+ const { handle } = registrar;
+
+ handle(IPC.invoke.voiceStart, (settings: unknown) =>
+ voiceService.start(settings as any),
+ );
+
+ handle(IPC.invoke.voiceStop, () => voiceService.stop());
+
+ handle(IPC.invoke.voiceCancel, () => {
+ voiceService.cancel();
+ return { ok: true };
+ });
+
+ handle(IPC.invoke.voiceGetState, () => voiceService.getState());
+
+ handle(IPC.invoke.voiceGetDevices, () => voiceService.getDevices());
+
+ handle(IPC.invoke.voiceGetModels, () => voiceService.getModels());
+
+ handle(IPC.invoke.voiceDownloadModel, (input: unknown) => {
+ const { modelId } = input as { modelId: string };
+ return voiceService.downloadModel(modelId);
+ });
+
+ handle(IPC.invoke.voiceDeleteModel, (input: unknown) => {
+ const { modelId } = input as { modelId: string };
+ return voiceService.deleteModel(modelId);
+ });
+
+ handle(IPC.invoke.voiceUpdateSettings, (input: unknown) =>
+ voiceService.updateSettings(input as any),
+ );
+
+ handle(IPC.invoke.voiceCheckPermission, () =>
+ voiceService.checkPermission(),
+ );
+
+ handle(IPC.invoke.voiceRequestPermission, () =>
+ voiceService.requestPermission(),
+ );
+}
diff --git a/apps/desktop/electron/main/voice-service.ts b/apps/desktop/electron/main/voice-service.ts
new file mode 100644
index 000000000..6413c5589
--- /dev/null
+++ b/apps/desktop/electron/main/voice-service.ts
@@ -0,0 +1,173 @@
+/**
+ * VoiceService — orchestrates voice input in the Electron main process.
+ *
+ * Lazily loads @pi-desktop/voice-runtime on first use so that Voice disabled
+ * means zero import overhead at startup.
+ */
+
+import { BrowserWindow } from "electron";
+import { PvRecorderBackend, checkMicrophonePermission, requestMicrophonePermission } from "./audio-backend";
+import type {
+ AudioCaptureFactory,
+ AudioInputDevice,
+ ModelState,
+ VoiceResult,
+ VoiceSettings,
+ VoiceState,
+} from "@pi-desktop/voice-runtime";
+
+// Lazy-loaded runtime classes
+type VoiceControllerT = import("@pi-desktop/voice-runtime").VoiceController;
+type TranscriptionEngineT = import("@pi-desktop/voice-runtime").TranscriptionEngine;
+type ModelManagerT = import("@pi-desktop/voice-runtime").ModelManager;
+
+export class VoiceService {
+ private controller: VoiceControllerT | null = null;
+ private engine: TranscriptionEngineT | null = null;
+ private modelManager: ModelManagerT | null = null;
+ private captureFactory: AudioCaptureFactory;
+ private settings: VoiceSettings;
+ private disposed = false;
+
+ constructor(
+ private readonly modelCacheDir: string,
+ private readonly getWindow: () => BrowserWindow | null,
+ ) {
+ this.captureFactory = new PvRecorderBackend();
+ // Will be overridden from app settings
+ this.settings = {
+ enabled: false,
+ deviceId: null,
+ languages: ["zh", "en"],
+ chineseVariant: "simplified",
+ modelId: "",
+ };
+ }
+
+ // ---- Settings ----
+
+ updateSettings(patch: Partial<VoiceSettings>): void {
+ this.settings = { ...this.settings, ...patch };
+ }
+
+ getSettings(): VoiceSettings {
+ return { ...this.settings };
+ }
+
+ // ---- Lazy initialization ----
+
+ private async ensureRuntime(): Promise<void> {
+ if (this.controller) return;
+
+ const {
+ VoiceController,
+ TranscriptionEngine,
+ ModelManager,
+ } = await import("@pi-desktop/voice-runtime");
+
+ this.modelManager = new ModelManager(this.modelCacheDir);
+ this.engine = new TranscriptionEngine(this.modelManager);
+ this.controller = new VoiceController(
+ this.engine,
+ this.captureFactory,
+ () => this.settings,
+ );
+
+ // Forward state changes to renderer
+ this.controller.on("stateChange", (state: VoiceState) => {
+ this.sendToRenderer("voice:stateChanged", state);
+ });
+ }
+
+ // ---- Recording lifecycle ----
+
+ async start(overrides?: Partial<VoiceSettings>): Promise<void> {
+ if (this.disposed) throw new Error("VoiceService is disposed");
+
+ if (overrides) {
+ this.updateSettings(overrides);
+ }
+
+ await this.ensureRuntime();
+ await this.controller!.start();
+ }
+
+ async stop(): Promise<VoiceResult> {
+ if (!this.controller) throw new Error("Voice not started");
+ return this.controller.stop();
+ }
+
+ cancel(): void {
+ this.controller?.cancel();
+ }
+
+ getState(): VoiceState {
+ return (
+ this.controller?.state ?? {
+ phase: "idle" as const,
+ durationSeconds: 0,
+ volumeLevel: 0,
+ }
+ );
+ }
+
+ // ---- Devices ----
+
+ async getDevices(): Promise<AudioInputDevice[]> {
+ return this.captureFactory.getDevices();
+ }
+
+ // ---- Models ----
+
+ getModels(): ModelState[] {
+ return this.modelManager?.getAllStates() ?? [];
+ }
+
+ async downloadModel(modelId: string): Promise<void> {
+ await this.ensureRuntime();
+ const gen = this.modelManager!.download(modelId);
+ for await (const progress of gen) {
+ this.sendToRenderer("voice:modelProgress", { modelId, progress });
+ }
+ }
+
+ async deleteModel(modelId: string): Promise<void> {
+ await this.ensureRuntime();
+ await this.modelManager!.deleteModel(modelId);
+ }
+
+ // ---- Permissions ----
+
+ async checkPermission(): Promise<"granted" | "denied" | "undetermined"> {
+ return checkMicrophonePermission();
+ }
+
+ async requestPermission(): Promise<boolean> {
+ return requestMicrophonePermission();
+ }
+
+ // ---- Lifecycle ----
+
+ dispose(): void {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.controller?.dispose();
+ this.engine?.shutdown();
+ this.controller = null;
+ this.engine = null;
+ this.modelManager = null;
+ }
+
+ // ---- IPC helpers ----
+
+ private sendToRenderer(channel: string, data: unknown): void {
+ try {
+ const win = this.getWindow();
+ if (win && !win.isDestroyed()) {
+ win.webContents.send(channel, data);
+ }
+ } catch {
+ // Window may be closing
+ }
+ }
+}
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 0637f7098..f81ae3bde 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -43,11 +43,14 @@
"@pi-desktop/plugin-sdk": "workspace:*",
"@pi-desktop/racp": "workspace:*",
"@pi-desktop/shared": "workspace:*",
+ "@pi-desktop/voice-runtime": "workspace:*",
"@tailwindcss/vite": "^4.3.3",
+ "@picovoice/pvrecorder-node": "1.2.9",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.4",
"@types/ws": "^8.18.1",
"@vitejs/plugin-react": "^4.6.0",
+ "transcribe-cpp": "0.2.2",
"dompurify": "^3.4.13",
"electron": "^43.4.1",
"electron-builder": "^26.15.3",
@@ -278,6 +281,12 @@
}
]
},
+ "asarUnpack": [
+ "node_modules/transcribe-cpp/**/*.node",
+ "node_modules/transcribe-cpp/**/bin/**",
+ "node_modules/@picovoice/pvrecorder-node/**/*.node",
+ "node_modules/@picovoice/pvrecorder-node/**/lib/**"
+ ],
"asar": {
"smartUnpack": false
}
diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsx
index d964d6be4..abf119faa 100644
--- a/apps/desktop/src/components/Composer.tsx
+++ b/apps/desktop/src/components/Composer.tsx
@@ -58,6 +58,9 @@ import { ComposerImageAttachments } from "../features/chat/composer/ComposerImag
import { ComposerInput } from "../features/chat/composer/ComposerInput";
import { useComposerModelMenu } from "../features/chat/composer/hooks/useComposerModelMenu";
import { ComposerToolbar } from "../features/chat/composer/ComposerToolbar";
+import { useVoiceInput } from "../features/voice/useVoiceInput";
+import { VoiceOverlay } from "../features/voice/VoiceOverlay";
+import "../styles/voice.css";
import { ComposerStatus } from "../features/chat/composer/ComposerStatus";
const EMPTY_QUEUED_PROMPTS: QueuedPrompt[] = [];
@@ -438,6 +441,21 @@ export function Composer({
submit,
} = submitController;
+ const voiceEnabled = !!settings?.voice?.enabled;
+ const voice = useVoiceInput({
+ enabled: voiceEnabled,
+ onTranscriptionComplete: (text) => {
+ // Insert transcribed text into Composer
+ const current = readLiveDraft();
+ if (!current.trim()) {
+ applyEditorDraft(text, fileReferencesRef.current, text.length);
+ } else {
+ const next = current + " " + text;
+ applyEditorDraft(next, fileReferencesRef.current, next.length);
+ }
+ },
+ });
+
const composerAc = useComposerAutocomplete({
value,
cursor,
@@ -580,6 +598,7 @@ export function Composer({
persistDraft();
}}
/>
+ <VoiceOverlay t={t} state={voice.state} onCancel={voice.cancel} />
<ComposerToolbar
t={t}
mode={mode}
@@ -612,6 +631,10 @@ export function Composer({
hasDraftContent={hasDraftContent}
abort={abort}
submit={submit}
+ voicePhase={voice.state.phase}
+ voiceEnabled={voiceEnabled}
+ onVoiceToggle={voice.toggle}
+ onVoiceCancel={voice.cancel}
/>
</div>
</div>
diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
index 2f27e84e6..648af3240 100644
--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
@@ -19,12 +19,14 @@ import {
IconUndo2,
} from "../../../components/icons";
import { ModeIcon } from "./ComposerModeIcon";
+import { VoiceMicButton } from "../../voice/VoiceMicButton";
import { ComposerModelPicker } from "./ComposerModelPicker";
import {
MODE_LABEL_KEYS,
nextMode,
} from "./model";
import type { useComposerModelMenu } from "./hooks/useComposerModelMenu";
+import type { VoicePhase } from "../../voice/useVoiceInput";
type ModelMenuController = ReturnType<typeof useComposerModelMenu>;
type ContextUsage = Parameters<typeof ContextUsageInspector>[0];
@@ -61,6 +63,10 @@ export type ComposerToolbarProps = {
hasDraftContent: boolean;
abort: AppState["abort"];
submit: () => Promise<void>;
+ voicePhase: VoicePhase;
+ voiceEnabled: boolean;
+ onVoiceToggle: () => void;
+ onVoiceCancel: () => void;
};
/** Composer controls: mode, permission, model, enhancement, and send/stop. */
@@ -96,6 +102,10 @@ export function ComposerToolbar({
hasDraftContent,
abort,
submit,
+ voicePhase,
+ voiceEnabled,
+ onVoiceToggle,
+ onVoiceCancel,
}: ComposerToolbarProps) {
const platform = (window.piDesktop?.platform ?? "darwin") as ShortcutPlatform;
const steeringShortcut = keybindingDisplayParts("Alt+Enter", platform).join("+");
@@ -117,6 +127,15 @@ export function ComposerToolbar({
<IconPlus size={15} aria-hidden="true" />
</TooltipButton>
</div>
+ {voiceEnabled && (
+ <VoiceMicButton
+ t={t}
+ phase={voicePhase}
+ disabled={controlsBlocked}
+ onToggle={onVoiceToggle}
+ onCancel={onVoiceCancel}
+ />
+ )}
<TooltipButton
type="button"
className="icon-btn mode-chip composer-mode-chip"
diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsx
index e186d87d8..3060b43ec 100644
--- a/apps/desktop/src/features/settings/SettingsPage.tsx
+++ b/apps/desktop/src/features/settings/SettingsPage.tsx
@@ -31,6 +31,7 @@ import {
IconSliders,
IconSparkles,
IconCloudDown,
+ IconMic,
} from "../../components/icons";
import { Badge, Button, cx } from "../../components/ui";
import { ModelConfigPage } from "../../components/settings/ModelConfigPage";
@@ -47,6 +48,7 @@ import { AgentSkillsPage } from "../../components/settings/AgentSkillsPage";
import { AgentMcpPage } from "../../components/settings/AgentMcpPage";
import { AgentSubagentsPage } from "../../components/settings/AgentSubagentsPage";
import { RemoteHostsPage } from "../../components/settings/RemoteHostsPage";
+import { VoiceSettingsSection } from "./voice/VoiceSettingsSection";
import {
CommandShellRow,
ContextUsageDisplayRow,
@@ -230,6 +232,7 @@ export function SettingsPage() {
projects: <IconArchive size={14} />,
sync: <IconCloudDown size={14} />,
remoteHosts: <IconGlobe size={14} />,
+ voice: <IconMic size={14} />,
about: <IconInfo size={14} />,
};
return navEntries.map((entry) => ({
@@ -544,6 +547,10 @@ export function SettingsPage() {
</div>
)}
+ {tab === "voice" && settings && (
+ <VoiceSettingsSection t={t} />
+ )}
+
{tab === "shortcuts" && settings && (
<div className="settings-stack">
<KeyboardShortcutsSection
diff --git a/apps/desktop/src/features/settings/voice/VoiceSettingsSection.tsx b/apps/desktop/src/features/settings/voice/VoiceSettingsSection.tsx
new file mode 100644
index 000000000..c24c80068
--- /dev/null
+++ b/apps/desktop/src/features/settings/voice/VoiceSettingsSection.tsx
@@ -0,0 +1,246 @@
+/**
+ * Voice settings panel in the Settings page.
+ */
+
+import { useCallback, useEffect, useState } from "react";
+import type { TFunction } from "i18next";
+import { useAppStore } from "../../../stores/app-store";
+import { voiceIpc } from "../../voice/voice-ipc";
+
+interface AudioInputDevice {
+ deviceId: string;
+ label: string;
+ isDefault: boolean;
+}
+
+interface ModelState {
+ info: {
+ id: string;
+ name: string;
+ description: string;
+ sizeBytes: number;
+ recommended: boolean;
+ };
+ status: string;
+ downloadProgress?: number;
+ error?: string;
+}
+
+export function VoiceSettingsSection({ t }: { t: TFunction }) {
+ const settings = useAppStore((s) => s.settings);
+ const updateSettings = useAppStore((s) => s.updateSettings);
+
+ const voiceSettings = settings?.voice ?? {
+ enabled: false,
+ deviceId: null,
+ languages: ["zh", "en"],
+ chineseVariant: "simplified" as const,
+ modelId: "",
+ };
+
+ const [devices, setDevices] = useState<AudioInputDevice[]>([]);
+ const [models, setModels] = useState<ModelState[]>([]);
+ const [permission, setPermission] = useState<string>("undetermined");
+
+ // Load devices and models on mount
+ useEffect(() => {
+ voiceIpc.getDevices().then(setDevices).catch(() => {});
+ voiceIpc.getModels().then(setModels).catch(() => {});
+ voiceIpc.checkPermission().then(setPermission).catch(() => {});
+ }, []);
+
+ // Listen for model progress
+ useEffect(() => {
+ return voiceIpc.onModelProgress(({ modelId, progress }) => {
+ setModels((prev) =>
+ prev.map((m) =>
+ m.info.id === modelId
+ ? { ...m, status: progress >= 1 ? "downloaded" : "downloading", downloadProgress: progress }
+ : m,
+ ),
+ );
+ });
+ }, []);
+
+ const update = useCallback(
+ (patch: Record<string, unknown>) => {
+ const next = { ...voiceSettings, ...patch };
+ void updateSettings({ voice: next as any });
+ void voiceIpc.updateSettings(next);
+ },
+ [voiceSettings, updateSettings],
+ );
+
+ const formatSize = (bytes: number) => {
+ if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
+ return `${(bytes / 1e6).toFixed(0)} MB`;
+ };
+
+ return (
+ <div className="settings-section">
+ {/* Enable toggle */}
+ <label className="settings-row settings-row-toggle">
+ <span>{t("settings.voiceEnable")}</span>
+ <input
+ type="checkbox"
+ checked={voiceSettings.enabled}
+ onChange={(e) => update({ enabled: e.target.checked })}
+ />
+ </label>
+
+ {/* Microphone permission warning */}
+ {permission === "denied" && (
+ <div className="settings-row settings-warning">
+ <span>{t("settings.voiceMicDenied")}</span>
+ <p className="text-xs opacity-70">{t("settings.voiceMicDeniedDesc")}</p>
+ </div>
+ )}
+
+ {/* Microphone selection */}
+ <div className="settings-row">
+ <label>{t("settings.voiceMicrophone")}</label>
+ <select
+ value={voiceSettings.deviceId ?? ""}
+ onChange={(e) => update({ deviceId: e.target.value || null })}
+ disabled={!voiceSettings.enabled}
+ >
+ <option value="">{t("settings.voiceSystemDefault")}</option>
+ {devices.map((d) => (
+ <option key={d.deviceId} value={d.deviceId}>
+ {d.label}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Languages */}
+ <div className="settings-row">
+ <label>{t("settings.voiceLanguages")}</label>
+ <div className="flex gap-3">
+ {[
+ { code: "zh", label: "Chinese" },
+ { code: "en", label: "English" },
+ { code: "ja", label: "Japanese" },
+ { code: "ko", label: "Korean" },
+ ].map(({ code, label }) => (
+ <label key={code} className="flex items-center gap-1 text-sm">
+ <input
+ type="checkbox"
+ checked={voiceSettings.languages.includes(code)}
+ disabled={!voiceSettings.enabled}
+ onChange={(e) => {
+ const langs = e.target.checked
+ ? [...voiceSettings.languages, code]
+ : voiceSettings.languages.filter((l: string) => l !== code);
+ update({ languages: langs.length > 0 ? langs : [code] });
+ }}
+ />
+ {label}
+ </label>
+ ))}
+ </div>
+ </div>
+
+ {/* Chinese variant */}
+ <div className="settings-row">
+ <label>{t("settings.voiceChineseVariant")}</label>
+ <select
+ value={voiceSettings.chineseVariant}
+ onChange={(e) => update({ chineseVariant: e.target.value })}
+ disabled={!voiceSettings.enabled}
+ >
+ <option value="simplified">{t("settings.voiceSimplified")}</option>
+ <option value="traditional-taiwan">{t("settings.voiceTraditionalTaiwan")}</option>
+ <option value="traditional-hong-kong">{t("settings.voiceTraditionalHK")}</option>
+ </select>
+ </div>
+
+ {/* Model selection */}
+ <div className="settings-row">
+ <label>{t("settings.voiceModel")}</label>
+ <select
+ value={voiceSettings.modelId}
+ onChange={(e) => update({ modelId: e.target.value })}
+ disabled={!voiceSettings.enabled}
+ >
+ <option value="">{t("settings.voiceNoModelSelected")}</option>
+ {models.map((m) => (
+ <option key={m.info.id} value={m.info.id}>
+ {m.info.name}
+ {m.info.recommended ? " ★" : ""}
+ {m.status === "downloaded" || m.status === "loaded" ? " ✓" : ""}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Local models management */}
+ <div className="settings-row">
+ <label>{t("settings.voiceLocalModels")}</label>
+ </div>
+ <div className="settings-model-list">
+ {models.map((m) => (
+ <div key={m.info.id} className="settings-model-item">
+ <div className="settings-model-info">
+ <span className="settings-model-name">
+ {m.info.name}
+ {m.info.recommended && <span className="text-xs opacity-60"> ★</span>}
+ </span>
+ <span className="text-xs opacity-60">
+ {formatSize(m.info.sizeBytes)}
+ </span>
+ </div>
+ <div className="settings-model-status">
+ {m.status === "downloaded" || m.status === "loaded" ? (
+ <>
+ <span className="text-xs text-green-500">{t("settings.voiceModelDownloaded")}</span>
+ <button
+ type="button"
+ className="text-xs text-red-400 hover:underline"
+ onClick={() => {
+ void voiceIpc.deleteModel(m.info.id);
+ setModels((prev) =>
+ prev.map((x) =>
+ x.info.id === m.info.id ? { ...x, status: "not-downloaded" } : x,
+ ),
+ );
+ }}
+ >
+ {t("settings.voiceModelDelete")}
+ </button>
+ </>
+ ) : m.status === "downloading" ? (
+ <div className="flex items-center gap-2">
+ <div className="voice-volume-bar" style={{ width: 100 }}>
+ <div
+ className="voice-volume-fill"
+ style={{ width: `${(m.downloadProgress ?? 0) * 100}%` }}
+ />
+ </div>
+ <span className="text-xs opacity-60">
+ {Math.round((m.downloadProgress ?? 0) * 100)}%
+ </span>
+ </div>
+ ) : (
+ <button
+ type="button"
+ className="text-xs text-blue-400 hover:underline"
+ onClick={() => {
+ void voiceIpc.downloadModel(m.info.id);
+ setModels((prev) =>
+ prev.map((x) =>
+ x.info.id === m.info.id ? { ...x, status: "downloading", downloadProgress: 0 } : x,
+ ),
+ );
+ }}
+ >
+ {t("settings.voiceModelDownload")}
+ </button>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/voice/VoiceMicButton.tsx b/apps/desktop/src/features/voice/VoiceMicButton.tsx
new file mode 100644
index 000000000..c381c6b73
--- /dev/null
+++ b/apps/desktop/src/features/voice/VoiceMicButton.tsx
@@ -0,0 +1,110 @@
+/**
+ * Microphone button for the Composer toolbar.
+ */
+
+import type { TFunction } from "i18next";
+import { TooltipButton } from "../../components/ui";
+import type { VoicePhase } from "./useVoiceInput";
+
+interface VoiceMicButtonProps {
+ t: TFunction;
+ phase: VoicePhase;
+ disabled: boolean;
+ onToggle: () => void;
+ onCancel: () => void;
+}
+
+export function VoiceMicButton({
+ t,
+ phase,
+ disabled,
+ onToggle,
+ onCancel,
+}: VoiceMicButtonProps) {
+ const isActive =
+ phase === "starting" ||
+ phase === "listening" ||
+ phase === "transcribing";
+
+ const tooltip = isActive
+ ? t("settings.voiceCancel")
+ : t("settings.voiceRecording").replace("…", "");
+
+ return (
+ <TooltipButton
+ type="button"
+ className={`icon-btn${isActive ? " voice-active" : ""}`}
+ tooltip={tooltip}
+ ariaLabel={tooltip}
+ disabled={disabled && !isActive}
+ onClick={isActive ? onCancel : onToggle}
+ >
+ <MicIcon active={isActive} phase={phase} />
+ </TooltipButton>
+ );
+}
+
+function MicIcon({ active, phase }: { active: boolean; phase: VoicePhase }) {
+ return (
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ aria-hidden="true"
+ className={active ? "voice-mic-active" : undefined}
+ >
+ {/* Microphone body */}
+ <rect
+ x="5.5"
+ y="1.5"
+ width="5"
+ height="8"
+ rx="2.5"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ fill={active ? "currentColor" : "none"}
+ />
+ {/* Stand arc */}
+ <path
+ d="M3.5 7.5a4.5 4.5 0 0 0 9 0"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ strokeLinecap="round"
+ fill="none"
+ />
+ {/* Stand line */}
+ <line
+ x1="8"
+ y1="12"
+ x2="8"
+ y2="14"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ strokeLinecap="round"
+ />
+ {/* Base */}
+ <line
+ x1="6"
+ y1="14"
+ x2="10"
+ y2="14"
+ stroke="currentColor"
+ strokeWidth="1.2"
+ strokeLinecap="round"
+ />
+ {/* Recording indicator */}
+ {phase === "listening" && (
+ <circle cx="13" cy="3" r="2.5" fill="var(--color-danger, #ef4444)">
+ <animate
+ attributeName="opacity"
+ values="1;0.3;1"
+ dur="1.2s"
+ repeatCount="indefinite"
+ />
+ </circle>
+ )}
+ </svg>
+ );
+}
diff --git a/apps/desktop/src/features/voice/VoiceOverlay.tsx b/apps/desktop/src/features/voice/VoiceOverlay.tsx
new file mode 100644
index 000000000..e694b9ea4
--- /dev/null
+++ b/apps/desktop/src/features/voice/VoiceOverlay.tsx
@@ -0,0 +1,81 @@
+/**
+ * Lightweight overlay shown above the Composer during voice input.
+ */
+
+import type { TFunction } from "i18next";
+import type { VoiceState } from "./useVoiceInput";
+
+interface VoiceOverlayProps {
+ t: TFunction;
+ state: VoiceState;
+ onCancel: () => void;
+}
+
+export function VoiceOverlay({ t, state, onCancel }: VoiceOverlayProps) {
+ if (
+ state.phase !== "starting" &&
+ state.phase !== "listening" &&
+ state.phase !== "transcribing" &&
+ state.phase !== "error"
+ ) {
+ return null;
+ }
+
+ return (
+ <div className="voice-overlay" role="status" aria-live="polite">
+ <div className="voice-overlay-content">
+ <div className="voice-overlay-left">
+ {state.phase === "listening" && (
+ <>
+ <span className="voice-recording-dot" aria-hidden="true" />
+ <span>{t("settings.voiceRecording")}</span>
+ <span className="voice-duration">
+ {formatDuration(state.durationSeconds)}
+ </span>
+ </>
+ )}
+ {state.phase === "starting" && <span>{t("settings.voiceRecording")}</span>}
+ {state.phase === "transcribing" && (
+ <>
+ <span className="voice-spinner" aria-hidden="true" />
+ <span>{t("settings.voiceTranscribing")}</span>
+ </>
+ )}
+ {state.phase === "error" && (
+ <span className="voice-error">{state.error}</span>
+ )}
+ </div>
+ <div className="voice-overlay-right">
+ {state.phase === "listening" && (
+ <VolumeBar level={state.volumeLevel} />
+ )}
+ {(state.phase === "listening" || state.phase === "starting") && (
+ <button
+ type="button"
+ className="voice-cancel-btn"
+ onClick={onCancel}
+ >
+ {t("settings.voiceCancel")}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function VolumeBar({ level }: { level: number }) {
+ const width = Math.min(100, Math.max(0, level * 100));
+ return (
+ <div className="voice-volume-bar" aria-hidden="true">
+ <div className="voice-volume-fill" style={{ width: `${width}%` }} />
+ </div>
+ );
+}
+
+function formatDuration(seconds: number): string {
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.floor(seconds % 60);
+ const tenths = Math.floor((seconds % 1) * 10);
+ return `${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}.${tenths}`;
+}
diff --git a/apps/desktop/src/features/voice/useVoiceInput.ts b/apps/desktop/src/features/voice/useVoiceInput.ts
new file mode 100644
index 000000000..85e01135b
--- /dev/null
+++ b/apps/desktop/src/features/voice/useVoiceInput.ts
@@ -0,0 +1,106 @@
+/**
+ * React hook managing voice input state and Composer integration.
+ */
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { voiceIpc } from "./voice-ipc";
+
+export type VoicePhase =
+ | "idle"
+ | "preparing"
+ | "ready"
+ | "starting"
+ | "listening"
+ | "transcribing"
+ | "done"
+ | "error"
+ | "cancelling";
+
+export interface VoiceState {
+ phase: VoicePhase;
+ durationSeconds: number;
+ volumeLevel: number;
+ error?: string;
+ result?: {
+ text: string;
+ speechSeconds: number;
+ transcribeSeconds: number;
+ language: string;
+ };
+}
+
+const IDLE_STATE: VoiceState = {
+ phase: "idle",
+ durationSeconds: 0,
+ volumeLevel: 0,
+};
+
+interface UseVoiceInputOptions {
+ /** Called when transcription completes with the resulting text. */
+ onTranscriptionComplete?: (text: string) => void;
+ /** Whether voice is enabled in settings. */
+ enabled?: boolean;
+}
+
+export function useVoiceInput(options: UseVoiceInputOptions = {}) {
+ const { onTranscriptionComplete, enabled = false } = options;
+ const [state, setState] = useState<VoiceState>(IDLE_STATE);
+ const onCompleteRef = useRef(onTranscriptionComplete);
+ onCompleteRef.current = onTranscriptionComplete;
+
+ // Listen for state changes from main process
+ useEffect(() => {
+ if (!enabled) return;
+
+ const unsubscribe = voiceIpc.onStateChanged((newState) => {
+ const s = newState as VoiceState;
+ setState(s);
+
+ // When transcription completes, call the callback
+ if (s.phase === "done" && s.result?.text) {
+ onCompleteRef.current?.(s.result.text);
+ // Reset to idle after a short delay
+ setTimeout(() => setState(IDLE_STATE), 100);
+ }
+
+ // Auto-reset error after 3 seconds
+ if (s.phase === "error") {
+ setTimeout(() => setState(IDLE_STATE), 3000);
+ }
+ });
+
+ return unsubscribe;
+ }, [enabled]);
+
+ const toggle = useCallback(async () => {
+ if (!enabled) return;
+
+ try {
+ if (state.phase === "idle" || state.phase === "ready") {
+ await voiceIpc.start();
+ } else if (state.phase === "listening") {
+ await voiceIpc.stop();
+ }
+ } catch (error) {
+ setState({
+ phase: "error",
+ durationSeconds: 0,
+ volumeLevel: 0,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }, [enabled, state.phase]);
+
+ const cancel = useCallback(() => {
+ if (!enabled) return;
+ voiceIpc.cancel();
+ setState(IDLE_STATE);
+ }, [enabled]);
+
+ const isActive =
+ state.phase === "starting" ||
+ state.phase === "listening" ||
+ state.phase === "transcribing";
+
+ return { state, toggle, cancel, isActive };
+}
diff --git a/apps/desktop/src/features/voice/voice-ipc.ts b/apps/desktop/src/features/voice/voice-ipc.ts
new file mode 100644
index 000000000..ec41acb48
--- /dev/null
+++ b/apps/desktop/src/features/voice/voice-ipc.ts
@@ -0,0 +1,51 @@
+/**
+ * Renderer-side IPC wrapper for voice operations.
+ */
+
+const { ipcRenderer } = window.require("electron");
+
+export const voiceIpc = {
+ start: (settings?: Record<string, unknown>) =>
+ ipcRenderer.invoke("pi-desktop/voice/start", settings),
+
+ stop: () => ipcRenderer.invoke("pi-desktop/voice/stop"),
+
+ cancel: () => ipcRenderer.invoke("pi-desktop/voice/cancel"),
+
+ getState: () => ipcRenderer.invoke("pi-desktop/voice/getState"),
+
+ getDevices: () => ipcRenderer.invoke("pi-desktop/voice/getDevices"),
+
+ getModels: () => ipcRenderer.invoke("pi-desktop/voice/getModels"),
+
+ downloadModel: (modelId: string) =>
+ ipcRenderer.invoke("pi-desktop/voice/downloadModel", { modelId }),
+
+ deleteModel: (modelId: string) =>
+ ipcRenderer.invoke("pi-desktop/voice/deleteModel", { modelId }),
+
+ updateSettings: (settings: Record<string, unknown>) =>
+ ipcRenderer.invoke("pi-desktop/voice/updateSettings", settings),
+
+ checkPermission: () =>
+ ipcRenderer.invoke("pi-desktop/voice/checkPermission"),
+
+ requestPermission: () =>
+ ipcRenderer.invoke("pi-desktop/voice/requestPermission"),
+
+ onStateChanged: (callback: (state: unknown) => void) => {
+ const handler = (_event: unknown, state: unknown) => callback(state);
+ ipcRenderer.on("pi-desktop/voice/event/stateChanged", handler);
+ return () => {
+ ipcRenderer.removeListener("pi-desktop/voice/event/stateChanged", handler);
+ };
+ },
+
+ onModelProgress: (callback: (data: { modelId: string; progress: number }) => void) => {
+ const handler = (_event: unknown, data: { modelId: string; progress: number }) => callback(data);
+ ipcRenderer.on("pi-desktop/voice/event/modelProgress", handler);
+ return () => {
+ ipcRenderer.removeListener("pi-desktop/voice/event/modelProgress", handler);
+ };
+ },
+};
diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.ts
index e2561ed8b..c8052c434 100644
--- a/apps/desktop/src/lib/settings-search.ts
+++ b/apps/desktop/src/lib/settings-search.ts
@@ -18,6 +18,7 @@ export type SettingsTabId =
| "projects"
| "sync"
| "remoteHosts"
+ | "voice"
| "about";
export type SettingsNavGroupId =
@@ -118,6 +119,20 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [
"settings.largePasteThreshold",
],
},
+ {
+ id: "voice",
+ labelKey: "settings.nav.voice",
+ titleKey: "settings.voice",
+ group: "preferences",
+ keywordKeys: [
+ "settings.voiceEnable",
+ "settings.voiceMicrophone",
+ "settings.voiceLanguages",
+ "settings.voiceChineseVariant",
+ "settings.voiceModel",
+ "settings.voiceLocalModels",
+ ],
+ },
{
id: "shortcuts",
labelKey: "settings.nav.shortcuts",
diff --git a/apps/desktop/src/styles/voice.css b/apps/desktop/src/styles/voice.css
new file mode 100644
index 000000000..422b4c0ee
--- /dev/null
+++ b/apps/desktop/src/styles/voice.css
@@ -0,0 +1,109 @@
+/* Voice input styles */
+
+.voice-active {
+ color: var(--color-danger, #ef4444) !important;
+}
+
+.voice-mic-active {
+ animation: voice-pulse 1.2s ease-in-out infinite;
+}
+
+@keyframes voice-pulse {
+ 0%, 100% { opacity: 1; }
+ 50% { opacity: 0.6; }
+}
+
+/* Voice overlay */
+.voice-overlay {
+ position: absolute;
+ bottom: 100%;
+ left: 0;
+ right: 0;
+ padding: 0 8px 4px;
+ z-index: 10;
+ pointer-events: auto;
+}
+
+.voice-overlay-content {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 6px 12px;
+ border-radius: 8px;
+ background: var(--color-surface-elevated, #1e1e2e);
+ border: 1px solid var(--color-border, #333);
+ font-size: 13px;
+ gap: 12px;
+}
+
+.voice-overlay-left {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.voice-overlay-right {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.voice-recording-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--color-danger, #ef4444);
+ animation: voice-pulse 1.2s ease-in-out infinite;
+}
+
+.voice-duration {
+ font-variant-numeric: tabular-nums;
+ opacity: 0.7;
+}
+
+.voice-spinner {
+ width: 14px;
+ height: 14px;
+ border: 2px solid var(--color-border, #555);
+ border-top-color: var(--color-primary, #3b82f6);
+ border-radius: 50%;
+ animation: voice-spin 0.8s linear infinite;
+}
+
+@keyframes voice-spin {
+ to { transform: rotate(360deg); }
+}
+
+.voice-volume-bar {
+ width: 80px;
+ height: 4px;
+ border-radius: 2px;
+ background: var(--color-border, #333);
+ overflow: hidden;
+}
+
+.voice-volume-fill {
+ height: 100%;
+ background: var(--color-primary, #3b82f6);
+ border-radius: 2px;
+ transition: width 100ms ease-out;
+}
+
+.voice-cancel-btn {
+ padding: 2px 8px;
+ border-radius: 4px;
+ font-size: 12px;
+ background: transparent;
+ color: var(--color-text-secondary, #999);
+ border: 1px solid var(--color-border, #444);
+ cursor: pointer;
+ transition: background 150ms;
+}
+
+.voice-cancel-btn:hover {
+ background: var(--color-surface-hover, #2a2a3e);
+}
+
+.voice-error {
+ color: var(--color-danger, #ef4444);
+}
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index a68acb4ce..62c849aea 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -686,7 +686,8 @@ sklm: {
"projects": "Projekte",
"sync": "Cloud-Synchronisierung",
"remoteHosts": "Remote-Hosts",
- "info": "Informationen"
+ "info": "Informationen",
+ "voice": "Sprache"
},
"configSync": {
title: "Cloud sync",
@@ -866,6 +867,33 @@ sklm: {
"shortcutSaveFailed": "Die Verknüpfung konnte nicht gespeichert werden.",
"shortcutUnbound": "Ungebunden",
"shortcutDisable": "Verknüpfung für {{action}} deaktivieren",
+ "voice": "Sprache",
+ "voiceEnable": "Spracheingabe aktivieren",
+ "voiceMicrophone": "Mikrofon",
+ "voiceSystemDefault": "Systemstandard",
+ "voiceLanguages": "Sprachen",
+ "voiceChineseVariant": "Chinesische Variante",
+ "voiceSimplified": "Vereinfacht",
+ "voiceTraditionalTaiwan": "Traditionell (Taiwan)",
+ "voiceTraditionalHK": "Traditionell (Hongkong)",
+ "voiceModel": "Transkriptionsmodell",
+ "voiceModelDownload": "Herunterladen",
+ "voiceModelDelete": "Löschen",
+ "voiceModelDownloaded": "Heruntergeladen",
+ "voiceModelDownloading": "Wird heruntergeladen…",
+ "voiceModelNotDownloaded": "Nicht heruntergeladen",
+ "voiceModelSize": "{{size}}",
+ "voiceShortcut": "Tastenkürzel",
+ "voiceLocalModels": "Lokale Modelle",
+ "voiceNoModelSelected": "Kein Modell ausgewählt",
+ "voiceSelectModel": "Wählen Sie ein Modell aus",
+ "voiceMicDenied": "Mikrofonzugriff verweigert",
+ "voiceMicDeniedDesc": "Gewähren Sie den Mikrofonzugriff in den Systemeinstellungen.",
+ "voiceMicUnavailable": "Mikrofon nicht verfügbar",
+ "voiceOpenSystemSettings": "Systemeinstellungen öffnen",
+ "voiceRecording": "Aufnahme…",
+ "voiceTranscribing": "Transkription…",
+ "voiceCancel": "Abbrechen",
"shortcutGroup": {
"navigation": "Navigation",
"agent": "Agent",
@@ -887,7 +915,9 @@ sklm: {
"resetZoom": "Zoom zurücksetzen",
"zoomIn": "Vergrößern",
"zoomOut": "Verkleinern",
- "toggleFullScreen": "Vollbild umschalten"
+ "toggleFullScreen": "Vollbild umschalten",
+ "voiceToggle": "Spracheingabe umschalten",
+ "voiceCancel": "Spracheingabe abbrechen"
},
"skills": "Fähigkeiten",
"skillsGlobalPath": "Globaler Kompetenzpfad",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index b7d3df364..e6b2e3bd3 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -694,6 +694,7 @@ sklm: {
sync: "Cloud sync",
remoteHosts: "Remote hosts",
info: "Info",
+ voice: "Voice",
},
general: "General",
ai: "AI",
@@ -715,6 +716,33 @@ sklm: {
shortcutSaveFailed: "Could not save the shortcut.",
shortcutUnbound: "Unbound",
shortcutDisable: "Disable shortcut for {{action}}",
+ voice: "Voice",
+ voiceEnable: "Enable voice input",
+ voiceMicrophone: "Microphone",
+ voiceSystemDefault: "System Default",
+ voiceLanguages: "Languages",
+ voiceChineseVariant: "Chinese variant",
+ voiceSimplified: "Simplified",
+ voiceTraditionalTaiwan: "Traditional (Taiwan)",
+ voiceTraditionalHK: "Traditional (Hong Kong)",
+ voiceModel: "Transcription model",
+ voiceModelDownload: "Download",
+ voiceModelDelete: "Delete",
+ voiceModelDownloaded: "Downloaded",
+ voiceModelDownloading: "Downloading…",
+ voiceModelNotDownloaded: "Not downloaded",
+ voiceModelSize: "{{size}}",
+ voiceShortcut: "Shortcut",
+ voiceLocalModels: "Local models",
+ voiceNoModelSelected: "No model selected",
+ voiceSelectModel: "Select a model to get started",
+ voiceMicDenied: "Microphone access denied",
+ voiceMicDeniedDesc: "Grant microphone access in System Settings.",
+ voiceMicUnavailable: "Microphone unavailable",
+ voiceOpenSystemSettings: "Open System Settings",
+ voiceRecording: "Listening…",
+ voiceTranscribing: "Transcribing…",
+ voiceCancel: "Cancel",
shortcutGroup: {
navigation: "Navigation",
agent: "Agent",
@@ -737,6 +765,8 @@ sklm: {
zoomIn: "Zoom in",
zoomOut: "Zoom out",
toggleFullScreen: "Toggle full screen",
+ voiceToggle: "Toggle voice input",
+ voiceCancel: "Cancel voice input",
},
skills: "Skills",
skillsGlobalPath: "Global skills path",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index eaf5c09be..4b63fbf7d 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -686,7 +686,8 @@ sklm: {
"projects": "Proyectos",
"sync": "Sincronización en la nube",
"remoteHosts": "Hosts remotos",
- "info": "Información"
+ "info": "Información",
+ "voice": "Voz"
},
"configSync": {
title: "Cloud sync",
@@ -866,6 +867,33 @@ sklm: {
"shortcutSaveFailed": "No se pudo guardar el acceso directo.",
"shortcutUnbound": "Sin enlazar",
"shortcutDisable": "Deshabilitar el acceso directo para {{action}}",
+ "voice": "Voz",
+ "voiceEnable": "Habilitar entrada de voz",
+ "voiceMicrophone": "Micrófono",
+ "voiceSystemDefault": "Predeterminado del sistema",
+ "voiceLanguages": "Idiomas",
+ "voiceChineseVariant": "Variante china",
+ "voiceSimplified": "Simplificado",
+ "voiceTraditionalTaiwan": "Tradicional (Taiwán)",
+ "voiceTraditionalHK": "Tradicional (Hong Kong)",
+ "voiceModel": "Modelo de transcripción",
+ "voiceModelDownload": "Descargar",
+ "voiceModelDelete": "Eliminar",
+ "voiceModelDownloaded": "Descargado",
+ "voiceModelDownloading": "Descargando…",
+ "voiceModelNotDownloaded": "No descargado",
+ "voiceModelSize": "{{size}}",
+ "voiceShortcut": "Atajo",
+ "voiceLocalModels": "Modelos locales",
+ "voiceNoModelSelected": "Ningún modelo seleccionado",
+ "voiceSelectModel": "Seleccione un modelo para comenzar",
+ "voiceMicDenied": "Acceso al micrófono denegado",
+ "voiceMicDeniedDesc": "Conceda acceso al micrófono en la configuración del sistema.",
+ "voiceMicUnavailable": "Micrófono no disponible",
+ "voiceOpenSystemSettings": "Abrir configuración del sistema",
+ "voiceRecording": "Grabando…",
+ "voiceTranscribing": "Transcribiendo…",
+ "voiceCancel": "Cancelar",
"shortcutGroup": {
"navigation": "Navegación",
"agent": "Agente",
@@ -887,7 +915,9 @@ sklm: {
"resetZoom": "Restablecer zoom",
"zoomIn": "Acercar",
"zoomOut": "Zoom out",
- "toggleFullScreen": "Alternar pantalla completa"
+ "toggleFullScreen": "Alternar pantalla completa",
+ "voiceToggle": "Alternar entrada de voz",
+ "voiceCancel": "Cancelar entrada de voz"
},
"skills": "Habilidades",
"skillsGlobalPath": "Ruta de habilidades globales",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 34f138e3a..f79b7f25d 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -686,7 +686,8 @@ sklm: {
"projects": "Projets",
"sync": "Synchronisation cloud",
"remoteHosts": "Hôtes distants",
- "info": "Informations"
+ "info": "Informations",
+ "voice": "Voix"
},
"configSync": {
title: "Cloud sync",
@@ -866,6 +867,33 @@ sklm: {
"shortcutSaveFailed": "Impossible d'enregistrer le raccourci.",
"shortcutUnbound": "Non lié",
"shortcutDisable": "Désactiver le raccourci pour {{action}}",
+ "voice": "Voix",
+ "voiceEnable": "Activer la saisie vocale",
+ "voiceMicrophone": "Microphone",
+ "voiceSystemDefault": "Par défaut du système",
+ "voiceLanguages": "Langues",
+ "voiceChineseVariant": "Variante chinoise",
+ "voiceSimplified": "Simplifié",
+ "voiceTraditionalTaiwan": "Traditionnel (Taïwan)",
+ "voiceTraditionalHK": "Traditionnel (Hong Kong)",
+ "voiceModel": "Modèle de transcription",
+ "voiceModelDownload": "Télécharger",
+ "voiceModelDelete": "Supprimer",
+ "voiceModelDownloaded": "Téléchargé",
+ "voiceModelDownloading": "Téléchargement…",
+ "voiceModelNotDownloaded": "Non téléchargé",
+ "voiceModelSize": "{{size}}",
+ "voiceShortcut": "Raccourci",
+ "voiceLocalModels": "Modèles locaux",
+ "voiceNoModelSelected": "Aucun modèle sélectionné",
+ "voiceSelectModel": "Sélectionnez un modèle pour commencer",
+ "voiceMicDenied": "Accès au microphone refusé",
+ "voiceMicDeniedDesc": "Accordez l'accès au microphone dans les paramètres système.",
+ "voiceMicUnavailable": "Microphone non disponible",
+ "voiceOpenSystemSettings": "Ouvrir les paramètres système",
+ "voiceRecording": "Enregistrement…",
+ "voiceTranscribing": "Transcription…",
+ "voiceCancel": "Annuler",
"shortcutGroup": {
"navigation": "Navigation",
"agent": "Agent",
@@ -887,7 +915,9 @@ sklm: {
"resetZoom": "Réinitialiser le zoom",
"zoomIn": "Zoom avant",
"zoomOut": "Zoom arrière",
- "toggleFullScreen": "Basculer en mode plein écran"
+ "toggleFullScreen": "Basculer en mode plein écran",
+ "voiceToggle": "Activer/désactiver la saisie vocale",
+ "voiceCancel": "Annuler la saisie vocale"
},
"skills": "Compétences",
"skillsGlobalPath": "Parcours de compétences global",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 20559bbdf..f46329061 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -695,6 +695,7 @@ sklm: {
sync: "클라우드 동기화",
remoteHosts: "원격 호스트",
info: "정보",
+ voice: "음성",
},
configSync: {
title: "Cloud sync",
@@ -874,6 +875,33 @@ sklm: {
shortcutSaveFailed: "단축키를 저장할 수 없습니다.",
shortcutUnbound: "할당되지 않음",
shortcutDisable: "{{action}} 단축키 비활성화",
+ voice: "음성",
+ voiceEnable: "음성 입력 활성화",
+ voiceMicrophone: "마이크",
+ voiceSystemDefault: "시스템 기본값",
+ voiceLanguages: "언어",
+ voiceChineseVariant: "중국어 변형",
+ voiceSimplified: "간체",
+ voiceTraditionalTaiwan: "번체 (대만)",
+ voiceTraditionalHK: "번체 (홍콩)",
+ voiceModel: "전사 모델",
+ voiceModelDownload: "다운로드",
+ voiceModelDelete: "삭제",
+ voiceModelDownloaded: "다운로드됨",
+ voiceModelDownloading: "다운로드 중…",
+ voiceModelNotDownloaded: "다운로드되지 않음",
+ voiceModelSize: "{{size}}",
+ voiceShortcut: "단축키",
+ voiceLocalModels: "로컬 모델",
+ voiceNoModelSelected: "모델이 선택되지 않음",
+ voiceSelectModel: "시작하려면 모델을 선택하세요",
+ voiceMicDenied: "마이크 접근 거부됨",
+ voiceMicDeniedDesc: "시스템 설정에서 마이크 접근 권한을 허용하세요.",
+ voiceMicUnavailable: "마이크를 사용할 수 없음",
+ voiceOpenSystemSettings: "시스템 설정 열기",
+ voiceRecording: "녹음 중…",
+ voiceTranscribing: "전사 중…",
+ voiceCancel: "취소",
shortcutGroup: {
navigation: "탐색",
agent: "에이전트",
@@ -896,6 +924,8 @@ sklm: {
zoomIn: "확대",
zoomOut: "축소",
toggleFullScreen: "전체 화면 전환",
+ voiceToggle: "음성 입력 전환",
+ voiceCancel: "음성 입력 취소",
},
skills: "스킬",
skillsGlobalPath: "전역 스킬 경로",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 8303cce1c..2cda6c193 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -671,7 +671,8 @@ export const ptBR = {
projects: "Projetos",
sync: "Sincronização",
remoteHosts: "Hosts remotos",
- info: "Sobre"
+ info: "Sobre",
+ voice: "Voz"
},
general: "Geral",
ai: "IA",
@@ -693,6 +694,33 @@ export const ptBR = {
shortcutSaveFailed: "Não foi possível salvar o atalho",
shortcutUnbound: "Sem atalho",
shortcutDisable: "Desativar atalho para {{action}}",
+ voice: "Voz",
+ voiceEnable: "Ativar entrada de voz",
+ voiceMicrophone: "Microfone",
+ voiceSystemDefault: "Padrão do sistema",
+ voiceLanguages: "Idiomas",
+ voiceChineseVariant: "Variante chinesa",
+ voiceSimplified: "Simplificado",
+ voiceTraditionalTaiwan: "Tradicional (Taiwan)",
+ voiceTraditionalHK: "Tradicional (Hong Kong)",
+ voiceModel: "Modelo de transcrição",
+ voiceModelDownload: "Baixar",
+ voiceModelDelete: "Excluir",
+ voiceModelDownloaded: "Baixado",
+ voiceModelDownloading: "Baixando…",
+ voiceModelNotDownloaded: "Não baixado",
+ voiceModelSize: "{{size}}",
+ voiceShortcut: "Atalho",
+ voiceLocalModels: "Modelos locais",
+ voiceNoModelSelected: "Nenhum modelo selecionado",
+ voiceSelectModel: "Selecione um modelo para começar",
+ voiceMicDenied: "Acesso ao microfone negado",
+ voiceMicDeniedDesc: "Conceda acesso ao microfone nas configurações do sistema.",
+ voiceMicUnavailable: "Microfone indisponível",
+ voiceOpenSystemSettings: "Abrir configurações do sistema",
+ voiceRecording: "Gravando…",
+ voiceTranscribing: "Transcrevendo…",
+ voiceCancel: "Cancelar",
shortcutGroup: {
navigation: "Navegação",
agent: "Agente",
@@ -714,7 +742,9 @@ export const ptBR = {
resetZoom: "Redefinir zoom",
zoomIn: "Aumentar zoom",
zoomOut: "Diminuir zoom",
- toggleFullScreen: "Alternar tela completa"
+ toggleFullScreen: "Alternar tela completa",
+ voiceToggle: "Alternar entrada de voz",
+ voiceCancel: "Cancelar entrada de voz"
},
skills: "Habilidades",
skillsGlobalPath: "Caminho global de habilidades",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index e179186a8..17ebb602c 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -695,6 +695,7 @@ sklm: {
sync: "Bulut senkronizasyonu",
remoteHosts: "Uzak ana bilgisayarlar",
info: "Bilgi",
+ voice: "Ses",
},
configSync: {
title: "Bulut senkronizasyonu",
@@ -864,6 +865,33 @@ sklm: {
shortcutSaveFailed: "Kısayol kaydedilemedi.",
shortcutUnbound: "Atanmamış",
shortcutDisable: "{{action}} kısayolunu kapat",
+ voice: "Ses",
+ voiceEnable: "Sesli girişi etkinleştir",
+ voiceMicrophone: "Mikrofon",
+ voiceSystemDefault: "Sistem varsayılanı",
+ voiceLanguages: "Diller",
+ voiceChineseVariant: "Çince varyantı",
+ voiceSimplified: "Basitleştirilmiş",
+ voiceTraditionalTaiwan: "Geleneksel (Tayvan)",
+ voiceTraditionalHK: "Geleneksel (Hong Kong)",
+ voiceModel: "Transkripsiyon modeli",
+ voiceModelDownload: "İndir",
+ voiceModelDelete: "Sil",
+ voiceModelDownloaded: "İndirildi",
+ voiceModelDownloading: "İndiriliyor…",
+ voiceModelNotDownloaded: "İndirilmedi",
+ voiceModelSize: "{{size}}",
+ voiceShortcut: "Kısayol",
+ voiceLocalModels: "Yerel modeller",
+ voiceNoModelSelected: "Model seçilmedi",
+ voiceSelectModel: "Başlamak için bir model seçin",
+ voiceMicDenied: "Mikrofon erişimi reddedildi",
+ voiceMicDeniedDesc: "Sistem ayarlarından mikrofon erişimi verin.",
+ voiceMicUnavailable: "Mikrofon kullanılamıyor",
+ voiceOpenSystemSettings: "Sistem ayarlarını aç",
+ voiceRecording: "Kaydediliyor…",
+ voiceTranscribing: "Transkripsiyon…",
+ voiceCancel: "İptal",
shortcutGroup: {
navigation: "Gezinme",
agent: "Ajan",
@@ -886,6 +914,8 @@ sklm: {
zoomIn: "Yakınlaştır",
zoomOut: "Uzaklaştır",
toggleFullScreen: "Tam ekranı aç/kapat",
+ voiceToggle: "Sesli girişi aç/kapat",
+ voiceCancel: "Sesli girişi iptal et",
},
skills: "Beceriler",
skillsGlobalPath: "Genel beceriler yolu",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 06cb1d5a7..fa7f387ec 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -685,6 +685,7 @@ sklm: {
sync: "云同步",
remoteHosts: "远程主机",
info: "信息",
+ voice: "语音",
},
configSync: {
title: "云同步",
@@ -851,6 +852,33 @@ sklm: {
shortcutSaveFailed: "无法保存快捷键。",
shortcutUnbound: "未绑定",
shortcutDisable: "禁用“{{action}}”快捷键",
+ voice: "语音",
+ voiceEnable: "启用语音输入",
+ voiceMicrophone: "麦克风",
+ voiceSystemDefault: "系统默认",
+ voiceLanguages: "语言",
+ voiceChineseVariant: "中文变体",
+ voiceSimplified: "简体",
+ voiceTraditionalTaiwan: "繁体(台湾)",
+ voiceTraditionalHK: "繁体(香港)",
+ voiceModel: "转写模型",
+ voiceModelDownload: "下载",
+ voiceModelDelete: "删除",
+ voiceModelDownloaded: "已下载",
+ voiceModelDownloading: "下载中…",
+ voiceModelNotDownloaded: "未下载",
+ voiceModelSize: "{{size}}",
+ voiceShortcut: "快捷键",
+ voiceLocalModels: "本地模型",
+ voiceNoModelSelected: "未选择模型",
+ voiceSelectModel: "请选择模型以开始使用",
+ voiceMicDenied: "麦克风权限被拒绝",
+ voiceMicDeniedDesc: "请在系统设置中授予麦克风访问权限。",
+ voiceMicUnavailable: "麦克风不可用",
+ voiceOpenSystemSettings: "打开系统设置",
+ voiceRecording: "正在录音…",
+ voiceTranscribing: "正在转写…",
+ voiceCancel: "取消",
shortcutGroup: {
navigation: "导航",
agent: "智能体",
@@ -873,6 +901,8 @@ sklm: {
zoomIn: "放大",
zoomOut: "缩小",
toggleFullScreen: "切换全屏",
+ voiceToggle: "切换语音输入",
+ voiceCancel: "取消语音输入",
},
skills: "技能",
skillsGlobalPath: "全局技能路径",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index fa9d4e12b..5c06b70c2 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -685,6 +685,7 @@ sklm: {
sync: "雲端同步",
remoteHosts: "遠端主機",
info: "資訊",
+ voice: "語音",
},
configSync: {
title: "雲端同步",
@@ -851,6 +852,33 @@ sklm: {
shortcutSaveFailed: "無法儲存快捷鍵。",
shortcutUnbound: "未繫結",
shortcutDisable: "停用“{{action}}”快捷鍵",
+ voice: "語音",
+ voiceEnable: "啟用語音輸入",
+ voiceMicrophone: "麥克風",
+ voiceSystemDefault: "系統預設",
+ voiceLanguages: "語言",
+ voiceChineseVariant: "中文變體",
+ voiceSimplified: "簡體",
+ voiceTraditionalTaiwan: "繁體(台灣)",
+ voiceTraditionalHK: "繁體(香港)",
+ voiceModel: "轉寫模型",
+ voiceModelDownload: "下載",
+ voiceModelDelete: "刪除",
+ voiceModelDownloaded: "已下載",
+ voiceModelDownloading: "下載中…",
+ voiceModelNotDownloaded: "未下載",
+ voiceModelSize: "{{size}}",
+ voiceShortcut: "快捷鍵",
+ voiceLocalModels: "本機模型",
+ voiceNoModelSelected: "未選擇模型",
+ voiceSelectModel: "請選擇模型以開始使用",
+ voiceMicDenied: "麥克風權限被拒絕",
+ voiceMicDeniedDesc: "請在系統設定中授予麥克風存取權限。",
+ voiceMicUnavailable: "麥克風不可用",
+ voiceOpenSystemSettings: "開啟系統設定",
+ voiceRecording: "正在錄音…",
+ voiceTranscribing: "正在轉寫…",
+ voiceCancel: "取消",
shortcutGroup: {
navigation: "導航",
agent: "智慧體",
@@ -873,6 +901,8 @@ sklm: {
zoomIn: "放大",
zoomOut: "縮小",
toggleFullScreen: "切換全屏",
+ voiceToggle: "切換語音輸入",
+ voiceCancel: "取消語音輸入",
},
skills: "技能",
skillsGlobalPath: "全域性技能路徑",
diff --git a/packages/shared/src/keyboard-shortcuts.ts b/packages/shared/src/keyboard-shortcuts.ts
index 130f022d5..4ec1a4fa1 100644
--- a/packages/shared/src/keyboard-shortcuts.ts
+++ b/packages/shared/src/keyboard-shortcuts.ts
@@ -15,6 +15,8 @@ export const KEYBOARD_SHORTCUT_IDS = [
"zoomIn",
"zoomOut",
"toggleFullScreen",
+ "voiceToggle",
+ "voiceCancel",
] as const;
export type KeyboardShortcutId = (typeof KEYBOARD_SHORTCUT_IDS)[number];
@@ -63,6 +65,16 @@ export const KEYBOARD_SHORTCUTS: readonly KeyboardShortcutDefinition[] = [
defaultBinding: "F11",
macDefaultBinding: "Mod+Ctrl+F",
},
+ {
+ id: "voiceToggle",
+ group: "agent",
+ defaultBinding: "Mod+Shift+V",
+ },
+ {
+ id: "voiceCancel",
+ group: "agent",
+ defaultBinding: "Escape",
+ },
] as const;
/**
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index 95c948a9c..035bfb822 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -80,6 +80,17 @@ export const IPC = {
speechTranscribe: "pi-desktop/speech/transcribe",
speechSynthesize: "pi-desktop/speech/synthesize",
speechGetStatus: "pi-desktop/speech/getStatus",
+ voiceStart: "pi-desktop/voice/start",
+ voiceStop: "pi-desktop/voice/stop",
+ voiceCancel: "pi-desktop/voice/cancel",
+ voiceGetState: "pi-desktop/voice/getState",
+ voiceGetDevices: "pi-desktop/voice/getDevices",
+ voiceGetModels: "pi-desktop/voice/getModels",
+ voiceDownloadModel: "pi-desktop/voice/downloadModel",
+ voiceDeleteModel: "pi-desktop/voice/deleteModel",
+ voiceUpdateSettings: "pi-desktop/voice/updateSettings",
+ voiceCheckPermission: "pi-desktop/voice/checkPermission",
+ voiceRequestPermission: "pi-desktop/voice/requestPermission",
agentCompact: "pi-desktop/agent/compact",
agentAbort: "pi-desktop/agent/abort",
agentStop: "pi-desktop/agent/stop",
@@ -373,6 +384,8 @@ export const IPC = {
providersOauth: "pi-desktop/providers/oauth/event",
mcpOauth: "pi-desktop/mcp/oauth/event",
updatesState: "pi-desktop/updates/event/state",
+ voiceStateChanged: "pi-desktop/voice/event/stateChanged",
+ voiceModelProgress: "pi-desktop/voice/event/modelProgress",
},
} as const;
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index daac475b3..591218516 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -151,9 +151,25 @@ export type AppSettings = {
* disabled when the system prefers reduced motion.
*/
smoothStreaming?: boolean;
+ /** Voice input settings (D-voice-runtime). */
+ voice?: VoiceInputSettings;
onboardingDismissed: boolean;
};
+export type ChineseVariant = "simplified" | "traditional-taiwan" | "traditional-hong-kong";
+
+export type VoiceInputSettings = {
+ enabled: boolean;
+ /** Microphone device ID; null means system default. */
+ deviceId: string | null;
+ /** Language codes for recognition, e.g. ["zh", "en"]. */
+ languages: string[];
+ /** Chinese output variant. */
+ chineseVariant: ChineseVariant;
+ /** Catalog model ID. Empty string means no model selected yet. */
+ modelId: string;
+};
+
export type LinkOpenTarget = "workpanel" | "external";
export type ContextUsageDisplay = "remaining" | "used";
diff --git a/packages/voice-runtime/package.json b/packages/voice-runtime/package.json
new file mode 100644
index 000000000..ae244a37f
--- /dev/null
+++ b/packages/voice-runtime/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "@pi-desktop/voice-runtime",
+ "version": "0.15.6",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": {
+ "types": "./src/index.ts",
+ "import": "./dist/index.js"
+ }
+ },
+ "scripts": {
+ "build": "tsc --build",
+ "test": "vitest run",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "opencc-js": "^1.4.1"
+ },
+ "optionalDependencies": {
+ "transcribe-cpp": "0.2.2",
+ "@picovoice/pvrecorder-node": "1.2.9",
+ "@huggingface/hub": "2.15.0"
+ },
+ "devDependencies": {
+ "vitest": "^3.2.1",
+ "typescript": "~5.9.3"
+ }
+}
diff --git a/packages/voice-runtime/src/audio-constants.ts b/packages/voice-runtime/src/audio-constants.ts
new file mode 100644
index 000000000..d1e33cdab
--- /dev/null
+++ b/packages/voice-runtime/src/audio-constants.ts
@@ -0,0 +1,8 @@
+/** Capture sample rate for all voice processing (16 kHz mono). */
+export const CAPTURE_SAMPLE_RATE = 16_000;
+
+/** PvRecorder frame length in samples. */
+export const FRAME_LENGTH = 512;
+
+/** Default streaming chunk size: 0.5 seconds of audio at 16 kHz. */
+export const STREAM_CHUNK_SAMPLES = CAPTURE_SAMPLE_RATE / 2;
diff --git a/packages/voice-runtime/src/chinese.ts b/packages/voice-runtime/src/chinese.ts
new file mode 100644
index 000000000..01edfcf5c
--- /dev/null
+++ b/packages/voice-runtime/src/chinese.ts
@@ -0,0 +1,43 @@
+import type { ChineseVariant } from "./types.js";
+
+type Converter = (text: string) => string;
+
+const converters = new Map<ChineseVariant, Promise<Converter>>();
+
+async function createConverter(variant: ChineseVariant): Promise<Converter> {
+ const { default: OpenCC } = await import("opencc-js");
+ switch (variant) {
+ case "simplified":
+ return OpenCC.Converter({ from: "t", to: "cn" });
+ case "traditional-taiwan":
+ return OpenCC.Converter({ from: "cn", to: "tw" });
+ case "traditional-hong-kong":
+ return OpenCC.Converter({ from: "cn", to: "hk" });
+ }
+}
+
+function converterFor(variant: ChineseVariant): Promise<Converter> {
+ const existing = converters.get(variant);
+ if (existing) return existing;
+
+ const loading = createConverter(variant);
+ converters.set(variant, loading);
+ void loading.catch(() => {
+ if (converters.get(variant) === loading) converters.delete(variant);
+ });
+ return loading;
+}
+
+/** Check whether a language code represents Chinese (Mandarin or Cantonese). */
+export function isChineseLanguage(language: string): boolean {
+ const base = language.toLowerCase().split("-", 1)[0];
+ return base === "zh" || base === "yue";
+}
+
+/** Convert Chinese text to the specified variant using OpenCC. */
+export async function convertChineseOutput(
+ text: string,
+ variant: ChineseVariant,
+): Promise<string> {
+ return (await converterFor(variant))(text);
+}
diff --git a/packages/voice-runtime/src/externals.d.ts b/packages/voice-runtime/src/externals.d.ts
new file mode 100644
index 000000000..daed7d603
--- /dev/null
+++ b/packages/voice-runtime/src/externals.d.ts
@@ -0,0 +1,50 @@
+/**
+ * Ambient declarations for optional native dependencies.
+ * These modules are loaded dynamically at runtime and may not be installed
+ * during development or on all platforms.
+ */
+
+declare module "opencc-js" {
+ interface ConverterOptions {
+ from: string;
+ to: string;
+ }
+ const OpenCC: {
+ Converter(options: ConverterOptions): (text: string) => string;
+ };
+ export default OpenCC;
+}
+
+declare module "transcribe-cpp" {
+ interface TranscribeModel {
+ transcribe(
+ pcm: Float32Array,
+ options?: { language?: string },
+ ): Promise<{ text: string }>;
+ createSession(): TranscribeSession | null;
+ readonly capabilities: { languages: string[]; supportsStreaming: boolean };
+ dispose(): void;
+ }
+ interface TranscribeSession {
+ stream(options?: { language?: string }): TranscribeStream;
+ }
+ interface TranscribeStream {
+ feed(chunk: Float32Array): void;
+ finalize(): Promise<string>;
+ reset(): void;
+ }
+ const TranscribeModel: {
+ load(modelPath: string): Promise<TranscribeModel>;
+ };
+ export { TranscribeModel };
+}
+
+declare module "@huggingface/hub" {
+ interface DownloadFileOptions {
+ repo: string;
+ path: string;
+ requestInit?: RequestInit;
+ }
+ function downloadFile(options: DownloadFileOptions): Promise<Response | null>;
+ export { downloadFile };
+}
diff --git a/packages/voice-runtime/src/index.ts b/packages/voice-runtime/src/index.ts
new file mode 100644
index 000000000..9a70155fc
--- /dev/null
+++ b/packages/voice-runtime/src/index.ts
@@ -0,0 +1,32 @@
+// Types
+export type {
+ VoicePhase,
+ VoiceState,
+ VoiceResult,
+ VoiceSettings,
+ ChineseVariant,
+ ModelInfo,
+ ModelStatus,
+ ModelState,
+ AudioInputDevice,
+ AudioCapture,
+ AudioCaptureFactory,
+ TranscribeOptions,
+ TranscriptionStream,
+} from "./types.js";
+export { DEFAULT_VOICE_SETTINGS } from "./types.js";
+
+// Constants
+export { CAPTURE_SAMPLE_RATE, FRAME_LENGTH, STREAM_CHUNK_SAMPLES } from "./audio-constants.js";
+
+// Core classes
+export { VoiceController } from "./voice-controller.js";
+export { TranscriptionEngine } from "./transcription-engine.js";
+export { ModelManager } from "./model-manager.js";
+
+// Utilities
+export { PcmChunker } from "./pcm-chunker.js";
+export { convertFrames, computeRms } from "./pcm-utils.js";
+export { isChineseLanguage, convertChineseOutput } from "./chinese.js";
+export { SUPPORTED_LANGUAGES, languageLabel } from "./languages.js";
+export { getCatalog, findModel, getRecommendedModel } from "./model-catalog.js";
diff --git a/packages/voice-runtime/src/languages.ts b/packages/voice-runtime/src/languages.ts
new file mode 100644
index 000000000..b1cf34e1f
--- /dev/null
+++ b/packages/voice-runtime/src/languages.ts
@@ -0,0 +1,22 @@
+/** Common language codes used in voice recognition. */
+export const SUPPORTED_LANGUAGES = [
+ { code: "zh", label: "Chinese (Mandarin)" },
+ { code: "en", label: "English" },
+ { code: "ja", label: "Japanese" },
+ { code: "ko", label: "Korean" },
+ { code: "de", label: "German" },
+ { code: "fr", label: "French" },
+ { code: "es", label: "Spanish" },
+ { code: "pt", label: "Portuguese" },
+ { code: "ru", label: "Russian" },
+ { code: "ar", label: "Arabic" },
+ { code: "yue", label: "Chinese (Cantonese)" },
+] as const;
+
+export type LanguageCode = (typeof SUPPORTED_LANGUAGES)[number]["code"];
+
+/** Find a language label by its code. */
+export function languageLabel(code: string): string {
+ const entry = SUPPORTED_LANGUAGES.find((l) => l.code === code);
+ return entry?.label ?? code;
+}
diff --git a/packages/voice-runtime/src/model-catalog.ts b/packages/voice-runtime/src/model-catalog.ts
new file mode 100644
index 000000000..489a80639
--- /dev/null
+++ b/packages/voice-runtime/src/model-catalog.ts
@@ -0,0 +1,79 @@
+import type { ModelInfo } from "./types.js";
+
+/**
+ * Static model catalog. In a real implementation this would be loaded from
+ * catalog/catalog.json and catalog/recommendations.json. For now we include
+ * a curated set of recommended models inline.
+ */
+const CATALOG: ModelInfo[] = [
+ {
+ id: "whisper-large-v3-turbo",
+ name: "Whisper Large V3 Turbo",
+ description: "Fast and accurate multilingual model (Q8 quantized)",
+ languages: ["zh", "en", "ja", "ko", "de", "fr", "es", "pt", "ru", "ar", "yue"],
+ sizeBytes: 1_654_846_464,
+ hfRepo: "handy-computer/whisper-large-v3-turbo-GGUF",
+ hfFilename: "ggml-large-v3-turbo-q8_0.bin",
+ sha256: "",
+ supportsStreaming: false,
+ recommended: true,
+ },
+ {
+ id: "whisper-small",
+ name: "Whisper Small",
+ description: "Lightweight multilingual model (Q8 quantized)",
+ languages: ["zh", "en", "ja", "ko", "de", "fr", "es", "pt", "ru", "ar"],
+ sizeBytes: 466_616_320,
+ hfRepo: "handy-computer/whisper-small-GGUF",
+ hfFilename: "ggml-small-q8_0.bin",
+ sha256: "",
+ supportsStreaming: false,
+ recommended: false,
+ },
+ {
+ id: "whisper-medium",
+ name: "Whisper Medium",
+ description: "Balanced multilingual model (Q8 quantized)",
+ languages: ["zh", "en", "ja", "ko", "de", "fr", "es", "pt", "ru", "ar"],
+ sizeBytes: 809_181_184,
+ hfRepo: "handy-computer/whisper-medium-GGUF",
+ hfFilename: "ggml-medium-q8_0.bin",
+ sha256: "",
+ supportsStreaming: false,
+ recommended: false,
+ },
+ {
+ id: "sensevoice-small",
+ name: "SenseVoice Small",
+ description: "Compact Chinese/English model with good accuracy",
+ languages: ["zh", "en", "ja", "ko", "yue"],
+ sizeBytes: 466_000_000,
+ hfRepo: "handy-computer/SenseVoiceSmall-GGUF",
+ hfFilename: "ggml-sensevoice-small-q8_0.bin",
+ sha256: "",
+ supportsStreaming: false,
+ recommended: false,
+ },
+];
+
+/** Get the full model catalog. */
+export function getCatalog(): readonly ModelInfo[] {
+ return CATALOG;
+}
+
+/** Find a model by its ID. */
+export function findModel(modelId: string): ModelInfo | undefined {
+ return CATALOG.find((m) => m.id === modelId);
+}
+
+/** Get the recommended model for the given languages. */
+export function getRecommendedModel(languages: string[]): ModelInfo {
+ // Prefer a model that covers all requested languages
+ const covering = CATALOG.filter(
+ (m) => m.recommended && languages.every((l) => m.languages.includes(l)),
+ );
+ if (covering.length > 0) return covering[0]!;
+
+ // Fallback: first recommended, then first in catalog
+ return CATALOG.find((m) => m.recommended) ?? CATALOG[0]!;
+}
diff --git a/packages/voice-runtime/src/model-downloader.ts b/packages/voice-runtime/src/model-downloader.ts
new file mode 100644
index 000000000..47be63b53
--- /dev/null
+++ b/packages/voice-runtime/src/model-downloader.ts
@@ -0,0 +1,67 @@
+import { mkdir } from "node:fs/promises";
+import path from "node:path";
+import type { ModelInfo } from "./types.js";
+
+/**
+ * Download a model from HuggingFace Hub to targetDir.
+ * Yields progress 0–1. Supports abort via signal.
+ */
+export async function* downloadModel(
+ info: ModelInfo,
+ targetDir: string,
+ signal?: AbortSignal,
+): AsyncGenerator<number, void, unknown> {
+ await mkdir(targetDir, { recursive: true });
+
+ const targetPath = path.join(targetDir, info.hfFilename);
+
+ // Dynamic import of @huggingface/hub
+ const { downloadFile } = await import("@huggingface/hub");
+
+ const response = await downloadFile({
+ repo: info.hfRepo,
+ path: info.hfFilename,
+ requestInit: signal ? { signal } : undefined,
+ });
+
+ if (!response || !response.body) {
+ throw new Error(`Failed to download model: no response body`);
+ }
+
+ const contentLength = Number(response.headers.get("content-length") || info.sizeBytes);
+ let received = 0;
+
+ const { createWriteStream } = await import("node:fs");
+ const writer = createWriteStream(targetPath);
+
+ try {
+ const reader = response.body.getReader();
+
+ while (true) {
+ if (signal?.aborted) {
+ reader.cancel();
+ throw new DOMException("Download aborted", "AbortError");
+ }
+
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ writer.write(Buffer.from(value));
+ received += value.byteLength;
+ yield contentLength > 0 ? received / contentLength : 0;
+ }
+
+ await new Promise<void>((resolve, reject) => {
+ writer.end(() => resolve());
+ writer.on("error", reject);
+ });
+
+ yield 1;
+ } catch (error) {
+ writer.destroy();
+ // Clean up partial file
+ const { unlink } = await import("node:fs/promises");
+ await unlink(targetPath).catch(() => {});
+ throw error;
+ }
+}
diff --git a/packages/voice-runtime/src/model-manager.ts b/packages/voice-runtime/src/model-manager.ts
new file mode 100644
index 000000000..88f15d4d0
--- /dev/null
+++ b/packages/voice-runtime/src/model-manager.ts
@@ -0,0 +1,173 @@
+import { EventEmitter } from "node:events";
+import { existsSync } from "node:fs";
+import path from "node:path";
+import type { ModelInfo, ModelState, ModelStatus } from "./types.js";
+import { findModel, getCatalog } from "./model-catalog.js";
+
+/**
+ * Manages model discovery, download, loading, and unloading.
+ *
+ * - Models are cached in `cacheDir` (typically ~/.cache/pi-desktop/voice-models/).
+ * - Loading uses transcribe-cpp's TranscribeModel (lazy-imported).
+ * - Only one model is loaded at a time.
+ */
+export class ModelManager extends EventEmitter {
+ private states = new Map<string, ModelState>();
+ private loadedModelId: string | null = null;
+ private loadedModel: unknown = null; // TranscribeModel instance (lazy typed)
+
+ constructor(private readonly cacheDir: string) {
+ super();
+ this.initializeStates();
+ }
+
+ private initializeStates(): void {
+ for (const info of getCatalog()) {
+ const localPath = this.modelPath(info);
+ const downloaded = existsSync(localPath);
+ this.states.set(info.id, {
+ info,
+ status: downloaded ? "downloaded" : "not-downloaded",
+ localPath: downloaded ? localPath : undefined,
+ });
+ }
+ }
+
+ private modelPath(info: ModelInfo): string {
+ return path.join(this.cacheDir, info.id, info.hfFilename);
+ }
+
+ /** Get all known model states. */
+ getAllStates(): ModelState[] {
+ return [...this.states.values()];
+ }
+
+ /** Get a single model state. */
+ getState(modelId: string): ModelState | undefined {
+ return this.states.get(modelId);
+ }
+
+ /** Get the currently loaded model ID. */
+ getLoadedModelId(): string | null {
+ return this.loadedModelId;
+ }
+
+ /**
+ * Download a model from HuggingFace Hub with progress reporting.
+ * Returns an async generator yielding progress 0–1.
+ */
+ async *download(
+ modelId: string,
+ signal?: AbortSignal,
+ ): AsyncGenerator<number, void, unknown> {
+ const info = findModel(modelId);
+ if (!info) throw new Error(`Unknown model: ${modelId}`);
+
+ const state = this.states.get(modelId)!;
+ if (state.status === "downloaded" || state.status === "loaded") {
+ yield 1;
+ return;
+ }
+
+ this.updateState(modelId, { status: "downloading", downloadProgress: 0 });
+
+ try {
+ const { downloadModel } = await import("./model-downloader.js");
+ const targetDir = path.join(this.cacheDir, modelId);
+
+ for await (const progress of downloadModel(info, targetDir, signal)) {
+ this.updateState(modelId, { status: "downloading", downloadProgress: progress });
+ yield progress;
+ }
+
+ const localPath = this.modelPath(info);
+ this.updateState(modelId, {
+ status: "downloaded",
+ downloadProgress: 1,
+ localPath,
+ });
+ yield 1;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.updateState(modelId, {
+ status: "error",
+ error: `Download failed: ${message}`,
+ });
+ throw error;
+ }
+ }
+
+ /** Delete a downloaded model. */
+ async deleteModel(modelId: string): Promise<void> {
+ if (this.loadedModelId === modelId) {
+ this.unload();
+ }
+
+ const info = findModel(modelId);
+ if (!info) return;
+
+ const modelDir = path.join(this.cacheDir, modelId);
+ const { rm } = await import("node:fs/promises");
+ await rm(modelDir, { recursive: true, force: true });
+ this.updateState(modelId, { status: "not-downloaded", localPath: undefined });
+ }
+
+ /** Ensure a model is loaded into memory. Lazy-imports transcribe-cpp. */
+ async ensureLoaded(modelId: string): Promise<void> {
+ if (this.loadedModelId === modelId && this.loadedModel) return;
+
+ const state = this.states.get(modelId);
+ if (!state || !state.localPath) {
+ throw new Error(`Model ${modelId} is not downloaded`);
+ }
+
+ // Unload any previously loaded model
+ this.unload();
+
+ this.updateState(modelId, { status: "loading" });
+
+ try {
+ const transcribeCpp = await import("transcribe-cpp");
+ const model = await transcribeCpp.TranscribeModel.load(state.localPath);
+ this.loadedModel = model;
+ this.loadedModelId = modelId;
+ this.updateState(modelId, { status: "loaded" });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.updateState(modelId, { status: "error", error: `Load failed: ${message}` });
+ throw error;
+ }
+ }
+
+ /** Get the loaded transcribe-cpp model instance. */
+ getLoadedModel(): unknown {
+ return this.loadedModel;
+ }
+
+ /** Unload the currently loaded model to free memory. */
+ unload(): void {
+ if (this.loadedModel && typeof (this.loadedModel as any).dispose === "function") {
+ try {
+ (this.loadedModel as any).dispose();
+ } catch {
+ // Best-effort cleanup
+ }
+ }
+ if (this.loadedModelId) {
+ const state = this.states.get(this.loadedModelId);
+ if (state && state.status === "loaded") {
+ this.updateState(this.loadedModelId, { status: "downloaded" });
+ }
+ }
+ this.loadedModel = null;
+ this.loadedModelId = null;
+ }
+
+ private updateState(modelId: string, patch: Partial<ModelState>): void {
+ const current = this.states.get(modelId);
+ if (!current) return;
+ const next = { ...current, ...patch };
+ this.states.set(modelId, next);
+ this.emit("modelStateChanged", modelId, next);
+ }
+}
diff --git a/packages/voice-runtime/src/pcm-chunker.ts b/packages/voice-runtime/src/pcm-chunker.ts
new file mode 100644
index 000000000..726c598ef
--- /dev/null
+++ b/packages/voice-runtime/src/pcm-chunker.ts
@@ -0,0 +1,44 @@
+import { STREAM_CHUNK_SAMPLES } from "./audio-constants.js";
+import { convertFrames } from "./pcm-utils.js";
+
+/**
+ * Coalesces recorder frames into Float32 PCM chunks without timers.
+ * Used for streaming transcription: frames are accumulated and emitted
+ * once the target sample count is reached.
+ */
+export class PcmChunker {
+ private frames: Int16Array[] = [];
+ private sampleCount = 0;
+
+ constructor(
+ private readonly onChunk: (chunk: Float32Array) => void,
+ private readonly targetSamples = STREAM_CHUNK_SAMPLES,
+ ) {
+ if (!Number.isInteger(targetSamples) || targetSamples <= 0) {
+ throw new Error("PCM chunk size must be a positive integer");
+ }
+ }
+
+ push(frame: Int16Array): void {
+ if (frame.length === 0) return;
+ this.frames.push(frame);
+ this.sampleCount += frame.length;
+ if (this.sampleCount >= this.targetSamples) this.emit();
+ }
+
+ flush(): void {
+ if (this.sampleCount > 0) this.emit();
+ }
+
+ discard(): void {
+ this.frames = [];
+ this.sampleCount = 0;
+ }
+
+ private emit(): void {
+ const pcm = convertFrames(this.frames);
+ this.frames = [];
+ this.sampleCount = 0;
+ this.onChunk(pcm);
+ }
+}
diff --git a/packages/voice-runtime/src/pcm-utils.ts b/packages/voice-runtime/src/pcm-utils.ts
new file mode 100644
index 000000000..81bb0a290
--- /dev/null
+++ b/packages/voice-runtime/src/pcm-utils.ts
@@ -0,0 +1,32 @@
+/**
+ * Coalesce Int16 recorder frames into one Float32 PCM buffer.
+ * Kept free of native imports so pure-logic modules can share it.
+ */
+export function convertFrames(frames: readonly Int16Array[]): Float32Array {
+ const sampleCount = frames.reduce((total, frame) => total + frame.length, 0);
+ const pcm = new Float32Array(sampleCount);
+ let offset = 0;
+
+ for (const frame of frames) {
+ for (let i = 0; i < frame.length; i++) {
+ pcm[offset + i] = (frame[i] ?? 0) / 32_768;
+ }
+ offset += frame.length;
+ }
+
+ return pcm;
+}
+
+/**
+ * Compute the RMS (Root Mean Square) volume level from a Float32 PCM buffer.
+ * Returns a value in 0–1 range.
+ */
+export function computeRms(pcm: Float32Array): number {
+ if (pcm.length === 0) return 0;
+ let sum = 0;
+ for (let i = 0; i < pcm.length; i++) {
+ const sample = pcm[i] ?? 0;
+ sum += sample * sample;
+ }
+ return Math.sqrt(sum / pcm.length);
+}
diff --git a/packages/voice-runtime/src/transcription-engine.ts b/packages/voice-runtime/src/transcription-engine.ts
new file mode 100644
index 000000000..9f9f89abd
--- /dev/null
+++ b/packages/voice-runtime/src/transcription-engine.ts
@@ -0,0 +1,95 @@
+import { isChineseLanguage, convertChineseOutput } from "./chinese.js";
+import type { ModelManager } from "./model-manager.js";
+import type { TranscribeOptions, TranscriptionStream, ChineseVariant } from "./types.js";
+
+/**
+ * Wraps transcribe-cpp to provide a simpler transcription API.
+ * Handles model lifecycle through ModelManager.
+ */
+export class TranscriptionEngine {
+ constructor(readonly modelManager: ModelManager) {}
+
+ /**
+ * Transcribe a complete PCM audio buffer.
+ * Automatically loads the model if needed.
+ */
+ async transcribe(
+ pcm: Float32Array,
+ options: TranscribeOptions,
+ signal?: AbortSignal,
+ ): Promise<string> {
+ const modelId = this.modelManager.getLoadedModelId();
+ if (!modelId) throw new Error("No model loaded");
+
+ const model = this.modelManager.getLoadedModel() as any;
+ if (!model) throw new Error("Model instance not available");
+
+ signal?.throwIfAborted();
+
+ const result = await model.transcribe(pcm, {
+ language: options.language,
+ });
+
+ signal?.throwIfAborted();
+
+ let text: string = typeof result === "string" ? result : result?.text ?? "";
+ text = text.trim();
+
+ // Post-process Chinese output
+ if (text && options.chineseVariant && isChineseLanguage(options.language)) {
+ text = await postProcessChinese(text, options.chineseVariant);
+ }
+
+ return text;
+ }
+
+ /**
+ * Create a streaming transcription session if the loaded model supports it.
+ * Returns null if streaming is not supported.
+ */
+ createStream(options: TranscribeOptions): TranscriptionStream | null {
+ const model = this.modelManager.getLoadedModel() as any;
+ if (!model?.createSession) return null;
+
+ try {
+ const session = model.createSession();
+ if (!session) return null;
+
+ const stream = session.stream({ language: options.language });
+ if (!stream) return null;
+
+ return {
+ feed(chunk: Float32Array): void {
+ stream.feed(chunk);
+ },
+ async finalize(): Promise<string> {
+ let text: string = await stream.finalize();
+ text = text.trim();
+ if (text && options.chineseVariant && isChineseLanguage(options.language)) {
+ text = await postProcessChinese(text, options.chineseVariant);
+ }
+ return text;
+ },
+ cancel(): void {
+ stream.reset?.();
+ },
+ };
+ } catch {
+ return null;
+ }
+ }
+
+ /** Shut down the engine and unload models. */
+ async shutdown(): Promise<void> {
+ this.modelManager.unload();
+ }
+}
+
+async function postProcessChinese(text: string, variant: ChineseVariant): Promise<string> {
+ try {
+ return await convertChineseOutput(text, variant);
+ } catch {
+ // If conversion fails, return original text
+ return text;
+ }
+}
diff --git a/packages/voice-runtime/src/types.ts b/packages/voice-runtime/src/types.ts
new file mode 100644
index 000000000..0ea96d188
--- /dev/null
+++ b/packages/voice-runtime/src/types.ts
@@ -0,0 +1,118 @@
+// ---- Voice Phase ----
+export type VoicePhase =
+ | "idle"
+ | "preparing"
+ | "ready"
+ | "starting"
+ | "listening"
+ | "transcribing"
+ | "done"
+ | "error"
+ | "cancelling";
+
+// ---- Voice State ----
+export interface VoiceState {
+ phase: VoicePhase;
+ /** Recording duration in seconds, updated in real-time during listening. */
+ durationSeconds: number;
+ /** Current volume level 0–1, updated in real-time during listening. */
+ volumeLevel: number;
+ /** Error message when phase is "error". */
+ error?: string;
+ /** Transcription result when phase is "done". */
+ result?: VoiceResult;
+}
+
+export interface VoiceResult {
+ text: string;
+ speechSeconds: number;
+ transcribeSeconds: number;
+ language: string;
+}
+
+// ---- Voice Settings ----
+export type ChineseVariant = "simplified" | "traditional-taiwan" | "traditional-hong-kong";
+
+export interface VoiceSettings {
+ enabled: boolean;
+ /** Device ID; null means system default. */
+ deviceId: string | null;
+ /** Language codes, e.g. ["zh", "en"]. */
+ languages: string[];
+ /** Chinese output variant. */
+ chineseVariant: ChineseVariant;
+ /** Model catalog ID. */
+ modelId: string;
+}
+
+export const DEFAULT_VOICE_SETTINGS: VoiceSettings = {
+ enabled: false,
+ deviceId: null,
+ languages: ["zh", "en"],
+ chineseVariant: "simplified",
+ modelId: "",
+};
+
+// ---- Model ----
+export interface ModelInfo {
+ id: string;
+ name: string;
+ description: string;
+ languages: string[];
+ sizeBytes: number;
+ hfRepo: string;
+ hfFilename: string;
+ sha256: string;
+ supportsStreaming: boolean;
+ recommended: boolean;
+}
+
+export type ModelStatus =
+ | "not-downloaded"
+ | "downloading"
+ | "downloaded"
+ | "loading"
+ | "loaded"
+ | "error";
+
+export interface ModelState {
+ info: ModelInfo;
+ status: ModelStatus;
+ downloadProgress?: number;
+ localPath?: string;
+ error?: string;
+}
+
+// ---- Audio Capture Interface ----
+export interface AudioInputDevice {
+ deviceId: string;
+ label: string;
+ isDefault: boolean;
+}
+
+export interface AudioCapture {
+ start(): Promise<void>;
+ stop(): Promise<Float32Array>;
+ cancel(): void;
+ onFrame(cb: (frame: Int16Array) => void): void;
+ readonly isActive: boolean;
+}
+
+export interface AudioCaptureFactory {
+ getDevices(): Promise<AudioInputDevice[]>;
+ create(deviceId: string | null): AudioCapture;
+ checkPermission(): Promise<"granted" | "denied" | "undetermined">;
+ requestPermission(): Promise<boolean>;
+}
+
+// ---- Transcription ----
+export interface TranscribeOptions {
+ language: string;
+ chineseVariant?: ChineseVariant;
+}
+
+export interface TranscriptionStream {
+ feed(chunk: Float32Array): void;
+ finalize(): Promise<string>;
+ cancel(): void;
+}
diff --git a/packages/voice-runtime/src/voice-controller.ts b/packages/voice-runtime/src/voice-controller.ts
new file mode 100644
index 000000000..c91e0fdd8
--- /dev/null
+++ b/packages/voice-runtime/src/voice-controller.ts
@@ -0,0 +1,266 @@
+import { EventEmitter } from "node:events";
+import { PcmChunker } from "./pcm-chunker.js";
+import { convertFrames, computeRms } from "./pcm-utils.js";
+import { TranscriptionEngine } from "./transcription-engine.js";
+import type {
+ AudioCapture,
+ AudioCaptureFactory,
+ TranscribeOptions,
+ TranscriptionStream,
+ VoicePhase,
+ VoiceResult,
+ VoiceSettings,
+ VoiceState,
+} from "./types.js";
+
+const INITIAL_STATE: VoiceState = {
+ phase: "idle",
+ durationSeconds: 0,
+ volumeLevel: 0,
+};
+
+/**
+ * Manages the full voice input lifecycle:
+ * prepare → start → listen → stop → transcribe → result.
+ *
+ * Events:
+ * - "stateChange" (state: VoiceState)
+ * - "error" (error: Error)
+ */
+export class VoiceController extends EventEmitter {
+ private _state: VoiceState = { ...INITIAL_STATE };
+ private capture: AudioCapture | null = null;
+ private stream: TranscriptionStream | null = null;
+ private allFrames: Int16Array[] = [];
+ private chunker: PcmChunker | null = null;
+ private abort: AbortController | null = null;
+ private startedAt = 0;
+ private disposed = false;
+
+ constructor(
+ private readonly engine: TranscriptionEngine,
+ private readonly captureFactory: AudioCaptureFactory,
+ private readonly getSettings: () => VoiceSettings,
+ ) {
+ super();
+ }
+
+ get state(): VoiceState {
+ return this._state;
+ }
+
+ /** Pre-load the model for faster first recording. */
+ async prepare(): Promise<void> {
+ if (this.disposed) return;
+
+ const settings = this.getSettings();
+ if (!settings.modelId) {
+ throw new Error("No model selected");
+ }
+
+ this.setState({ phase: "preparing", durationSeconds: 0, volumeLevel: 0 });
+
+ try {
+ await this.engine.modelManager.ensureLoaded(settings.modelId);
+ this.setState({ phase: "ready", durationSeconds: 0, volumeLevel: 0 });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.setState({ phase: "error", durationSeconds: 0, volumeLevel: 0, error: message });
+ throw error;
+ }
+ }
+
+ /** Start recording. Auto-prepares the model if needed. */
+ async start(): Promise<void> {
+ if (this.disposed) throw new Error("Controller is disposed");
+
+ const { phase } = this._state;
+ if (phase !== "idle" && phase !== "ready") {
+ throw new Error(`Cannot start from phase: ${phase}`);
+ }
+
+ const settings = this.getSettings();
+ if (!settings.modelId) throw new Error("No model selected");
+
+ this.abort = new AbortController();
+
+ // Prepare model if not ready
+ if (phase !== "ready") {
+ await this.prepare();
+ }
+
+ this.setState({ phase: "starting", durationSeconds: 0, volumeLevel: 0 });
+
+ try {
+ // Set up streaming transcription if supported
+ const transcribeOpts: TranscribeOptions = {
+ language: settings.languages[0] ?? "en",
+ chineseVariant: settings.chineseVariant,
+ };
+ this.stream = this.engine.createStream(transcribeOpts);
+
+ // Set up PCM chunker for streaming
+ this.chunker = new PcmChunker((chunk) => {
+ this.stream?.feed(chunk);
+ });
+
+ // Reset frame collection
+ this.allFrames = [];
+
+ // Create and start capture
+ this.capture = this.captureFactory.create(settings.deviceId);
+ this.capture.onFrame((frame) => {
+ if (this._state.phase !== "listening") return;
+
+ // Collect Int16 frame for batch fallback
+ this.allFrames.push(frame);
+
+ // Feed to streaming chunker
+ this.chunker?.push(frame);
+
+ // Compute volume from Int16 samples
+ let sum = 0;
+ for (let i = 0; i < frame.length; i++) {
+ const v = (frame[i] ?? 0) / 32_768;
+ sum += v * v;
+ }
+ const rms = frame.length > 0 ? Math.sqrt(sum / frame.length) : 0;
+
+ // Update volume and duration
+ const elapsed = (performance.now() - this.startedAt) / 1000;
+ this.setState({
+ ...this._state,
+ phase: "listening",
+ durationSeconds: elapsed,
+ volumeLevel: rms,
+ });
+ this.emit("volumeLevel", rms);
+ });
+
+ await this.capture.start();
+ this.startedAt = performance.now();
+ this.setState({ phase: "listening", durationSeconds: 0, volumeLevel: 0 });
+ } catch (error) {
+ this.cleanup();
+ const message = error instanceof Error ? error.message : String(error);
+ this.setState({ phase: "error", durationSeconds: 0, volumeLevel: 0, error: message });
+ throw error;
+ }
+ }
+
+ /** Stop recording and transcribe the captured audio. */
+ async stop(): Promise<VoiceResult> {
+ if (this._state.phase !== "listening") {
+ throw new Error(`Cannot stop from phase: ${this._state.phase}`);
+ }
+
+ const settings = this.getSettings();
+ const speechSeconds = (performance.now() - this.startedAt) / 1000;
+
+ this.setState({ ...this._state, phase: "transcribing" });
+
+ try {
+ // Stop capture
+ if (this.capture) {
+ await this.capture.stop();
+ }
+
+ // Flush remaining chunks
+ this.chunker?.flush();
+
+ const transcribeStart = performance.now();
+ let text: string;
+
+ if (this.stream) {
+ // Streaming path: finalize the stream
+ try {
+ text = await this.stream.finalize();
+ } catch {
+ // Streaming failed, fall back to batch
+ text = await this.batchTranscribe(settings);
+ }
+ } else {
+ // Batch path
+ text = await this.batchTranscribe(settings);
+ }
+
+ const transcribeSeconds = (performance.now() - transcribeStart) / 1000;
+
+ const result: VoiceResult = {
+ text,
+ speechSeconds,
+ transcribeSeconds,
+ language: settings.languages[0] ?? "en",
+ };
+
+ this.setState({
+ phase: "done",
+ durationSeconds: speechSeconds,
+ volumeLevel: 0,
+ result,
+ });
+
+ this.cleanup();
+ return result;
+ } catch (error) {
+ this.cleanup();
+ const message = error instanceof Error ? error.message : String(error);
+ this.setState({
+ phase: "error",
+ durationSeconds: speechSeconds,
+ volumeLevel: 0,
+ error: message,
+ });
+ throw error;
+ }
+ }
+
+ /** Cancel recording without transcribing. */
+ cancel(): void {
+ if (this._state.phase === "idle") return;
+
+ this.setState({ phase: "cancelling", durationSeconds: 0, volumeLevel: 0 });
+ this.abort?.abort();
+ this.stream?.cancel();
+
+ if (this.capture?.isActive) {
+ this.capture.cancel();
+ }
+
+ this.cleanup();
+ this.setState({ ...INITIAL_STATE });
+ }
+
+ /** Release all resources. */
+ dispose(): void {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.cancel();
+ this.removeAllListeners();
+ }
+
+ private async batchTranscribe(settings: VoiceSettings): Promise<string> {
+ const pcm = convertFrames(this.allFrames);
+ return this.engine.transcribe(
+ pcm,
+ {
+ language: settings.languages[0] ?? "en",
+ chineseVariant: settings.chineseVariant,
+ },
+ this.abort?.signal,
+ );
+ }
+
+ private cleanup(): void {
+ this.capture = null;
+ this.stream = null;
+ this.chunker = null;
+ this.allFrames = [];
+ this.abort = null;
+ }
+
+ private setState(state: VoiceState): void {
+ this._state = state;
+ this.emit("stateChange", state);
+ }
+}
diff --git a/packages/voice-runtime/test/chinese.test.ts b/packages/voice-runtime/test/chinese.test.ts
new file mode 100644
index 000000000..eb20c1f5d
--- /dev/null
+++ b/packages/voice-runtime/test/chinese.test.ts
@@ -0,0 +1,33 @@
+import { describe, it, expect } from "vitest";
+import { isChineseLanguage } from "../src/chinese.js";
+
+describe("isChineseLanguage", () => {
+ it("detects zh as Chinese", () => {
+ expect(isChineseLanguage("zh")).toBe(true);
+ });
+
+ it("detects zh-CN as Chinese", () => {
+ expect(isChineseLanguage("zh-CN")).toBe(true);
+ });
+
+ it("detects zh-TW as Chinese", () => {
+ expect(isChineseLanguage("zh-TW")).toBe(true);
+ });
+
+ it("detects yue as Chinese (Cantonese)", () => {
+ expect(isChineseLanguage("yue")).toBe(true);
+ });
+
+ it("rejects en", () => {
+ expect(isChineseLanguage("en")).toBe(false);
+ });
+
+ it("rejects ja", () => {
+ expect(isChineseLanguage("ja")).toBe(false);
+ });
+
+ it("is case-insensitive", () => {
+ expect(isChineseLanguage("ZH")).toBe(true);
+ expect(isChineseLanguage("Zh-cn")).toBe(true);
+ });
+});
diff --git a/packages/voice-runtime/test/languages.test.ts b/packages/voice-runtime/test/languages.test.ts
new file mode 100644
index 000000000..af540d528
--- /dev/null
+++ b/packages/voice-runtime/test/languages.test.ts
@@ -0,0 +1,21 @@
+import { describe, it, expect } from "vitest";
+import { SUPPORTED_LANGUAGES, languageLabel } from "../src/languages.js";
+
+describe("SUPPORTED_LANGUAGES", () => {
+ it("contains at least Chinese and English", () => {
+ const codes = SUPPORTED_LANGUAGES.map((l) => l.code);
+ expect(codes).toContain("zh");
+ expect(codes).toContain("en");
+ });
+});
+
+describe("languageLabel", () => {
+ it("returns label for known code", () => {
+ expect(languageLabel("zh")).toBe("Chinese (Mandarin)");
+ expect(languageLabel("en")).toBe("English");
+ });
+
+ it("returns code itself for unknown language", () => {
+ expect(languageLabel("xx")).toBe("xx");
+ });
+});
diff --git a/packages/voice-runtime/test/model-catalog.test.ts b/packages/voice-runtime/test/model-catalog.test.ts
new file mode 100644
index 000000000..1e3914f0a
--- /dev/null
+++ b/packages/voice-runtime/test/model-catalog.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect } from "vitest";
+import { getCatalog, findModel, getRecommendedModel } from "../src/model-catalog.js";
+
+describe("getCatalog", () => {
+ it("returns a non-empty array", () => {
+ const catalog = getCatalog();
+ expect(catalog.length).toBeGreaterThan(0);
+ });
+
+ it("each model has required fields", () => {
+ for (const model of getCatalog()) {
+ expect(model.id).toBeTruthy();
+ expect(model.name).toBeTruthy();
+ expect(model.languages.length).toBeGreaterThan(0);
+ expect(model.sizeBytes).toBeGreaterThan(0);
+ expect(model.hfRepo).toBeTruthy();
+ expect(model.hfFilename).toBeTruthy();
+ }
+ });
+});
+
+describe("findModel", () => {
+ it("finds a known model", () => {
+ const model = findModel("whisper-large-v3-turbo");
+ expect(model).toBeDefined();
+ expect(model!.name).toContain("Whisper");
+ });
+
+ it("returns undefined for unknown model", () => {
+ expect(findModel("nonexistent")).toBeUndefined();
+ });
+});
+
+describe("getRecommendedModel", () => {
+ it("returns a model for common languages", () => {
+ const model = getRecommendedModel(["zh", "en"]);
+ expect(model).toBeDefined();
+ expect(model.recommended).toBe(true);
+ });
+
+ it("always returns a model even for exotic languages", () => {
+ const model = getRecommendedModel(["xx"]);
+ expect(model).toBeDefined();
+ });
+});
diff --git a/packages/voice-runtime/test/pcm-chunker.test.ts b/packages/voice-runtime/test/pcm-chunker.test.ts
new file mode 100644
index 000000000..42b1469eb
--- /dev/null
+++ b/packages/voice-runtime/test/pcm-chunker.test.ts
@@ -0,0 +1,73 @@
+import { describe, it, expect, vi } from "vitest";
+import { PcmChunker } from "../src/pcm-chunker.js";
+
+describe("PcmChunker", () => {
+ it("throws on invalid chunk size", () => {
+ expect(() => new PcmChunker(() => {}, 0)).toThrow();
+ expect(() => new PcmChunker(() => {}, -1)).toThrow();
+ expect(() => new PcmChunker(() => {}, 1.5)).toThrow();
+ });
+
+ it("does not emit until target samples reached", () => {
+ const onChunk = vi.fn();
+ const chunker = new PcmChunker(onChunk, 10);
+
+ chunker.push(new Int16Array([1, 2, 3]));
+ expect(onChunk).not.toHaveBeenCalled();
+ });
+
+ it("emits when target samples are reached", () => {
+ const onChunk = vi.fn();
+ const chunker = new PcmChunker(onChunk, 4);
+
+ chunker.push(new Int16Array([1, 2]));
+ chunker.push(new Int16Array([3, 4]));
+
+ expect(onChunk).toHaveBeenCalledTimes(1);
+ const chunk = onChunk.mock.calls[0][0];
+ expect(chunk).toBeInstanceOf(Float32Array);
+ expect(chunk.length).toBe(4);
+ });
+
+ it("flush emits remaining samples", () => {
+ const onChunk = vi.fn();
+ const chunker = new PcmChunker(onChunk, 100);
+
+ chunker.push(new Int16Array([10, 20]));
+ expect(onChunk).not.toHaveBeenCalled();
+
+ chunker.flush();
+ expect(onChunk).toHaveBeenCalledTimes(1);
+ expect(onChunk.mock.calls[0][0].length).toBe(2);
+ });
+
+ it("flush does nothing when empty", () => {
+ const onChunk = vi.fn();
+ const chunker = new PcmChunker(onChunk, 10);
+
+ chunker.flush();
+ expect(onChunk).not.toHaveBeenCalled();
+ });
+
+ it("discard clears accumulated frames", () => {
+ const onChunk = vi.fn();
+ const chunker = new PcmChunker(onChunk, 10);
+
+ chunker.push(new Int16Array([1, 2, 3]));
+ chunker.discard();
+ chunker.flush();
+
+ expect(onChunk).not.toHaveBeenCalled();
+ });
+
+ it("ignores empty frames", () => {
+ const onChunk = vi.fn();
+ const chunker = new PcmChunker(onChunk, 2);
+
+ chunker.push(new Int16Array([]));
+ chunker.push(new Int16Array([1, 2]));
+
+ expect(onChunk).toHaveBeenCalledTimes(1);
+ expect(onChunk.mock.calls[0][0].length).toBe(2);
+ });
+});
diff --git a/packages/voice-runtime/test/pcm-utils.test.ts b/packages/voice-runtime/test/pcm-utils.test.ts
new file mode 100644
index 000000000..1e6bd6072
--- /dev/null
+++ b/packages/voice-runtime/test/pcm-utils.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect } from "vitest";
+import { convertFrames, computeRms } from "../src/pcm-utils.js";
+
+describe("convertFrames", () => {
+ it("converts empty array to empty Float32Array", () => {
+ const result = convertFrames([]);
+ expect(result).toBeInstanceOf(Float32Array);
+ expect(result.length).toBe(0);
+ });
+
+ it("converts Int16 to normalized Float32", () => {
+ const frame = new Int16Array([0, 16384, -16384, 32767, -32768]);
+ const result = convertFrames([frame]);
+
+ expect(result.length).toBe(5);
+ expect(result[0]).toBeCloseTo(0, 5);
+ expect(result[1]).toBeCloseTo(0.5, 2);
+ expect(result[2]).toBeCloseTo(-0.5, 2);
+ expect(result[3]).toBeCloseTo(1.0, 2);
+ expect(result[4]).toBeCloseTo(-1.0, 2);
+ });
+
+ it("concatenates multiple frames", () => {
+ const frame1 = new Int16Array([100, 200]);
+ const frame2 = new Int16Array([300]);
+ const result = convertFrames([frame1, frame2]);
+
+ expect(result.length).toBe(3);
+ expect(result[0]).toBeCloseTo(100 / 32768, 5);
+ expect(result[1]).toBeCloseTo(200 / 32768, 5);
+ expect(result[2]).toBeCloseTo(300 / 32768, 5);
+ });
+
+ it("handles single empty frame", () => {
+ const result = convertFrames([new Int16Array([])]);
+ expect(result.length).toBe(0);
+ });
+});
+
+describe("computeRms", () => {
+ it("returns 0 for empty buffer", () => {
+ expect(computeRms(new Float32Array([]))).toBe(0);
+ });
+
+ it("returns 0 for silent audio", () => {
+ expect(computeRms(new Float32Array([0, 0, 0, 0]))).toBe(0);
+ });
+
+ it("computes correct RMS for known values", () => {
+ // RMS of [1, -1, 1, -1] = sqrt(4/4) = 1
+ const pcm = new Float32Array([1, -1, 1, -1]);
+ expect(computeRms(pcm)).toBeCloseTo(1, 5);
+ });
+
+ it("returns value between 0 and 1 for normalized audio", () => {
+ const pcm = new Float32Array([0.5, -0.3, 0.1, -0.7]);
+ const rms = computeRms(pcm);
+ expect(rms).toBeGreaterThan(0);
+ expect(rms).toBeLessThanOrEqual(1);
+ });
+});
diff --git a/packages/voice-runtime/test/voice-controller.test.ts b/packages/voice-runtime/test/voice-controller.test.ts
new file mode 100644
index 000000000..624210d20
--- /dev/null
+++ b/packages/voice-runtime/test/voice-controller.test.ts
@@ -0,0 +1,109 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { VoiceController } from "../src/voice-controller.js";
+import type { AudioCapture, AudioCaptureFactory, VoiceSettings } from "../src/types.js";
+
+// Mock TranscriptionEngine
+function createMockEngine() {
+ return {
+ transcribe: vi.fn().mockResolvedValue("hello world"),
+ createStream: vi.fn().mockReturnValue(null),
+ shutdown: vi.fn(),
+ modelManager: {
+ ensureLoaded: vi.fn().mockResolvedValue(undefined),
+ getLoadedModelId: vi.fn().mockReturnValue("whisper-large-v3-turbo"),
+ getLoadedModel: vi.fn().mockReturnValue({}),
+ unload: vi.fn(),
+ },
+ };
+}
+
+// Mock AudioCaptureFactory
+function createMockCaptureFactory(): AudioCaptureFactory {
+ let frameCallback: ((frame: Int16Array) => void) | null = null;
+
+ const capture: AudioCapture = {
+ start: vi.fn().mockResolvedValue(undefined),
+ stop: vi.fn().mockResolvedValue(new Float32Array([])),
+ cancel: vi.fn(),
+ onFrame: vi.fn((cb) => { frameCallback = cb; }),
+ get isActive() { return true; },
+ };
+
+ return {
+ getDevices: vi.fn().mockResolvedValue([]),
+ create: vi.fn().mockReturnValue(capture),
+ checkPermission: vi.fn().mockResolvedValue("granted"),
+ requestPermission: vi.fn().mockResolvedValue(true),
+ };
+}
+
+function defaultSettings(): VoiceSettings {
+ return {
+ enabled: true,
+ deviceId: null,
+ languages: ["zh", "en"],
+ chineseVariant: "simplified",
+ modelId: "whisper-large-v3-turbo",
+ };
+}
+
+describe("VoiceController", () => {
+ let engine: ReturnType<typeof createMockEngine>;
+ let factory: AudioCaptureFactory;
+ let settings: VoiceSettings;
+ let controller: VoiceController;
+
+ beforeEach(() => {
+ engine = createMockEngine();
+ factory = createMockCaptureFactory();
+ settings = defaultSettings();
+ controller = new VoiceController(engine as any, factory, () => settings);
+ });
+
+ it("starts in idle state", () => {
+ expect(controller.state.phase).toBe("idle");
+ });
+
+ it("prepare transitions to ready", async () => {
+ await controller.prepare();
+ expect(controller.state.phase).toBe("ready");
+ });
+
+ it("prepare throws if no model selected", async () => {
+ settings.modelId = "";
+ await expect(controller.prepare()).rejects.toThrow("No model selected");
+ });
+
+ it("start transitions through states", async () => {
+ const phases: string[] = [];
+ controller.on("stateChange", (s) => phases.push(s.phase));
+
+ await controller.start();
+ expect(phases).toContain("preparing");
+ expect(phases).toContain("starting");
+ expect(controller.state.phase).toBe("listening");
+ });
+
+ it("cancel returns to idle", async () => {
+ await controller.start();
+ controller.cancel();
+ expect(controller.state.phase).toBe("idle");
+ });
+
+ it("cannot start from non-idle/ready phase", async () => {
+ await controller.start();
+ await expect(controller.start()).rejects.toThrow("Cannot start from phase");
+ });
+
+ it("dispose prevents further use", async () => {
+ controller.dispose();
+ await expect(controller.start()).rejects.toThrow("disposed");
+ });
+
+ it("emits stateChange events", async () => {
+ const listener = vi.fn();
+ controller.on("stateChange", listener);
+ await controller.start();
+ expect(listener).toHaveBeenCalled();
+ });
+});
diff --git a/packages/voice-runtime/tsconfig.json b/packages/voice-runtime/tsconfig.json
new file mode 100644
index 000000000..d231bbc57
--- /dev/null
+++ b/packages/voice-runtime/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "outDir": "dist",
+ "rootDir": "src",
+ "composite": true
+ },
+ "include": ["src"]
+}
diff --git a/packages/voice-runtime/vitest.config.ts b/packages/voice-runtime/vitest.config.ts
new file mode 100644
index 000000000..8b5840aca
--- /dev/null
+++ b/packages/voice-runtime/vitest.config.ts
@@ -0,0 +1,7 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["test/**/*.test.ts"],
+ },
+});