:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mobilehog): real speech-to-text for composer dictation (#109521)
Dylan Martin20b000309489
diff --git a/products/desktop/apps/mobilehog/src/components/Composer.tsx b/products/desktop/apps/mobilehog/src/components/Composer.tsxindex d2709b872908..7eec5876a8df 100644--- a/products/desktop/apps/mobilehog/src/components/Composer.tsx+++ b/products/desktop/apps/mobilehog/src/components/Composer.tsx@@ -1,8 +1,8 @@import { Host, Image as SymbolImage } from "@expo/ui/swift-ui";import { getReasoningEffortOptions } from "@posthog/shared";import * as Haptics from "expo-haptics";-import { useRouter } from "expo-router";-import { useState } from "react";+import { useFocusEffect, useRouter } from "expo-router";+import { useCallback, useState } from "react";import {ActivityIndicator,Alert,@@ -70,9 +70,13 @@ export function Composer({const router = useRouter();const [text, setText] = useState("");const [photos, setPhotos] = useState<Photo[]>([]);- const dictation = useDictation();const withSpeech = (base: string, heard: string): string =>[base.trim(), heard.trim()].filter(Boolean).join(" ");+ const dictation = useDictation((heard) =>+ setText((current) => withSpeech(current, heard)),+ );+ // Drawer screens stay mounted when another route gets focus, so stop the microphone on blur.+ useFocusEffect(useCallback(() => dictation.cancel, [dictation.cancel]));const { model, adapter, reasoning } = useComposer();const effort = getReasoningEffortOptions(adapter, model)?.find((option) => option.value === reasoning,@@ -80,7 +84,10 @@ export function Composer({const shown = dictation.active? withSpeech(text, dictation.transcript): text;- const canSend = (shown.trim().length > 0 || photos.length > 0) && !sending;+ const canSend =+ (shown.trim().length > 0 || photos.length > 0) &&+ !sending &&+ !dictation.stopping;const attach = async (): Promise<void> => {try {@@ -96,14 +103,23 @@ export function Composer({dictation.start();};- const stopDictation = (): string => {- const value = withSpeech(text, dictation.stop());+ const stopDictation = async (): Promise<void> => {+ const heard = await dictation.stop();+ if (heard !== null) setText((current) => withSpeech(current, heard));+ };++ // The input shows the live transcript, so an edit already holds it. Dropping the transcript keeps it from being added twice.+ const editText = (value: string): void => {+ if (dictation.active) dictation.cancel();setText(value);- return value;};const submit = async (): Promise<void> => {- const value = (dictation.active ? stopDictation() : text).trim();+ if (dictation.stopping || sending) return;+ const heard = dictation.active ? await dictation.stop() : "";+ // An edit, cancel or blur during the wait ends the send and keeps the draft.+ if (heard === null) return;+ const value = withSpeech(text, heard).trim();if ((!value && !photos.length) || sending) return;const attached = photos;setText("");@@ -151,7 +167,7 @@ export function Composer({) : null}<TextInputvalue={shown}- onChangeText={setText}+ onChangeText={editText}placeholder={placeholder}placeholderTextColor={colors.inkMute}style={styles.input}diff --git a/products/desktop/apps/mobilehog/src/lib/dictation.test.ts b/products/desktop/apps/mobilehog/src/lib/dictation.test.tsnew file mode 100644index 000000000000..39ac64edd2d4--- /dev/null+++ b/products/desktop/apps/mobilehog/src/lib/dictation.test.ts@@ -0,0 +1,241 @@+import { ExpoSpeechRecognitionModule } from "expo-speech-recognition";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const listeners = vi.hoisted(+ () => new Map<string, (event?: unknown) => void>(),+);++vi.mock("expo-speech-recognition", () => ({+ ExpoSpeechRecognitionModule: {+ requestPermissionsAsync: vi.fn(async () => ({ granted: true })),+ start: vi.fn(),+ stop: vi.fn(),+ abort: vi.fn(),+ },+ useSpeechRecognitionEvent: (+ name: string,+ listener: (event?: unknown) => void,+ ) => listeners.set(name, listener),+}));+vi.mock("react", () => ({+ useCallback: <T>(fn: T) => fn,+ useEffect: () => {},+ useRef: <T>(current: T) => ({ current }),+ useState: <T>(initial: T) => [initial, () => {}],+}));+vi.mock("react-native-reanimated", () => ({+ Easing: { linear: (t: number) => t },+ useSharedValue: <T>(value: T) => ({ value, modify: () => {} }),+ withTiming: (value: number) => value,+}));+vi.mock("@/components/Waveform", () => ({ RING: 96, SAMPLE_MS: 80 }));++import {+ applyResult,+ type Dictation,+ type Heard,+ joinHeard,+ recognitionLang,+ useDictation,+ volumeToLevel,+} from "./dictation";++const result = (transcript: string, isFinal: boolean) => ({+ isFinal,+ results: [{ transcript, confidence: 0, segments: [] }],+});++describe("volumeToLevel", () => {+ it.each([+ [-2, 0],+ [0, 0],+ [1, 0],+ [4.5, 0.5],+ [8, 1],+ [10, 1],+ ])("maps volume %d to level %d", (volume, level) => {+ expect(volumeToLevel(volume)).toBeCloseTo(level);+ });+});++describe("applyResult", () => {+ const empty: Heard = { finals: [], interim: "" };++ it("replaces the interim text until a result is final", () => {+ const first = applyResult(empty, result("open the", false));+ const second = applyResult(first, result("open the pull request", false));+ expect(second).toEqual({ finals: [], interim: "open the pull request" });+ });++ it("moves a final result into finals and clears the interim text", () => {+ const partial = applyResult(empty, result("fix the bug", false));+ const done = applyResult(partial, result(" Fix the bug.", true));+ expect(done).toEqual({ finals: ["Fix the bug."], interim: "" });+ });++ it("ignores empty final results", () => {+ const heard: Heard = { finals: ["Hello."], interim: "and" };+ const event = { isFinal: true, results: [] };+ expect(applyResult(heard, event)).toEqual({+ finals: ["Hello."],+ interim: "",+ });+ });+});++describe("joinHeard", () => {+ it("joins finals and the interim text with single spaces", () => {+ expect(+ joinHeard({ finals: ["Fix the bug.", " Then ship it."], interim: "now" }),+ ).toBe("Fix the bug. Then ship it. now");+ });++ it("returns an empty string when nothing was heard", () => {+ expect(joinHeard({ finals: [], interim: "" })).toBe("");+ });+});++describe("recognitionLang", () => {+ it.each([+ ["en-US", "en-US"],+ ["de-DE", "de-DE"],+ ["en-GB-u-ca-gregory", "en-GB"],+ ["zh-Hans-CN", "zh-CN"],+ ["zh-Hant-TW", "zh-TW"],+ ["en", undefined],+ ["zh-Hans", undefined],+ ["", undefined],+ ])("maps locale %j to %j", (locale, lang) => {+ expect(recognitionLang(locale)).toBe(lang);+ });+});++describe("useDictation", () => {+ const native = vi.mocked(ExpoSpeechRecognitionModule);++ beforeEach(() => {+ vi.clearAllMocks();+ listeners.clear();+ });++ const startNative = async (): Promise<Dictation> => {+ const dictation = useDictation();+ dictation.start();+ await vi.waitFor(() => expect(native.start).toHaveBeenCalledTimes(1));+ return dictation;+ };++ it.each([+ ["stop", (dictation: Dictation) => dictation.stop()],+ ["cancel", (dictation: Dictation) => dictation.cancel()],+ ])("aborts a native start that finishes after %s", async (_, end) => {+ end(await startNative());+ native.abort.mockClear();+ listeners.get("start")?.();+ expect(native.abort).toHaveBeenCalledTimes(1);+ });++ it("keeps a native start while dictation is active", async () => {+ await startNative();+ listeners.get("start")?.();+ expect(native.abort).not.toHaveBeenCalled();+ });++ it("ignores a native start that it did not request", () => {+ useDictation();+ listeners.get("start")?.();+ expect(native.abort).not.toHaveBeenCalled();+ });+});++describe("useDictation stop", () => {+ const native = vi.mocked(ExpoSpeechRecognitionModule);+ const emit = (name: string, event?: unknown) => listeners.get(name)?.(event);++ beforeEach(() => {+ vi.clearAllMocks();+ listeners.clear();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ const listen = async (+ onEnd?: (heard: string) => void,+ ): Promise<Dictation> => {+ const dictation = useDictation(onEnd);+ dictation.start();+ await vi.waitFor(() => expect(native.start).toHaveBeenCalledTimes(1));+ emit("start");+ return dictation;+ };++ it("keeps the final result that arrives after stop", async () => {+ const onEnd = vi.fn();+ const dictation = await listen(onEnd);+ emit("result", result("Fix the", false));+ const stopped = dictation.stop();+ expect(native.stop).toHaveBeenCalledTimes(1);+ emit("result", result("Fix the bug.", true));+ emit("end");+ await expect(stopped).resolves.toBe("Fix the bug.");+ expect(onEnd).not.toHaveBeenCalled();+ });++ it("resolves a second stop with nothing so the words are kept once", async () => {+ const dictation = await listen();+ emit("result", result("Ship it.", true));+ const first = dictation.stop();+ const second = dictation.stop();+ emit("end");+ await expect(first).resolves.toBe("Ship it.");+ await expect(second).resolves.toBe("");+ expect(native.stop).toHaveBeenCalledTimes(1);+ });++ it("resolves with null when cancel comes during a stop", async () => {+ const dictation = await listen();+ emit("result", result("Ship it.", true));+ const stopped = dictation.stop();+ dictation.cancel();+ await expect(stopped).resolves.toBeNull();+ expect(native.abort).toHaveBeenCalledTimes(1);+ });++ it("ends with what was heard when the recognizer never reports end", async () => {+ const dictation = await listen();+ emit("result", result("Ship it", false));+ vi.useFakeTimers();+ const stopped = dictation.stop();+ vi.advanceTimersByTime(1500);+ await expect(stopped).resolves.toBe("Ship it");+ expect(native.abort).toHaveBeenCalledTimes(1);+ });++ it("aborts a native start that lands while a stop waits", async () => {+ const dictation = useDictation();+ dictation.start();+ await vi.waitFor(() => expect(native.start).toHaveBeenCalledTimes(1));+ const stopped = dictation.stop();+ emit("start");+ expect(native.abort).toHaveBeenCalledTimes(1);+ emit("end");+ await expect(stopped).resolves.toBe("");+ });++ it("stops at once when the recognizer has not started", async () => {+ const dictation = useDictation();+ dictation.start();+ await expect(dictation.stop()).resolves.toBe("");+ expect(native.stop).not.toHaveBeenCalled();+ });++ it("passes the words to onEnd when the recognizer ends on its own", async () => {+ const onEnd = vi.fn();+ await listen(onEnd);+ emit("result", result("Ship it.", true));+ emit("end");+ expect(onEnd).toHaveBeenCalledWith("Ship it.");+ });+});diff --git a/products/desktop/apps/mobilehog/src/lib/dictation.ts b/products/desktop/apps/mobilehog/src/lib/dictation.tsindex 89d9f9f420aa..a204328c28dc 100644--- a/products/desktop/apps/mobilehog/src/lib/dictation.ts+++ b/products/desktop/apps/mobilehog/src/lib/dictation.ts@@ -1,3 +1,8 @@+import {+ ExpoSpeechRecognitionModule,+ type ExpoSpeechRecognitionResultEvent,+ useSpeechRecognitionEvent,+} from "expo-speech-recognition";import { useCallback, useEffect, useRef, useState } from "react";import {Easing,@@ -8,25 +13,89 @@ import {import { RING, SAMPLE_MS } from "@/components/Waveform";export interface Dictation {+ // Stays true while a stop waits for the final result.active: boolean;+ stopping: boolean;transcript: string;// Read on the UI thread by the waveform; updating them never re-renders React.levels: SharedValue<number[]>;head: SharedValue<number>;start: () => void;- // Ends dictation and keeps what was heard.- stop: () => string;+ // Ends dictation and resolves with what was heard once the recognizer delivers its final result.+ // A second call during the wait resolves with "", so each caller gets the words only once.+ // Resolves with null when cancel ends the wait.+ stop: () => Promise<string | null>;+ // Ends dictation and drops what was heard.cancel: () => void;}+export interface Heard {+ finals: string[];+ interim: string;+}++// The recognizer reports volume from -2 to 10; below QUIET is room noise.+const QUIET = 1;+const LOUD = 8;+// Safety net for a recognizer that never reports end after stop.+const STOP_TIMEOUT_MS = 1500;++export function volumeToLevel(value: number): number {+ return Math.min(1, Math.max(0, (value - QUIET) / (LOUD - QUIET)));+}++export function applyResult(+ heard: Heard,+ event: ExpoSpeechRecognitionResultEvent,+): Heard {+ const text = event.results[0]?.transcript.trim() ?? "";+ if (!event.isFinal) return { finals: heard.finals, interim: text };+ return { finals: text ? [...heard.finals, text] : heard.finals, interim: "" };+}++export function joinHeard({ finals, interim }: Heard): string {+ return [...finals, interim]+ .map((part) => part.trim())+ .filter(Boolean)+ .join(" ");+}++// Recognizers name locales by language and region, so a script subtag is dropped: zh-Hans-CN becomes zh-CN.+// Any other shape returns undefined, and the recognizer then uses its en-US default.+export function recognitionLang(locale: string): string | undefined {+ const match = /^([a-z]{2,3})(?:-[A-Z][a-z]{3})?(-[A-Z]{2})(?:-u-|$)/.exec(+ locale,+ );+ return match ? match[1] + match[2] : undefined;+}+const emptyRing = (): number[] => new Array(RING).fill(-1);+const nothingHeard = (): Heard => ({ finals: [], interim: "" });-export function useDictation(): Dictation {+// onEnd receives what was heard when the recognizer ends on its own.+export function useDictation(onEnd?: (heard: string) => void): Dictation {const [active, setActive] = useState(false);+ const [stopping, setStopping] = useState(false);const [transcript, setTranscript] = useState("");const levels = useSharedValue<number[]>(emptyRing());const head = useSharedValue(-1);const count = useRef(0);+ const heard = useRef<Heard>(nothingHeard());+ // Bumped on every start and finish so a late permission answer cannot restart a finished session.+ const session = useRef(0);+ const live = useRef(false);+ const listening = useRef(false);+ // True from this hook's native start call until the recognizer reports start or a startup error.+ const starting = useRef(false);+ const pendingStop = useRef<((heard: string | null) => void) | null>(null);+ const stopTimer = useRef<ReturnType<typeof setTimeout> | undefined>(+ undefined,+ );+ const endRef = useRef(onEnd);++ useEffect(() => {+ endRef.current = onEnd;+ }, [onEnd]);const push = useCallback((level: number) => {@@ -44,40 +113,132 @@ export function useDictation(): Dictation {[levels, head],);- // DEMO: bursts of speech-like levels until the recognizer is wired in.- useEffect(() => {- if (!active) return;- let speaking = true;- let flipAt = Date.now() + 900;- const timer = setInterval(() => {- if (Date.now() > flipAt) {- speaking = !speaking;- flipAt =- Date.now() +- (speaking ? 600 + Math.random() * 900 : 250 + Math.random() * 400);+ const finish = useCallback((kept: string | null = ""): boolean => {+ const wasListening = listening.current;+ const resolve = pendingStop.current;+ session.current++;+ live.current = false;+ listening.current = false;+ pendingStop.current = null;+ clearTimeout(stopTimer.current);+ setStopping(false);+ setActive(false);+ resolve?.(kept);+ return wasListening;+ }, []);++ // Before native start, an end or error can only come from the previous session.+ const endQuietly = useCallback(() => {+ if (!live.current || !listening.current) return;+ const text = joinHeard(heard.current);+ if (pendingStop.current) {+ finish(text);+ return;+ }+ finish();+ endRef.current?.(text);+ }, [finish]);++ useSpeechRecognitionEvent("volumechange", (event) => {+ if (live.current) push(volumeToLevel(event.value));+ });++ useSpeechRecognitionEvent("result", (event) => {+ if (!live.current) return;+ heard.current = applyResult(heard.current, event);+ setTranscript(joinHeard(heard.current));+ });++ // On iOS, native start runs in a task that stop and abort do not wait for.+ // A stop or cancel during startup can finish first, and the microphone then opens after dictation ended.+ useSpeechRecognitionEvent("start", () => {+ if (!starting.current) return;+ starting.current = false;+ if (!live.current || pendingStop.current) {+ ExpoSpeechRecognitionModule.abort();+ }+ });++ useSpeechRecognitionEvent("error", (event) => {+ if (event.error === "aborted") return;+ starting.current = false;+ endQuietly();+ });++ useSpeechRecognitionEvent("end", endQuietly);++ useEffect(+ () => () => {+ session.current++;+ live.current = false;+ clearTimeout(stopTimer.current);+ if (listening.current || starting.current) {+ ExpoSpeechRecognitionModule.abort();}- push(speaking ? 0.25 + Math.random() * 0.75 : 0);- }, SAMPLE_MS);- return () => clearInterval(timer);- }, [active, push]);+ },+ [],+ );const start = useCallback(() => {+ const id = ++session.current;count.current = 0;levels.value = emptyRing();head.value = -1;+ heard.current = nothingHeard();+ live.current = true;+ listening.current = false;setTranscript("");setActive(true);- }, [levels, head]);+ ExpoSpeechRecognitionModule.requestPermissionsAsync()+ .then((permission) => {+ if (id !== session.current) return;+ if (!permission.granted) {+ finish();+ return;+ }+ listening.current = true;+ starting.current = true;+ ExpoSpeechRecognitionModule.start({+ lang: recognitionLang(Intl.DateTimeFormat().resolvedOptions().locale),+ interimResults: true,+ continuous: true,+ addsPunctuation: true,+ volumeChangeEventOptions: {+ enabled: true,+ intervalMillis: SAMPLE_MS,+ },+ });+ })+ .catch(() => {+ if (id === session.current) finish();+ });+ }, [levels, head, finish]);- const stop = useCallback(() => {- setActive(false);- return transcript;- }, [transcript]);+ // Results keep arriving after native stop, so the session stays live until the recognizer reports end.+ const stop = useCallback((): Promise<string | null> => {+ if (!live.current || pendingStop.current) return Promise.resolve("");+ if (!listening.current) {+ finish();+ return Promise.resolve(joinHeard(heard.current));+ }+ const done = new Promise<string | null>((resolve) => {+ pendingStop.current = resolve;+ });+ stopTimer.current = setTimeout(() => {+ if (finish(joinHeard(heard.current))) {+ ExpoSpeechRecognitionModule.abort();+ }+ }, STOP_TIMEOUT_MS);+ setStopping(true);+ ExpoSpeechRecognitionModule.stop();+ return done;+ }, [finish]);const cancel = useCallback(() => {- setActive(false);+ if (finish(null)) ExpoSpeechRecognitionModule.abort();+ heard.current = nothingHeard();setTranscript("");- }, []);+ }, [finish]);- return { active, transcript, levels, head, start, stop, cancel };+ return { active, stopping, transcript, levels, head, start, stop, cancel };}