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(voice): 保持重录原文可见并支持主动结束录音

DavidShenb684813a7a44
diff --git a/apps/desktop/src/main/voice-input/speaker/__tests__/speakerFilterService.test.ts b/apps/desktop/src/main/voice-input/speaker/__tests__/speakerFilterService.test.ts
index a87f96bbc3..641433c00e 100644
--- a/apps/desktop/src/main/voice-input/speaker/__tests__/speakerFilterService.test.ts
+++ b/apps/desktop/src/main/voice-input/speaker/__tests__/speakerFilterService.test.ts
@@ -154,7 +154,13 @@ describe('parseEnrollmentClips', () => {
expect(parseEnrollmentClips({ clips: [clip(320), clip(320), 'nope'] })).toBeNull();
expect(parseEnrollmentClips({ clips: [clip(320), clip(320), clip(0)] })).toBeNull();
expect(parseEnrollmentClips({ clips: [clip(320), clip(320), clip(321)] })).toBeNull();
- // Longer than the 20-second limit.
- expect(parseEnrollmentClips({ clips: [clip(320), clip(320), clip(20 * 16_000 * 2 + 2)] })).toBeNull();
+ // Longer than the 30-second limit.
+ expect(parseEnrollmentClips({ clips: [clip(320), clip(320), clip(30 * 16_000 * 2 + 2)] })).toBeNull();
+ });
+
+ it('accepts three full 30-second recordings', () => {
+ const clips = [clip(30 * 16_000 * 2), clip(30 * 16_000 * 2), clip(30 * 16_000 * 2)];
+ expect(parseEnrollmentClips({ clips })?.map((buffer) => buffer.byteLength))
+ .toEqual([960_000, 960_000, 960_000]);
});
});
diff --git a/apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx b/apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx
index 618bb17a43..be31ea7076 100644
--- a/apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx
+++ b/apps/desktop/src/renderer/components/settings/VoiceSpeakerEnrollmentDialog.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState, type CSSProperties } from 'react';
import { useTranslation } from 'react-i18next';
import * as Dialog from '@radix-ui/react-dialog';
-import { Check, Mic } from 'lucide-react';
+import { Check, Mic, Square } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { createLogger } from '@/lib/logger';
@@ -37,7 +37,7 @@ interface VoiceSpeakerEnrollmentDialogProps {
/**
* Reads three short passages aloud to build the voiceprint. Each clip records
- * a fixed time and stops by itself; any clip can be re-recorded, and main
+ * up to 30 seconds or until the user finishes; any clip can be re-recorded, and main
* points at the clip to redo when one does not match the others.
*/
export function VoiceSpeakerEnrollmentDialog({
@@ -58,6 +58,7 @@ export function VoiceSpeakerEnrollmentDialog({
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<EnrollError | null>(null);
const abortRef = useRef<AbortController | null>(null);
+ const stopRef = useRef<AbortController | null>(null);
const recordButtonRef = useRef<HTMLButtonElement>(null);
const submitButtonRef = useRef<HTMLButtonElement>(null);
const returnFocusRef = useRef<HTMLElement | null>(null);
@@ -67,6 +68,7 @@ export function VoiceSpeakerEnrollmentDialog({
const reset = useCallback(() => {
abortRef.current?.abort();
abortRef.current = null;
+ stopRef.current = null;
setClips(CLIP_INDEXES.map(() => null));
setCurrent(0);
setRecording(false);
@@ -99,6 +101,8 @@ export function VoiceSpeakerEnrollmentDialog({
setError(null);
const controller = new AbortController();
abortRef.current = controller;
+ const stopController = new AbortController();
+ stopRef.current = stopController;
const index = current;
setRecording(true);
setProgress(0);
@@ -113,9 +117,14 @@ export function VoiceSpeakerEnrollmentDialog({
const clip = await recordSpeakerEnrollmentClip({
deviceId: microphoneDeviceId ?? undefined,
durationMs: VOICE_SPEAKER_ENROLLMENT_TARGET_CLIP_SEC * 1000,
- onLevel: setLevel,
- onProgress: setProgress,
+ onLevel: (value) => {
+ if (!controller.signal.aborted) setLevel(value);
+ },
+ onProgress: (value) => {
+ if (!controller.signal.aborted) setProgress(value);
+ },
signal: controller.signal,
+ stopSignal: stopController.signal,
});
if (controller.signal.aborted) return;
const next = [...clipsRef.current];
@@ -130,6 +139,7 @@ export function VoiceSpeakerEnrollmentDialog({
} finally {
if (abortRef.current === controller && !controller.signal.aborted) {
abortRef.current = null;
+ stopRef.current = null;
setRecording(false);
setLevel(0);
}
@@ -267,16 +277,19 @@ export function VoiceSpeakerEnrollmentDialog({
variant="secondary"
size="md"
type="button"
- disabled={recording || submitting}
+ disabled={submitting || (recording && progress === 0)}
onClick={() => {
- void record();
+ if (recording) stopRef.current?.abort();
+ else void record();
}}
>
- <Mic size={14} />
+ {recording ? <Square size={14} /> : <Mic size={14} />}
{t(
- clips[current]
- ? 'settings.voiceInput.speakerFilter.enroll.rerecord'
- : 'settings.voiceInput.speakerFilter.enroll.record',
+ recording
+ ? 'settings.voiceInput.speakerFilter.enroll.stop'
+ : clips[current]
+ ? 'settings.voiceInput.speakerFilter.enroll.rerecord'
+ : 'settings.voiceInput.speakerFilter.enroll.record',
)}
</Button>
<p
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/VoiceSpeakerEnrollmentDialog.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/VoiceSpeakerEnrollmentDialog.test.tsx
index 9fcaaa99b3..752521c18c 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/VoiceSpeakerEnrollmentDialog.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/VoiceSpeakerEnrollmentDialog.test.tsx
@@ -45,6 +45,32 @@ beforeEach(() => {
afterEach(cleanup);
describe('VoiceSpeakerEnrollmentDialog', () => {
+ it('lets the user finish each clip early, then submit the three captured clips', async () => {
+ const clips: ArrayBuffer[] = [];
+ mocks.record.mockImplementation((options) => {
+ expect(options.durationMs).toBe(30_000);
+ options.onProgress(0.4);
+ return new Promise<ArrayBuffer>((resolve) => {
+ options.stopSignal.addEventListener('abort', () => {
+ expect(options.signal.aborted).toBe(false);
+ const clip = new ArrayBuffer(12 * 16_000 * 2);
+ clips.push(clip);
+ resolve(clip);
+ }, { once: true });
+ });
+ });
+ mocks.enroll.mockResolvedValue({ ok: true, status: {} });
+ render(<Harness />);
+ await openDialog();
+ for (let index = 0; index < 3; index += 1) {
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: key('record') })); });
+ expect(screen.getByRole('button', { name: key('submit') }).hasAttribute('disabled')).toBe(true);
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: key('stop') })); });
+ }
+ await act(async () => { fireEvent.click(screen.getByRole('button', { name: key('submit') })); });
+ expect(mocks.enroll).toHaveBeenCalledExactlyOnceWith(clips);
+ });
+
it('restores the opener after cancelling', async () => {
render(<Harness />);
const opener = await openDialog();
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 50ac2a5c0f..95e9ca56a8 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2558,7 +2558,7 @@
},
"profile": {
"missing": "No voiceprint yet",
- "missingHint": "Record your voiceprint to enable filtering. It takes about 20 seconds.",
+ "missingHint": "Record your voiceprint to enable filtering.",
"enrolled": "Voiceprint recorded",
"enrolledAt": "Recorded {{date}}",
"enroll": "Record voiceprint",
@@ -2583,10 +2583,11 @@
},
"enroll": {
"title": "Record voiceprint",
- "description": "Where you usually use voice input, read the {{clips}} passages below in your normal voice. Each recording lasts {{seconds}} seconds. Make sure no one else is talking.",
+ "description": "Read the {{clips}} passages below in your normal voice. Each recording lasts up to {{seconds}} seconds; stop recording when you finish reading. Record where you usually use voice input, with no one else talking.",
"stepsAriaLabel": "Passages to read",
"step": "{{current}} of {{total}}",
"record": "Start reading",
+ "stop": "Stop Recording",
"rerecord": "Record this one again",
"recording": "Recording, {{seconds}} s left",
"recorded": "Recorded",
@@ -2599,7 +2600,7 @@
"p3": "Please make this text more concise, keep the key numbers and conclusions, and then sum up the main points in three to five sentences."
},
"errors": {
- "too_short": "Passage {{index}} has too little speech. Record it again without long pauses.",
+ "too_short": "Too little speech was detected in passage {{index}}. Record it again.",
"no_embedding": "No voiceprint could be read from passage {{index}}. Record it again.",
"inconsistent": "Passage {{index}} does not sound like the same person as the others; another voice or noise may have been picked up. Record it again.",
"models_missing": "The recognition model has not finished downloading. Try again shortly.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 4bb9af7d9d..8cd54f4c0d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2531,7 +2531,7 @@
},
"profile": {
"missing": "声紋が未登録です",
- "missingHint": "声紋を登録すると有効になります。約 20 秒かかります。",
+ "missingHint": "声紋を登録すると有効になります。",
"enrolled": "声紋を登録済み",
"enrolledAt": "{{date}} に登録",
"enroll": "声紋を登録",
@@ -2556,10 +2556,11 @@
},
"enroll": {
"title": "声紋を登録",
- "description": "普段音声入力を使う場所で、下の {{clips}} つの文章をいつもの話し方で読み上げてください。1 つにつき {{seconds}} 秒録音します。録音中は他の人が話さないようにしてください。",
+ "description": "以下の {{clips}} つの文章を普段の声で読み上げてください。各録音は最大 {{seconds}} 秒です。読み終えたら録音を終了してください。普段音声入力を使う場所で、ほかの人が同時に話さないように録音してください。",
"stepsAriaLabel": "読み上げる文章",
"step": "{{current}} / {{total}}",
"record": "読み上げを開始",
+ "stop": "録音を終了",
"rerecord": "この文章を録り直す",
"recording": "録音中、残り {{seconds}} 秒",
"recorded": "録音済み",
@@ -2572,7 +2573,7 @@
"p3": "この文章をもう少し簡潔にして、重要な数字と結論は残したうえで、要点を三つから五つの文でまとめてください。"
},
"errors": {
- "too_short": "{{index}} つ目の録音は話している時間が短すぎます。長く止まらずに読み上げて、録り直してください。",
+ "too_short": "{{index}} つ目の録音で検出された音声が短すぎます。録り直してください。",
"no_embedding": "{{index}} つ目の録音から声紋を読み取れませんでした。録り直してください。",
"inconsistent": "{{index}} つ目の録音が他と同じ人の声に聞こえません。他の人の声や雑音が入った可能性があります。録り直してください。",
"models_missing": "認識モデルのダウンロードがまだ完了していません。しばらくしてからお試しください。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 10a8e0e412..957a05213d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2531,7 +2531,7 @@
},
"profile": {
"missing": "등록된 성문이 없습니다",
- "missingHint": "성문을 등록하면 적용됩니다. 약 20초 걸립니다.",
+ "missingHint": "성문을 등록하면 적용됩니다.",
"enrolled": "성문 등록됨",
"enrolledAt": "{{date}} 등록",
"enroll": "성문 등록",
@@ -2556,10 +2556,11 @@
},
"enroll": {
"title": "성문 등록",
- "description": "평소 음성 입력을 사용하는 곳에서 아래 문장 {{clips}}개를 평소 말투로 읽어 주세요. 문장마다 {{seconds}}초씩 녹음합니다. 녹음하는 동안 다른 사람이 말하지 않도록 해 주세요.",
+ "description": "아래 {{clips}}개 문장을 평소 목소리로 읽어 주세요. 각 녹음은 최대 {{seconds}}초이며, 다 읽으면 녹음을 종료하세요. 평소 음성 입력을 사용하는 장소에서 다른 사람이 동시에 말하지 않도록 녹음하세요.",
"stepsAriaLabel": "읽을 문장",
"step": "{{current}} / {{total}}",
"record": "읽기 시작",
+ "stop": "녹음 종료",
"rerecord": "이 문장 다시 녹음",
"recording": "녹음 중, {{seconds}}초 남음",
"recorded": "녹음 완료",
@@ -2572,7 +2573,7 @@
"p3": "이 내용을 좀 더 간결하게 다듬고, 중요한 숫자와 결론은 남긴 다음 핵심을 세 문장에서 다섯 문장으로 요약해 주세요."
},
"errors": {
- "too_short": "{{index}}번째 녹음은 말한 시간이 너무 짧습니다. 오래 멈추지 말고 다시 녹음하세요.",
+ "too_short": "{{index}}번째 녹음에서 감지된 음성이 너무 짧습니다. 다시 녹음하세요.",
"no_embedding": "{{index}}번째 녹음에서 성문을 읽지 못했습니다. 다시 녹음하세요.",
"inconsistent": "{{index}}번째 녹음이 다른 녹음과 같은 사람의 목소리로 들리지 않습니다. 다른 사람의 목소리나 소음이 섞였을 수 있으니 다시 녹음하세요.",
"models_missing": "인식 모델 다운로드가 아직 끝나지 않았습니다. 잠시 후 다시 시도하세요.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 3d1166a215..d95d455072 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2531,7 +2531,7 @@
},
"profile": {
"missing": "还没有录入声纹",
- "missingHint": "录入声纹后才会生效,大约需要 20 秒。",
+ "missingHint": "录入声纹后才会生效。",
"enrolled": "已录入声纹",
"enrolledAt": "{{date}} 录入",
"enroll": "录入声纹",
@@ -2556,10 +2556,11 @@
},
"enroll": {
"title": "录入声纹",
- "description": "请在平时使用语音输入的地方,用平常的语气朗读下面 {{clips}} 段文字,每段录音 {{seconds}} 秒。录音时请不要让别人说话。",
+ "description": "请用平常的语气朗读下面 {{clips}} 段文字。每段最多录音 {{seconds}} 秒,读完点击结束录音。请在平时使用语音输入的地方录制,避免其他人同时说话。",
"stepsAriaLabel": "朗读段落",
"step": "第 {{current}} / {{total}} 段",
"record": "开始朗读",
+ "stop": "结束录音",
"rerecord": "重录这段",
"recording": "正在录音,还剩 {{seconds}} 秒",
"recorded": "这段已录好",
@@ -2572,7 +2573,7 @@
"p3": "请帮我把这段内容改得更简洁一些,保留关键数字和结论,然后用三到五句话总结一下重点。"
},
"errors": {
- "too_short": "第 {{index}} 段里说话的时间太短,请重录这段,朗读时不要停顿太久。",
+ "too_short": "第 {{index}} 段检测到的语音不足,请重新录制。",
"no_embedding": "第 {{index}} 段没能识别出声纹,请重录这段。",
"inconsistent": "第 {{index}} 段和其他几段不像同一个人,可能混进了别人的声音或噪音,请重录这段。",
"models_missing": "识别模型还没有下载完成,请稍后再试。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index ed62544b18..ca1109e68a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -2531,7 +2531,7 @@
},
"profile": {
"missing": "尚未錄製聲紋",
- "missingHint": "錄製聲紋後才會生效,大約需要 20 秒。",
+ "missingHint": "錄入聲紋後才會生效。",
"enrolled": "已錄製聲紋",
"enrolledAt": "{{date}} 錄製",
"enroll": "錄製聲紋",
@@ -2556,10 +2556,11 @@
},
"enroll": {
"title": "錄製聲紋",
- "description": "請在平常使用語音輸入的地方,用平常的語氣朗讀下面 {{clips}} 段文字,每段錄音 {{seconds}} 秒。錄音時請不要讓別人說話。",
+ "description": "請用平常的語氣朗讀下面 {{clips}} 段文字。每段最多錄音 {{seconds}} 秒,讀完點選結束錄音。請在平時使用語音輸入的地方錄製,避免其他人同時說話。",
"stepsAriaLabel": "朗讀段落",
"step": "第 {{current}} / {{total}} 段",
"record": "開始朗讀",
+ "stop": "結束錄音",
"rerecord": "重錄這段",
"recording": "正在錄音,還剩 {{seconds}} 秒",
"recorded": "這段已錄好",
@@ -2572,7 +2573,7 @@
"p3": "請幫我把這段內容改得更簡潔一些,保留關鍵數字和結論,然後用三到五句話總結重點。"
},
"errors": {
- "too_short": "第 {{index}} 段裡說話的時間太短,請重錄這段,朗讀時不要停頓太久。",
+ "too_short": "第 {{index}} 段偵測到的語音不足,請重新錄製。",
"no_embedding": "第 {{index}} 段沒能辨識出聲紋,請重錄這段。",
"inconsistent": "第 {{index}} 段和其他幾段不像同一個人,可能混入了別人的聲音或噪音,請重錄這段。",
"models_missing": "辨識模型尚未下載完成,請稍後再試。",
diff --git a/apps/desktop/src/renderer/voice-input/__tests__/speakerEnrollmentRecorder.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/speakerEnrollmentRecorder.test.ts
new file mode 100644
index 0000000000..919aa833b8
--- /dev/null
+++ b/apps/desktop/src/renderer/voice-input/__tests__/speakerEnrollmentRecorder.test.ts
@@ -0,0 +1,78 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const audio = vi.hoisted(() => ({
+ start: vi.fn(async () => {}),
+ stop: vi.fn(async () => {}),
+ onPcm: null as null | ((chunk: { pcm16k: ArrayBuffer }) => void),
+}));
+vi.mock('../WebMicAudioEngine', () => ({
+ WebMicAudioEngine: class {
+ start = audio.start;
+ stop = audio.stop;
+ onPcm16k(callback: NonNullable<typeof audio.onPcm>) { audio.onPcm = callback; }
+ },
+}));
+vi.mock('../workletUrl', () => ({ getVoiceInputWorkletUrl: () => '' }));
+
+import {
+ recordSpeakerEnrollmentClip,
+ SpeakerEnrollmentAbortedError,
+ SpeakerEnrollmentNoAudioError,
+} from '../speakerEnrollmentRecorder';
+
+const emit = (samples: number) => audio.onPcm?.({ pcm16k: new Int16Array(samples).fill(1234).buffer });
+
+beforeEach(() => { vi.clearAllMocks(); });
+afterEach(() => { vi.useRealTimers(); });
+
+describe('speaker enrollment recording', () => {
+ it('keeps the captured samples when stopped early, with no padding or late chunks', async () => {
+ const stop = new AbortController();
+ const recording = recordSpeakerEnrollmentClip({ durationMs: 30_000, stopSignal: stop.signal });
+ emit(12 * 16_000);
+ stop.abort();
+ emit(16_000);
+ expect(new Int16Array(await recording)).toEqual(new Int16Array(12 * 16_000).fill(1234));
+ expect(audio.stop).toHaveBeenCalledOnce();
+ });
+
+ it('continues past six seconds and caps automatic completion at thirty seconds', async () => {
+ const resolved = vi.fn();
+ const recording = recordSpeakerEnrollmentClip({ durationMs: 30_000 }).then((clip) => { resolved(); return clip; });
+ emit(6 * 16_000);
+ await Promise.resolve();
+ expect(resolved).not.toHaveBeenCalled();
+ emit(25 * 16_000);
+ expect((await recording).byteLength).toBe(960_000);
+ expect(audio.stop).toHaveBeenCalledOnce();
+ });
+
+ it('rejects an empty manually stopped clip', async () => {
+ const stop = new AbortController();
+ const recording = recordSpeakerEnrollmentClip({ durationMs: 30_000, stopSignal: stop.signal });
+ stop.abort();
+ await expect(recording).rejects.toBeInstanceOf(SpeakerEnrollmentNoAudioError);
+ expect(audio.stop).toHaveBeenCalledOnce();
+ });
+
+ it('discards audio on cancellation even when finish was also requested', async () => {
+ const stop = new AbortController();
+ const cancel = new AbortController();
+ const recording = recordSpeakerEnrollmentClip({ durationMs: 30_000, stopSignal: stop.signal, signal: cancel.signal });
+ emit(16_000);
+ stop.abort();
+ cancel.abort();
+ await expect(recording).rejects.toBeInstanceOf(SpeakerEnrollmentAbortedError);
+ expect(audio.stop).toHaveBeenCalledOnce();
+ });
+
+ it('does not treat a stalled partial capture as a successful manual stop', async () => {
+ vi.useFakeTimers();
+ const recording = recordSpeakerEnrollmentClip({ durationMs: 30_000 });
+ const rejected = expect(recording).rejects.toBeInstanceOf(SpeakerEnrollmentNoAudioError);
+ emit(16_000);
+ await vi.advanceTimersByTimeAsync(35_000);
+ await rejected;
+ expect(audio.stop).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/renderer/voice-input/speakerEnrollmentRecorder.ts b/apps/desktop/src/renderer/voice-input/speakerEnrollmentRecorder.ts
index 9a222e7b8c..1785027c41 100644
--- a/apps/desktop/src/renderer/voice-input/speakerEnrollmentRecorder.ts
+++ b/apps/desktop/src/renderer/voice-input/speakerEnrollmentRecorder.ts
@@ -11,6 +11,8 @@ export type SpeakerEnrollmentClipOptions = {
/** Elapsed fraction in [0, 1]. */
onProgress?: (fraction: number) => void;
signal?: AbortSignal;
+ /** Finish and keep captured audio; `signal` instead cancels and discards it. */
+ stopSignal?: AbortSignal;
};
export class SpeakerEnrollmentNoAudioError extends Error {
@@ -35,10 +37,11 @@ export class SpeakerEnrollmentAbortedError extends Error {
*
* Uses the dictation capture profile (same processing, no keep-alive) so the
* enrolled voice sounds like the audio the gate later judges. Stops by
- * itself after `durationMs`; aborting releases the microphone and rejects.
+ * itself at `durationMs` or on `stopSignal`; aborting `signal` discards the clip.
*/
export async function recordSpeakerEnrollmentClip(options: SpeakerEnrollmentClipOptions): Promise<ArrayBuffer> {
if (options.signal?.aborted) throw new SpeakerEnrollmentAbortedError();
+ if (options.stopSignal?.aborted) throw new SpeakerEnrollmentNoAudioError();
const engine = new WebMicAudioEngine({
workletUrl: getVoiceInputWorkletUrl(),
deviceId: options.deviceId,
@@ -51,9 +54,15 @@ export async function recordSpeakerEnrollmentClip(options: SpeakerEnrollmentClip
const done = new Promise<void>((resolve) => {
finish = resolve;
});
+ let stoppedEarly = false;
+ const onStop = (): void => {
+ stoppedEarly = true;
+ finish();
+ };
+ options.stopSignal?.addEventListener('abort', onStop, { once: true });
engine.onPcm16k(({ pcm16k }) => {
- if (samples >= targetSamples) return;
+ if (options.signal?.aborted || stoppedEarly || samples >= targetSamples) return;
const chunk = new Int16Array(pcm16k.slice(0));
chunks.push(chunk);
samples += chunk.length;
@@ -81,10 +90,11 @@ export async function recordSpeakerEnrollmentClip(options: SpeakerEnrollmentClip
} finally {
clearTimeout(watchdog);
options.signal?.removeEventListener('abort', onAbort);
+ options.stopSignal?.removeEventListener('abort', onStop);
await engine.stop().catch(() => undefined);
}
if (options.signal?.aborted) throw new SpeakerEnrollmentAbortedError();
- if (stalled && samples < targetSamples) throw new SpeakerEnrollmentNoAudioError();
+ if (samples === 0 || (stalled && !stoppedEarly && samples < targetSamples)) throw new SpeakerEnrollmentNoAudioError();
const out = new Int16Array(Math.min(samples, targetSamples));
let offset = 0;
diff --git a/apps/desktop/src/shared/voiceSpeakerFilter.ts b/apps/desktop/src/shared/voiceSpeakerFilter.ts
index fb645322b5..73da75a345 100644
--- a/apps/desktop/src/shared/voiceSpeakerFilter.ts
+++ b/apps/desktop/src/shared/voiceSpeakerFilter.ts
@@ -5,6 +5,8 @@
* encrypted per account, and the renderer only ever sees whether one exists.
*/
+import { SPEAKER_ENROLLMENT_MAX_CLIP_SEC } from '@cindy/voice-input-core';
+
export const VOICE_SPEAKER_FILTER_CHANNELS = {
getStatus: 'voice-input:speaker:get-status',
downloadModels: 'voice-input:speaker:download-models',
@@ -32,9 +34,9 @@ export type VoiceSpeakerFilterStatus = {
/** Read-aloud clips collected during enrollment. */
export const VOICE_SPEAKER_ENROLLMENT_CLIP_COUNT = 3;
/** Each clip is PCM16 mono 16 kHz; anything longer is rejected by main. */
-export const VOICE_SPEAKER_ENROLLMENT_MAX_CLIP_SEC = 20;
+export const VOICE_SPEAKER_ENROLLMENT_MAX_CLIP_SEC = SPEAKER_ENROLLMENT_MAX_CLIP_SEC;
/** Recording UI stops each clip automatically after this long. */
-export const VOICE_SPEAKER_ENROLLMENT_TARGET_CLIP_SEC = 6;
+export const VOICE_SPEAKER_ENROLLMENT_TARGET_CLIP_SEC = SPEAKER_ENROLLMENT_MAX_CLIP_SEC;
export type VoiceSpeakerEnrollRequest = {
/** PCM16 little-endian mono 16 kHz clips. */
diff --git a/apps/mobile/app/settings/voice-speaker-filter.tsx b/apps/mobile/app/settings/voice-speaker-filter.tsx
index 8f348d1096..f60b19a5a9 100644
--- a/apps/mobile/app/settings/voice-speaker-filter.tsx
+++ b/apps/mobile/app/settings/voice-speaker-filter.tsx
@@ -1,16 +1,20 @@
import { useRouter } from 'expo-router';
+import { useHeaderHeight } from 'expo-router/react-navigation';
import { useCallback, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';
-import { Alert, Pressable, ScrollView, StyleSheet, View } from 'react-native';
+import { Alert, Platform, Pressable, ScrollView, StyleSheet, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react-native';
import {
SPEAKER_ENROLLMENT_CLIP_COUNT,
+ SPEAKER_ENROLLMENT_MAX_CLIP_SEC,
SPEAKER_GATE_STRICTNESS_VALUES,
type SpeakerGateStrictness,
} from '@cindy/voice-input-core';
import { Text } from '@/components/AppText';
+import { MainWindowActionButton, MainWindowOptionButton } from '@/components/MobilePrimitives';
+import { MOBILE_VISUAL_MOCK_ENABLED } from '@/config/env';
import { SimpleStackHeader, simpleScrollInsetProps, simpleScrollScreenSafeAreaEdges } from '@/platform/chrome';
import {
ActionInfoRow,
@@ -37,10 +41,10 @@ import {
recordMobileSpeakerClip,
} from '@/session/mobileSpeakerEnrollmentRecorder';
import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
-import { iconSize, iconStroke, spacing } from '@/theme/tokens';
+import { fontWeight, iconSize, iconStroke, lineHeight, spacing, typeScale } from '@/theme/tokens';
import { goBackGuarded } from '@/utils/backGuard';
-const CLIP_SECONDS = 6;
+const CLIP_SECONDS = SPEAKER_ENROLLMENT_MAX_CLIP_SEC;
const CLIP_INDEXES = Array.from({ length: SPEAKER_ENROLLMENT_CLIP_COUNT }, (_, index) => index);
type EnrollErrorKey =
@@ -62,7 +66,27 @@ type EnrollErrorKey =
*
* SettingsGroup 按直接子元素画分隔线,所以每组的行都以带 key 的数组给出,不包 Fragment。
*/
-export default function VoiceSpeakerFilterScreen() {
+const liveServices = {
+ cancelMobileSpeakerModelDownload, deleteMobileSpeakerProfile, downloadMobileSpeakerModels,
+ enrollMobileSpeaker, getMobileSpeakerFilterSnapshot, hydrateMobileSpeakerFilter,
+ setMobileSpeakerFilterEnabled, setMobileSpeakerFilterStrictness, subscribeMobileSpeakerFilter,
+};
+
+export default function VoiceSpeakerFilterRoute() {
+ // Explicit development fixture: real capture/UI, deterministic validation
+ // failures. Never loads models or writes voiceprints to a user's account.
+ const services: typeof liveServices = __DEV__ && MOBILE_VISUAL_MOCK_ENABLED
+ && process.env.EXPO_PUBLIC_CINDY_SPEAKER_ENROLLMENT_SCENARIO === '1'
+ ? require('@/debug/speakerEnrollmentScenario').speakerEnrollmentScenario : liveServices;
+ return <VoiceSpeakerFilterScreen services={services} />;
+}
+
+export function VoiceSpeakerFilterScreen({ services = liveServices }: { services?: typeof liveServices }) {
+ const {
+ deleteMobileSpeakerProfile, enrollMobileSpeaker, getMobileSpeakerFilterSnapshot,
+ hydrateMobileSpeakerFilter, setMobileSpeakerFilterEnabled, setMobileSpeakerFilterStrictness,
+ subscribeMobileSpeakerFilter,
+ } = services;
const router = useRouter();
const { t, i18n } = useTranslation();
const language = i18n.resolvedLanguage || i18n.language;
@@ -70,7 +94,6 @@ export default function VoiceSpeakerFilterScreen() {
const passageLanguage = language === 'zh-CN' || language === 'zh-TW' ? language : 'en';
const rowStyles = useSettingsRowStyles();
const styles = useThemedStyles(makeStyles);
- const { colors } = useTheme();
const state = useSyncExternalStore(subscribeMobileSpeakerFilter, getMobileSpeakerFilterSnapshot);
const [enrolling, setEnrolling] = useState(false);
@@ -80,7 +103,15 @@ export default function VoiceSpeakerFilterScreen() {
const [progress, setProgress] = useState(0);
const [saving, setSaving] = useState(false);
const [enrollError, setEnrollError] = useState<{ key: EnrollErrorKey; clipIndex?: number } | null>(null);
+ const [retryIndex, setRetryIndex] = useState<number | null>(null);
+ const scrollRef = useRef<ScrollView>(null);
+ const passageRef = useRef<View>(null);
+ const scrollOffset = useRef(0);
+ const revealFrame = useRef<number | null>(null);
+ const revealGeneration = useRef(0);
+ const headerHeight = useHeaderHeight();
const abortRef = useRef<AbortController | null>(null);
+ const stopRef = useRef<AbortController | null>(null);
const clipsRef = useRef(clips);
clipsRef.current = clips;
const reportActionFailure = useCallback(() => {
@@ -94,15 +125,47 @@ export default function VoiceSpeakerFilterScreen() {
// Never leave the microphone open behind a closed screen.
useEffect(() => () => abortRef.current?.abort(), []);
+ // Measure the committed native layout, including iOS's transparent navigation
+ // bar. Only move an off-screen passage; recording updates must not move it.
+ const revealPassage = useCallback(() => {
+ if (revealFrame.current !== null) cancelAnimationFrame(revealFrame.current);
+ const generation = ++revealGeneration.current;
+ revealFrame.current = requestAnimationFrame(() => {
+ revealFrame.current = null;
+ scrollRef.current?.getNativeScrollRef()?.measureInWindow((_x, viewportY, _width, viewportHeight) => {
+ passageRef.current?.measureInWindow((_px, passageY, _pw, passageHeight) => {
+ if (generation !== revealGeneration.current || passageHeight <= 0) return;
+ const top = Math.max(viewportY, Platform.OS === 'ios' ? headerHeight : viewportY) + spacing.lg;
+ const bottom = viewportY + viewportHeight - spacing.lg;
+ if (passageY >= top && passageY + passageHeight <= bottom) return;
+ scrollRef.current?.scrollTo({
+ y: Math.max(Platform.OS === 'ios' ? -headerHeight : 0, scrollOffset.current + passageY - top),
+ animated: false,
+ });
+ });
+ });
+ });
+ }, [headerHeight]);
+
+ useEffect(() => {
+ if (enrolling && !recording) revealPassage();
+ return () => {
+ revealGeneration.current += 1;
+ if (revealFrame.current !== null) cancelAnimationFrame(revealFrame.current);
+ };
+ }, [current, enrolling, enrollError, recording, revealPassage]);
+
const resetEnrollment = useCallback(() => {
abortRef.current?.abort();
abortRef.current = null;
+ stopRef.current = null;
setClips(CLIP_INDEXES.map(() => null));
setCurrent(0);
setRecording(false);
setProgress(0);
setSaving(false);
setEnrollError(null);
+ setRetryIndex(null);
}, []);
const record = useCallback(async () => {
@@ -110,6 +173,8 @@ export default function VoiceSpeakerFilterScreen() {
setEnrollError(null);
const controller = new AbortController();
abortRef.current = controller;
+ const stopController = new AbortController();
+ stopRef.current = stopController;
const index = current;
setRecording(true);
setProgress(0);
@@ -120,11 +185,13 @@ export default function VoiceSpeakerFilterScreen() {
if (abortRef.current === controller && !controller.signal.aborted) setProgress(fraction);
},
signal: controller.signal,
+ stopSignal: stopController.signal,
});
if (abortRef.current !== controller || controller.signal.aborted) return;
const next = [...clipsRef.current];
next[index] = clip;
setClips(next);
+ setRetryIndex((previous) => previous === index ? null : previous);
const nextEmpty = CLIP_INDEXES.find((candidate) => !next[candidate]);
if (nextEmpty !== undefined) setCurrent(nextEmpty);
} catch (error) {
@@ -134,6 +201,7 @@ export default function VoiceSpeakerFilterScreen() {
} finally {
if (abortRef.current === controller) {
abortRef.current = null;
+ stopRef.current = null;
setRecording(false);
}
}
@@ -153,6 +221,7 @@ export default function VoiceSpeakerFilterScreen() {
setEnrollError({ key: result.reason, clipIndex: result.clipIndex });
if (result.clipIndex !== undefined) {
const redo = result.clipIndex;
+ setRetryIndex(redo);
setClips((previous) => previous.map((clip, index) => (index === redo ? null : clip)));
setCurrent(redo);
}
@@ -178,9 +247,13 @@ export default function VoiceSpeakerFilterScreen() {
const showDetails = state.supported && state.hydrated && (state.enabled || state.enrolled);
const modelsReady = state.modelState === 'ready';
const allRecorded = clips.every((clip) => clip !== null);
- const recordLabel = t(clips[current]
- ? 'settings.voiceSpeakerFilter.enroll.rerecord'
- : 'settings.voiceSpeakerFilter.enroll.record');
+ const recordLabel = t(recording
+ ? 'settings.voiceSpeakerFilter.enroll.stop'
+ : clips[current] || retryIndex === current
+ ? 'settings.voiceSpeakerFilter.enroll.rerecordStep'
+ : 'settings.voiceSpeakerFilter.enroll.record', { index: current + 1 });
+ const visibleError = enrollError && (enrollError.clipIndex === undefined || enrollError.clipIndex === current)
+ ? enrollError : null;
const deleteRow = (
<ActionInfoRow
@@ -201,74 +274,73 @@ export default function VoiceSpeakerFilterScreen() {
})}
</Text>
</View>,
- ...CLIP_INDEXES.map((index) => {
- const stepLabel = t('settings.voiceSpeakerFilter.enroll.step', {
- current: index + 1,
- total: SPEAKER_ENROLLMENT_CLIP_COUNT,
- });
- return (
- <Pressable
- key={`step-${index}`}
- accessibilityLabel={stepLabel}
- accessibilityRole="button"
- accessibilityState={{ selected: index === current, disabled: recording || saving }}
- disabled={recording || saving}
- onPress={() => {
- setCurrent(index);
- setEnrollError(null);
- }}
- style={({ pressed }) => [rowStyles.row, pressed && rowStyles.pressed]}
- testID={`settings.voiceSpeakerFilter.enroll.step.${index}`}
- >
- <View style={rowStyles.rowLine}>
- <Text style={rowStyles.rowLabel}>{stepLabel}</Text>
- {clips[index] ? (
- <Check color={colors.textSecondary} size={iconSize.md} strokeWidth={iconStroke.regular} />
- ) : null}
- </View>
- {index === current ? (
- <Text style={rowStyles.rowLabel}>
- {t(`settings.voiceSpeakerFilter.enroll.passages.p${index + 1}`, { lng: passageLanguage })}
- </Text>
- ) : null}
- </Pressable>
- );
- }),
- <ActionInfoRow
- key="record"
- accessibilityLabel={recordLabel}
- disabled={recording || saving}
- label={recordLabel}
- onPress={() => {
- void record();
- }}
- testID="settings.voiceSpeakerFilter.enroll.record"
- value={recording
- ? t('settings.voiceSpeakerFilter.enroll.recording', {
- seconds: Math.max(0, Math.ceil(CLIP_SECONDS * (1 - progress))),
- })
- : ''}
- />,
- enrollError ? (
- <View key="error" style={rowStyles.row}>
- <Text accessibilityRole="alert" style={rowStyles.rowDetail}>
- {t(`settings.voiceSpeakerFilter.enroll.errors.${enrollError.key}`, {
- index: (enrollError.clipIndex ?? 0) + 1,
- })}
+ <View key="reader" style={[rowStyles.row, styles.reader]}>
+ <View style={styles.steps}>
+ {CLIP_INDEXES.map((index) => {
+ const status = recording && index === current ? 'recording'
+ : retryIndex === index ? 'retry' : clips[index] ? 'recorded' : 'pending';
+ const label = t('settings.voiceSpeakerFilter.enroll.stepChoice', {
+ index: index + 1,
+ status: t(`settings.voiceSpeakerFilter.enroll.stepStatus.${status}`),
+ });
+ return (
+ <View key={index} style={styles.step}>
+ <MainWindowOptionButton
+ density="default"
+ label={String(index + 1)}
+ accessibilityLabel={label}
+ selected={index === current}
+ disabled={recording || saving}
+ onPress={() => setCurrent(index)}
+ style={styles.stepButton}
+ testID={`settings.voiceSpeakerFilter.enroll.step.${index}`}
+ />
+ <Text style={styles.stepStatus}>{t(`settings.voiceSpeakerFilter.enroll.stepStatus.${status}`)}</Text>
+ </View>
+ );
+ })}
+ </View>
+ <View ref={passageRef} collapsable={false} onLayout={revealPassage} style={styles.passageBlock}>
+ <Text style={styles.passageTitle}>
+ {t('settings.voiceSpeakerFilter.enroll.step', { current: current + 1, total: SPEAKER_ENROLLMENT_CLIP_COUNT })}
+ </Text>
+ <Text style={styles.passage} testID="settings.voiceSpeakerFilter.enroll.passage">
+ {t(`settings.voiceSpeakerFilter.enroll.passages.p${current + 1}`, { lng: passageLanguage })}
</Text>
</View>
- ) : null,
- <ActionInfoRow
- key="submit"
- accessibilityLabel={t('settings.voiceSpeakerFilter.enroll.submit')}
- disabled={!allRecorded || recording || saving}
- label={t('settings.voiceSpeakerFilter.enroll.submit')}
- onPress={() => {
- void submit();
- }}
- testID="settings.voiceSpeakerFilter.enroll.submit"
- value={saving ? t('settings.voiceSpeakerFilter.enroll.saving') : ''}
- />,
+ <View style={styles.status} testID="settings.voiceSpeakerFilter.enroll.status">
+ <Text accessibilityRole={visibleError ? 'alert' : undefined} style={rowStyles.rowDetail}>
+ {recording
+ ? t('settings.voiceSpeakerFilter.enroll.recording', { seconds: Math.max(0, Math.ceil(CLIP_SECONDS * (1 - progress))) })
+ : saving ? t('settings.voiceSpeakerFilter.enroll.saving')
+ : visibleError ? t(`settings.voiceSpeakerFilter.enroll.errors.${visibleError.key}`, { index: (visibleError.clipIndex ?? 0) + 1 })
+ : t('settings.voiceSpeakerFilter.enroll.readHint')}
+ </Text>
+ {visibleError?.clipIndex !== undefined && clips.some(Boolean) ? (
+ <Text style={rowStyles.rowDetail}>{t('settings.voiceSpeakerFilter.enroll.otherClipsKept')}</Text>
+ ) : null}
+ </View>
+ <MainWindowActionButton action={{
+ label: recordLabel,
+ disabled: saving || (recording && progress === 0),
+ tone: allRecorded && !recording ? 'secondary' : 'primary',
+ onPress: () => {
+ if (recording) stopRef.current?.abort();
+ else void record();
+ },
+ testID: 'settings.voiceSpeakerFilter.enroll.record',
+ }} />
+ </View>,
+ <View key="submit" style={rowStyles.row}>
+ <MainWindowActionButton action={{
+ label: t('settings.voiceSpeakerFilter.enroll.submit'),
+ disabled: !allRecorded || recording || saving,
+ busy: saving,
+ tone: allRecorded && !recording ? 'primary' : 'secondary',
+ onPress: () => { void submit(); },
+ testID: 'settings.voiceSpeakerFilter.enroll.submit',
+ }} />
+ </View>,
<ActionInfoRow
key="cancel"
accessibilityLabel={t('settings.voiceSpeakerFilter.enroll.cancel')}
@@ -321,7 +393,10 @@ export default function VoiceSpeakerFilterScreen() {
onBack={() => goBackGuarded(router, '/settings')}
title={t('settings.voiceSpeakerFilter.title')}
/>
- <ScrollView {...simpleScrollInsetProps} contentContainerStyle={styles.content} testID="settings.voiceSpeakerFilter.scroll">
+ <ScrollView ref={scrollRef} {...simpleScrollInsetProps}
+ onScroll={(event) => { scrollOffset.current = event.nativeEvent.contentOffset.y; }}
+ scrollEventThrottle={16}
+ contentContainerStyle={styles.content} testID="settings.voiceSpeakerFilter.scroll">
<SettingsGroup footer={t('settings.voiceSpeakerFilter.privacy')}>
<SettingsSwitchRow
accessibilityLabel={t('settings.voiceSpeakerFilter.label')}
@@ -473,4 +548,14 @@ function formatMegabytes(bytes: number): string {
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
safeArea: { backgroundColor: colors.surface, flex: 1 },
content: { paddingBottom: spacing.xxl, paddingHorizontal: spacing.lg, paddingTop: spacing.lg },
+ reader: { gap: spacing.lg },
+ steps: { flexDirection: 'row', gap: spacing.md },
+ step: { flex: 1, minWidth: 0, gap: spacing.sm },
+ stepButton: { alignSelf: 'stretch' },
+ stepStatus: { color: colors.textTertiary, fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular, textAlign: 'center' },
+ passageBlock: { gap: spacing.sm },
+ passageTitle: { color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium },
+ // Reading content is not a flexing label in a horizontal settings row.
+ passage: { color: colors.textPrimary, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.regular },
+ status: { gap: spacing.xs },
});
diff --git a/apps/mobile/src/__tests__/mobileSpeakerEnrollmentRecorder.test.ts b/apps/mobile/src/__tests__/mobileSpeakerEnrollmentRecorder.test.ts
index cddb98d60d..1dd39e1f9f 100644
--- a/apps/mobile/src/__tests__/mobileSpeakerEnrollmentRecorder.test.ts
+++ b/apps/mobile/src/__tests__/mobileSpeakerEnrollmentRecorder.test.ts
@@ -135,4 +135,57 @@ describe('speaker enrollment microphone lifecycle', () => {
expect(audio.get).not.toHaveBeenCalled();
expect(audio.start).not.toHaveBeenCalled();
});
+
+ it('keeps only captured audio when the user finishes early, ignoring late chunks', async () => {
+ const finish = new AbortController();
+ const progress = vi.fn();
+ const recording = recordMobileSpeakerClip({ durationMs: 30_000, stopSignal: finish.signal, onProgress: progress });
+ await flush();
+ const pcm = new Int16Array(12 * 16_000).fill(1234);
+ audio.start.mock.calls[0][0].onChunk({ pcm16: pcm.buffer });
+ finish.abort();
+ emit(16_000);
+ const clip = await recording;
+ expect(new Int16Array(clip)).toEqual(pcm);
+ expect(progress).toHaveBeenCalledExactlyOnceWith(0.4);
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
+ it('continues beyond six seconds and automatically caps the clip at thirty seconds', async () => {
+ const resolved = vi.fn();
+ const recording = recordMobileSpeakerClip({ durationMs: 30_000 }).then((clip) => { resolved(); return clip; });
+ await flush();
+ emit(6 * 16_000);
+ await flush();
+ expect(resolved).not.toHaveBeenCalled();
+ emit(25 * 16_000);
+ expect((await recording).byteLength).toBe(30 * 16_000 * 2);
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
+ it('does not create an empty clip when stopped before audio arrives', async () => {
+ const finish = new AbortController();
+ const recording = recordMobileSpeakerClip({ durationMs: 30_000, stopSignal: finish.signal });
+ const rejected = expect(recording).rejects.toBeInstanceOf(MobileSpeakerEnrollmentNoAudioError);
+ await flush();
+ finish.abort();
+ await rejected;
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
+ it('cancellation still discards a manually finished clip while the microphone is stopping', async () => {
+ const finish = new AbortController();
+ const cancel = new AbortController();
+ const stopping = deferred<void>();
+ stop.mockReturnValueOnce(stopping.promise);
+ const recording = recordMobileSpeakerClip({ durationMs: 30_000, stopSignal: finish.signal, signal: cancel.signal });
+ const rejected = expect(recording).rejects.toBeInstanceOf(MobileSpeakerEnrollmentAbortedError);
+ await flush();
+ emit(16_000);
+ finish.abort();
+ await flush();
+ cancel.abort();
+ stopping.resolve();
+ await rejected;
+ });
});
diff --git a/apps/mobile/src/__tests__/voiceSpeakerFilterScreen.render.test.tsx b/apps/mobile/src/__tests__/voiceSpeakerFilterScreen.render.test.tsx
new file mode 100644
index 0000000000..28470d9e79
--- /dev/null
+++ b/apps/mobile/src/__tests__/voiceSpeakerFilterScreen.render.test.tsx
@@ -0,0 +1,172 @@
+// @vitest-environment jsdom
+import React, { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import settings from '@/i18n/locales/zh-CN/settings.json';
+
+const h = vi.hoisted(() => ({
+ record: vi.fn(), enroll: vi.fn(), scroll: vi.fn(), platform: 'ios',
+ frames: new Map<number, FrameRequestCallback>(), nextFrame: 0,
+ passageY: 180, passageHeight: 100,
+ onScroll: null as null | ((event: any) => void),
+ snapshot: { supported: true, hydrated: true, enabled: true, enrolled: false,
+ strictness: 'standard', strictnessCustomized: false, modelState: 'ready', downloadedBytes: 0, totalBytes: 0 },
+}));
+vi.mock('react-native', async () => {
+ const { createElement: el, useImperativeHandle, useEffect } = await import('react');
+ return {
+ Alert: { alert: vi.fn() }, Platform: { get OS() { return h.platform; } }, StyleSheet: { create: (styles: unknown) => styles },
+ View: ({ ref, children, testID, onLayout }: any) => {
+ useImperativeHandle(ref, () => ({ measureInWindow: (cb: any) => cb(0, h.passageY, 320, h.passageHeight) }));
+ useEffect(() => { onLayout?.(); }, [onLayout]);
+ return el('div', { 'data-testid': testID }, children);
+ },
+ ScrollView: ({ ref, children, onScroll }: any) => {
+ h.onScroll = onScroll;
+ useImperativeHandle(ref, () => ({ getNativeScrollRef: () => ({ measureInWindow: (cb: any) => cb(0, 0, 360, 640) }), scrollTo: h.scroll }));
+ return el('div', {}, children);
+ },
+ Pressable: ({ children, onPress, disabled, testID }: any) => el('button', { onClick: onPress, disabled, 'data-testid': testID }, children),
+ };
+});
+vi.mock('react-native-safe-area-context', async () => ({ SafeAreaView: (await import('react-native')).View }));
+vi.mock('lucide-react-native', () => ({ Check: () => null }));
+vi.mock('expo-router', () => ({ useRouter: () => ({}) }));
+vi.mock('expo-router/react-navigation', () => ({ useHeaderHeight: () => 96 }));
+vi.mock('@/config/env', () => ({ MOBILE_VISUAL_MOCK_ENABLED: false }));
+vi.mock('@/utils/backGuard', () => ({ goBackGuarded: vi.fn() }));
+vi.mock('@/theme', () => ({ useTheme: () => ({ colors: {} }), useThemedStyles: (fn: any) => fn({}) }));
+vi.mock('@/components/AppText', async () => {
+ const { createElement: el } = await import('react');
+ return { Text: ({ children, testID, style, accessibilityRole }: any) => el('span', { 'data-testid': testID, style, role: accessibilityRole }, children) };
+});
+vi.mock('@/components/MobilePrimitives', async () => {
+ const { createElement: el } = await import('react');
+ const Button = ({ label, onPress, disabled, selected, testID, accessibilityLabel }: any) => el('button', {
+ onClick: onPress, disabled, 'data-testid': testID, 'aria-label': accessibilityLabel, 'aria-selected': selected,
+ }, label);
+ return { MainWindowActionButton: ({ action }: any) => el(Button, action), MainWindowOptionButton: Button };
+});
+vi.mock('@/session/SettingsGroupRows', async () => {
+ const { createElement: el } = await import('react');
+ return {
+ useSettingsRowStyles: () => ({}), SettingsGroup: ({ children }: any) => el('section', {}, children),
+ SettingsSwitchRow: () => null, InfoRow: () => null,
+ ActionInfoRow: ({ onPress, label, testID, disabled }: any) => el('button', { onClick: onPress, disabled, 'data-testid': testID }, label),
+ };
+});
+vi.mock('@/platform/chrome', () => ({ SimpleStackHeader: () => null, simpleScrollInsetProps: {}, simpleScrollScreenSafeAreaEdges: () => [] }));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ i18n: { language: 'zh-CN' }, t: (key: string, vars: Record<string, any> = {}) => {
+ const value = key.replace(/^settings\./, '').split('.').reduce((data: any, part) => data?.[part], settings);
+ return typeof value === 'string' ? value.replace(/{{(\w+)}}/g, (_, name) => String(vars[name])) : key;
+} }) }));
+vi.mock('@/session/mobileSpeakerFilter', () => ({
+ getMobileSpeakerFilterSnapshot: () => h.snapshot, subscribeMobileSpeakerFilter: () => () => {},
+ hydrateMobileSpeakerFilter: async () => {}, enrollMobileSpeaker: h.enroll,
+ setMobileSpeakerFilterEnabled: async () => {}, setMobileSpeakerFilterStrictness: async () => {},
+ deleteMobileSpeakerProfile: async () => {}, downloadMobileSpeakerModels: async () => {}, cancelMobileSpeakerModelDownload: () => {},
+}));
+vi.mock('@/session/mobileSpeakerEnrollmentRecorder', () => ({
+ recordMobileSpeakerClip: h.record, MobileSpeakerEnrollmentAbortedError: class extends Error {},
+ MobileSpeakerEnrollmentNoAudioError: class extends Error {},
+}));
+
+import { VoiceSpeakerFilterScreen } from '../../app/settings/voice-speaker-filter';
+
+let root: Root;
+let host: HTMLDivElement;
+const prefix = 'settings.voiceSpeakerFilter.';
+function node(id: string) { return host.querySelector(`[data-testid="${prefix}${id}"]`)! as HTMLElement; }
+async function click(id: string) { await act(async () => { node(id).click(); }); }
+async function frame() {
+ await act(async () => { const callbacks = [...h.frames.values()]; h.frames.clear(); callbacks.forEach((cb) => cb(0)); });
+}
+async function recordAll() {
+ await click('profile.enroll');
+ for (let i = 0; i < 3; i++) await click('enroll.record');
+ await frame();
+}
+beforeEach(async () => {
+ (globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+ h.record.mockReset().mockImplementation(async () => new ArrayBuffer(20));
+ h.enroll.mockReset(); h.scroll.mockReset(); h.frames.clear(); h.platform = 'ios'; h.passageY = 180;
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { h.frames.set(++h.nextFrame, cb); return h.nextFrame; });
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => { h.frames.delete(id); });
+ host = document.createElement('div'); document.body.append(host); root = createRoot(host);
+ await act(async () => root.render(<VoiceSpeakerFilterScreen />));
+});
+afterEach(async () => { await act(async () => root.unmount()); host.remove(); vi.unstubAllGlobals(); });
+
+describe('speaker enrollment reader', () => {
+ it.each(['too_short', 'no_embedding', 'inconsistent'])('recovers %s into the first passage and keeps other recordings', async (reason) => {
+ await recordAll();
+ expect(node('enroll.passage').textContent).toBe(settings.voiceSpeakerFilter.enroll.passages.p3);
+ h.enroll.mockResolvedValueOnce({ ok: false, reason, clipIndex: 0 });
+ h.passageY = -200;
+ h.onScroll?.({ nativeEvent: { contentOffset: { y: 480 } } });
+ await click('enroll.submit'); await frame();
+ expect(node('enroll.passage').textContent).toBe(settings.voiceSpeakerFilter.enroll.passages.p1);
+ expect(node('enroll.step.0').getAttribute('aria-label')).toContain('待重录');
+ expect(node('enroll.step.1').getAttribute('aria-label')).toContain('已录音');
+ expect(node('enroll.step.2').getAttribute('aria-label')).toContain('已录音');
+ expect(node('enroll.status').textContent).toContain('其他段录音已保留');
+ expect(h.scroll).toHaveBeenCalledWith({ y: 168, animated: false });
+ const before = h.enroll.mock.calls[0][0];
+ await click('enroll.record');
+ h.enroll.mockResolvedValueOnce({ ok: false, reason: 'failed' });
+ await click('enroll.submit');
+ const after = h.enroll.mock.calls[1][0];
+ expect(after[0]).not.toBe(before[0]); expect(after[1]).toBe(before[1]); expect(after[2]).toBe(before[2]);
+ });
+
+ it('keeps the same passage mounted throughout manual stop and recording progress', async () => {
+ await recordAll();
+ h.enroll.mockResolvedValueOnce({ ok: false, reason: 'too_short', clipIndex: 2 });
+ await click('enroll.submit');
+ const passage = node('enroll.passage');
+ h.record.mockImplementationOnce((options) => new Promise<ArrayBuffer>((resolve) => {
+ options.onProgress(0.2);
+ options.stopSignal.addEventListener('abort', () => resolve(new ArrayBuffer(32)), { once: true });
+ }));
+ await click('enroll.record'); await frame();
+ expect(node('enroll.record').textContent).toBe('结束录音');
+ expect(node('enroll.passage')).toBe(passage);
+ expect(passage.textContent).toBe(settings.voiceSpeakerFilter.enroll.passages.p3);
+ expect(passage.style.flex).toBe('');
+ expect(node('enroll.status').textContent).toContain('还剩 24 秒');
+ expect((node('enroll.step.0') as HTMLButtonElement).disabled).toBe(true);
+ expect(h.record.mock.lastCall?.[0].durationMs).toBe(30_000);
+ await click('enroll.record');
+ expect(node('enroll.passage')).toBe(passage);
+ expect(node('enroll.step.2').getAttribute('aria-label')).toContain('已录音');
+ expect((node('enroll.submit') as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it('retains the retry marker when manually inspecting another passage', async () => {
+ await recordAll();
+ h.enroll.mockResolvedValueOnce({ ok: false, reason: 'no_embedding', clipIndex: 0 });
+ await click('enroll.submit'); await click('enroll.step.1');
+ expect(node('enroll.passage').textContent).toBe(settings.voiceSpeakerFilter.enroll.passages.p2);
+ expect(node('enroll.step.0').getAttribute('aria-label')).toContain('待重录');
+ await click('enroll.step.0');
+ expect(node('enroll.status').textContent).toContain('没能识别出声纹');
+ });
+
+ it('does not move an already visible passage or clear clips for a storage failure', async () => {
+ await recordAll();
+ h.scroll.mockClear();
+ h.enroll.mockResolvedValueOnce({ ok: false, reason: 'storage_unavailable' });
+ await click('enroll.submit'); await frame();
+ expect(h.scroll).not.toHaveBeenCalled();
+ for (let i = 0; i < 3; i++) expect(node(`enroll.step.${i}`).getAttribute('aria-label')).toContain('已录音');
+ expect((node('enroll.submit') as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it('uses the Android viewport without subtracting a native iOS header', async () => {
+ h.platform = 'android'; await recordAll();
+ h.enroll.mockResolvedValueOnce({ ok: false, reason: 'too_short', clipIndex: 0 });
+ h.passageY = -100; h.onScroll?.({ nativeEvent: { contentOffset: { y: 300 } } });
+ await click('enroll.submit'); await frame();
+ expect(h.scroll).toHaveBeenLastCalledWith({ y: 184, animated: false });
+ });
+});
diff --git a/apps/mobile/src/__tests__/voiceSpeakerFilterScreen.test.ts b/apps/mobile/src/__tests__/voiceSpeakerFilterScreen.test.ts
index 75f71ef9fa..6db156990c 100644
--- a/apps/mobile/src/__tests__/voiceSpeakerFilterScreen.test.ts
+++ b/apps/mobile/src/__tests__/voiceSpeakerFilterScreen.test.ts
@@ -31,11 +31,12 @@ function deferred<T>() {
function harness() {
const bindings = {
abortRef: { current: null as AbortController | null },
+ stopRef: { current: null as AbortController | null },
clipsRef: { current: [null, null, null] },
recording: false, saving: false, current: 0,
- CLIP_INDEXES: [0, 1, 2], CLIP_SECONDS: 6,
+ CLIP_INDEXES: [0, 1, 2], CLIP_SECONDS: 30,
setClips: vi.fn(), setCurrent: vi.fn(), setRecording: vi.fn(),
- setProgress: vi.fn(), setSaving: vi.fn(), setEnrollError: vi.fn(), setEnrolling: vi.fn(),
+ setProgress: vi.fn(), setSaving: vi.fn(), setEnrollError: vi.fn(), setEnrolling: vi.fn(), setRetryIndex: vi.fn(),
setMobileSpeakerFilterEnabled: vi.fn(async () => {}),
reportActionFailure: vi.fn(),
recordMobileSpeakerClip: vi.fn(),
diff --git a/apps/mobile/src/debug/speakerEnrollmentScenario.ts b/apps/mobile/src/debug/speakerEnrollmentScenario.ts
new file mode 100644
index 0000000000..293e07b07c
--- /dev/null
+++ b/apps/mobile/src/debug/speakerEnrollmentScenario.ts
@@ -0,0 +1,49 @@
+/**
+ * Opt-in Android/iOS UI acceptance fixture. The screen still uses the real
+ * microphone recorder. Only model availability, validation and storage are
+ * replaced. No audio, voiceprint or preferences are persisted.
+ * Enable with BOTH CINDY_MOBILE_VISUAL_MOCK and CINDY_SPEAKER_ENROLLMENT_SCENARIO
+ * EXPO_PUBLIC flags in a development build. Submissions exercise each retry.
+ */
+import type { MobileSpeakerEnrollResult, MobileSpeakerFilterSnapshot } from '@/session/mobileSpeakerFilter';
+
+let snapshot: MobileSpeakerFilterSnapshot = {
+ supported: true, hydrated: true, enabled: true, enrolled: false,
+ strictness: 'standard', strictnessCustomized: false,
+ modelState: 'ready', downloadedBytes: 0, totalBytes: 0,
+};
+const listeners = new Set<() => void>();
+let submission = 0;
+const failures: MobileSpeakerEnrollResult[] = [
+ { ok: false, reason: 'too_short', clipIndex: 0 },
+ { ok: false, reason: 'no_embedding', clipIndex: 1 },
+ { ok: false, reason: 'inconsistent', clipIndex: 2 },
+ { ok: false, reason: 'too_short', clipIndex: 2 },
+];
+function update(patch: Partial<MobileSpeakerFilterSnapshot>) {
+ snapshot = { ...snapshot, ...patch };
+ listeners.forEach((listener) => listener());
+}
+
+export const speakerEnrollmentScenario = {
+ getMobileSpeakerFilterSnapshot: () => snapshot,
+ subscribeMobileSpeakerFilter(listener: () => void) {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+ },
+ hydrateMobileSpeakerFilter: async () => {},
+ setMobileSpeakerFilterEnabled: async (enabled: boolean) => { update({ enabled }); },
+ setMobileSpeakerFilterStrictness: async (strictness: MobileSpeakerFilterSnapshot['strictness'] | null) => {
+ update({ strictness: strictness ?? 'standard', strictnessCustomized: strictness !== null });
+ },
+ deleteMobileSpeakerProfile: async () => { submission = 0; update({ enrolled: false, enrolledAt: undefined }); },
+ downloadMobileSpeakerModels: async () => {},
+ cancelMobileSpeakerModelDownload: () => {},
+ async enrollMobileSpeaker(_clips: ArrayBuffer[]): Promise<MobileSpeakerEnrollResult> {
+ await new Promise((resolve) => setTimeout(resolve, 700));
+ const failure = failures[submission++];
+ if (failure) return failure;
+ update({ enrolled: true, enrolledAt: Date.now() });
+ return { ok: true };
+ },
+};
diff --git a/apps/mobile/src/i18n/locales/en/settings.json b/apps/mobile/src/i18n/locales/en/settings.json
index ef9145befc..f441c123f7 100644
--- a/apps/mobile/src/i18n/locales/en/settings.json
+++ b/apps/mobile/src/i18n/locales/en/settings.json
@@ -245,7 +245,7 @@
"profile": {
"title": "Voiceprint",
"missing": "No voiceprint yet",
- "missingHint": "Record your voiceprint to turn this on. It takes about 20 seconds.",
+ "missingHint": "Record your voiceprint to enable filtering.",
"enrolled": "Voiceprint recorded",
"enrolledAt": "Recorded {{date}}",
"enroll": "Record voiceprint",
@@ -269,11 +269,12 @@
}
},
"enroll": {
- "description": "Where you usually use voice input, read the {{clips}} passages below in your normal voice. Each recording lasts {{seconds}} seconds. Make sure no one else is talking.",
+ "description": "Read the {{clips}} passages below in your normal voice. Each recording lasts up to {{seconds}} seconds; stop recording when you finish reading. Record where you usually use voice input, with no one else talking.",
"step": "Passage {{current}} of {{total}}",
"record": "Start reading",
+ "stop": "Stop Recording",
"rerecord": "Record this one again",
- "recording": "{{seconds}} s left",
+ "recording": "Recording… {{seconds}} seconds left",
"saving": "Creating voiceprint…",
"submit": "Finish",
"cancel": "Cancel",
@@ -283,7 +284,7 @@
"p3": "Please make this text more concise, keep the key numbers and conclusions, and then sum up the main points in three to five sentences."
},
"errors": {
- "too_short": "Passage {{index}} has too little speech. Record it again without long pauses.",
+ "too_short": "Too little speech was detected in passage {{index}}. Record it again.",
"no_embedding": "No voiceprint could be read from passage {{index}}. Record it again.",
"inconsistent": "Passage {{index}} does not sound like the same person as the others; another voice or noise may have been picked up. Record it again.",
"models_missing": "The recognition model has not finished downloading. Try again shortly.",
@@ -291,7 +292,17 @@
"failed": "The voiceprint could not be created. Try again.",
"microphone": "The microphone cannot be used. Check microphone permission and try again.",
"noAudio": "No sound came from the microphone. Check it and try again."
- }
+ },
+ "stepChoice": "Passage {{index}}, {{status}}",
+ "stepStatus": {
+ "pending": "Not recorded",
+ "recorded": "Recorded",
+ "retry": "Record again",
+ "recording": "Recording"
+ },
+ "rerecordStep": "Record Passage {{index}} Again",
+ "readHint": "Start when you are ready. Stop recording when you finish reading.",
+ "otherClipsKept": "Your other recordings have been kept."
}
},
"deviceNameEditor": {
diff --git a/apps/mobile/src/i18n/locales/ja/settings.json b/apps/mobile/src/i18n/locales/ja/settings.json
index 4cf796b483..8b6f1e50e1 100644
--- a/apps/mobile/src/i18n/locales/ja/settings.json
+++ b/apps/mobile/src/i18n/locales/ja/settings.json
@@ -245,7 +245,7 @@
"profile": {
"title": "声紋",
"missing": "声紋が未登録です",
- "missingHint": "声紋を登録すると有効になります。約 20 秒かかります。",
+ "missingHint": "声紋を登録すると有効になります。",
"enrolled": "声紋を登録済み",
"enrolledAt": "{{date}} に登録",
"enroll": "声紋を登録",
@@ -269,11 +269,12 @@
}
},
"enroll": {
- "description": "普段音声入力を使う場所で、下の {{clips}} つの文章をいつもの話し方で読み上げてください。1 つにつき {{seconds}} 秒録音します。録音中は他の人が話さないようにしてください。",
+ "description": "以下の {{clips}} つの文章を普段の声で読み上げてください。各録音は最大 {{seconds}} 秒です。読み終えたら録音を終了してください。普段音声入力を使う場所で、ほかの人が同時に話さないように録音してください。",
"step": "{{current}} / {{total}} つ目",
"record": "読み上げを開始",
+ "stop": "録音を終了",
"rerecord": "この文章を録り直す",
- "recording": "残り {{seconds}} 秒",
+ "recording": "録音中…残り {{seconds}} 秒",
"saving": "声紋を作成中…",
"submit": "登録を完了",
"cancel": "キャンセル",
@@ -283,7 +284,7 @@
"p3": "この文章をもう少し簡潔にして、重要な数字と結論は残したうえで、要点を三つから五つの文でまとめてください。"
},
"errors": {
- "too_short": "{{index}} つ目の録音は話している時間が短すぎます。長く止まらずに読み上げて、録り直してください。",
+ "too_short": "{{index}} つ目の録音で検出された音声が短すぎます。録り直してください。",
"no_embedding": "{{index}} つ目の録音から声紋を読み取れませんでした。録り直してください。",
"inconsistent": "{{index}} つ目の録音が他と同じ人の声に聞こえません。他の人の声や雑音が入った可能性があります。録り直してください。",
"models_missing": "認識モデルのダウンロードがまだ完了していません。しばらくしてからお試しください。",
@@ -291,7 +292,17 @@
"failed": "声紋を作成できませんでした。もう一度お試しください。",
"microphone": "マイクを使用できません。マイクの許可を確認してもう一度お試しください。",
"noAudio": "マイクから音が届いていません。確認してもう一度お試しください。"
- }
+ },
+ "stepChoice": "{{index}} つ目、{{status}}",
+ "stepStatus": {
+ "pending": "未録音",
+ "recorded": "録音済み",
+ "retry": "再録音",
+ "recording": "録音中"
+ },
+ "rerecordStep": "{{index}} つ目を録り直す",
+ "readHint": "準備ができたら読み上げを開始し、読み終えたら録音を終了してください。",
+ "otherClipsKept": "ほかの録音は保持されています。"
}
},
"deviceNameEditor": {
diff --git a/apps/mobile/src/i18n/locales/ko/settings.json b/apps/mobile/src/i18n/locales/ko/settings.json
index a3dc9199af..55c6d3a3a8 100644
--- a/apps/mobile/src/i18n/locales/ko/settings.json
+++ b/apps/mobile/src/i18n/locales/ko/settings.json
@@ -245,7 +245,7 @@
"profile": {
"title": "성문",
"missing": "등록된 성문이 없습니다",
- "missingHint": "성문을 등록하면 적용됩니다. 약 20초 걸립니다.",
+ "missingHint": "성문을 등록하면 적용됩니다.",
"enrolled": "성문 등록됨",
"enrolledAt": "{{date}} 등록",
"enroll": "성문 등록",
@@ -269,11 +269,12 @@
}
},
"enroll": {
- "description": "평소 음성 입력을 사용하는 곳에서 아래 문장 {{clips}}개를 평소 말투로 읽어 주세요. 문장마다 {{seconds}}초씩 녹음합니다. 녹음하는 동안 다른 사람이 말하지 않도록 해 주세요.",
+ "description": "아래 {{clips}}개 문장을 평소 목소리로 읽어 주세요. 각 녹음은 최대 {{seconds}}초이며, 다 읽으면 녹음을 종료하세요. 평소 음성 입력을 사용하는 장소에서 다른 사람이 동시에 말하지 않도록 녹음하세요.",
"step": "{{current}} / {{total}}번째 문장",
"record": "읽기 시작",
+ "stop": "녹음 종료",
"rerecord": "이 문장 다시 녹음",
- "recording": "{{seconds}}초 남음",
+ "recording": "녹음 중…{{seconds}}초 남음",
"saving": "성문 만드는 중…",
"submit": "등록 완료",
"cancel": "취소",
@@ -283,7 +284,7 @@
"p3": "이 내용을 좀 더 간결하게 다듬고, 중요한 숫자와 결론은 남긴 다음 핵심을 세 문장에서 다섯 문장으로 요약해 주세요."
},
"errors": {
- "too_short": "{{index}}번째 녹음은 말한 시간이 너무 짧습니다. 오래 멈추지 말고 다시 녹음하세요.",
+ "too_short": "{{index}}번째 녹음에서 감지된 음성이 너무 짧습니다. 다시 녹음하세요.",
"no_embedding": "{{index}}번째 녹음에서 성문을 읽지 못했습니다. 다시 녹음하세요.",
"inconsistent": "{{index}}번째 녹음이 다른 녹음과 같은 사람의 목소리로 들리지 않습니다. 다른 사람의 목소리나 소음이 섞였을 수 있으니 다시 녹음하세요.",
"models_missing": "인식 모델 다운로드가 아직 끝나지 않았습니다. 잠시 후 다시 시도하세요.",
@@ -291,7 +292,17 @@
"failed": "성문을 만들지 못했습니다. 다시 시도하세요.",
"microphone": "마이크를 사용할 수 없습니다. 마이크 권한을 확인한 후 다시 시도하세요.",
"noAudio": "마이크에서 소리가 들어오지 않습니다. 확인한 후 다시 시도하세요."
- }
+ },
+ "stepChoice": "{{index}}번째 문장, {{status}}",
+ "stepStatus": {
+ "pending": "녹음 전",
+ "recorded": "녹음됨",
+ "retry": "다시 녹음",
+ "recording": "녹음 중"
+ },
+ "rerecordStep": "{{index}}번째 문장 다시 녹음",
+ "readHint": "준비되면 읽기를 시작하고, 다 읽으면 녹음을 종료하세요.",
+ "otherClipsKept": "다른 녹음은 유지됩니다."
}
},
"deviceNameEditor": {
diff --git a/apps/mobile/src/i18n/locales/zh-CN/settings.json b/apps/mobile/src/i18n/locales/zh-CN/settings.json
index 2347d6102c..0394396833 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/settings.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/settings.json
@@ -245,7 +245,7 @@
"profile": {
"title": "声纹",
"missing": "还没有录入声纹",
- "missingHint": "录入声纹后才会生效,大约需要 20 秒。",
+ "missingHint": "录入声纹后才会生效。",
"enrolled": "已录入声纹",
"enrolledAt": "{{date}} 录入",
"enroll": "录入声纹",
@@ -269,11 +269,12 @@
}
},
"enroll": {
- "description": "请在平时使用语音输入的地方,用平常的语气朗读下面 {{clips}} 段文字,每段录音 {{seconds}} 秒。录音时请不要让别人说话。",
+ "description": "请用平常的语气朗读下面 {{clips}} 段文字。每段最多录音 {{seconds}} 秒,读完点击结束录音。请在平时使用语音输入的地方录制,避免其他人同时说话。",
"step": "第 {{current}} / {{total}} 段",
"record": "开始朗读",
+ "stop": "结束录音",
"rerecord": "重录这段",
- "recording": "还剩 {{seconds}} 秒",
+ "recording": "正在录音…还剩 {{seconds}} 秒",
"saving": "正在生成声纹…",
"submit": "完成录入",
"cancel": "取消",
@@ -283,7 +284,7 @@
"p3": "请帮我把这段内容改得更简洁一些,保留关键数字和结论,然后用三到五句话总结一下重点。"
},
"errors": {
- "too_short": "第 {{index}} 段里说话的时间太短,请重录这段,朗读时不要停顿太久。",
+ "too_short": "第 {{index}} 段检测到的语音不足,请重新录制。",
"no_embedding": "第 {{index}} 段没能识别出声纹,请重录这段。",
"inconsistent": "第 {{index}} 段和其他几段不像同一个人,可能混进了别人的声音或噪音,请重录这段。",
"models_missing": "识别模型还没有下载完成,请稍后再试。",
@@ -291,7 +292,17 @@
"failed": "生成声纹失败,请重试。",
"microphone": "无法使用麦克风,请检查麦克风权限后重试。",
"noAudio": "麦克风没有传来声音,请检查后重试。"
- }
+ },
+ "stepChoice": "第 {{index}} 段,{{status}}",
+ "stepStatus": {
+ "pending": "待录音",
+ "recorded": "已录音",
+ "retry": "待重录",
+ "recording": "录音中"
+ },
+ "rerecordStep": "重录第 {{index}} 段",
+ "readHint": "准备好后开始朗读,读完点击结束录音。",
+ "otherClipsKept": "其他段录音已保留。"
}
},
"deviceNameEditor": {
diff --git a/apps/mobile/src/i18n/locales/zh-TW/settings.json b/apps/mobile/src/i18n/locales/zh-TW/settings.json
index 266b8ac689..256d4064f2 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/settings.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/settings.json
@@ -245,7 +245,7 @@
"profile": {
"title": "聲紋",
"missing": "尚未錄製聲紋",
- "missingHint": "錄製聲紋後才會生效,大約需要 20 秒。",
+ "missingHint": "錄入聲紋後才會生效。",
"enrolled": "已錄製聲紋",
"enrolledAt": "{{date}} 錄製",
"enroll": "錄製聲紋",
@@ -269,11 +269,12 @@
}
},
"enroll": {
- "description": "請在平常使用語音輸入的地方,用平常的語氣朗讀下面 {{clips}} 段文字,每段錄音 {{seconds}} 秒。錄音時請不要讓別人說話。",
+ "description": "請用平常的語氣朗讀下面 {{clips}} 段文字。每段最多錄音 {{seconds}} 秒,讀完點選結束錄音。請在平時使用語音輸入的地方錄製,避免其他人同時說話。",
"step": "第 {{current}} / {{total}} 段",
"record": "開始朗讀",
+ "stop": "結束錄音",
"rerecord": "重錄這段",
- "recording": "還剩 {{seconds}} 秒",
+ "recording": "正在錄音…還剩 {{seconds}} 秒",
"saving": "正在產生聲紋…",
"submit": "完成錄製",
"cancel": "取消",
@@ -283,7 +284,7 @@
"p3": "請幫我把這段內容改得更簡潔一些,保留關鍵數字和結論,然後用三到五句話總結重點。"
},
"errors": {
- "too_short": "第 {{index}} 段裡說話的時間太短,請重錄這段,朗讀時不要停頓太久。",
+ "too_short": "第 {{index}} 段偵測到的語音不足,請重新錄製。",
"no_embedding": "第 {{index}} 段沒能辨識出聲紋,請重錄這段。",
"inconsistent": "第 {{index}} 段和其他幾段不像同一個人,可能混入了別人的聲音或噪音,請重錄這段。",
"models_missing": "辨識模型尚未下載完成,請稍後再試。",
@@ -291,7 +292,17 @@
"failed": "產生聲紋失敗,請重試。",
"microphone": "無法使用麥克風,請檢查麥克風權限後重試。",
"noAudio": "麥克風沒有傳來聲音,請檢查後重試。"
- }
+ },
+ "stepChoice": "第 {{index}} 段,{{status}}",
+ "stepStatus": {
+ "pending": "待錄音",
+ "recorded": "已錄音",
+ "retry": "待重錄",
+ "recording": "錄音中"
+ },
+ "rerecordStep": "重錄第 {{index}} 段",
+ "readHint": "準備好後開始朗讀,讀完點選結束錄音。",
+ "otherClipsKept": "其他段錄音已保留。"
}
},
"deviceNameEditor": {
diff --git a/apps/mobile/src/session/mobileSpeakerEnrollmentRecorder.ts b/apps/mobile/src/session/mobileSpeakerEnrollmentRecorder.ts
index 9922c80ac5..3eac94845b 100644
--- a/apps/mobile/src/session/mobileSpeakerEnrollmentRecorder.ts
+++ b/apps/mobile/src/session/mobileSpeakerEnrollmentRecorder.ts
@@ -27,6 +27,8 @@ type RecordOptions = {
/** Elapsed fraction in [0, 1]. */
onProgress?: (fraction: number) => void;
signal?: AbortSignal;
+ /** Finish and keep captured audio; `signal` instead cancels and discards it. */
+ stopSignal?: AbortSignal;
/** Injection point for tests. */
startAudio?: typeof startMobileRealtimeAudio;
};
@@ -34,10 +36,11 @@ type RecordOptions = {
/**
* Records one read-aloud clip for voiceprint enrollment as PCM16 mono 16 kHz,
* through the same capture dictation uses, so the voiceprint matches the
- * audio the gate later judges. Stops by itself after `durationMs`.
+ * audio the gate later judges. Stops at `durationMs` or on `stopSignal`.
*/
export async function recordMobileSpeakerClip(options: RecordOptions): Promise<ArrayBuffer> {
if (options.signal?.aborted) throw new MobileSpeakerEnrollmentAbortedError();
+ if (options.stopSignal?.aborted) throw new MobileSpeakerEnrollmentNoAudioError();
const startAudio = options.startAudio ?? startMobileRealtimeAudio;
const targetSamples = Math.round((options.durationMs / 1000) * SPEAKER_GATE_SAMPLE_RATE);
const chunks: Int16Array[] = [];
@@ -47,6 +50,12 @@ export async function recordMobileSpeakerClip(options: RecordOptions): Promise<A
const done = new Promise<void>((resolve) => {
finish = resolve;
});
+ let stoppedEarly = false;
+ const onStop = (): void => {
+ stoppedEarly = true;
+ finish();
+ };
+ options.stopSignal?.addEventListener('abort', onStop, { once: true });
const lifecycle = new AbortController();
const onAbort = (): void => {
@@ -77,13 +86,14 @@ export async function recordMobileSpeakerClip(options: RecordOptions): Promise<A
});
if (permission === 'cancelled') throw new MobileSpeakerEnrollmentAbortedError();
if (permission === 'denied') throw new Error('microphone permission denied');
+ if (stoppedEarly) throw new MobileSpeakerEnrollmentNoAudioError();
removeBackgroundListener = subscribeToAppState((state) => {
if (state !== 'active') onAbort();
});
stop = await startAudio({
sampleRate: SPEAKER_GATE_SAMPLE_RATE,
onChunk: (chunk) => {
- if (lifecycle.signal.aborted || samples >= targetSamples) return;
+ if (lifecycle.signal.aborted || stoppedEarly || samples >= targetSamples) return;
const pcm = new Int16Array(chunk.pcm16.slice(0, chunk.pcm16.byteLength - (chunk.pcm16.byteLength % 2)));
chunks.push(pcm);
samples += pcm.length;
@@ -104,13 +114,14 @@ export async function recordMobileSpeakerClip(options: RecordOptions): Promise<A
clearTimeout(watchdog);
removeBackgroundListener?.();
options.signal?.removeEventListener('abort', onAbort);
+ options.stopSignal?.removeEventListener('abort', onStop);
await stop?.().catch(() => undefined);
}
- if (lifecycle.signal.aborted) throw new MobileSpeakerEnrollmentAbortedError();
+ if (lifecycle.signal.aborted || options.signal?.aborted) throw new MobileSpeakerEnrollmentAbortedError();
if (failure) throw failure;
- if (samples < targetSamples) throw new MobileSpeakerEnrollmentNoAudioError();
+ if (samples === 0 || (!stoppedEarly && samples < targetSamples)) throw new MobileSpeakerEnrollmentNoAudioError();
- const out = new Int16Array(targetSamples);
+ const out = new Int16Array(Math.min(samples, targetSamples));
let offset = 0;
for (const chunk of chunks) {
const take = Math.min(chunk.length, out.length - offset);
diff --git a/packages/voice-input-core/src/speakerEnrollment.ts b/packages/voice-input-core/src/speakerEnrollment.ts
index c0973004e0..8835ceb503 100644
--- a/packages/voice-input-core/src/speakerEnrollment.ts
+++ b/packages/voice-input-core/src/speakerEnrollment.ts
@@ -27,6 +27,8 @@ export type SpeakerEnrollmentResult =
};
export const SPEAKER_ENROLLMENT_CLIP_COUNT = 3;
+/** Recording may finish earlier when the user has read the passage. */
+export const SPEAKER_ENROLLMENT_MAX_CLIP_SEC = 30;
export const SPEAKER_ENROLLMENT_MIN_CLIP_SPEECH_SEC = 2;
// Own-voice windows scored 0.77–0.88 in validation; clips of one person that
// disagree this much usually mean a second voice or heavy noise in a clip.