Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(voiceNotes): add voice note recorder hook and upload api

Steven Enamakel970c599c1e61
diff --git a/app/src/features/voiceNotes/useVoiceNoteRecorder.ts b/app/src/features/voiceNotes/useVoiceNoteRecorder.ts
new file mode 100644
index 0000000000..aaa0633280
--- /dev/null
+++ b/app/src/features/voiceNotes/useVoiceNoteRecorder.ts
@@ -0,0 +1,193 @@
+/**
+ * useVoiceNoteRecorder - MediaRecorder capture for the voice-note composer.
+ *
+ * Unlike push-to-talk (`features/voice/pttAudio`), which hands the buffer
+ * straight to STT, this keeps the recording as a draft the user can preview
+ * and then send or discard. A coarse amplitude waveform is sampled while
+ * recording so the bubble can draw bars without decoding the audio again.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+export type RecorderPhase = 'idle' | 'recording' | 'recorded';
+
+export interface VoiceNoteDraft {
+ blob: Blob;
+ durationMs: number;
+ waveform: number[];
+}
+
+export const WAVEFORM_BARS = 40;
+/** Longest recording; the recorder stops itself here. */
+export const MAX_RECORDING_MS = 5 * 60 * 1000;
+const SAMPLE_INTERVAL_MS = 100;
+
+const MIME_PREFERENCE = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/mp4'];
+
+function pickMimeType(): string | undefined {
+ if (typeof MediaRecorder === 'undefined') return undefined;
+ return MIME_PREFERENCE.find(m => MediaRecorder.isTypeSupported(m));
+}
+
+/** Resample raw amplitude samples to `bars` values in 0..1. */
+export function reduceWaveform(samples: number[], bars: number = WAVEFORM_BARS): number[] {
+ if (samples.length === 0) return [];
+ const out: number[] = [];
+ for (let i = 0; i < bars; i++) {
+ const from = Math.floor((i * samples.length) / bars);
+ const to = Math.max(from + 1, Math.floor(((i + 1) * samples.length) / bars));
+ let peak = 0;
+ for (let j = from; j < Math.min(to, samples.length); j++) peak = Math.max(peak, samples[j]);
+ out.push(Math.min(1, Math.round(peak * 100) / 100));
+ }
+ return out;
+}
+
+export interface VoiceNoteRecorder {
+ phase: RecorderPhase;
+ elapsedMs: number;
+ draft: VoiceNoteDraft | null;
+ /** Rejects when the microphone is unavailable or permission is denied. */
+ start: () => Promise<void>;
+ stop: () => void;
+ /** Drop the recording or the draft. */
+ discard: () => void;
+}
+
+export function useVoiceNoteRecorder(): VoiceNoteRecorder {
+ const [phase, setPhase] = useState<RecorderPhase>('idle');
+ const [elapsedMs, setElapsedMs] = useState(0);
+ const [draft, setDraft] = useState<VoiceNoteDraft | null>(null);
+ const live = useRef<{
+ recorder: MediaRecorder;
+ stream: MediaStream;
+ chunks: Blob[];
+ startedAt: number;
+ samples: number[];
+ timer: ReturnType<typeof setInterval>;
+ audioCtx?: AudioContext;
+ analyser?: AnalyserNode;
+ cancelled: boolean;
+ } | null>(null);
+
+ const teardown = useCallback(() => {
+ const session = live.current;
+ if (!session) return;
+ live.current = null;
+ clearInterval(session.timer);
+ for (const track of session.stream.getTracks()) {
+ try {
+ track.stop();
+ } catch {
+ /* ignore */
+ }
+ }
+ void session.audioCtx?.close().catch(() => undefined);
+ }, []);
+
+ const start = useCallback(async () => {
+ if (live.current) return;
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ const mimeType = pickMimeType();
+ const recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
+ const chunks: Blob[] = [];
+ const samples: number[] = [];
+ let audioCtx: AudioContext | undefined;
+ let analyser: AnalyserNode | undefined;
+ try {
+ if (typeof AudioContext !== 'undefined') {
+ audioCtx = new AudioContext();
+ analyser = audioCtx.createAnalyser();
+ analyser.fftSize = 512;
+ audioCtx.createMediaStreamSource(stream).connect(analyser);
+ }
+ } catch {
+ analyser = undefined;
+ }
+ const buffer = new Uint8Array(analyser?.fftSize ?? 0);
+ const startedAt = window.performance.now();
+
+ const timer = setInterval(() => {
+ const session = live.current;
+ if (!session) return;
+ const elapsed = window.performance.now() - session.startedAt;
+ setElapsedMs(elapsed);
+ if (session.analyser) {
+ session.analyser.getByteTimeDomainData(buffer);
+ let peak = 0;
+ for (const v of buffer) peak = Math.max(peak, Math.abs(v - 128) / 128);
+ session.samples.push(peak);
+ }
+ if (elapsed >= MAX_RECORDING_MS && session.recorder.state !== 'inactive') {
+ session.recorder.stop();
+ }
+ }, SAMPLE_INTERVAL_MS);
+
+ recorder.addEventListener('dataavailable', (e: BlobEvent) => {
+ if (e.data && e.data.size > 0) chunks.push(e.data);
+ });
+ recorder.addEventListener('stop', () => {
+ const session = live.current;
+ const cancelled = session?.cancelled ?? true;
+ const durationMs = Math.round(window.performance.now() - startedAt);
+ const recorded = session ? [...session.samples] : [];
+ teardown();
+ if (cancelled || chunks.length === 0) {
+ setPhase('idle');
+ setElapsedMs(0);
+ return;
+ }
+ const blob = new Blob(chunks, { type: recorder.mimeType || mimeType || 'audio/webm' });
+ setDraft({ blob, durationMs, waveform: reduceWaveform(recorded) });
+ setElapsedMs(durationMs);
+ setPhase('recorded');
+ });
+
+ live.current = {
+ recorder,
+ stream,
+ chunks,
+ startedAt,
+ samples,
+ timer,
+ audioCtx,
+ analyser,
+ cancelled: false,
+ };
+ setDraft(null);
+ setElapsedMs(0);
+ setPhase('recording');
+ recorder.start();
+ }, [teardown]);
+
+ const stop = useCallback(() => {
+ const session = live.current;
+ if (session && session.recorder.state !== 'inactive') session.recorder.stop();
+ }, []);
+
+ const discard = useCallback(() => {
+ const session = live.current;
+ if (session) {
+ session.cancelled = true;
+ if (session.recorder.state !== 'inactive') session.recorder.stop();
+ else teardown();
+ }
+ setDraft(null);
+ setElapsedMs(0);
+ setPhase('idle');
+ }, [teardown]);
+
+ // Release the microphone if the composer unmounts mid-recording.
+ useEffect(
+ () => () => {
+ const session = live.current;
+ if (session) {
+ session.cancelled = true;
+ if (session.recorder.state !== 'inactive') session.recorder.stop();
+ teardown();
+ }
+ },
+ [teardown]
+ );
+
+ return { phase, elapsedMs, draft, start, stop, discard };
+}
diff --git a/app/src/features/voiceNotes/voiceNoteApi.ts b/app/src/features/voiceNotes/voiceNoteApi.ts
new file mode 100644
index 0000000000..1c3d816d0f
--- /dev/null
+++ b/app/src/features/voiceNotes/voiceNoteApi.ts
@@ -0,0 +1,101 @@
+/**
+ * voiceNoteApi - core RPC wrappers for in-app voice notes.
+ *
+ * The core owns the audio: a recording is stored through
+ * `channel.web_voice_note_store` and a thread row only keeps `{ noteId, mime }`
+ * in its `extraMetadata.voiceNote`. Assistant spoken replies use the same
+ * store, so one reader serves both directions.
+ */
+import { callCoreRpc } from '../../services/coreRpcClient';
+import { openhumanVoiceTranscribeBytes } from '../../utils/tauriCommands/voice';
+
+/** `extraMetadata.voiceNote` as persisted on a thread row. */
+export interface VoiceNoteMeta {
+ noteId: string;
+ mime?: string;
+ durationMs?: number;
+ /** Normalised 0..1 bar heights, user recordings only. */
+ waveform?: number[];
+}
+
+/** `source` the composer stamps on a turn that began as a voice note. */
+export const VOICE_NOTE_SOURCE = 'voice_note';
+
+export function extensionForMime(mime: string): string {
+ if (mime.includes('ogg')) return 'ogg';
+ if (mime.includes('mp4')) return 'm4a';
+ return 'webm';
+}
+
+export function bytesToBase64(bytes: Uint8Array): string {
+ let binary = '';
+ const chunk = 0x8000;
+ for (let i = 0; i < bytes.length; i += chunk) {
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
+ }
+ return btoa(binary);
+}
+
+export function base64ToBytes(b64: string): Uint8Array {
+ const binary = atob(b64);
+ const out = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
+ return out;
+}
+
+/** Narrow untyped `extraMetadata` to a voice-note reference, or `null`. */
+export function readVoiceNoteMeta(extraMetadata: unknown): VoiceNoteMeta | null {
+ if (!extraMetadata || typeof extraMetadata !== 'object') return null;
+ const raw = (extraMetadata as Record<string, unknown>).voiceNote;
+ if (!raw || typeof raw !== 'object') return null;
+ const note = raw as Record<string, unknown>;
+ if (typeof note.noteId !== 'string' || note.noteId.length === 0) return null;
+ return {
+ noteId: note.noteId,
+ mime: typeof note.mime === 'string' ? note.mime : undefined,
+ durationMs: typeof note.durationMs === 'number' ? note.durationMs : undefined,
+ waveform: Array.isArray(note.waveform)
+ ? note.waveform.filter((v): v is number => typeof v === 'number')
+ : undefined,
+ };
+}
+
+export async function storeVoiceNote(noteId: string, blob: Blob): Promise<{ mime: string }> {
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ const mime = blob.type || 'audio/webm';
+ const result = await callCoreRpc<{ mime?: string }>({
+ method: 'openhuman.channel_web_voice_note_store',
+ params: { note_id: noteId, audio_base64: bytesToBase64(bytes), mime },
+ });
+ return { mime: result?.mime ?? mime };
+}
+
+/** Fetch a stored note's audio; `null` when the core has none. */
+export async function readVoiceNote(noteId: string): Promise<Blob | null> {
+ const result = await callCoreRpc<{ audio_base64?: string | null; mime?: string | null }>({
+ method: 'openhuman.channel_web_voice_note_read',
+ params: { note_id: noteId },
+ });
+ if (!result?.audio_base64) return null;
+ const bytes = base64ToBytes(result.audio_base64);
+ return new Blob([bytes as BlobPart], { type: result.mime || 'audio/webm' });
+}
+
+/** Run the configured STT engine over a recording. Empty string when nothing was heard. */
+export async function transcribeVoiceNote(blob: Blob): Promise<string> {
+ const bytes = Array.from(new Uint8Array(await blob.arrayBuffer()));
+ const result = await openhumanVoiceTranscribeBytes(
+ bytes,
+ extensionForMime(blob.type || 'audio/webm'),
+ undefined,
+ false
+ );
+ return (result?.text ?? result?.raw_text ?? '').trim();
+}
+
+export function formatDuration(ms: number | undefined): string {
+ const total = Math.max(0, Math.round((ms ?? 0) / 1000));
+ const m = Math.floor(total / 60);
+ const s = total % 60;
+ return `${m}:${String(s).padStart(2, '0')}`;
+}