Skip to content

Commit b5ddc2a

Browse files
committed
fix(mobile): wait for Bluetooth microphone routing
1 parent 5030d80 commit b5ddc2a

5 files changed

Lines changed: 306 additions & 58 deletions

File tree

‎apps/mobile/src/features/voice-input/lazyVoiceRecorder.test.ts‎

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,23 @@ function createNativeRecorder(uri: string) {
2626
{ uid: "car", name: "CarPlay", type: "CarAudio" },
2727
{ uid: "built-in", name: "iPhone Microphone", type: "MicrophoneBuiltIn" },
2828
]),
29-
setInput: vi.fn((_uid: string) => undefined),
29+
setInput: vi.fn((_uid: string): void | Promise<void> => undefined),
30+
cancelInputSelection: vi.fn(() => undefined),
3031
release: vi.fn(),
3132
emit: (status: Status) => listeners.forEach((listener) => listener(status)),
3233
};
3334
}
3435

3536
function createHarness(
3637
selectInput?: (inputs: ReadonlyArray<VoiceRecordingInput>) => VoiceRecordingInput | null,
38+
configure?: (native: ReturnType<typeof createNativeRecorder>) => void,
3739
) {
3840
const created: Array<ReturnType<typeof createNativeRecorder>> = [];
3941
const statuses: Status[] = [];
4042
const recorder = createLazyVoiceRecorder({
4143
create: () => {
4244
const native = createNativeRecorder(`file:///voice-${created.length}.m4a`);
45+
configure?.(native);
4346
created.push(native);
4447
return native;
4548
},
@@ -61,6 +64,15 @@ describe("createLazyVoiceRecorder", () => {
6164
throw new Error("Preferred input not found");
6265
});
6366
await expect(disconnected.recorder.prepareToRecordAsync()).resolves.toBeUndefined();
67+
68+
const failure = new Error("Input routing timed out");
69+
const timedOut = createHarness(
70+
(inputs) => inputs[1] ?? null,
71+
(native) => {
72+
native.setInput.mockImplementationOnce(() => Promise.reject(failure));
73+
},
74+
);
75+
await expect(timedOut.recorder.prepareToRecordAsync()).rejects.toBe(failure);
6476
});
6577

6678
it("forwards status events until the recorder is released", async () => {
@@ -76,8 +88,12 @@ describe("createLazyVoiceRecorder", () => {
7688
});
7789

7890
describe("with the voice input controller", () => {
79-
function createController(granted: boolean) {
80-
const harness = createHarness();
91+
function createController(
92+
granted: boolean,
93+
selectInput?: (inputs: ReadonlyArray<VoiceRecordingInput>) => VoiceRecordingInput | null,
94+
configure?: (native: ReturnType<typeof createNativeRecorder>) => void,
95+
) {
96+
const harness = createHarness(selectInput, configure);
8197
const deleted: string[] = [];
8298
const controller = new VoiceInputController({
8399
recorder: harness.recorder,
@@ -108,5 +124,35 @@ describe("createLazyVoiceRecorder", () => {
108124
expect(controller.currentState.phase).toBe("error");
109125
expect(created).toHaveLength(0);
110126
});
127+
128+
it("cancels a pending input route before recording and deletes the prepared audio", async () => {
129+
const selecting = Promise.withResolvers<void>();
130+
const selected = Promise.withResolvers<void>();
131+
let routeActive = false;
132+
const harness = createController(
133+
true,
134+
(inputs) => inputs[1] ?? null,
135+
(native) => {
136+
native.setInput.mockImplementationOnce(() => {
137+
routeActive = true;
138+
selecting.resolve();
139+
return selected.promise;
140+
});
141+
native.cancelInputSelection.mockImplementation(() => {
142+
routeActive = false;
143+
selected.reject(new Error("Input selection canceled"));
144+
});
145+
},
146+
);
147+
const starting = harness.controller.start();
148+
await selecting.promise;
149+
harness.controller.cancel();
150+
await starting;
151+
152+
expect(routeActive).toBe(false);
153+
expect(harness.controller.currentState.phase).toBe("idle");
154+
expect(harness.deleted).toEqual(["file:///voice-0.m4a"]);
155+
harness.recorder.release();
156+
});
111157
});
112158
});

‎apps/mobile/src/features/voice-input/lazyVoiceRecorder.ts‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1-
import type { VoiceRecorder } from "@t3tools/client-runtime/voice-input";
1+
import {
2+
throwIfVoiceTranscriptionAborted,
3+
type VoiceRecorder,
4+
} from "@t3tools/client-runtime/voice-input";
25

36
type Subscription = { remove(): void };
47

@@ -19,7 +22,8 @@ export interface NativeVoiceRecorder<TStatus, TRecorderState> {
1922
listener: (status: TStatus) => void,
2023
): Subscription;
2124
getAvailableInputs(): ReadonlyArray<VoiceRecordingInput>;
22-
setInput(uid: string): void;
25+
setInput(uid: string): void | Promise<void>;
26+
cancelInputSelection?(): void;
2327
release(): void;
2428
}
2529

@@ -50,19 +54,37 @@ export function createLazyVoiceRecorder<TStatus, TRecorderState>(input: {
5054
if (recorder) return recorder.uri;
5155
return retired ? retired.uri : retiredUri;
5256
},
53-
prepareToRecordAsync() {
57+
prepareToRecordAsync(signal) {
5458
if (!recorder) {
5559
recorder = input.create();
5660
subscription = recorder.addListener("recordingStatusUpdate", input.onStatus);
5761
}
5862
const prepared = recorder;
5963
return track(
60-
prepared.prepareToRecordAsync().then(() => {
64+
prepared.prepareToRecordAsync().then(async () => {
65+
if (signal) throwIfVoiceTranscriptionAborted(signal);
6166
if (!input.selectInput) return;
67+
let selected: VoiceRecordingInput | null;
6268
try {
63-
const selected = input.selectInput(prepared.getAvailableInputs());
64-
if (selected) prepared.setInput(selected.uid);
65-
} catch {}
69+
selected = input.selectInput(prepared.getAvailableInputs());
70+
} catch {
71+
return;
72+
}
73+
if (!selected) return;
74+
const abort = () => prepared.cancelInputSelection?.();
75+
signal?.addEventListener("abort", abort, { once: true });
76+
try {
77+
let selecting: void | Promise<void>;
78+
try {
79+
selecting = prepared.setInput(selected.uid);
80+
} catch {
81+
return;
82+
}
83+
await selecting;
84+
if (signal) throwIfVoiceTranscriptionAborted(signal);
85+
} finally {
86+
signal?.removeEventListener("abort", abort);
87+
}
6688
}),
6789
);
6890
},
@@ -79,6 +101,7 @@ export function createLazyVoiceRecorder<TStatus, TRecorderState>(input: {
79101
release() {
80102
const released = recorder;
81103
if (!released) return;
104+
released.cancelInputSelection?.();
82105
recorder = null;
83106
subscription?.remove();
84107
subscription = null;

‎packages/client-runtime/src/voice-input/controller.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ export type VoiceRecorderStatus = {
3434

3535
export interface VoiceRecorder {
3636
readonly uri: string | null;
37-
prepareToRecordAsync(): Promise<void>;
37+
prepareToRecordAsync(signal?: AbortSignal): Promise<void>;
3838
record(options: { readonly forDuration: number }): void;
3939
stop(): Promise<void>;
4040
}
@@ -261,7 +261,7 @@ export class VoiceInputController {
261261
await this.dependencies.configureRecording();
262262
this.recordingConfigured = true;
263263
if (!this.isCurrent(operationToken)) return;
264-
await this.dependencies.recorder.prepareToRecordAsync();
264+
await this.dependencies.recorder.prepareToRecordAsync(abortController.signal);
265265
if (!this.isCurrent(operationToken)) return;
266266
this.recordingUri = this.dependencies.recorder.uri;
267267
this.rememberRecordingUri(this.recordingUri);

0 commit comments

Comments
 (0)