Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/mobile/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 5 additions & 2 deletions apps/mobile/src/features/voice-input/VoiceInputProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,11 @@ const voiceInputAtom = Atom.make((get) => {
);
let keepAwakeSequence = 0;
let audioToken: ReturnType<typeof acquireAudioSession> | 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"),
Expand Down
18 changes: 18 additions & 0 deletions apps/mobile/src/features/voice-input/voiceInputSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ vi.mock("expo-audio", () => ({
setAudioModeAsync: audio.setMode,
setIsAudioActiveAsync: audio.setActive,
}));
vi.mock("react-native", () => ({ Platform: { OS: "ios" } }));

import {
createVoiceInputTarget,
Expand Down Expand Up @@ -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();
Expand Down
6 changes: 6 additions & 0 deletions apps/mobile/src/features/voice-input/voiceInputSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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();
});
Original file line number Diff line number Diff line change
@@ -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 () => {
Expand Down
5 changes: 5 additions & 0 deletions apps/mobile/src/lib/audioSession.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { AudioModule, setAudioModeAsync, setIsAudioActiveAsync } from "expo-audio";
import { Platform } from "react-native";

type AudioSessionToken = {
readonly kind: "playback" | "recording";
Expand Down Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/lib/filePreview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1141,6 +1141,7 @@ describe("ThreadInlineFilePreview playback", () => {
await activateAudioSession(recording);
expect(audio.setAudioMode).toHaveBeenLastCalledWith({
allowsRecording: true,
allowsBackgroundRecording: true,
interruptionMode: "doNotMix",
playsInSilentMode: true,
shouldPlayInBackground: false,
Expand Down
8 changes: 5 additions & 3 deletions docs/user/composer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 15 additions & 1 deletion packages/client-runtime/src/voice-input/controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<PreparedVoiceTranscription>();
const preparationEntered = deferred<AbortSignal>();
Expand All @@ -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;
Expand Down
11 changes: 5 additions & 6 deletions packages/client-runtime/src/voice-input/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,12 +426,11 @@ export class VoiceInputController {
return this.discardRecording(message);
}

appMovedToBackground(): Promise<void> | 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> | 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> | void {
Expand Down