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): 修复 Android 首次语音授权竞态 (#317)

Dash44ef72cd5310
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 7a4467969a..e97eaef5cf 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -27,6 +27,7 @@ import {
X,
} from 'lucide-react-native';
import {
+ getRecordingPermissionsAsync,
requestRecordingPermissionsAsync,
setAudioModeAsync,
} from 'expo-audio';
@@ -311,6 +312,11 @@ import {
takePrewarmedMobileVoiceAsr,
type PrewarmedMobileVoiceAsr,
} from '@/session/mobileVoicePrewarm';
+import {
+ resolveMobileVoiceRecordingPermission,
+ shouldCancelMobileVoiceForBackground,
+ waitForMobileVoiceAppActive,
+} from '@/session/mobileVoiceStartup';
import {
CINDY_MANAGED_REFINER_PROVIDER,
createMobileCindyVoiceCredential,
@@ -1091,6 +1097,9 @@ export default function SessionScreen() {
}), [deleteRemoteMediaObject]);
remoteMediaQueueRef.current ??= createRemoteMediaQueue();
const voiceRecordingActiveRef = useRef(false);
+ const voicePermissionRequestInFlightRef = useRef(false);
+ const voicePermissionRequestSeqRef = useRef(0);
+ const voicePermissionRequestAbortRef = useRef<AbortController | null>(null);
const voiceStartupInFlightRef = useRef(false);
// Increments whenever a startup is superseded (screen unmount / session
// switch). startVoiceRecording re-checks it after each await so a startup
@@ -3299,7 +3308,8 @@ export default function SessionScreen() {
const startVoiceRecording = useCallback(async () => {
if (
- voiceStartupInFlightRef.current
+ voicePermissionRequestInFlightRef.current
+ || voiceStartupInFlightRef.current
|| voiceStopInFlightRef.current
|| voiceRecordingActiveRef.current
|| voiceState === 'listening'
@@ -3309,7 +3319,10 @@ export default function SessionScreen() {
setVoiceError(null);
setVoiceReleaseToSendActive(false);
let claimedPrewarm: PrewarmedMobileVoiceAsr | null = null;
+ let permissionRequestSeq: number | null = null;
+ let permissionRequestAbortController: AbortController | null = null;
let startupSeq: number | null = null;
+ let audioModeEnabled = false;
// The controller THIS startup created. Stale-teardown paths must only touch
// this one: by the time a superseded continuation resumes, the shared ref
// may already point at a newer session's live recording. Read through the
@@ -3327,28 +3340,61 @@ export default function SessionScreen() {
setVoiceError(mobileVoiceRealtimeAudioUnavailableError());
return;
}
- startupSeq = voiceStartupSeqRef.current + 1;
- voiceStartupSeqRef.current = startupSeq;
- voiceStartupInFlightRef.current = true;
- const permission = await requestRecordingPermissionsAsync();
- if (voiceStartupSeqRef.current !== startupSeq) {
- // Unmounted / superseded while the permission prompt was up: bail out
- // before touching audio mode so a stale continuation can't re-enable
- // recording mode on a dead screen.
- return;
+ permissionRequestSeq = voicePermissionRequestSeqRef.current + 1;
+ voicePermissionRequestSeqRef.current = permissionRequestSeq;
+ const currentPermissionAbortController = new AbortController();
+ permissionRequestAbortController = currentPermissionAbortController;
+ voicePermissionRequestAbortRef.current = currentPermissionAbortController;
+ voicePermissionRequestInFlightRef.current = true;
+ let permissionResult: Awaited<ReturnType<typeof resolveMobileVoiceRecordingPermission>>;
+ try {
+ permissionResult = await resolveMobileVoiceRecordingPermission({
+ getPermission: getRecordingPermissionsAsync,
+ requestPermission: requestRecordingPermissionsAsync,
+ isRequestCurrent: () => voicePermissionRequestSeqRef.current === permissionRequestSeq,
+ isAppActive: () => AppState.currentState === 'active',
+ subscribeToAppState: (listener) => {
+ const subscription = AppState.addEventListener('change', listener);
+ return () => subscription.remove();
+ },
+ signal: currentPermissionAbortController.signal,
+ waitForAppActive: () => waitForMobileVoiceAppActive({
+ isAppActive: () => AppState.currentState === 'active',
+ subscribe: (listener) => {
+ const subscription = AppState.addEventListener('change', listener);
+ return () => subscription.remove();
+ },
+ signal: currentPermissionAbortController.signal,
+ }),
+ });
+ } finally {
+ if (voicePermissionRequestSeqRef.current === permissionRequestSeq) {
+ voicePermissionRequestInFlightRef.current = false;
+ }
+ if (voicePermissionRequestAbortRef.current === permissionRequestAbortController) {
+ voicePermissionRequestAbortRef.current = null;
+ }
}
- if (!permission.granted) {
- voiceStartupInFlightRef.current = false;
+ if (permissionResult === 'cancelled') return;
+ if (permissionResult === 'denied') {
voiceRecordingActiveRef.current = false;
voiceStopAfterStartRef.current = false;
setVoiceState('error');
setVoiceError(mobileVoiceMicPermissionError());
return;
}
+ if (
+ voicePermissionRequestSeqRef.current !== permissionRequestSeq
+ || AppState.currentState !== 'active'
+ ) return;
+ startupSeq = voiceStartupSeqRef.current + 1;
+ voiceStartupSeqRef.current = startupSeq;
+ voiceStartupInFlightRef.current = true;
await setAudioModeAsync({
allowsRecording: true,
playsInSilentMode: true,
});
+ audioModeEnabled = true;
// Open the device link in the background: voice dictation writes into the
// local composer via the cloud ASR proxy and does not need the mobile↔desktop
// link (only submitting the composed message later does). Awaiting it used
@@ -3460,6 +3506,11 @@ export default function SessionScreen() {
// (e.g. session construction threw); closing it again after the
// controller's own teardown is harmless — provider stop is idempotent.
void claimedPrewarm?.asr.stop().catch(() => undefined);
+ if (
+ startupSeq === null
+ && permissionRequestSeq !== null
+ && voicePermissionRequestSeqRef.current !== permissionRequestSeq
+ ) return;
if (startupSeq !== null && voiceStartupSeqRef.current !== startupSeq) {
// Superseded: tear down only what THIS startup created; the shared ref
// may already belong to a newer session's recording.
@@ -3467,9 +3518,18 @@ export default function SessionScreen() {
if (created) {
if (voiceControllerSessionRef.current === created) {
voiceControllerSessionRef.current = null;
+ voiceRecordingActiveRef.current = false;
}
await created.cancel().catch(() => undefined);
}
+ if (
+ audioModeEnabled
+ && !voiceControllerSessionRef.current
+ && !voiceStartupInFlightRef.current
+ && !voiceRecordingActiveRef.current
+ ) {
+ await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
+ }
return;
}
const controller = voiceControllerSessionRef.current;
@@ -3488,11 +3548,11 @@ export default function SessionScreen() {
const cancelVoiceForAppBackground = useCallback(() => {
const controller = voiceControllerSessionRef.current;
- const ownsActiveRun = Boolean(
- controller
- || voiceStartupInFlightRef.current
- || voiceRecordingActiveRef.current,
- );
+ const ownsActiveRun = shouldCancelMobileVoiceForBackground({
+ startupInFlight: voiceStartupInFlightRef.current,
+ recordingActive: voiceRecordingActiveRef.current,
+ hasController: Boolean(controller),
+ });
if (!ownsActiveRun) {
// pressIn may have opened a speculative ASR connection without creating
// a controller yet; backgrounding must not leave that parked connection.
@@ -3520,7 +3580,8 @@ export default function SessionScreen() {
useEffect(() => {
const subscription = AppState.addEventListener('change', (nextState) => {
// iOS permission sheets and Control Center can briefly report `inactive`.
- // Only a real background transition owns the foreground-only voice teardown.
+ // Android permission sheets can report `background`, but permission
+ // resolution has not claimed audio resources and must survive that event.
if (nextState !== 'background') return;
cancelVoiceForAppBackground();
});
@@ -3533,6 +3594,10 @@ export default function SessionScreen() {
voiceControllerSessionRef.current = null;
// Supersede any in-flight startup so its post-await re-checks tear down
// the resources it acquired for this now-dead screen.
+ voicePermissionRequestSeqRef.current += 1;
+ voicePermissionRequestAbortRef.current?.abort();
+ voicePermissionRequestAbortRef.current = null;
+ voicePermissionRequestInFlightRef.current = false;
voiceStartupSeqRef.current += 1;
voiceStartupInFlightRef.current = false;
voiceStopInFlightRef.current = false;
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 1f3eff1bbc..8a66e8dcac 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -45,6 +45,7 @@ import {
Zap,
} from 'lucide-react-native';
import {
+ getRecordingPermissionsAsync,
requestRecordingPermissionsAsync,
setAudioModeAsync,
} from 'expo-audio';
@@ -205,6 +206,11 @@ import {
takePrewarmedMobileVoiceAsr,
type PrewarmedMobileVoiceAsr,
} from '@/session/mobileVoicePrewarm';
+import {
+ resolveMobileVoiceRecordingPermission,
+ shouldCancelMobileVoiceForBackground,
+ waitForMobileVoiceAppActive,
+} from '@/session/mobileVoiceStartup';
import {
CINDY_MANAGED_REFINER_PROVIDER,
createMobileCindyVoiceCredential,
@@ -460,6 +466,9 @@ export default function NewRemoteSessionScreen() {
const firstMessageInputRef = useRef<NativeTextInput>(null);
const voiceDraftScrollRef = useRef<ScrollView>(null);
const voiceRecordingActiveRef = useRef(false);
+ const voicePermissionRequestInFlightRef = useRef(false);
+ const voicePermissionRequestSeqRef = useRef(0);
+ const voicePermissionRequestAbortRef = useRef<AbortController | null>(null);
const voiceStartupInFlightRef = useRef(false);
const voiceStopInFlightRef = useRef(false);
const voiceStartupSeqRef = useRef(0);
@@ -880,6 +889,10 @@ export default function NewRemoteSessionScreen() {
}, []);
const cancelVoiceForDeviceSwitch = useCallback(() => {
+ voicePermissionRequestSeqRef.current += 1;
+ voicePermissionRequestAbortRef.current?.abort();
+ voicePermissionRequestAbortRef.current = null;
+ voicePermissionRequestInFlightRef.current = false;
voiceStartupSeqRef.current += 1;
const controller = voiceControllerSessionRef.current;
voiceControllerSessionRef.current = null;
@@ -897,13 +910,14 @@ export default function NewRemoteSessionScreen() {
useEffect(() => {
const subscription = AppState.addEventListener('change', (nextState) => {
// iOS permission sheets and Control Center can briefly report `inactive`.
- // Only a real background transition owns the foreground-only voice teardown.
+ // Android permission sheets can report `background`, but permission
+ // resolution has not claimed audio resources and must survive that event.
if (nextState !== 'background') return;
- if (
- voiceStartupInFlightRef.current
- || voiceRecordingActiveRef.current
- || voiceControllerSessionRef.current
- ) {
+ if (shouldCancelMobileVoiceForBackground({
+ startupInFlight: voiceStartupInFlightRef.current,
+ recordingActive: voiceRecordingActiveRef.current,
+ hasController: Boolean(voiceControllerSessionRef.current),
+ })) {
cancelVoiceForDeviceSwitch();
} else {
// pressIn may have opened a speculative ASR connection without creating
@@ -916,7 +930,11 @@ export default function NewRemoteSessionScreen() {
const selectDevice = useCallback((option: NewSessionDeviceOption) => {
if (creating) return;
- if (voiceStopInFlightRef.current || voiceIsProcessing) return;
+ if (
+ voicePermissionRequestInFlightRef.current
+ || voiceStopInFlightRef.current
+ || voiceIsProcessing
+ ) return;
if (voiceStartupInFlightRef.current || voiceRecordingActiveRef.current || voiceState === 'listening') {
cancelVoiceForDeviceSwitch();
}
@@ -1360,15 +1378,20 @@ export default function NewRemoteSessionScreen() {
const startVoiceRecording = useCallback(async () => {
if (
- voiceStartupInFlightRef.current
+ voicePermissionRequestInFlightRef.current
+ || voiceStartupInFlightRef.current
|| voiceStopInFlightRef.current
|| voiceRecordingActiveRef.current
|| voiceState === 'listening'
|| voiceIsProcessing
) return;
setVoiceError(null);
+ let permissionRequestSeq: number | null = null;
+ let permissionRequestAbortController: AbortController | null = null;
let startupSeq: number | null = null;
let claimedPrewarm: PrewarmedMobileVoiceAsr | null = null;
+ let audioModeEnabled = false;
+ let createdController: MobileVoiceControllerSession | null = null;
try {
if (!selectedDeviceId) {
setVoiceState('error');
@@ -1380,23 +1403,61 @@ export default function NewRemoteSessionScreen() {
setVoiceError(mobileVoiceRealtimeAudioUnavailableError());
return;
}
- startupSeq = voiceStartupSeqRef.current + 1;
- voiceStartupSeqRef.current = startupSeq;
- voiceStartupInFlightRef.current = true;
- const permission = await requestRecordingPermissionsAsync();
- if (voiceStartupSeqRef.current !== startupSeq) return;
- if (!permission.granted) {
- voiceStartupInFlightRef.current = false;
+ permissionRequestSeq = voicePermissionRequestSeqRef.current + 1;
+ voicePermissionRequestSeqRef.current = permissionRequestSeq;
+ const currentPermissionAbortController = new AbortController();
+ permissionRequestAbortController = currentPermissionAbortController;
+ voicePermissionRequestAbortRef.current = currentPermissionAbortController;
+ voicePermissionRequestInFlightRef.current = true;
+ let permissionResult: Awaited<ReturnType<typeof resolveMobileVoiceRecordingPermission>>;
+ try {
+ permissionResult = await resolveMobileVoiceRecordingPermission({
+ getPermission: getRecordingPermissionsAsync,
+ requestPermission: requestRecordingPermissionsAsync,
+ isRequestCurrent: () => voicePermissionRequestSeqRef.current === permissionRequestSeq,
+ isAppActive: () => AppState.currentState === 'active',
+ subscribeToAppState: (listener) => {
+ const subscription = AppState.addEventListener('change', listener);
+ return () => subscription.remove();
+ },
+ signal: currentPermissionAbortController.signal,
+ waitForAppActive: () => waitForMobileVoiceAppActive({
+ isAppActive: () => AppState.currentState === 'active',
+ subscribe: (listener) => {
+ const subscription = AppState.addEventListener('change', listener);
+ return () => subscription.remove();
+ },
+ signal: currentPermissionAbortController.signal,
+ }),
+ });
+ } finally {
+ if (voicePermissionRequestSeqRef.current === permissionRequestSeq) {
+ voicePermissionRequestInFlightRef.current = false;
+ }
+ if (voicePermissionRequestAbortRef.current === permissionRequestAbortController) {
+ voicePermissionRequestAbortRef.current = null;
+ }
+ }
+ if (permissionResult === 'cancelled') return;
+ if (permissionResult === 'denied') {
voiceStopInFlightRef.current = false;
voiceRecordingActiveRef.current = false;
setVoiceState('error');
setVoiceError(mobileVoiceMicPermissionError());
return;
}
+ if (
+ voicePermissionRequestSeqRef.current !== permissionRequestSeq
+ || AppState.currentState !== 'active'
+ ) return;
+ startupSeq = voiceStartupSeqRef.current + 1;
+ voiceStartupSeqRef.current = startupSeq;
+ voiceStartupInFlightRef.current = true;
await setAudioModeAsync({
allowsRecording: true,
playsInSilentMode: true,
});
+ audioModeEnabled = true;
// Open the device link in the background: voice dictation writes into the
// local composer via the cloud ASR proxy and does not need the mobile↔desktop
// link (only submitting the composed message later does). Awaiting it here
@@ -1473,6 +1534,7 @@ export default function NewRemoteSessionScreen() {
});
},
});
+ createdController = controller;
voiceControllerSessionRef.current = controller;
voiceRecordingActiveRef.current = true;
await controller.start();
@@ -1492,7 +1554,29 @@ export default function NewRemoteSessionScreen() {
// (e.g. session construction threw); closing it again after the
// controller's own teardown is harmless — provider stop is idempotent.
void claimedPrewarm?.asr.stop().catch(() => undefined);
- if (startupSeq !== null && voiceStartupSeqRef.current !== startupSeq) return;
+ if (
+ startupSeq === null
+ && permissionRequestSeq !== null
+ && voicePermissionRequestSeqRef.current !== permissionRequestSeq
+ ) return;
+ if (startupSeq !== null && voiceStartupSeqRef.current !== startupSeq) {
+ if (createdController) {
+ if (voiceControllerSessionRef.current === createdController) {
+ voiceControllerSessionRef.current = null;
+ voiceRecordingActiveRef.current = false;
+ }
+ await createdController.cancel().catch(() => undefined);
+ }
+ if (
+ audioModeEnabled
+ && !voiceControllerSessionRef.current
+ && !voiceStartupInFlightRef.current
+ && !voiceRecordingActiveRef.current
+ ) {
+ await setAudioModeAsync({ allowsRecording: false }).catch(() => undefined);
+ }
+ return;
+ }
const controller = voiceControllerSessionRef.current;
voiceControllerSessionRef.current = null;
await controller?.cancel().catch(() => undefined);
@@ -1577,6 +1661,10 @@ export default function NewRemoteSessionScreen() {
return () => {
const controller = voiceControllerSessionRef.current;
voiceControllerSessionRef.current = null;
+ voicePermissionRequestSeqRef.current += 1;
+ voicePermissionRequestAbortRef.current?.abort();
+ voicePermissionRequestAbortRef.current = null;
+ voicePermissionRequestInFlightRef.current = false;
voiceStartupSeqRef.current += 1;
voiceStartupInFlightRef.current = false;
voiceStopInFlightRef.current = false;
@@ -2069,6 +2157,7 @@ export default function NewRemoteSessionScreen() {
const create = useCallback(async () => {
if (
creatingRef.current
+ || voicePermissionRequestInFlightRef.current
|| voiceStartupInFlightRef.current
|| voiceStopInFlightRef.current
|| voiceIsProcessing
diff --git a/apps/mobile/src/__tests__/mobileVoiceStartup.test.ts b/apps/mobile/src/__tests__/mobileVoiceStartup.test.ts
new file mode 100644
index 0000000000..9c828435ac
--- /dev/null
+++ b/apps/mobile/src/__tests__/mobileVoiceStartup.test.ts
@@ -0,0 +1,194 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ resolveMobileVoiceRecordingPermission,
+ shouldCancelMobileVoiceForBackground,
+ waitForMobileVoiceAppActive,
+} from '@/session/mobileVoiceStartup';
+
+function deferred<T>(): {
+ promise: Promise<T>;
+ resolve: (value: T) => void;
+} {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((settle) => {
+ resolve = settle;
+ });
+ return { promise, resolve };
+}
+
+function stableAppStateLifecycle(): {
+ signal: AbortSignal;
+ subscribeToAppState: () => () => void;
+} {
+ return {
+ signal: new AbortController().signal,
+ subscribeToAppState: () => () => undefined,
+ };
+}
+
+describe('mobileVoiceStartup', () => {
+ it('uses an existing microphone grant without opening the system prompt', async () => {
+ const requestPermission = vi.fn(async () => ({ granted: true }));
+
+ await expect(resolveMobileVoiceRecordingPermission({
+ getPermission: async () => ({ granted: true }),
+ requestPermission,
+ ...stableAppStateLifecycle(),
+ isRequestCurrent: () => true,
+ isAppActive: () => true,
+ waitForAppActive: async () => true,
+ })).resolves.toBe('granted');
+ expect(requestPermission).not.toHaveBeenCalled();
+ });
+
+ it('does not open the system prompt after backgrounding during permission preflight', async () => {
+ const pendingPermission = deferred<{ granted: boolean }>();
+ const requestPermission = vi.fn(async () => ({ granted: true }));
+ const abortController = new AbortController();
+ const unsubscribe = vi.fn();
+ let publishAppState = (_state: string): void => undefined;
+ let appActive = true;
+ const result = resolveMobileVoiceRecordingPermission({
+ getPermission: () => pendingPermission.promise,
+ requestPermission,
+ isRequestCurrent: () => true,
+ isAppActive: () => appActive,
+ subscribeToAppState: (listener) => {
+ publishAppState = listener;
+ return unsubscribe;
+ },
+ signal: abortController.signal,
+ waitForAppActive: async () => true,
+ });
+
+ appActive = false;
+ publishAppState('background');
+ appActive = true;
+ pendingPermission.resolve({ granted: false });
+
+ await expect(result).resolves.toBe('cancelled');
+ expect(requestPermission).not.toHaveBeenCalled();
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ });
+
+ it('removes the preflight listener when the permission request is aborted', async () => {
+ const pendingPermission = deferred<{ granted: boolean }>();
+ const abortController = new AbortController();
+ const unsubscribe = vi.fn();
+ const result = resolveMobileVoiceRecordingPermission({
+ getPermission: () => pendingPermission.promise,
+ requestPermission: async () => ({ granted: true }),
+ isRequestCurrent: () => true,
+ isAppActive: () => true,
+ subscribeToAppState: () => unsubscribe,
+ signal: abortController.signal,
+ waitForAppActive: async () => true,
+ });
+
+ abortController.abort();
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ pendingPermission.resolve({ granted: false });
+ await expect(result).resolves.toBe('cancelled');
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ });
+
+ it('waits for Android to publish active after the first permission prompt resolves', async () => {
+ const pendingPermission = deferred<{ granted: boolean }>();
+ const pendingForeground = deferred<boolean>();
+ let appActive = true;
+ const result = resolveMobileVoiceRecordingPermission({
+ getPermission: async () => ({ granted: false }),
+ requestPermission: () => pendingPermission.promise,
+ ...stableAppStateLifecycle(),
+ isRequestCurrent: () => true,
+ isAppActive: () => appActive,
+ waitForAppActive: () => pendingForeground.promise,
+ });
+
+ await Promise.resolve();
+ appActive = false;
+ expect(shouldCancelMobileVoiceForBackground({
+ startupInFlight: false,
+ recordingActive: false,
+ hasController: false,
+ })).toBe(false);
+
+ pendingPermission.resolve({ granted: true });
+ let settled = false;
+ void result.then(() => {
+ settled = true;
+ });
+ await Promise.resolve();
+ expect(settled).toBe(false);
+
+ appActive = true;
+ pendingForeground.resolve(true);
+ await expect(result).resolves.toBe('granted');
+ });
+
+ it('reports a denied microphone request', async () => {
+ await expect(resolveMobileVoiceRecordingPermission({
+ getPermission: async () => ({ granted: false }),
+ requestPermission: async () => ({ granted: false }),
+ ...stableAppStateLifecycle(),
+ isRequestCurrent: () => true,
+ isAppActive: () => true,
+ waitForAppActive: async () => true,
+ })).resolves.toBe('denied');
+ });
+
+ it('cancels an already-granted request that genuinely backgrounds', async () => {
+ const waitForAppActive = vi.fn(async () => true);
+ await expect(resolveMobileVoiceRecordingPermission({
+ getPermission: async () => ({ granted: true }),
+ requestPermission: async () => ({ granted: true }),
+ ...stableAppStateLifecycle(),
+ isRequestCurrent: () => true,
+ isAppActive: () => false,
+ waitForAppActive,
+ })).resolves.toBe('cancelled');
+ expect(waitForAppActive).not.toHaveBeenCalled();
+ expect(shouldCancelMobileVoiceForBackground({
+ startupInFlight: true,
+ recordingActive: false,
+ hasController: false,
+ })).toBe(true);
+ });
+
+ it('cancels a granted request when the screen is superseded while the prompt is open', async () => {
+ const pendingPermission = deferred<{ granted: boolean }>();
+ let requestCurrent = true;
+ const result = resolveMobileVoiceRecordingPermission({
+ getPermission: async () => ({ granted: false }),
+ requestPermission: () => pendingPermission.promise,
+ ...stableAppStateLifecycle(),
+ isRequestCurrent: () => requestCurrent,
+ isAppActive: () => true,
+ waitForAppActive: async () => true,
+ });
+
+ await Promise.resolve();
+ requestCurrent = false;
+ pendingPermission.resolve({ granted: true });
+ await expect(result).resolves.toBe('cancelled');
+ });
+
+ it('removes the foreground listener when a waiting screen is superseded', async () => {
+ let appStateListener: ((state: string) => void) | null = null;
+ const unsubscribe = vi.fn();
+ const abortController = new AbortController();
+ const result = waitForMobileVoiceAppActive({
+ isAppActive: () => false,
+ subscribe: (listener) => {
+ appStateListener = listener;
+ return unsubscribe;
+ },
+ signal: abortController.signal,
+ });
+
+ expect(appStateListener).not.toBeNull();
+ abortController.abort();
+ await expect(result).resolves.toBe(false);
+ expect(unsubscribe).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/mobile/src/__tests__/newSession.test.ts b/apps/mobile/src/__tests__/newSession.test.ts
index 0f8ae5a3db..327ceec92a 100644
--- a/apps/mobile/src/__tests__/newSession.test.ts
+++ b/apps/mobile/src/__tests__/newSession.test.ts
@@ -860,15 +860,27 @@ describe('new session composer surface', () => {
expect(voiceButtonSource).toContain('disabled={creating || voiceIsProcessing}');
expect(newSource).toContain('const startVoiceRecording = useCallback(async () => {');
expect(newSource).toContain('const voiceStartupInFlightRef = useRef(false);');
+ expect(newSource).toContain('const voicePermissionRequestInFlightRef = useRef(false);');
expect(newSource).toContain('const voiceStopInFlightRef = useRef(false);');
expect(newSource).toContain('const voiceStartupSeqRef = useRef(0);');
expect(newSource).toContain('|| voiceStopInFlightRef.current');
- expect(newSource.indexOf('voiceStartupInFlightRef.current = true;')).toBeLessThan(
- newSource.indexOf('const permission = await requestRecordingPermissionsAsync();'),
+ expect(newSource).toContain('resolveMobileVoiceRecordingPermission({');
+ expect(newSource).toContain('voiceStartupInFlightRef.current = true;');
+ expect(newSource.indexOf('resolveMobileVoiceRecordingPermission({')).toBeLessThan(
+ newSource.indexOf('voiceStartupInFlightRef.current = true;'),
+ );
+ expect(newSource).toContain('getPermission: getRecordingPermissionsAsync');
+ expect(newSource).toContain("isAppActive: () => AppState.currentState === 'active'");
+ expect(newSource).toContain(
+ "voicePermissionRequestSeqRef.current !== permissionRequestSeq\n"
+ + " || AppState.currentState !== 'active'\n"
+ + " ) return;\n"
+ + " startupSeq = voiceStartupSeqRef.current + 1;",
);
- expect(newSource).toContain('if (voiceStartupSeqRef.current !== startupSeq) return;');
expect(newSource).toContain('const cancelVoiceForDeviceSwitch = useCallback(() => {');
- expect(selectDeviceSource).toContain('if (voiceStopInFlightRef.current || voiceIsProcessing) return;');
+ expect(selectDeviceSource).toContain('voicePermissionRequestInFlightRef.current');
+ expect(selectDeviceSource).toContain('|| voiceStopInFlightRef.current');
+ expect(selectDeviceSource).toContain('|| voiceIsProcessing');
expect(selectDeviceSource).toContain('cancelVoiceForDeviceSwitch();');
expect(newSource).toContain('voiceStartupInFlightRef.current = false;');
expect(newSource).toContain('createMobileVoiceControllerSession({');
diff --git a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
index 8ec598481e..d788dd46b2 100644
--- a/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/sessionComposerDesktopFirst.test.ts
@@ -551,16 +551,27 @@ describe('mobile session composer desktop-first surface', () => {
expect(voiceSource).toContain('readCurrentDraft: () => draftRef.current');
expect(source).toContain('const voiceStartupInFlightRef = useRef(false);');
+ expect(source).toContain('const voicePermissionRequestInFlightRef = useRef(false);');
expect(source).toContain('const voiceStopInFlightRef = useRef(false);');
expect(voiceSource).toContain('|| voiceStopInFlightRef.current');
- expect(voiceSource.indexOf('voiceStartupInFlightRef.current = true;')).toBeLessThan(
- voiceSource.indexOf('const permission = await requestRecordingPermissionsAsync();'),
+ expect(voiceSource).toContain('resolveMobileVoiceRecordingPermission({');
+ expect(voiceSource).toContain('voiceStartupInFlightRef.current = true;');
+ expect(voiceSource.indexOf('resolveMobileVoiceRecordingPermission({')).toBeLessThan(
+ voiceSource.indexOf('voiceStartupInFlightRef.current = true;'),
+ );
+ expect(voiceSource).toContain('getPermission: getRecordingPermissionsAsync');
+ expect(voiceSource).toContain("isAppActive: () => AppState.currentState === 'active'");
+ expect(voiceSource).toContain(
+ "voicePermissionRequestSeqRef.current !== permissionRequestSeq\n"
+ + " || AppState.currentState !== 'active'\n"
+ + " ) return;\n"
+ + " startupSeq = voiceStartupSeqRef.current + 1;",
);
expect(voiceSource).toContain('voiceStartupInFlightRef.current = false;');
expect(voiceSource).toContain('onDraftChanged: setComposerDraft');
expect(voiceSource).toContain('isMobileRealtimeAudioAvailable()');
expect(voiceSource.indexOf('isMobileRealtimeAudioAvailable()')).toBeLessThan(
- voiceSource.indexOf('requestRecordingPermissionsAsync()'),
+ voiceSource.indexOf('resolveMobileVoiceRecordingPermission({'),
);
expect(voiceSource).toContain('mobileVoiceRealtimeAudioUnavailableError()');
expect(voiceSource).toContain('const documentBeforeStop = composerDocumentRef.current;');
diff --git a/apps/mobile/src/session/mobileVoiceStartup.ts b/apps/mobile/src/session/mobileVoiceStartup.ts
new file mode 100644
index 0000000000..ff4908ef34
--- /dev/null
+++ b/apps/mobile/src/session/mobileVoiceStartup.ts
@@ -0,0 +1,138 @@
+export type MobileVoiceRecordingPermission = {
+ granted: boolean;
+};
+
+export type MobileVoicePermissionResult = 'granted' | 'denied' | 'cancelled';
+
+type ResolveMobileVoiceRecordingPermissionOptions = {
+ getPermission: () => Promise<MobileVoiceRecordingPermission>;
+ requestPermission: () => Promise<MobileVoiceRecordingPermission>;
+ isRequestCurrent: () => boolean;
+ isAppActive: () => boolean;
+ subscribeToAppState: (listener: (state: string) => void) => () => void;
+ signal: AbortSignal;
+ waitForAppActive: () => Promise<boolean>;
+};
+
+type MobileVoiceBackgroundState = {
+ startupInFlight: boolean;
+ recordingActive: boolean;
+ hasController: boolean;
+};
+
+type WaitForMobileVoiceAppActiveOptions = {
+ isAppActive: () => boolean;
+ subscribe: (listener: (state: string) => void) => () => void;
+ signal: AbortSignal;
+};
+
+/**
+ * Waits for React Native to publish the foreground transition that can trail
+ * Android's permission result. The caller aborts this wait when its screen or
+ * permission request is superseded, which also removes the AppState listener.
+ */
+export function waitForMobileVoiceAppActive(
+ options: WaitForMobileVoiceAppActiveOptions,
+): Promise<boolean> {
+ if (options.isAppActive()) return Promise.resolve(true);
+ if (options.signal.aborted) return Promise.resolve(false);
+
+ return new Promise<boolean>((resolve) => {
+ let unsubscribe: (() => void) | null = null;
+ let settled = false;
+ const finish = (active: boolean): void => {
+ if (settled) return;
+ settled = true;
+ unsubscribe?.();
+ options.signal.removeEventListener('abort', onAbort);
+ resolve(active);
+ };
+ const onAbort = (): void => finish(false);
+
+ options.signal.addEventListener('abort', onAbort, { once: true });
+ const removeSubscription = options.subscribe((state) => {
+ if (state === 'active') finish(true);
+ });
+ // A synchronous subscription callback may settle before subscribe returns.
+ if (settled) {
+ removeSubscription();
+ return;
+ }
+ unsubscribe = removeSubscription;
+ // Close the gap between the initial check and listener registration.
+ if (options.isAppActive()) finish(true);
+ else if (options.signal.aborted) finish(false);
+ });
+}
+
+/**
+ * Resolves microphone permission before voice startup claims any audio
+ * resources. Android may report the app as backgrounded while its system
+ * permission sheet is open, and the permission promise can resolve before the
+ * matching foreground event. Only backgrounding after the system prompt opens
+ * may wait for active; a tap that backgrounds during permission preflight is
+ * stale even if the app returns before the permission query resolves.
+ */
+export async function resolveMobileVoiceRecordingPermission(
+ options: ResolveMobileVoiceRecordingPermissionOptions,
+): Promise<MobileVoicePermissionResult> {
+ if (
+ options.signal.aborted
+ || !options.isRequestCurrent()
+ || !options.isAppActive()
+ ) return 'cancelled';
+
+ let backgroundedDuringPreflight = false;
+ let removePreflightSubscription: (() => void) | null = options.subscribeToAppState((state) => {
+ if (state === 'background') backgroundedDuringPreflight = true;
+ });
+ const stopObservingPreflight = (): void => {
+ removePreflightSubscription?.();
+ removePreflightSubscription = null;
+ };
+ const onAbort = (): void => stopObservingPreflight();
+ options.signal.addEventListener('abort', onAbort, { once: true });
+ let permission: MobileVoiceRecordingPermission;
+ try {
+ permission = await options.getPermission();
+ } finally {
+ stopObservingPreflight();
+ options.signal.removeEventListener('abort', onAbort);
+ }
+ if (
+ options.signal.aborted
+ || !options.isRequestCurrent()
+ || backgroundedDuringPreflight
+ || !options.isAppActive()
+ ) return 'cancelled';
+
+ let openedSystemPrompt = false;
+ if (!permission.granted) {
+ openedSystemPrompt = true;
+ permission = await options.requestPermission();
+ if (options.signal.aborted || !options.isRequestCurrent()) return 'cancelled';
+ }
+
+ if (!permission.granted) return 'denied';
+ if (!options.isAppActive()) {
+ if (!openedSystemPrompt) return 'cancelled';
+ const becameActive = await options.waitForAppActive();
+ if (
+ !becameActive
+ || !options.isRequestCurrent()
+ || !options.isAppActive()
+ ) return 'cancelled';
+ }
+ return 'granted';
+}
+
+/**
+ * Permission prompts do not own a controller or an active audio session.
+ * Backgrounding cancels only startup work that has moved past permission, or
+ * a recording that is already active.
+ */
+export function shouldCancelMobileVoiceForBackground(
+ state: MobileVoiceBackgroundState,
+): boolean {
+ return state.startupInFlight || state.recordingActive || state.hasController;
+}