Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 补充语音收音诊断并改善空结果提示

Dash5e2943ea0208
diff --git a/apps/mobile/modules/xdt-mobile-realtime-audio/ios/XdtMobileRealtimeAudioModule.swift b/apps/mobile/modules/xdt-mobile-realtime-audio/ios/XdtMobileRealtimeAudioModule.swift
index feb5c0ac87..caffbbe4ba 100644
--- a/apps/mobile/modules/xdt-mobile-realtime-audio/ios/XdtMobileRealtimeAudioModule.swift
+++ b/apps/mobile/modules/xdt-mobile-realtime-audio/ios/XdtMobileRealtimeAudioModule.swift
@@ -37,7 +37,16 @@ public class XdtMobileRealtimeAudioModule: Module {
Events(onAudioChunk, onAudioError)
AsyncFunction("start") { (options: [String: Any]?) in
- try self.startCapture(options: options)
+ return try self.sessionStateQueue.sync { () -> [String: Any] in
+ try self.startCaptureLocked(options: options)
+ let session = AVAudioSession.sharedInstance()
+ // Port types only: names and UIDs can contain personal information.
+ return [
+ "inputPortTypes": session.currentRoute.inputs.map { $0.portType.rawValue },
+ "inputSampleRate": session.sampleRate,
+ "inputChannels": session.inputNumberOfChannels
+ ]
+ }
}
AsyncFunction("stop") {
@@ -139,12 +148,6 @@ public class XdtMobileRealtimeAudioModule: Module {
try? session.setActive(false, options: .notifyOthersOnDeactivation)
}
- private func startCapture(options: [String: Any]?) throws {
- try sessionStateQueue.sync {
- try self.startCaptureLocked(options: options)
- }
- }
-
// Must run on sessionStateQueue.
private func startCaptureLocked(options: [String: Any]?) throws {
cancelScheduledDeactivateLocked()
diff --git a/apps/mobile/modules/xdt-mobile-realtime-audio/src/index.ts b/apps/mobile/modules/xdt-mobile-realtime-audio/src/index.ts
index 6a5f88e480..1af2c6e070 100644
--- a/apps/mobile/modules/xdt-mobile-realtime-audio/src/index.ts
+++ b/apps/mobile/modules/xdt-mobile-realtime-audio/src/index.ts
@@ -16,7 +16,11 @@ export type XdtMobileAudioErrorEvent = {
};
export type XdtMobileRealtimeAudioModule = {
- start(options?: { sampleRate?: number; bufferSize?: number }): Promise<void>;
+ start(options?: { sampleRate?: number; bufferSize?: number }): Promise<{
+ inputPortTypes: string[];
+ inputSampleRate: number;
+ inputChannels: number;
+ } | void>;
stop(): Promise<void>;
prewarm(): Promise<void>;
};
diff --git a/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts b/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts
index 26108421b2..8ac5354401 100644
--- a/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts
+++ b/apps/mobile/src/__tests__/mobileRealtimeAudio.test.ts
@@ -2,6 +2,9 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { requireNativeModule } from 'expo-modules-core';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { logMobileVoice } from '@/session/mobileVoiceDiagnostics';
+
+vi.mock('@/session/mobileVoiceDiagnostics', () => ({ logMobileVoice: vi.fn() }));
vi.mock('expo-modules-core', () => ({
EventEmitter: class {
@@ -32,6 +35,26 @@ afterEach(async () => {
});
describe('mobileRealtimeAudio', () => {
+ it.each([undefined, { inputPortTypes: ['MicrophoneBuiltIn'], inputSampleRate: 48000, inputChannels: 1 }])(
+ 'logs input metadata and supports installed modules without it: %j', async (input) => {
+ const native = {
+ addListener: vi.fn(() => ({ remove: vi.fn() })),
+ start: vi.fn(async () => input),
+ stop: vi.fn(async () => undefined),
+ };
+ vi.mocked(requireNativeModule).mockReturnValue(native);
+ const { startMobileRealtimeAudio } = await import('@/session/mobileRealtimeAudio');
+ const stop = await startMobileRealtimeAudio({ onChunk: vi.fn() });
+ expect(logMobileVoice).toHaveBeenLastCalledWith('debug', 'capture input', {
+ backend: 'ios-native',
+ inputPortTypes: input?.inputPortTypes ?? ['unknown'],
+ inputSampleRate: input?.inputSampleRate,
+ inputChannels: input?.inputChannels,
+ });
+ await stop();
+ },
+ );
+
it('waits for the previous singleton recorder to finish starting and stopping before reuse', async () => {
let finishStart!: () => void;
let finishStop!: () => void;
diff --git a/apps/mobile/src/__tests__/mobileVoiceAudioLevels.test.ts b/apps/mobile/src/__tests__/mobileVoiceAudioLevels.test.ts
new file mode 100644
index 0000000000..38aae4deb2
--- /dev/null
+++ b/apps/mobile/src/__tests__/mobileVoiceAudioLevels.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+import { MobileVoiceAudioLevels } from '@/session/mobileVoiceAudioLevels';
+
+describe('recording level diagnostics', () => {
+ it('distinguishes no samples from digital silence', () => {
+ const levels = new MobileVoiceAudioLevels();
+ expect(levels.summary()).toEqual({ capturedAudioMs: 0, rmsDbfs: undefined, peakDbfs: undefined });
+ levels.append(new Int16Array(160).buffer, 16000);
+ expect(levels.summary()).toEqual({ capturedAudioMs: 10, rmsDbfs: -90, peakDbfs: -90 });
+ });
+
+ it('weights RMS by samples rather than averaging packet levels', () => {
+ const levels = new MobileVoiceAudioLevels();
+ levels.append(new Int16Array(160).fill(-16384).buffer, 16000);
+ levels.append(new Int16Array(480).buffer, 16000);
+ expect(levels.summary()).toEqual({ capturedAudioMs: 40, rmsDbfs: -12, peakDbfs: -6 });
+ });
+});
diff --git a/apps/mobile/src/__tests__/mobileVoiceController.test.ts b/apps/mobile/src/__tests__/mobileVoiceController.test.ts
index 1b01b088d3..4230c63a6b 100644
--- a/apps/mobile/src/__tests__/mobileVoiceController.test.ts
+++ b/apps/mobile/src/__tests__/mobileVoiceController.test.ts
@@ -1225,6 +1225,7 @@ describe('mobileVoiceController', () => {
it('ends a silent recording at stop without waiting for the pending ASR handshake', async () => {
const asr = new GatedStartAsrProvider();
+ const onError = vi.fn();
const states: string[] = [];
const order: string[] = [];
let micStopped = false;
@@ -1233,6 +1234,7 @@ describe('mobileVoiceController', () => {
initialDraft: 'prefix',
asr,
refiner: null,
+ onError,
startAudio: async ({ onChunk }) => {
// Digital silence plus a noise floor well under the sound threshold.
onChunk({ pcm16: new Int16Array(320).buffer, trace: { capturedAt: 0, convertedAt: 0, chunkIndex: 0, sampleRate: 16_000, durationMs: 20 } });
@@ -1258,6 +1260,7 @@ describe('mobileVoiceController', () => {
// A handshake failing after the silent end is not an error for the caller.
asr.failStart(new Error('late connect failure'));
await expect(startPromise).resolves.toBeUndefined();
+ expect(onError).not.toHaveBeenCalled();
});
it('submits a ready pause refinement and keeps the raw transcript for dictionary learning', async () => {
diff --git a/apps/mobile/src/__tests__/mobileVoiceDiagnostics.test.ts b/apps/mobile/src/__tests__/mobileVoiceDiagnostics.test.ts
index 2f1a922546..94b8d0989c 100644
--- a/apps/mobile/src/__tests__/mobileVoiceDiagnostics.test.ts
+++ b/apps/mobile/src/__tests__/mobileVoiceDiagnostics.test.ts
@@ -122,6 +122,11 @@ describe('mobile voice diagnostics', () => {
const logged = messages();
expect(logged.every((record) => record.scope === 'voice')).toBe(true);
const names = logged.map((record) => record.args[0]);
+ expect(logged.find((record) => record.args[0] === 'stop requested')?.args[1]).toMatchObject({
+ capturedAudioMs: 10,
+ rmsDbfs: -30,
+ peakDbfs: -30,
+ });
for (const name of [
'start',
'capture live',
diff --git a/apps/mobile/src/i18n/locales/en/composer.json b/apps/mobile/src/i18n/locales/en/composer.json
index 691acabf3d..356c050f9d 100644
--- a/apps/mobile/src/i18n/locales/en/composer.json
+++ b/apps/mobile/src/i18n/locales/en/composer.json
@@ -97,7 +97,7 @@
"sessionExpiredOrForbidden": "Your {{appName}} voice sign-in has expired or lacks permission. Check your sign-in status and try again (status {{status}}).",
"incomplete": "Voice input didn't finish. Try again.",
"missingRefinerTargetProvider": "Voice refinement is unavailable. Sign in to {{appName}} again and retry.",
- "emptyTranscript": "Speech was detected but no text was recognized. Try again.",
+ "emptyTranscript": "Couldn't hear you clearly. Check your microphone or move closer and try again.",
"connectionInterrupted": "The voice connection was interrupted. Check your network and try again.",
"recognitionStalled": "Voice recognition stopped returning results. Try again.",
"transcriptKept": "{{message}} The text recognized so far was kept — you can edit it directly.",
diff --git a/apps/mobile/src/i18n/locales/ja/composer.json b/apps/mobile/src/i18n/locales/ja/composer.json
index 509206b457..de7d2cb831 100644
--- a/apps/mobile/src/i18n/locales/ja/composer.json
+++ b/apps/mobile/src/i18n/locales/ja/composer.json
@@ -97,7 +97,7 @@
"sessionExpiredOrForbidden": "{{appName}} の音声サービスのログインが失効したか、権限がありません。ログイン状態を確認してからやり直してください(ステータス {{status}})。",
"incomplete": "音声入力が完了しませんでした。もう一度お試しください。",
"missingRefinerTargetProvider": "音声の推敲を利用できません。{{appName}} にもう一度ログインしてから再試行してください。",
- "emptyTranscript": "音声を検出しましたが、テキストを認識できませんでした。もう一度お試しください。",
+ "emptyTranscript": "聞き取れませんでした。マイクを確認するか、近づいてもう一度お試しください。",
"connectionInterrupted": "音声接続が中断されました。ネットワークを確認してからやり直してください。",
"recognitionStalled": "音声認識の結果が返ってこなくなりました。もう一度お試しください。",
"transcriptKept": "{{message}}(ここまで認識したテキストは保持しており、そのまま編集できます)",
diff --git a/apps/mobile/src/i18n/locales/ko/composer.json b/apps/mobile/src/i18n/locales/ko/composer.json
index 9e157a74b1..e4c2ea179f 100644
--- a/apps/mobile/src/i18n/locales/ko/composer.json
+++ b/apps/mobile/src/i18n/locales/ko/composer.json
@@ -97,7 +97,7 @@
"sessionExpiredOrForbidden": "{{appName}} 음성 서비스 로그인이 만료되었거나 권한이 없습니다. 로그인 상태를 확인한 후 다시 시도하세요(상태 코드 {{status}}).",
"incomplete": "음성 입력이 완료되지 않았습니다. 다시 시도하세요.",
"missingRefinerTargetProvider": "음성 다듬기를 사용할 수 없습니다. {{appName}}에 다시 로그인한 후 다시 시도하세요.",
- "emptyTranscript": "음성이 감지되었지만 텍스트를 인식하지 못했습니다. 다시 시도해 주세요.",
+ "emptyTranscript": "잘 듣지 못했습니다. 마이크를 확인하거나 더 가까이에서 다시 시도해 주세요.",
"connectionInterrupted": "음성 연결이 중단되었습니다. 네트워크를 확인한 뒤 다시 시도하세요.",
"recognitionStalled": "음성 인식 결과가 더 이상 오지 않습니다. 다시 시도하세요.",
"transcriptKept": "{{message}} 지금까지 인식된 텍스트는 유지했습니다. 바로 이어서 편집할 수 있습니다.",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/composer.json b/apps/mobile/src/i18n/locales/zh-CN/composer.json
index 223b65ec4e..387e20535a 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/composer.json
@@ -97,7 +97,7 @@
"sessionExpiredOrForbidden": "{{appName}} 语音服务的登录已失效或没有权限,请确认登录状态后重试(状态码 {{status}})。",
"incomplete": "语音输入未完成,请重试。",
"missingRefinerTargetProvider": "语音润色暂不可用,请重新登录 {{appName}} 后重试。",
- "emptyTranscript": "检测到语音但未识别出文本,请重试。",
+ "emptyTranscript": "没听清,请检查麦克风或靠近一点再试。",
"connectionInterrupted": "语音连接中断了,请检查网络后重试。",
"recognitionStalled": "语音识别没有继续返回结果,请重试。",
"transcriptKept": "{{message}}(识别出的文字已经保留,可以直接编辑)",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/composer.json b/apps/mobile/src/i18n/locales/zh-TW/composer.json
index d2b0c5b15f..1e8f1e6253 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/composer.json
@@ -97,7 +97,7 @@
"sessionExpiredOrForbidden": "{{appName}} 語音服務的登入已失效或沒有權限,請確認登入狀態後重試(狀態碼 {{status}})。",
"incomplete": "語音輸入未完成,請重試。",
"missingRefinerTargetProvider": "語音潤色暫時無法使用,請重新登入 {{appName}} 後重試。",
- "emptyTranscript": "檢測到語音但未識別出文字,請重試。",
+ "emptyTranscript": "沒聽清楚,請檢查麥克風或靠近一點再試。",
"connectionInterrupted": "語音連線中斷了,請檢查網路後重試。",
"recognitionStalled": "語音識別沒有繼續返回結果,請重試。",
"transcriptKept": "{{message}}(識別出的文字已經保留,可以直接編輯)",
diff --git a/apps/mobile/src/session/mobileRealtimeAudio.ts b/apps/mobile/src/session/mobileRealtimeAudio.ts
index 6f7dba7998..4426f89633 100644
--- a/apps/mobile/src/session/mobileRealtimeAudio.ts
+++ b/apps/mobile/src/session/mobileRealtimeAudio.ts
@@ -5,6 +5,7 @@ import {
} from 'expo-modules-core';
import type { AudioTrace } from '@cindy/voice-input-core';
import { i18n } from '@/i18n';
+import { logMobileVoice } from '@/session/mobileVoiceDiagnostics';
export type MobileRealtimeAudioChunk = {
pcm16: ArrayBuffer;
@@ -24,7 +25,11 @@ type NativeAudioErrorEvent = {
};
type NativeRealtimeAudioModule = {
- start(options?: { sampleRate?: number; bufferSize?: number }): Promise<void>;
+ start(options?: { sampleRate?: number; bufferSize?: number }): Promise<{
+ inputPortTypes: string[];
+ inputSampleRate: number;
+ inputChannels: number;
+ } | void>;
stop(): Promise<void>;
prewarm(): Promise<void>;
};
@@ -170,10 +175,17 @@ async function startCustomNativeRealtimeAudio(
subscriptions.push(binding.module.addListener('onAudioError', (event) => {
options.onError?.(new Error(event.message));
}));
- await binding.module.start({
+ const input = await binding.module.start({
sampleRate: options.sampleRate ?? 16_000,
bufferSize: options.bufferSize ?? DEFAULT_NATIVE_AUDIO_BUFFER_SIZE,
});
+ logMobileVoice('debug', 'capture input', {
+ backend: 'ios-native',
+ // Older installed native modules return void; capture remains compatible.
+ inputPortTypes: input?.inputPortTypes ?? ['unknown'],
+ inputSampleRate: input?.inputSampleRate,
+ inputChannels: input?.inputChannels,
+ });
} catch (error) {
try {
subscriptions.forEach((subscription) => subscription.remove());
@@ -296,6 +308,12 @@ async function startExpoAudioRealtimeAudio(
try {
await stream.start();
+ logMobileVoice('debug', 'capture input', {
+ backend: 'expo-audio',
+ inputPortTypes: ['unknown'],
+ inputSampleRate: stream.sampleRate,
+ inputChannels: stream.channels,
+ });
streamStarted = true;
lastChunkAt = Date.now();
watchdog = setInterval(() => {
diff --git a/apps/mobile/src/session/mobileVoiceAudioLevels.ts b/apps/mobile/src/session/mobileVoiceAudioLevels.ts
new file mode 100644
index 0000000000..31f3924969
--- /dev/null
+++ b/apps/mobile/src/session/mobileVoiceAudioLevels.ts
@@ -0,0 +1,29 @@
+/** Aggregate PCM levels only; never retain audio or use volume as proof of speech. */
+export class MobileVoiceAudioLevels {
+ private samples = 0;
+ private energy = 0;
+ private peak = 0;
+ private durationMs = 0;
+
+ append(pcm: ArrayBuffer, sampleRate: number): void {
+ if (pcm.byteLength % 2 || !Number.isFinite(sampleRate) || sampleRate <= 0) return;
+ const view = new DataView(pcm);
+ for (let offset = 0; offset < pcm.byteLength; offset += 2) {
+ const value = view.getInt16(offset, true);
+ this.energy += value * value;
+ this.peak = Math.max(this.peak, Math.abs(value));
+ }
+ this.samples += pcm.byteLength / 2;
+ this.durationMs += pcm.byteLength / 2 / sampleRate * 1000;
+ }
+
+ summary(): { capturedAudioMs: number; rmsDbfs?: number; peakDbfs?: number } {
+ // Undefined means no samples. Digital silence uses a finite -90 dBFS floor.
+ const dbfs = (level: number): number => Math.round(20 * Math.log10(Math.max(1, level) / 32768));
+ return {
+ capturedAudioMs: Math.round(this.durationMs),
+ rmsDbfs: this.samples ? dbfs(Math.sqrt(this.energy / this.samples)) : undefined,
+ peakDbfs: this.samples ? dbfs(this.peak) : undefined,
+ };
+ }
+}
diff --git a/apps/mobile/src/session/mobileVoiceController.ts b/apps/mobile/src/session/mobileVoiceController.ts
index 133f86068f..1e98bc850a 100644
--- a/apps/mobile/src/session/mobileVoiceController.ts
+++ b/apps/mobile/src/session/mobileVoiceController.ts
@@ -34,6 +34,7 @@ import {
type MobileVoiceDraftInsertion,
} from '@/session/mobileVoiceInput';
import { startMobileRealtimeAudio } from '@/session/mobileRealtimeAudio';
+import { MobileVoiceAudioLevels } from '@/session/mobileVoiceAudioLevels';
import { readCachedMobileVoiceDictionary } from '@/session/mobileVoiceDictionaryCache';
import {
classifyMobileVoiceFailure,
@@ -215,6 +216,7 @@ export function createMobileVoiceControllerSession(
// recognition or refinement. Deliberately conservative: any plausible sound
// (including background noise) keeps the normal path.
let soundDetected = false;
+ let audioLevels = new MobileVoiceAudioLevels();
let runStartedAt = Date.now();
const runTag = (): string => shortRunId(controller.id);
const recordTimeline = createMobileVoiceTimelineRecorder({ provider: options.credential.asr.provider });
@@ -483,6 +485,7 @@ export function createMobileVoiceControllerSession(
captureLive = false;
listeningPendingCaptureLive = false;
soundDetected = false;
+ audioLevels = new MobileVoiceAudioLevels();
runStartedAt = Date.now();
// A fresh start() begins a new run from ANY previous phase — in particular
// 'failed': a mic interruption must not poison the next recording on the
@@ -519,6 +522,7 @@ export function createMobileVoiceControllerSession(
// early stop that waits for the in-flight handshake can't buffer and
// later flush post-stop speech/noise.
if (captureTornDown()) return;
+ audioLevels.append(chunk.pcm16, chunk.trace.sampleRate ?? options.credential.asr.pcmSampleRate ?? 16_000);
if (!soundDetected && hasPcmSound(chunk.pcm16)) soundDetected = true;
markCaptureLive();
controller.appendAudio(chunk.pcm16, chunk.trace);
@@ -601,6 +605,7 @@ export function createMobileVoiceControllerSession(
elapsedMs: stopRequestedAt - runStartedAt,
captureLive,
soundDetected,
+ ...audioLevels.summary(),
hasTranscript: Boolean(voiceInsertion),
});
if (stopAudio) {