Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(realtime): browser PCM worklet + /ws/audio client + voice-mode settings toggle
Ruben Lütked762bbaefc6b
diff --git a/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.tsnew file mode 100644index 0000000000..4a981ea4e9--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useVoiceMode.ts@@ -0,0 +1,30 @@+import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";++type VoiceModeResp = { mode: string; realtime_available: boolean; active_provider: string | null };++export function useVoiceMode() {+ const qc = useQueryClient();+ const q = useQuery<VoiceModeResp>({+ queryKey: ["voice-mode"],+ queryFn: async () => (await fetch("/api/settings/voice-mode")).json(),+ });+ const m = useMutation({+ mutationFn: async (mode: string) => {+ const r = await fetch("/api/settings/voice-mode", {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ mode, persist: true }),+ });+ if (!r.ok) throw new Error(await r.text());+ return r.json();+ },+ onSuccess: () => qc.invalidateQueries({ queryKey: ["voice-mode"] }),+ });+ return {+ mode: q.data?.mode ?? "pipeline",+ realtimeAvailable: q.data?.realtime_available ?? false,+ setMode: m.mutate,+ isLoading: q.isLoading,+ isSaving: m.isPending,+ };+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 768a33ec64..b22d571eb6 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1008,6 +1008,11 @@"save": "Team-Modus speichern"},"app_settings_group_title": "App-Einstellungen",+ "realtime_voice": {+ "title": "Echtzeit-Sprache (Browser)",+ "description": "Vollduplex-Sprachdialog direkt im Browser (OpenAI). Standardmäßig aus.",+ "unavailable": "Benötigt einen OpenAI-Schlüssel. Es wird die Standard-Sprachausgabe verwendet."+ },"jarvis_api": {"title": "{name} API","key_label": "API-Schlüssel",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex dc49249b16..0fafbd6705 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1009,6 +1009,11 @@"save": "Save team mode"},"app_settings_group_title": "App settings",+ "realtime_voice": {+ "title": "Realtime voice (browser)",+ "description": "Full-duplex speech-to-speech in the browser (OpenAI). Off by default.",+ "unavailable": "Needs an OpenAI key. Using standard voice."+ },"jarvis_api": {"title": "{name} API","key_label": "API key",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex af27a0a0b1..251b1cae7f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1008,6 +1008,11 @@"save": "Guardar modo equipo"},"app_settings_group_title": "Ajustes de la app",+ "realtime_voice": {+ "title": "Voz en tiempo real (navegador)",+ "description": "Conversación de voz dúplex completo directamente en el navegador (OpenAI). Desactivado de forma predeterminada.",+ "unavailable": "Necesita una clave de OpenAI. Se usa la voz estándar."+ },"jarvis_api": {"title": "{name} API","key_label": "Clave de API",diff --git a/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts b/jarvis/ui/web/frontend/src/lib/pcm-worklet.tsnew file mode 100644index 0000000000..993e143e9f--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/pcm-worklet.ts@@ -0,0 +1,71 @@+// Standalone AudioWorklet module (loaded via addModule). Not part of the main+// bundle graph. tsconfig lib lacks AudioWorklet globals, so declare them here.+// `export {}` makes this file a module so the declarations below stay scoped+// to it (isolatedModules requires every file to be a module or a script; as a+// script these ambient declarations would otherwise leak into the rest of the+// app's type-check).+export {};++declare const sampleRate: number;+declare function registerProcessor(name: string, ctor: unknown): void;+declare class AudioWorkletProcessor {+ readonly port: MessagePort;+ constructor();+ process(inputs: Float32Array[][], outputs: Float32Array[][]): boolean;+}++function floatToInt16(float32: Float32Array): ArrayBuffer {+ const out = new Int16Array(float32.length);+ for (let i = 0; i < float32.length; i++) {+ const s = Math.max(-1, Math.min(1, float32[i]));+ out[i] = s < 0 ? s * 0x8000 : s * 0x7fff;+ }+ return out.buffer;+}++class PcmCapture extends AudioWorkletProcessor {+ process(inputs: Float32Array[][]): boolean {+ const ch = inputs[0]?.[0];+ if (ch && ch.length) this.port.postMessage(floatToInt16(ch), [floatToInt16(ch)]);+ return true;+ }+}++class PcmPlayback extends AudioWorkletProcessor {+ private queue: Float32Array[] = [];+ constructor() {+ super();+ this.port.onmessage = (e: MessageEvent) => {+ const msg = e.data as { type: string; data?: ArrayBuffer };+ if (msg.type === "flush") this.queue = [];+ else if (msg.type === "pcm" && msg.data) {+ const i16 = new Int16Array(msg.data);+ const f32 = new Float32Array(i16.length);+ for (let i = 0; i < i16.length; i++) f32[i] = i16[i] / 0x8000;+ this.queue.push(f32);+ }+ };+ }+ process(_inputs: Float32Array[][], outputs: Float32Array[][]): boolean {+ const out = outputs[0]?.[0];+ if (!out) return true;+ let filled = 0;+ while (filled < out.length && this.queue.length) {+ const head = this.queue[0];+ const n = Math.min(head.length, out.length - filled);+ out.set(head.subarray(0, n), filled);+ filled += n;+ if (n === head.length) this.queue.shift();+ else this.queue[0] = head.subarray(n);+ }+ return true;+ }+}++registerProcessor("pcm-capture", PcmCapture);+registerProcessor("pcm-playback", PcmPlayback);++// (Note: the backend advertises 24 kHz TTS output while the browser+// AudioContext runs at its own rate — Phase 1 accepts minor pitch drift by+// playing 24 kHz samples through the context; a resampling playback pass is a+// Phase-2 polish item, logged here so it is not silently skipped.)diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.tsnew file mode 100644index 0000000000..2ea38a5331--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.test.ts@@ -0,0 +1,13 @@+import { describe, it, expect, beforeEach } from "vitest";+import { buildAudioSocketUrl } from "./realtimeAudio";++describe("realtime audio client", () => {+ beforeEach(() => {+ // @ts-expect-error test shim+ global.window = { location: { protocol: "https:", host: "app.example" }, __JARVIS_TOKEN: "tok" };+ });++ it("builds a wss /ws/audio url with the token", () => {+ expect(buildAudioSocketUrl()).toBe("wss://app.example/ws/audio?token=tok");+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts b/jarvis/ui/web/frontend/src/lib/realtimeAudio.tsnew file mode 100644index 0000000000..79a28e1e83--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/realtimeAudio.ts@@ -0,0 +1,70 @@+// Dedicated /ws/audio client for realtime voice. Separate from the JSON-only+// WSClient (src/lib/ws.ts): this one carries binary int16 PCM (arraybuffer).++export function buildAudioSocketUrl(): string {+ const proto = window.location.protocol === "https:" ? "wss" : "ws";+ const host = window.location.host;+ const token = (window as unknown as { __JARVIS_TOKEN?: string }).__JARVIS_TOKEN;+ const query = token ? `?token=${encodeURIComponent(token)}` : "";+ return `${proto}://${host}/ws/audio${query}`;+}++export type RealtimeCallbacks = {+ onTranscript?: (text: string, isFinal: boolean) => void;+ onStatus?: (status: string) => void;+};++export class RealtimeAudioClient {+ private ws: WebSocket | null = null;+ private ctx: AudioContext | null = null;+ private captureNode: AudioWorkletNode | null = null;+ private playbackNode: AudioWorkletNode | null = null;+ private stream: MediaStream | null = null;++ constructor(private cb: RealtimeCallbacks = {}) {}++ async connect(): Promise<void> {+ this.ctx = new AudioContext();+ await this.ctx.audioWorklet.addModule(new URL("./pcm-worklet.ts", import.meta.url));++ this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });+ const src = this.ctx.createMediaStreamSource(this.stream);+ this.captureNode = new AudioWorkletNode(this.ctx, "pcm-capture");+ this.playbackNode = new AudioWorkletNode(this.ctx, "pcm-playback");+ this.playbackNode.connect(this.ctx.destination);+ src.connect(this.captureNode);++ this.ws = new WebSocket(buildAudioSocketUrl());+ this.ws.binaryType = "arraybuffer";++ this.ws.onopen = () => {+ this.ws?.send(JSON.stringify({ type: "audio_start", sample_rate: this.ctx?.sampleRate ?? 48000 }));+ };+ this.captureNode.port.onmessage = (e) => {+ if (this.ws?.readyState === WebSocket.OPEN) this.ws.send(e.data as ArrayBuffer);+ };+ this.ws.onmessage = (e) => {+ if (typeof e.data === "string") {+ const msg = JSON.parse(e.data);+ if (msg.type === "transcript") this.cb.onTranscript?.(msg.text, !!msg.is_final);+ else if (msg.type === "tts_cancel") this.playbackNode?.port.postMessage({ type: "flush" });+ else this.cb.onStatus?.(msg.type);+ } else {+ this.playbackNode?.port.postMessage({ type: "pcm", data: e.data }, [e.data as ArrayBuffer]);+ }+ };+ }++ async disconnect(): Promise<void> {+ try {+ this.ws?.send(JSON.stringify({ type: "audio_stop" }));+ } catch {+ // socket may already be closing+ }+ this.ws?.close();+ this.stream?.getTracks().forEach((t) => t.stop());+ await this.ctx?.close();+ this.ws = null;+ this.ctx = null;+ }+}diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsxindex bd0c430225..2598d17e76 100644--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx@@ -12,6 +12,7 @@ import { Button } from "@/components/ui/button";import { OverlayTaskbarGroup } from "@/views/settings/OverlayTaskbarGroup";import { LanguagesGroup } from "@/views/settings/LanguagesGroup";import { AppSettingsGroup } from "@/views/settings/AppSettingsGroup";+import { RealtimeVoiceGroup } from "@/views/settings/RealtimeVoiceGroup";import { SilenceWindowGroup } from "@/views/settings/SilenceWindowGroup";import { VolumeGroup } from "@/views/settings/VolumeGroup";import { AudioDevicesGroup } from "@/views/settings/AudioDevicesGroup";@@ -70,6 +71,7 @@ export function SettingsView() {<div className="flex-1 overflow-y-auto scrollbar-jarvis p-6"><LanguagesGroup /><AppSettingsGroup />+ <RealtimeVoiceGroup /><SystemPromptGroup /><WakeWordPanel /><SilenceWindowGroup />diff --git a/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsxnew file mode 100644index 0000000000..ba47072cc1--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/settings/RealtimeVoiceGroup.tsx@@ -0,0 +1,43 @@+import { Radio } from "lucide-react";++import { Switch } from "@/components/ui/switch";+import { useVoiceMode } from "@/hooks/useVoiceMode";+import { useT } from "@/i18n";++/**+ * Realtime voice (browser) toggle inside the Settings view. Off by default —+ * flips ``mode`` between "pipeline" (the existing wake-word/STT/TTS pipeline)+ * and "realtime" (the browser-side full-duplex OpenAI Realtime engine). The+ * switch is disabled while loading/saving or when the backend reports the+ * realtime engine isn't available (e.g. no OpenAI key configured yet).+ *+ * Uses the in-house `useT()` i18n hook (see src/i18n/index.ts) rather than+ * react-i18next — this project doesn't depend on react-i18next.+ */+export function RealtimeVoiceGroup() {+ const t = useT();+ const { mode, realtimeAvailable, setMode, isLoading, isSaving } = useVoiceMode();+ const on = mode === "realtime";+ return (+ <div className="mt-2 rounded-lg border border-border bg-card/60 p-4">+ <div className="flex items-start gap-3">+ <Radio className="mt-0.5 h-4 w-4 shrink-0 text-primary" />+ <div className="min-w-0 flex-1">+ <div className="flex items-center justify-between gap-4">+ <h4 className="font-medium">{t("settings_view.realtime_voice.title")}</h4>+ <Switch+ checked={on}+ disabled={isLoading || isSaving || !realtimeAvailable}+ onCheckedChange={(next) => setMode(next ? "realtime" : "pipeline")}+ />+ </div>+ <p className="mt-0.5 text-xs text-muted-foreground">+ {realtimeAvailable+ ? t("settings_view.realtime_voice.description")+ : t("settings_view.realtime_voice.unavailable")}+ </p>+ </div>+ </div>+ </div>+ );+}