From 6295ddef411641ff493d1b15f73a75ff86a108d4 Mon Sep 17 00:00:00 2001 From: "fishdogdev (claw)" <263836300+fishdogdev@users.noreply.github.com> Date: Wed, 11 Nov 2026 20:09:33 -0800 Subject: [PATCH] fix(mobile): dictation no longer loses the recording when the app goes to the background Locking the phone or switching apps while dictating treated the recording as an interruption: the captured audio was deleted and the composer showed "Voice recording was interrupted." with nothing to retry from. Natively, expo-audio also paused the recorder on background because the recording audio mode never allowed background recording. iOS now sets allowsBackgroundRecording for recording sessions and leaves a running recording alone when the app goes to the background; returning with a recorder the system paused (call, Siri) finishes and transcribes it. Android, which cannot record in the background without a microphone foreground service, stops and transcribes what was captured instead of discarding it. Preparation is still cancelled on background, as before. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 --- apps/mobile/app.config.ts | 2 +- .../voice-input/VoiceInputProvider.tsx | 7 +++++-- .../voice-input/voiceInputSession.test.ts | 18 ++++++++++++++++++ .../features/voice-input/voiceInputSession.ts | 6 ++++++ .../voiceRecordingPermission.test.ts | 9 ++++++++- .../voice-input/voiceRecordingPermission.ts | 9 +++++++-- apps/mobile/src/lib/audioSession.ts | 5 +++++ apps/mobile/src/lib/filePreview.test.ts | 1 + docs/user/composer.md | 8 +++++--- .../src/voice-input/controller.test.ts | 16 +++++++++++++++- .../src/voice-input/controller.ts | 11 +++++------ 11 files changed, 76 insertions(+), 16 deletions(-) diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index 97fe5cf977acc..3f086e31fcff1 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -278,7 +278,7 @@ const config: ExpoConfig = { NSLocalNetworkUsageDescription: "Allow T3 Code to connect to T3 Code servers on your local network or tailnet.", NSPhotoLibraryAddUsageDescription: "Allow T3 Code to save images to your photo library.", - // System picture in picture needs background audio to start and survive outside the app. + // Background audio keeps system picture in picture and dictation running outside the app. UIBackgroundModes: ["audio"], ITSAppUsesNonExemptEncryption: false, // Capture builds disable multitasking because iPadOS otherwise ignores orientation requests. diff --git a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx index 6e891dd04e7e9..11d8a0958a4ab 100644 --- a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx +++ b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx @@ -85,8 +85,11 @@ const voiceInputAtom = Atom.make((get) => { ); let keepAwakeSequence = 0; let audioToken: ReturnType | null = null; - const permission = createVoiceRecordingPermission(() => { - void session.controller.appMovedToBackground(); + const permission = createVoiceRecordingPermission({ + onBackground: () => { + void session.controller.appMovedToBackground({ keepRecording: Platform.OS === "ios" }); + }, + onActive: () => void session.appBecameActive(), }); const recorder = createLazyVoiceRecorder({ getDestination: () => (registry.get(voiceRouteAtom) === null ? "local" : "environment"), diff --git a/apps/mobile/src/features/voice-input/voiceInputSession.test.ts b/apps/mobile/src/features/voice-input/voiceInputSession.test.ts index 9d30e376b54e2..cb5574c839d8b 100644 --- a/apps/mobile/src/features/voice-input/voiceInputSession.test.ts +++ b/apps/mobile/src/features/voice-input/voiceInputSession.test.ts @@ -18,6 +18,7 @@ vi.mock("expo-audio", () => ({ setAudioModeAsync: audio.setMode, setIsAudioActiveAsync: audio.setActive, })); +vi.mock("react-native", () => ({ Platform: { OS: "ios" } })); import { createVoiceInputTarget, @@ -399,6 +400,23 @@ describe("global voice input", () => { } }); + it("transcribes a recording the system paused while the app was away", async () => { + let sample: VoiceRecordingSample | null = { durationMillis: 1_000, metering: -40 }; + const commit = vi.fn(); + const { session, recorder } = createSession({ sampleRecording: () => sample }); + await session.start(createTarget("first", () => "", commit, { start: 0, end: 0 })); + + await session.appBecameActive(); + expect(session.controller.currentState.phase).toBe("recording"); + expect(recorder.stop).not.toHaveBeenCalled(); + + sample = null; + await session.appBecameActive(); + expect(commit).toHaveBeenCalledWith("spoken text", { start: 11, end: 11 }); + expect(session.controller.currentState.phase).toBe("idle"); + session.dispose(); + }); + it("publishes which owners are focused", () => { const { session } = createSession(); const listener = vi.fn(); diff --git a/apps/mobile/src/features/voice-input/voiceInputSession.ts b/apps/mobile/src/features/voice-input/voiceInputSession.ts index 5bf9395daf59c..efa3a5b4a9660 100644 --- a/apps/mobile/src/features/voice-input/voiceInputSession.ts +++ b/apps/mobile/src/features/voice-input/voiceInputSession.ts @@ -145,6 +145,12 @@ export class VoiceInputSession { return this.controller.start(); } + // iOS pauses the recorder for a call or Siri without a status event. + async appBecameActive() { + if (this.controller.currentState.phase === "recording" && !this.dependencies.sampleRecording()) + await this.controller.stop(); + } + dispose(): void { this.controller.dispose(); this.stopRecordingActivity(); diff --git a/apps/mobile/src/features/voice-input/voiceRecordingPermission.test.ts b/apps/mobile/src/features/voice-input/voiceRecordingPermission.test.ts index ccb108811f78a..62f36dfcb9527 100644 --- a/apps/mobile/src/features/voice-input/voiceRecordingPermission.test.ts +++ b/apps/mobile/src/features/voice-input/voiceRecordingPermission.test.ts @@ -31,7 +31,11 @@ it("keeps dictation alive while Android's permission activity backgrounds the ap const permission = Promise.withResolvers<{ granted: boolean; canAskAgain: boolean }>(); mocks.request.mockReturnValue(permission.promise); const interrupted = vi.fn(); - const recording = createVoiceRecordingPermission(interrupted); + const resumed = vi.fn(); + const recording = createVoiceRecordingPermission({ + onBackground: interrupted, + onActive: resumed, + }); let settled = false; const result = recording.requestPermission().then((value) => { settled = true; @@ -45,8 +49,11 @@ it("keeps dictation alive while Android's permission activity backgrounds the ap changeAppState("active"); expect(await result).toMatchObject({ granted: true }); expect(interrupted).not.toHaveBeenCalled(); + expect(resumed).not.toHaveBeenCalled(); changeAppState("background"); expect(interrupted).toHaveBeenCalledOnce(); + changeAppState("active"); + expect(resumed).toHaveBeenCalledOnce(); recording.dispose(); }); diff --git a/apps/mobile/src/features/voice-input/voiceRecordingPermission.ts b/apps/mobile/src/features/voice-input/voiceRecordingPermission.ts index 21ff1df02dd7e..26ec67d9e8b19 100644 --- a/apps/mobile/src/features/voice-input/voiceRecordingPermission.ts +++ b/apps/mobile/src/features/voice-input/voiceRecordingPermission.ts @@ -1,13 +1,18 @@ import { requestRecordingPermissionsAsync } from "expo-audio"; import { AppState, Platform } from "react-native"; -export function createVoiceRecordingPermission(onBackground: () => void) { +export function createVoiceRecordingPermission(handlers: { + readonly onBackground: () => void; + readonly onActive: () => void; +}) { let requesting = false; let disposed = false; let resume: (() => void) | null = null; const subscription = AppState.addEventListener("change", (state) => { if (state === "active") resume?.(); - if (state === "background" && !requesting) onBackground(); + if (requesting) return; + if (state === "active") handlers.onActive(); + if (state === "background") handlers.onBackground(); }); return { requestPermission: async () => { diff --git a/apps/mobile/src/lib/audioSession.ts b/apps/mobile/src/lib/audioSession.ts index 7ebcd0bf726ec..6faf1ff0b3c33 100644 --- a/apps/mobile/src/lib/audioSession.ts +++ b/apps/mobile/src/lib/audioSession.ts @@ -1,4 +1,5 @@ import { AudioModule, setAudioModeAsync, setIsAudioActiveAsync } from "expo-audio"; +import { Platform } from "react-native"; type AudioSessionToken = { readonly kind: "playback" | "recording"; @@ -73,6 +74,10 @@ export function activateAudioSession( interruptionMode: "doNotMix", playsInSilentMode: true, shouldPlayInBackground: false, + // Android would need expo-audio's microphone foreground service, which the app does not ship. + ...(Platform.OS === "ios" && token.kind === "recording" + ? { allowsBackgroundRecording: true } + : {}), }); if (!isAudioSessionOwner(token)) return false; await setIsAudioActiveAsync(true); diff --git a/apps/mobile/src/lib/filePreview.test.ts b/apps/mobile/src/lib/filePreview.test.ts index c5fee9e6dc008..4e696790fc580 100644 --- a/apps/mobile/src/lib/filePreview.test.ts +++ b/apps/mobile/src/lib/filePreview.test.ts @@ -1141,6 +1141,7 @@ describe("ThreadInlineFilePreview playback", () => { await activateAudioSession(recording); expect(audio.setAudioMode).toHaveBeenLastCalledWith({ allowsRecording: true, + allowsBackgroundRecording: true, interruptionMode: "doNotMix", playsInSilentMode: true, shouldPlayInBackground: false, diff --git a/docs/user/composer.md b/docs/user/composer.md index df880e49c6ca5..4d89438b43569 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -225,9 +225,11 @@ first of your preferred languages (**Settings → General → Language & Region* that Apple’s speech model supports. If none is supported, it tries the app’s language. Android transcribes on the device while you record and finishes after you stop. Recordings can be up to five -minutes long. Canceling or an audio interruption discards the recording and -preserves your existing draft. Navigating to another screen keeps dictation active; -use the floating controls to finish or cancel. While recording, the screen stays +minutes long. Canceling discards the recording and preserves your existing draft. +Navigating to another screen keeps dictation active; use the floating controls to +finish or cancel. On iPhone, locking the phone or switching to another app keeps +recording; finish when you come back. On Android, leaving the app finishes the +recording and transcribes what you said so far. While recording, the screen stays awake; it can sleep normally once recording stops. Choose a preferred order in **Settings → Voice**. Voice input requests the first diff --git a/packages/client-runtime/src/voice-input/controller.test.ts b/packages/client-runtime/src/voice-input/controller.test.ts index 41e56933ce104..c3a347f3eddda 100644 --- a/packages/client-runtime/src/voice-input/controller.test.ts +++ b/packages/client-runtime/src/voice-input/controller.test.ts @@ -833,6 +833,20 @@ describe("VoiceInputController", () => { expect(releaseRecording).toHaveBeenCalledOnce(); }); + it("keeps a backgrounded recording where allowed, and otherwise transcribes it", async () => { + const harness = createHarness(); + await harness.controller.start(); + + await harness.controller.appMovedToBackground({ keepRecording: true }); + expect(harness.controller.currentState.phase).toBe("recording"); + expect(harness.recorder.stop).not.toHaveBeenCalled(); + + await harness.controller.appMovedToBackground({ keepRecording: false }); + expect(harness.commits[0]?.text).toBe("hello new text"); + expect(harness.controller.currentState).toMatchObject({ phase: "idle", error: null }); + expect(harness.deleted).toEqual(["file:///voice.m4a"]); + }); + it("cancels preparation when the app reaches the background", async () => { const preparation = deferred(); const preparationEntered = deferred(); @@ -846,7 +860,7 @@ describe("VoiceInputController", () => { }); const starting = harness.controller.start(); const signal = await preparationEntered.promise; - harness.controller.appMovedToBackground(); + harness.controller.appMovedToBackground({ keepRecording: true }); expect(signal.aborted).toBe(true); preparation.resolve(preparedTranscription()); await starting; diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.ts index 668705546a489..488f40b4d59d5 100644 --- a/packages/client-runtime/src/voice-input/controller.ts +++ b/packages/client-runtime/src/voice-input/controller.ts @@ -426,12 +426,11 @@ export class VoiceInputController { return this.discardRecording(message); } - appMovedToBackground(): Promise | void { - return this.interruptRecording( - this.state.phase === "preparing" - ? "Voice input stopped when the app moved to the background." - : undefined, - ); + appMovedToBackground(options: { readonly keepRecording: boolean }): Promise | void { + if (this.state.phase === "preparing") { + return this.interruptRecording("Voice input stopped when the app moved to the background."); + } + if (!options.keepRecording) return this.stop(); } handleRecorderStatus(status: VoiceRecorderStatus): Promise | void {