Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): 完成 Android 语音输入 (#283)
Dash72b47375f587
diff --git a/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts b/apps/mobile/src/__tests__/mobileRealtimeAudio.test.tsindex c901b895e7..fc929437fc 100644--- a/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts+++ b/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts@@ -1,5 +1,6 @@import { readFileSync } from 'node:fs';import { resolve } from 'node:path';+import { requireNativeModule } from 'expo-modules-core';import { afterEach, describe, expect, it, vi } from 'vitest';vi.mock('expo-modules-core', () => ({@@ -19,8 +20,15 @@ vi.mock('expo-modules-core', () => ({}),}));-afterEach(() => {+afterEach(async () => {+ vi.restoreAllMocks();vi.unstubAllEnvs();+ vi.mocked(requireNativeModule).mockReset();+ vi.mocked(requireNativeModule).mockImplementation(() => {+ throw new Error('native module not linked');+ });+ const { __testing } = await import('@/session/mobileRealtimeAudio');+ __testing.resetNativeBindingForTests();});describe('mobileRealtimeAudio', () => {@@ -46,7 +54,7 @@ describe('mobileRealtimeAudio', () => {.rejects.toThrow('realtime microphone PCM capture');});- it('hides voice UI on Android without changing existing non-Android surfaces', async () => {+ it('hides voice UI when an Android build has no native PCM stream', async () => {const { shouldShowMobileVoiceUi } = await import('@/session/mobileRealtimeAudio');expect(shouldShowMobileVoiceUi('android')).toBe(false);@@ -54,6 +62,153 @@ describe('mobileRealtimeAudio', () => {expect(shouldShowMobileVoiceUi('web')).toBe(true);});+ it('streams and converts Android Expo AudioStream PCM into the ASR format', async () => {+ type StreamEvent = 'audioStreamBuffer' | 'audioStreamStatus';+ const listeners = new Map<StreamEvent, (event: never) => void>();+ const removedEvents: StreamEvent[] = [];+ const streamStart = vi.fn(async () => undefined);+ const streamStop = vi.fn();+ const streamRelease = vi.fn();+ let streamOptions: unknown;++ class MockExpoAudioStream {+ readonly id = 'android-pcm-stream';+ readonly sampleRate = 24_000;+ readonly channels = 2;+ readonly isStreaming = true;++ constructor(options: unknown) {+ streamOptions = options;+ }++ addListener(eventName: StreamEvent, listener: (event: never) => void) {+ listeners.set(eventName, listener);+ return {+ remove: () => {+ removedEvents.push(eventName);+ listeners.delete(eventName);+ },+ };+ }++ start = streamStart;+ stop = streamStop;+ release = streamRelease;+ }++ vi.mocked(requireNativeModule).mockImplementation((moduleName: string) => {+ if (moduleName === 'ExpoAudio') {+ return { AudioStream: MockExpoAudioStream };+ }+ throw new Error(`${moduleName} not linked`);+ });+ const {+ __testing,+ isMobileRealtimeAudioAvailable,+ shouldShowMobileVoiceUi,+ startMobileRealtimeAudio,+ } = await import('@/session/mobileRealtimeAudio');+ __testing.resetNativeBindingForTests();++ expect(isMobileRealtimeAudioAvailable()).toBe(true);+ expect(shouldShowMobileVoiceUi('android')).toBe(true);++ vi.spyOn(Date, 'now')+ .mockReturnValueOnce(1_000)+ .mockReturnValueOnce(1_100)+ .mockReturnValueOnce(1_200)+ .mockReturnValueOnce(1_225)+ .mockReturnValue(1_300);+ const onChunk = vi.fn();+ const onError = vi.fn();+ const stopCapture = await startMobileRealtimeAudio({+ sampleRate: 12_000,+ onChunk,+ onError,+ });++ expect(streamOptions).toEqual({+ sampleRate: 12_000,+ channels: 1,+ encoding: 'int16',+ });+ expect(streamStart).toHaveBeenCalledTimes(1);++ const input = new ArrayBuffer(16);+ const inputView = new DataView(input);+ [+ 1_000, 3_000,+ 5_000, 7_000,+ 9_000, 11_000,+ 13_000, 15_000,+ ].forEach((sample, index) => inputView.setInt16(index * 2, sample, true));+ listeners.get('audioStreamBuffer')?.({+ data: input,+ sampleRate: 24_000,+ channels: 2,+ timestamp: 0.1,+ } as never);++ expect(onChunk).toHaveBeenCalledTimes(1);+ const chunk = onChunk.mock.calls[0]?.[0];+ expect(Array.from(new Int16Array(chunk.pcm16))).toEqual([2_000, 10_000]);+ expect(chunk.trace).toMatchObject({+ capturedAt: 1_200,+ convertedAt: 1_225,+ chunkIndex: 0,+ sampleRate: 12_000,+ });+ expect(chunk.trace.durationMs).toBeCloseTo(2 / 12_000 * 1_000);++ listeners.get('audioStreamStatus')?.({+ isStreaming: false,+ } as never);+ expect(onError).toHaveBeenCalledTimes(1);+ expect(streamStop).toHaveBeenCalledTimes(1);+ expect(streamRelease).toHaveBeenCalledTimes(1);+ expect(removedEvents).toEqual(['audioStreamBuffer', 'audioStreamStatus']);++ await stopCapture();++ expect(streamStop).toHaveBeenCalledTimes(1);+ expect(streamRelease).toHaveBeenCalledTimes(1);+ });++ it('preserves non-integer resampling phase across native buffer boundaries', async () => {+ const { __testing } = await import('@/session/mobileRealtimeAudio');+ const convert = __testing.createExpoAudioPcm16Converter(16_000);++ const firstChunk = Int16Array.from(+ { length: 7 },+ (_, index) => index,+ );+ const secondChunk = Int16Array.from(+ { length: 7 },+ (_, index) => index + 7,+ );++ const firstOutput = new Int16Array(+ convert(firstChunk.buffer, 44_100, 1),+ );+ const secondOutput = new Int16Array(+ convert(secondChunk.buffer, 44_100, 1),+ );++ expect(Array.from(firstOutput)).toEqual([0, 2, 5]);+ expect(Array.from(secondOutput)).toEqual([8, 11, 13]);+ expect(firstOutput.length + secondOutput.length).toBe(+ Math.ceil(14 * 16_000 / 44_100),+ );+ });++ it('reuses an aligned mono PCM buffer when no conversion is needed', async () => {+ const { __testing } = await import('@/session/mobileRealtimeAudio');+ const input = new Int16Array([1, 2, 3]).buffer;++ expect(__testing.convertExpoAudioPcm16(input, 16_000, 1, 16_000))+ .toBe(input);+ });+it('keeps the Android voice entry available to explicit E2E mock runs', async () => {vi.stubEnv('EXPO_PUBLIC_XDT_MOBILE_E2E_MOCK_AUDIO', '1');const { shouldShowMobileVoiceUi } = await import('@/session/mobileRealtimeAudio');diff --git a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.tsindex 623c16dcf4..cd1eb942eb 100644--- a/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts+++ b/apps/mobile/src/__tests__/nativeE2eEnvironment.test.ts@@ -238,15 +238,23 @@ describe('native e2e environment', () => {expect(authContext).toContain('clearAllMobileVoiceCredentials().catch(() => undefined),');});- it('keeps Android voice input as an explicit unsupported native boundary for now', () => {+ it('backs Android realtime voice with the Expo AudioStream already shipped in the app', () => {const expoModuleConfig = readFileSync(resolve(process.cwd(), 'modules/xdt-mobile-realtime-audio/expo-module.config.json'),'utf8',);const realtimeAudio = readFileSync(resolve(process.cwd(), 'src/session/mobileRealtimeAudio.ts'), 'utf8');+ const appJson = readFileSync(resolve(process.cwd(), 'app.json'), 'utf8');+ // The latency-tuned custom recorder stays Apple-only. Android reuses the+ // PCM SharedObject from expo-audio, which is already a native dependency.expect(expoModuleConfig).toContain('"platforms": ["apple"]');expect(expoModuleConfig).not.toContain('"android"');+ expect(appJson).toContain('"recordAudioAndroid": true');+ expect(realtimeAudio).toContain("requireNativeModule<ExpoAudioNativeModule>('ExpoAudio')");+ expect(realtimeAudio).toContain('new module.AudioStream({');+ expect(realtimeAudio).toContain("encoding: 'int16'");+ expect(realtimeAudio).toContain('convertExpoAudioPcm16(');expect(realtimeAudio).toContain("throw new UnavailabilityError('Cindy mobile voice input', 'realtime microphone PCM capture')");expect(realtimeAudio).toContain('EXPO_PUBLIC_XDT_MOBILE_E2E_MOCK_AUDIO');});diff --git a/apps/mobile/src/session/mobileRealtimeAudio.ts b/apps/mobile/src/session/mobileRealtimeAudio.tsindex 7886894f66..ef5a731a48 100644--- a/apps/mobile/src/session/mobileRealtimeAudio.ts+++ b/apps/mobile/src/session/mobileRealtimeAudio.ts@@ -4,6 +4,7 @@ import {type EventSubscription,} from 'expo-modules-core';import type { AudioTrace } from '@cindy/voice-input-core';+import { i18n } from '@/i18n';export type MobileRealtimeAudioChunk = {pcm16: ArrayBuffer;@@ -33,6 +34,22 @@ type NativeRealtimeAudioEvents = {onAudioError: (event: NativeAudioErrorEvent) => void;};+type ExpoAudioStreamBufferEvent = {+ data: ArrayBuffer;+ sampleRate: number;+ channels: number;+ timestamp: number;+};++type ExpoAudioStreamStatusEvent = {+ isStreaming: boolean;+};++type ExpoAudioStreamEvents = {+ audioStreamBuffer: (event: ExpoAudioStreamBufferEvent) => void;+ audioStreamStatus: (event: ExpoAudioStreamStatusEvent) => void;+};+type NativeEventSource<TEvents extends Record<string, (event: never) => void>> = {addListener<EventName extends keyof TEvents>(eventName: EventName,@@ -48,26 +65,54 @@ type RealtimeAudioNativeBinding = {module: NativeRealtimeAudioBinding;};+type ExpoAudioStream = NativeEventSource<ExpoAudioStreamEvents> & {+ readonly id: string;+ readonly sampleRate: number;+ readonly channels: number;+ readonly isStreaming: boolean;+ start(): Promise<void>;+ stop(): void;+ release(): void;+};++type ExpoAudioNativeModule = {+ AudioStream: new (options: {+ sampleRate: number;+ channels: number;+ encoding: 'int16';+ }) => ExpoAudioStream;+};++type ExpoAudioPcm16ResampleState = {+ sourceSampleRate: number;+ sourceChannels: number;+ targetSampleRate: number;+ sourceFramesConsumed: number;+ outputFramesProduced: number;+};+const DEFAULT_NATIVE_AUDIO_BUFFER_SIZE = 4096;+const EXPO_AUDIO_STREAM_STALL_TIMEOUT_MS = 5_000;+const EXPO_AUDIO_STREAM_WATCHDOG_INTERVAL_MS = 1_000;let nativeBinding: RealtimeAudioNativeBinding | null | undefined;+let expoAudioNativeModule: ExpoAudioNativeModule | null | undefined;export function isMobileRealtimeAudioAvailable(): boolean {if (isE2eMockRealtimeAudioEnabled()) return true;- return getNativeBinding() !== null;+ return getNativeBinding() !== null || getExpoAudioNativeModule() !== null;}/**- * Keeps unfinished platform implementations out of the product surface. This- * is intentionally a UI-only gate; the native permission and runtime fallback- * stay unchanged so Android can be re-enabled without a native configuration- * migration.+ * Android uses expo-audio's native PCM AudioStream when the custom Apple module+ * is absent. Keep the entry hidden in builds that predate that native class or+ * otherwise failed to link it, instead of sending users into a known failure.*/export function shouldShowMobileVoiceUi(platform: string,): boolean {if (isE2eMockRealtimeAudioEnabled()) return true;- return platform !== 'android';+ return platform !== 'android' || isMobileRealtimeAudioAvailable();}export async function startMobileRealtimeAudio(@@ -82,9 +127,25 @@ export async function startMobileRealtimeAudio(return startE2eMockRealtimeAudio(options);}const binding = getNativeBinding();- if (!binding) {- throw new UnavailabilityError('Cindy mobile voice input', 'realtime microphone PCM capture');+ if (binding) {+ return startCustomNativeRealtimeAudio(binding, options);+ }+ const expoAudioModule = getExpoAudioNativeModule();+ if (expoAudioModule) {+ return startExpoAudioRealtimeAudio(expoAudioModule, options);}+ throw new UnavailabilityError('Cindy mobile voice input', 'realtime microphone PCM capture');+}++async function startCustomNativeRealtimeAudio(+ binding: RealtimeAudioNativeBinding,+ options: {+ onChunk: (chunk: MobileRealtimeAudioChunk) => void;+ onError?: (error: Error) => void;+ sampleRate?: number;+ bufferSize?: number;+ },+): Promise<() => Promise<void>> {const subscriptions: EventSubscription[] = [binding.module.addListener('onAudioChunk', (event) => {options.onChunk({@@ -122,13 +183,125 @@ export async function startMobileRealtimeAudio(};}+/**+ * Mobile already ships expo-audio for permission and audio-mode management.+ * SDK 56 also exposes the native SharedObject behind its public useAudioStream+ * hook. The voice controller is intentionally imperative, so construct that+ * same stream class directly rather than carrying a second AudioRecord stack.+ */+async function startExpoAudioRealtimeAudio(+ module: ExpoAudioNativeModule,+ options: {+ onChunk: (chunk: MobileRealtimeAudioChunk) => void;+ onError?: (error: Error) => void;+ sampleRate?: number;+ },+): Promise<() => Promise<void>> {+ const targetSampleRate = normalizeSampleRate(options.sampleRate);+ const convertPcm16 = createExpoAudioPcm16Converter(targetSampleRate);+ const stream = new module.AudioStream({+ sampleRate: targetSampleRate,+ channels: 1,+ encoding: 'int16',+ });+ let streamStarted = false;+ let stopping = false;+ let failureReported = false;+ let chunkIndex = 0;+ let lastChunkAt = Date.now();+ let watchdog: ReturnType<typeof setInterval> | null = null;+ const subscriptions: EventSubscription[] = [];++ const stopStream = (): void => {+ if (stopping) return;+ stopping = true;+ if (watchdog) {+ clearInterval(watchdog);+ watchdog = null;+ }+ subscriptions.splice(0).forEach((subscription) => subscription.remove());+ try {+ stream.stop();+ } catch {+ // The native stream may already have stopped after an Android audio+ // interruption. Releasing the SharedObject below is still required.+ }+ try {+ stream.release();+ } catch {+ // release() is best-effort and may already have run during teardown.+ }+ };++ const reportFailure = (): void => {+ if (stopping || failureReported) return;+ failureReported = true;+ stopStream();+ options.onError?.(new Error(i18n.t('composer.voice.incomplete')));+ };++ subscriptions.push(+ stream.addListener('audioStreamBuffer', (event) => {+ if (stopping) return;+ const capturedAt = Date.now();+ lastChunkAt = capturedAt;+ let pcm16: ArrayBuffer;+ try {+ pcm16 = convertPcm16(+ event.data,+ event.sampleRate,+ event.channels,+ );+ } catch {+ reportFailure();+ return;+ }+ if (pcm16.byteLength === 0) return;+ const convertedAt = Date.now();+ options.onChunk({+ pcm16,+ trace: {+ capturedAt,+ convertedAt,+ chunkIndex,+ sampleRate: targetSampleRate,+ durationMs: pcm16.byteLength / 2 / targetSampleRate * 1_000,+ },+ });+ chunkIndex += 1;+ }),+ stream.addListener('audioStreamStatus', (event) => {+ if (!event.isStreaming && streamStarted && !stopping) {+ reportFailure();+ }+ }),+ );++ try {+ await stream.start();+ streamStarted = true;+ lastChunkAt = Date.now();+ watchdog = setInterval(() => {+ if (Date.now() - lastChunkAt > EXPO_AUDIO_STREAM_STALL_TIMEOUT_MS) {+ reportFailure();+ }+ }, EXPO_AUDIO_STREAM_WATCHDOG_INTERVAL_MS);+ } catch (error) {+ stopStream();+ throw error;+ }++ return async () => {+ stopStream();+ };+}+/*** Best-effort microphone warm-up, wired to touch-down (pressIn) of the mic- * button. Activating the iOS audio session costs ~100-150ms; doing it while the- * finger is still down means capture is live almost immediately when the tap- * completes and recording actually starts, instead of losing the first syllable- * to the warm-up window. Never throws and never blocks the caller — a real- * failure will surface from the subsequent start.+ * button. The custom iOS module can activate AVAudioSession ahead of start;+ * Android's Expo AudioStream has no prepare phase, so Android safely no-ops+ * here while its ASR connection still prewarms in parallel. Never throws and+ * never blocks the caller — a real failure will surface from start.*/export function prewarmMobileRealtimeAudio(): void {if (isE2eMockRealtimeAudioEnabled()) return;@@ -139,8 +312,11 @@ export function prewarmMobileRealtimeAudio(): void {export const __testing = {decodeBase64ToArrayBuffer,+ convertExpoAudioPcm16,+ createExpoAudioPcm16Converter,resetNativeBindingForTests: () => {nativeBinding = undefined;+ expoAudioNativeModule = undefined;},};@@ -157,6 +333,20 @@ function getNativeBinding(): RealtimeAudioNativeBinding | null {return nativeBinding ?? null;}+function getExpoAudioNativeModule(): ExpoAudioNativeModule | null {+ if (expoAudioNativeModule !== undefined) return expoAudioNativeModule;+ try {+ const module = requireNativeModule<ExpoAudioNativeModule>('ExpoAudio');+ expoAudioNativeModule =+ typeof module.AudioStream === 'function'+ ? module+ : null;+ } catch {+ expoAudioNativeModule = null;+ }+ return expoAudioNativeModule ?? null;+}+function decodeBase64ToArrayBuffer(base64: string): ArrayBuffer {const binary = typeof atob === 'function'? atob(base64)@@ -187,6 +377,133 @@ function decodeBase64(base64: string): string {return output;}+function normalizeSampleRate(sampleRate: number | undefined): number {+ if (sampleRate === undefined) return 16_000;+ if (!Number.isFinite(sampleRate) || sampleRate < 8_000 || sampleRate > 192_000) {+ throw new RangeError(`Unsupported realtime audio sample rate: ${sampleRate}`);+ }+ return Math.round(sampleRate);+}++function createExpoAudioPcm16Converter(+ targetSampleRate: number,+): (+ input: ArrayBuffer,+ sourceSampleRate: number,+ sourceChannels: number,+) => ArrayBuffer {+ const state: ExpoAudioPcm16ResampleState = {+ sourceSampleRate: 0,+ sourceChannels: 0,+ targetSampleRate,+ sourceFramesConsumed: 0,+ outputFramesProduced: 0,+ };+ return (input, sourceSampleRate, sourceChannels) => convertExpoAudioPcm16(+ input,+ sourceSampleRate,+ sourceChannels,+ targetSampleRate,+ state,+ );+}++/**+ * Converts interleaved little-endian PCM16 from Expo AudioStream into the mono+ * sample rate declared to the ASR provider. AudioStream may fall back to a+ * hardware-supported rate, so forwarding its bytes unchanged would make the+ * provider interpret (for example) 48 kHz audio as 16 kHz. The optional state+ * keeps the resampling clock continuous across native buffer boundaries.+ */+function convertExpoAudioPcm16(+ input: ArrayBuffer,+ sourceSampleRate: number,+ sourceChannels: number,+ targetSampleRate: number,+ state?: ExpoAudioPcm16ResampleState,+): ArrayBuffer {+ if (!Number.isFinite(sourceSampleRate) || sourceSampleRate <= 0) {+ throw new RangeError(`Invalid source sample rate: ${sourceSampleRate}`);+ }+ if (!Number.isInteger(sourceChannels) || sourceChannels <= 0) {+ throw new RangeError(`Invalid source channel count: ${sourceChannels}`);+ }+ if (!Number.isFinite(targetSampleRate) || targetSampleRate <= 0) {+ throw new RangeError(`Invalid target sample rate: ${targetSampleRate}`);+ }++ const resampleState = state ?? {+ sourceSampleRate,+ sourceChannels,+ targetSampleRate,+ sourceFramesConsumed: 0,+ outputFramesProduced: 0,+ };+ if (+ resampleState.sourceSampleRate !== sourceSampleRate+ || resampleState.sourceChannels !== sourceChannels+ || resampleState.targetSampleRate !== targetSampleRate+ ) {+ resampleState.sourceSampleRate = sourceSampleRate;+ resampleState.sourceChannels = sourceChannels;+ resampleState.targetSampleRate = targetSampleRate;+ resampleState.sourceFramesConsumed = 0;+ resampleState.outputFramesProduced = 0;+ }++ const bytesPerFrame = sourceChannels * 2;+ const sourceFrameCount = Math.floor(input.byteLength / bytesPerFrame);+ if (sourceFrameCount === 0) return new ArrayBuffer(0);+ const sourceFrameStart = resampleState.sourceFramesConsumed;+ const sourceFrameEnd = sourceFrameStart + sourceFrameCount;+ const outputFrameEnd = Math.ceil(+ sourceFrameEnd * targetSampleRate / sourceSampleRate,+ );+ const outputFrameCount = outputFrameEnd - resampleState.outputFramesProduced;++ if (sourceChannels === 1 && sourceSampleRate === targetSampleRate) {+ resampleState.sourceFramesConsumed = sourceFrameEnd;+ resampleState.outputFramesProduced = outputFrameEnd;+ const alignedByteLength = sourceFrameCount * bytesPerFrame;+ return input.byteLength === alignedByteLength+ ? input+ : input.slice(0, alignedByteLength);+ }++ const inputView = new DataView(input);+ const output = new ArrayBuffer(outputFrameCount * 2);+ const outputView = new DataView(output);++ for (let outputIndex = 0; outputIndex < outputFrameCount; outputIndex += 1) {+ const globalOutputFrameIndex =+ resampleState.outputFramesProduced + outputIndex;+ const sourceFrameIndex = Math.floor(+ globalOutputFrameIndex * sourceSampleRate / targetSampleRate,+ ) - sourceFrameStart;+ if (sourceFrameIndex < 0 || sourceFrameIndex >= sourceFrameCount) {+ throw new RangeError(+ `Invalid realtime audio resampling phase: ${sourceFrameIndex}`,+ );+ }+ let monoSample = 0;+ for (let channelIndex = 0; channelIndex < sourceChannels; channelIndex += 1) {+ const byteOffset = (+ sourceFrameIndex * sourceChannels + channelIndex+ ) * 2;+ monoSample += inputView.getInt16(byteOffset, true);+ }+ const averagedSample = Math.max(+ -32_768,+ Math.min(32_767, Math.round(monoSample / sourceChannels)),+ );+ outputView.setInt16(outputIndex * 2, averagedSample, true);+ }++ resampleState.sourceFramesConsumed = sourceFrameEnd;+ resampleState.outputFramesProduced = outputFrameEnd;+ return output;+}+function isE2eMockRealtimeAudioEnabled(): boolean {return process.env.EXPO_PUBLIC_XDT_MOBILE_E2E_MOCK_AUDIO === '1';}