App icon indicating copy to clipboard operation
App copied to clipboard

[$250] [Sentry: APP-NTH] iOS sound playback throws "Session activation failed" in playSound

Open mountiny opened this issue 2 weeks ago • 54 comments

Sentry

https://expensify.sentry.io/issues/APP-NTH

Impact (snapshot at filing)

  • Users (total since first seen): 307
  • Events (total since first seen): 786
  • Users (last 7d): 272, with 680 events
  • First seen: Nov 3, 2026 (release 9.5.31)
  • Last seen: now (ongoing)
  • Platform: iOS only, HybridApp production builds
  • App versions: every release from 9.5.31 to 9.5.37, with an even spread
  • iOS versions: 26.5 to 27.2
  • Mechanism: onunhandledrejection

Stack trace (top frames, our code only)

Error: UnexpectedException: Session activation failed (at ExpoModulesCore/SyncFunctionDefinition.swift:96)
  src/libs/Sound/index.native.ts:53  playSound -> player.play()
  native play

Suspected cause

On iOS, player.play() in expo-audio 57.0.3 calls activateSession(), which calls AVAudioSession.setActive(true) (node_modules/expo-audio/ios/AudioModule.swift). iOS refuses to activate the session in some app states, and expo-audio throws "Session activation failed".

The event we inspected came from an app in the background (in_foreground: false). Pusher can still deliver new messages for a short time after the user leaves the app, and playSoundForMessageType in src/libs/actions/User.ts then plays a sound. The audio mode sets shouldPlayInBackground: false, so iOS does not let a backgrounded app start a session. A phone call or another app that holds the audio session can cause the same error.

Nothing catches the error, so Sentry reports it as an unhandled promise rejection:

  1. playSound in src/libs/Sound/index.native.ts is async, so the throw from player.play() becomes a rejected promise.
  2. withMinimalExecutionTime in src/libs/Sound/BaseSound.ts calls nextFunc() and ignores the promise it returns.
  3. The try/catch in playSoundForMessageType only covers synchronous code.

When player.play() throws, the code also never calls player.remove(), so the player stays in memory.

The first seen date matches the release that bumped @sentry/react-native from 8.27.0 to 8.32.0 (9.5.31). The Sound code did not change in that release. The error probably existed before, and the new SDK started to report it.

Possible fix

  1. Skip the sound when the app is not active (AppState.currentState !== 'active'). The user cannot hear an in-app sound in the background.
  2. Wrap player.play() in a try/catch. On failure, log it and call subscription.remove() and player.remove().

Reproduction

Not confirmed. Likely steps on an iOS HybridApp build:

  1. Log in on iOS and make sure sounds are not muted.
  2. Send the app to the background.
  3. Within a few seconds, mention this account in a chat from another account.
  4. Check Sentry or the device logs for "Session activation failed".

Related

  • Sibling Sentry IDs: none found
  • Prior GitHub issues: none for this error. APP-MD4 also involved expo-audio, but it was a different crash (Android, missing native module).
Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @eVoloshchak

mountiny avatar Nov 16 '26 04:11 mountiny

Triggered auto assignment to Contributor-plus team member for initial proposal review - @eVoloshchak (External)

Job added to Upwork: https://www.upwork.com/jobs/~022122187481936413737

Proposal

What is the root cause of that problem?

playSound in src/libs/Sound/index.native.ts (line ~53) calls player.play() with no error handling. On iOS, expo-audio activates the AVAudioSession there and throws "Session activation failed" when iOS refuses (app not active, or another app/call holds the session). Because playSound is async, the throw becomes a rejected promise. withMinimalExecutionTime in src/libs/Sound/BaseSound.ts (nextFunc(); inside processQueue) discards that promise, and the try/catch in playSoundForMessageType (src/libs/actions/User.ts, ~line 793) only covers synchronous code, so nothing handles it and it surfaces as onunhandledrejection.

The AppState check is already there, but too early: playSoundForMessageType checks Visibility.isVisible() (native: AppState.currentState === 'active', src/libs/Visibility/index.native.ts) before await isChannelMuted(...), then playSound waits for audioModeConfigured and the 300 ms queue. The app can go to the background in between, so that guard does not protect the play() call. The player is also never removed when play() throws.

What changes do you think we should make in order to solve the problem?

In src/libs/Sound/index.native.ts, at the point of playing:

  1. Return early if AppState.currentState !== 'active' right before createAudioPlayer, after the awaits.
  2. Wrap player.play() in try/catch; in catch, call subscription.remove() and player.remove(), and log with Log.hmmm instead of rethrowing. A failed notification sound should never be an app error.

This fixes the cause once for every playSound caller, not just the Pusher path. Test: a unit test in tests/unit/ that mocks expo-audio so play() throws, and asserts playSound resolves, player.remove is called, and no unhandled rejection occurs; plus one where AppState.currentState = 'background' asserts createAudioPlayer is not called.

What alternative solutions did you explore? (Optional)

  • The issue's possible fix 1 (check AppState) alone is already partly in place in playSoundForMessageType and still races, and it does not cover a phone call or another app holding the session.
  • Catching in withMinimalExecutionTime (.catch on nextFunc()) would also silence the error but leaves the leaked player and hides other failures.

Stephen3453 avatar Nov 16 '26 04:11 Stephen3453

Proposal

Please re-state the problem that we are trying to solve in this issue.

On iOS HybridApp builds, playing an in-app sound via playSound (src/libs/Sound/index.native.ts) throws UnexpectedException: Session activation failed from expo-audio's player.play() when iOS refuses AVAudioSession.setActive(true) (for example, when the app transitions to the background while a sound is queued/awaited, or when another app / phone call holds the audio session). Because playSound is async and withMinimalExecutionTime ignores its returned Promise, the exception escapes as an unhandled promise rejection (onunhandledrejection in Sentry APP-NTH) and leaks the AudioPlayer instance.

What is the root cause of that problem?

  1. Asynchronous gap between visibility check and player.play() (src/libs/actions/User.ts:793 -> src/libs/Sound/BaseSound.ts:44 -> src/libs/Sound/index.native.ts:27-53):
    • Even when playSoundForMessageType checks Visibility.isVisible() upfront, it subsequently awaits isChannelMuted(...) and then enqueues playSound through withMinimalExecutionTime(playSound, 300) (src/libs/Sound/BaseSound.ts:32-60), which spaces out executions by 300ms via setTimeout.
    • Furthermore, other callers of playSound (SOUNDS.DONE, SOUNDS.SUCCESS, SOUNDS.ATTENTION) do not check Visibility.isVisible() / AppState.currentState before or after the queue delay.
    • By the time playSound actually runs and resumes after await audioModeConfigured, the app may already be in the background (AppState.currentState !== 'active'), where shouldPlayInBackground: false causes iOS to reject AVAudioSession.setActive(true).
  2. Unhandled synchronous throw inside async playSound and resource leak (src/libs/Sound/index.native.ts:40-53):
    • player.play() synchronously calls the native ExpoModulesCore SyncFunctionDefinition (activateSession() -> player.play()). When iOS rejects session activation (either due to background state or an active phone call / Siri / exclusive audio session), player.play() throws UnexpectedException: Session activation failed.
    • Because playSound is async, that throw rejects the returned Promise, skipping subscription.remove() and player.remove() (leaking both the listener and the native AudioPlayer), while withMinimalExecutionTime (src/libs/Sound/BaseSound.ts:44) calls nextFunc() without .catch(...), turning the rejection into an unhandled promise rejection.
    • Additionally, at module initialization (src/libs/Sound/index.native.ts:25), const audioModeConfigured = setAudioModeAsync(...) has no .catch(...), so if setAudioModeAsync ever rejects, await audioModeConfigured would also reject every subsequent playSound call.

What changes do you think we should make in order to solve the problem?

  1. In src/libs/Sound/index.native.ts:

    • Guard audioModeConfigured with .catch(...) so a failure configuring audio mode logs via Log.hmmm instead of permanently rejecting audioModeConfigured.
    • Check AppState.currentState !== 'active' (or !Visibility.isVisible()) both at the start of playSound and immediately after await audioModeConfigured before creating the player, since the app state can change while waiting in the 300ms throttle queue or awaiting audioModeConfigured.
    • Wrap player.play() in a try / catch block. In the catch block, clean up subscription.remove() and player.remove(), and log the non-fatal audio session refusal via Log.hmmm:
    import {AppState} from 'react-native';
    import Log from '@libs/Log';
    ...
    const audioModeConfigured = setAudioModeAsync({
        playsInSilentMode: false,
        shouldPlayInBackground: false,
        interruptionMode: 'mixWithOthers',
    }).catch((error: unknown) => {
        Log.hmmm('[Sound] Failed to configure audio mode', {error});
    });
    
    const playSound = async (soundFile: ValueOf<typeof SOUNDS>) => {
        if (getIsMuted() || AppState.currentState !== 'active') {
            return;
        }
    
        const source = SOUND_ASSETS[soundFile];
        if (!source) {
            return;
        }
    
        await audioModeConfigured;
    
        if (AppState.currentState !== 'active') {
            return;
        }
    
        const player = createAudioPlayer(source);
    
        const subscription = player.addListener('playbackStatusUpdate', (status) => {
            if (!status.didJustFinish) {
                return;
            }
    
            subscription.remove();
            player.remove();
        });
    
        try {
            player.play();
        } catch (error) {
            subscription.remove();
            player.remove();
            Log.hmmm('[Sound] Failed to play sound', {soundFile, error});
        }
    };
    
  2. Add unit tests (tests/unit/SoundTest.ts):

    • Verify that when AppState.currentState is 'background' or 'inactive', playSound returns early without calling createAudioPlayer.
    • Verify that when player.play() throws Error('UnexpectedException: Session activation failed'), playSound catches the error without rejecting, calls subscription.remove() and player.remove(), and logs via Log.hmmm.

What alternative solutions did you explore? (Optional)

  • Only checking AppState.currentState === 'active' without wrapping player.play() in try/catch: Insufficient because iOS can also refuse AVAudioSession.setActive(true) while the app is in the foreground (e.g., during an active phone call, FaceTime, or Siri session). Both the AppState guard and try/catch with player.remove() cleanup are required.

cocvn157 avatar Nov 16 '26 04:11 cocvn157

Proposal

Please re-state the problem that we are trying to solve in this issue.

On iOS HybridApp builds, playSound throws an unhandled promise rejection in Sentry (APP-NTH: UnexpectedException: Session activation failed (at ExpoModulesCore/SyncFunctionDefinition.swift:96)). This occurs when expo-audio's player.play() attempts to activate the audio session via AVAudioSession.setActive(true) and iOS refuses (for example, when the app transitions to the background while a sound is queued or awaited, or when another application/phone call holds the audio session). In addition to triggering Sentry errors, this unhandled throw leaks the native AudioPlayer and event subscription in memory.

What is the root cause of that problem?

There are two main contributing causes in src/libs/Sound/index.native.ts:

  1. Racy background audio playback (src/libs/Sound/index.native.ts:27-53):

    • In src/libs/actions/User.ts:782, playSoundForMessageType checks Visibility.isVisible() upfront, but then asynchronously awaits isChannelMuted(reportID).
    • Furthermore, playSound is exported through withMinimalExecutionTime(playSound, 300) (src/libs/Sound/BaseSound.ts:35-65), which throttles executions with a 300ms delay, followed by await audioModeConfigured in src/libs/Sound/index.native.ts:39.
    • Other call sites across the app (such as Task.ts, PayMoneyRequest.ts, Split.ts, etc.) invoke playSound directly without checking visibility or AppState.
    • During any of these delays, the user may background the app. Because audio mode configures shouldPlayInBackground: false (src/libs/Sound/index.native.ts:25), iOS rejects AVAudioSession.setActive(true), causing player.play() to throw UnexpectedException: Session activation failed.
  2. Missing error handling & native resource leak (src/libs/Sound/index.native.ts:41-53):

    • player.play() throws synchronously inside the async playSound function, which converts the throw into a rejected promise.
    • withMinimalExecutionTime calls nextFunc() (src/libs/Sound/BaseSound.ts:48) without handling or .catch()-ing the returned promise, allowing it to bubble up as an unhandled promise rejection.
    • Because player.play() throws before playback finishes, the playbackStatusUpdate listener never receives status.didJustFinish, so subscription.remove() and player.remove() are never executed. This leaks the native AudioPlayer instance in memory on every failure.
    • Additionally, setAudioModeAsync at module scope (src/libs/Sound/index.native.ts:25) has no .catch() handler, so any failure during initial audio mode configuration would permanently reject audioModeConfigured and all subsequent playSound calls.

What changes do you think we should make in order to solve the problem?

In src/libs/Sound/index.native.ts:

  1. Handle setAudioModeAsync rejections: Attach a .catch() handler logging via Log.hmmm so an initial audio mode configuration failure does not permanently break playback or unhandled rejection handlers.
  2. Guard against background playback: Check AppState.currentState !== 'active' both before and after await audioModeConfigured to prevent creating players and requesting audio sessions when the app is inactive or backgrounded.
  3. Wrap player creation and play() in try / catch with guaranteed cleanup: Wrap createAudioPlayer, listener registration, and player.play() in a try / catch block. If player.play() or session activation throws:
    • Call subscription?.remove() and player?.remove() immediately to release native audio resources.
    • Log the event using Log.hmmm instead of rethrowing, as a transient notification sound failure (e.g. active phone call, FaceTime, Siri) is expected non-fatal system behavior and should never crash the app or alert Sentry.
import {AppState} from 'react-native';
import Log from '@libs/Log';

// Configure audio mode for in-app notification sounds:
// - playsInSilentMode: false — respect the device's silent/mute switch (iOS)
// - shouldPlayInBackground: false — push notification sounds are played by the system
// - interruptionMode: 'mixWithOthers' — don't interrupt other audio (e.g. music)
const audioModeConfigured = setAudioModeAsync({
    playsInSilentMode: false,
    shouldPlayInBackground: false,
    interruptionMode: 'mixWithOthers',
}).catch((error: unknown) => {
    Log.hmmm('[Sound] Failed to configure audio mode', {error});
});

const playSound = async (soundFile: ValueOf<typeof SOUNDS>) => {
    if (getIsMuted() || AppState.currentState !== 'active') {
        return;
    }

    const source = SOUND_ASSETS[soundFile];
    if (!source) {
        return;
    }

    // Wait for audio mode to be configured before playing to ensure the session
    // uses the .ambient category (which won't interrupt music or other audio)
    await audioModeConfigured;

    if (AppState.currentState !== 'active') {
        return;
    }

    let player;
    let subscription: {remove: () => void} | undefined;

    try {
        player = createAudioPlayer(source);

        // Listen for playback completion to release resources
        subscription = player.addListener('playbackStatusUpdate', (status) => {
            if (!status.didJustFinish) {
                return;
            }

            subscription?.remove();
            player?.remove();
        });

        player.play();
    } catch (error) {
        subscription?.remove();
        player?.remove();
        Log.hmmm('[Sound] Failed to play sound', {soundFile, error});
    }
};

What alternative solutions did you explore? (Optional)

  1. Only checking AppState.currentState === 'active' without try / catch: Insufficient on its own because iOS AVAudioSession.setActive(true) can also fail while the app is in the foreground (for example, during an ongoing phone call, FaceTime call, Siri interaction, or when another app holds exclusive audio focus).
  2. Catching inside withMinimalExecutionTime only: While adding .catch() inside withMinimalExecutionTime silences unhandled promise rejections, it does not prevent the native memory leak (player.remove() would never be called if player.play() threw). Both the state guard and cleanup inside try / catch are necessary.

What specific scenarios should we cover in automated tests to prevent reoccurrence?

Add a new unit test suite tests/unit/SoundTest.ts mocking expo-audio and react-native's AppState:

  1. Background AppState guard:
    • When AppState.currentState is 'background' or 'inactive', verify that calling playSound(SOUNDS.RECEIVE) returns early without calling createAudioPlayer.
    • When AppState.currentState transitions to 'background' while awaiting audioModeConfigured, verify that createAudioPlayer is not called.
  2. Session activation failure handling & cleanup:
    • When player.play() throws Error('UnexpectedException: Session activation failed'), verify that:
      • playSound resolves cleanly without throwing or rejecting.
      • subscription.remove() and player.remove() are invoked to prevent native memory leaks.
      • Log.hmmm is called with the error details.
  3. Muted state check:
    • Verify that when getIsMuted() is true, createAudioPlayer is not called.
  4. Playback completion cleanup:
    • Verify that when playbackStatusUpdate fires with didJustFinish: true, subscription.remove() and player.remove() are called.

Contributor details

  • Email: [email protected]
  • Upwork Profile: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 16 '26 04:11 kevinjosh10

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab

Proposal

Problem

On iOS, when a message sound is triggered while the app is backgrounded or the phone is locked, the audio session activation fails and Sentry records "Session activation failed". The app should not attempt to activate the audio session or play a sound at all in that state: silent, and no Sentry noise.

Root cause

The bug is in the sound layer, and it has three parts:

  1. No background guard where the session is activated. playSound in src/libs/Sound/index.native.ts awaits the module-level audioModeConfigured promise (the setAudioModeAsync call made at import time), then calls createAudioPlayer(source) and player.play(). There is no AppState check anywhere in the file, and nothing wraps those calls: if activation fails, the rejection propagates, the playback listener stays subscribed and the player is never removed.

  2. The one guarded caller cannot close the race. playSoundForMessageType (src/libs/actions/User.ts:777) checks Visibility.isVisible() && Visibility.hasFocus() at line 782, but that check runs BEFORE the async isChannelMuted(reportID, ...).then(...) boundary, and playSound only runs after it. If the user locks the phone or backgrounds the app during that gap, the check has already passed and the session still activates in the background. A call-site check can never fix this; the state has to be re-checked synchronously at activation time. Several other callers (Duplicate.ts, PayMoneyRequest.ts, useSearchBulkActions.ts) call playSound with no visibility check at all.

  3. Failures surface as unhandled rejections. The module-level audioModeConfigured promise has no .catch, so a rejected setAudioModeAsync is itself an unhandled rejection, and every later await audioModeConfigured throws. And withMinimalExecutionTime (src/libs/Sound/BaseSound.ts:35) calls nextFunc() with no try/catch and no catch handler on the returned promise, so a rejected playSound becomes an unhandled promise rejection - which is exactly the Sentry noise in this issue.

Changes

  1. src/libs/Sound/index.native.ts - guard at activation time. At the top of playSound, after the existing mute check, return silently when the app is not active: if (!Visibility.isVisible()) { return; }. Visibility.isVisible() on native is AppState.currentState === 'active' (src/libs/Visibility/index.native.ts), so this is a synchronous check made at the moment of activation, inside the one function every caller funnels through. It closes the race in part 2 for all callers, including the ones with no guard of their own.

  2. src/libs/Sound/index.native.ts - a failed configuration must not throw forever. Attach a catch handler to audioModeConfigured that logs once with Log.hmmm and resolves, so a setAudioModeAsync failure degrades to "no sound" instead of an unhandled rejection plus a throw on every play.

  3. src/libs/Sound/index.native.ts - contain playback failures. Wrap createAudioPlayer and player.play() in try/catch. On error, remove the playback listener and the player, log with Log.hmmm, and return. Log.hmmm, not Log.alert: a sound that cannot play while backgrounded is expected behaviour, not an error worth a Sentry event - the Sentry noise is the bug being fixed.

  4. src/libs/Sound/BaseSound.ts - the wrapper must not leak rejections. In withMinimalExecutionTime's processQueue, wrap nextFunc() in try/catch and attach a catch handler when it returns a promise, so a sound failure can never become an unhandled rejection regardless of which sound entry point produced it. The 300 ms minimal execution time and the queue semantics are unchanged.

Not changed: the web implementation (src/libs/Sound/index.ts), the mute logic (getIsMuted), the sound assets, and every call site - no caller needs to change, because the guard now lives in the layer that activates the session.

Tests

New file tests/unit/SoundTest.ts (no sound test exists today), mocking expo-audio and AppState:

  • AppState is background or inactive: playSound resolves, and setAudioModeAsync / createAudioPlayer / player.play are never called.
  • setAudioModeAsync rejects: playSound still resolves, nothing is thrown, no unhandled rejection is raised.
  • createAudioPlayer throws (or play throws): the listener is removed, the player is removed, playSound resolves.
  • AppState is active: the sound plays (regression control).
  • withMinimalExecutionTime: a wrapped function that rejects does not produce an unhandled rejection, and the queue still processes the next call.

Alternatives considered

  • Guard at each call site. Rejected: there are 10+ call sites, several with no guard today, and the guarded one still races across its async boundary. The check belongs where the session is activated.
  • Log.alert on playback failure so the team sees it. Rejected: the issue is precisely that these expected, harmless failures reach Sentry.
  • Skip setAudioModeAsync when backgrounded only. Rejected: the failure also comes from player.play() activating the session; both calls sit behind the same guard in this proposal, which is simpler and complete.
  • Remove the audioModeConfigured await. Rejected: foreground playback relies on the ambient/mixWithOthers configuration; the fix keeps it and only stops it from throwing.

dankezo avatar Nov 16 '26 06:11 dankezo

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 06:11 melvin-bot[bot]

Proposal updated: please review this version of my proposal above (https://github.com/Expensify/App/issues/106955#issuecomment-6909573749), reformatted into the official template. The solution and scope are unchanged.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~013b564a690d9bcdab

Please re-state the problem that we are trying to solve in this issue.

On iOS, when a message sound is triggered while the app is backgrounded or the phone is locked, the audio session activation fails and Sentry records "Session activation failed". The app should not attempt to activate the audio session or play a sound at all in that state: silent, and no Sentry noise.

What is the root cause of that problem?

The bug is in the sound layer, and it has three parts:

  1. No background guard where the session is activated. playSound in src/libs/Sound/index.native.ts awaits the module-level audioModeConfigured promise (the setAudioModeAsync call made at import time), then calls createAudioPlayer(source) and player.play(). There is no AppState check anywhere in the file, and nothing wraps those calls: if activation fails, the rejection propagates, the playback listener stays subscribed and the player is never removed.

  2. The one guarded caller cannot close the race. playSoundForMessageType (src/libs/actions/User.ts:777) checks Visibility.isVisible() && Visibility.hasFocus() at line 782, but that check runs BEFORE the async isChannelMuted(reportID, ...).then(...) boundary, and playSound only runs after it. If the user locks the phone or backgrounds the app during that gap, the check has already passed and the session still activates in the background. A call-site check can never fix this; the state has to be re-checked synchronously at activation time. Several other callers (Duplicate.ts, PayMoneyRequest.ts, useSearchBulkActions.ts) call playSound with no visibility check at all.

  3. Failures surface as unhandled rejections. The module-level audioModeConfigured promise has no .catch, so a rejected setAudioModeAsync is itself an unhandled rejection, and every later await audioModeConfigured throws. And withMinimalExecutionTime (src/libs/Sound/BaseSound.ts:35) calls nextFunc() with no try/catch and no catch handler on the returned promise, so a rejected playSound becomes an unhandled promise rejection - which is exactly the Sentry noise in this issue.

What changes do you think we should make in order to solve the problem?

  1. src/libs/Sound/index.native.ts - guard at activation time. At the top of playSound, after the existing mute check, return silently when the app is not active: if (!Visibility.isVisible()) { return; }. Visibility.isVisible() on native is AppState.currentState === 'active' (src/libs/Visibility/index.native.ts), so this is a synchronous check made at the moment of activation, inside the one function every caller funnels through. It closes the race in part 2 for all callers, including the ones with no guard of their own.

  2. src/libs/Sound/index.native.ts - a failed configuration must not throw forever. Attach a catch handler to audioModeConfigured that logs once with Log.hmmm and resolves, so a setAudioModeAsync failure degrades to "no sound" instead of an unhandled rejection plus a throw on every play.

  3. src/libs/Sound/index.native.ts - contain playback failures. Wrap createAudioPlayer and player.play() in try/catch. On error, remove the playback listener and the player, log with Log.hmmm, and return. Log.hmmm, not Log.alert: a sound that cannot play while backgrounded is expected behaviour, not an error worth a Sentry event - the Sentry noise is the bug being fixed.

  4. src/libs/Sound/BaseSound.ts - the wrapper must not leak rejections. In withMinimalExecutionTime's processQueue, wrap nextFunc() in try/catch and attach a catch handler when it returns a promise, so a sound failure can never become an unhandled rejection regardless of which sound entry point produced it. The 300 ms minimal execution time and the queue semantics are unchanged.

Not changed: the web implementation (src/libs/Sound/index.ts), the mute logic (getIsMuted), the sound assets, and every call site - no caller needs to change, because the guard now lives in the layer that activates the session.

Tests:

New file tests/unit/SoundTest.ts (no sound test exists today), mocking expo-audio and AppState:

  • AppState is background or inactive: playSound resolves, and setAudioModeAsync / createAudioPlayer / player.play are never called.
  • setAudioModeAsync rejects: playSound still resolves, nothing is thrown, no unhandled rejection is raised.
  • createAudioPlayer throws (or play throws): the listener is removed, the player is removed, playSound resolves.
  • AppState is active: the sound plays (regression control).
  • withMinimalExecutionTime: a wrapped function that rejects does not produce an unhandled rejection, and the queue still processes the next call.

What alternative solutions did you explore? (Optional)

  • Guard at each call site. Rejected: there are 10+ call sites, several with no guard today, and the guarded one still races across its async boundary. The check belongs where the session is activated.
  • Log.alert on playback failure so the team sees it. Rejected: the issue is precisely that these expected, harmless failures reach Sentry.
  • Skip setAudioModeAsync when backgrounded only. Rejected: the failure also comes from player.play() activating the session; both calls sit behind the same guard in this proposal, which is simpler and complete.
  • Remove the audioModeConfigured await. Rejected: foreground playback relies on the ambient/mixWithOthers configuration; the fix keeps it and only stops it from throwing.

dankezo avatar Nov 16 '26 10:11 dankezo

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 10:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~014898525b9c53fc32

Proposal

Please re-state the problem that we are trying to solve in this issue.

On iOS HybridApp production builds, in-app notification sounds triggered while the app is transitioning to the background or when the audio session is interrupted throw an unhandled promise rejection: UnexpectedException: Session activation failed (at ExpoModulesCore/SyncFunctionDefinition.swift:96) from playSound -> player.play(), reporting to Sentry as APP-NTH. Furthermore, when player.play() throws, the player and event subscription listeners remain allocated in memory without cleanup.

What is the root cause of that problem?

  1. In src/libs/Sound/index.native.ts, playSound is invoked asynchronously whenever a notification arrives (e.g. from Pusher/WebSockets via playSoundForMessageType).
  2. The audio mode is configured with shouldPlayInBackground: false (to prevent background audio takeover). Consequently, when a message arrives while the app is inactive or in the background (AppState.currentState !== 'active'), iOS refuses to activate the AVAudioSession category, causing native player.play() to reject with Session activation failed.
  3. player.play() in playSound is called synchronously within the async function without a try/catch guard. When it throws, the playback completion listener (playbackStatusUpdate) never fires, so subscription.remove() and player.remove() are never called, leaking the player instance in native memory.
  4. Additionally, withMinimalExecutionTime in src/libs/Sound/BaseSound.ts executes nextFunc() without handling the returned promise, allowing the rejected promise from playSound to bubble up to the global onunhandledrejection handler caught by Sentry.

What changes do you think we should make in order to solve the problem?

  1. In src/libs/Sound/index.native.ts:

    • Guard against playing sound if the app is not in the active foreground:
      import {AppState} from 'react-native';
      ...
      const playSound = async (soundFile: ValueOf<typeof SOUNDS>) => {
          if (getIsMuted() || AppState.currentState !== 'active') {
              return;
          }
      
    • Wrap player.play() in a try...catch block. If player.play() fails or the audio session cannot be activated, log a warning and safely clean up the subscription and player:
      try {
          player.play();
      } catch (error) {
          Log.warn('Failed to play sound', {error, soundFile});
          subscription.remove();
          player.remove();
      }
      
  2. In src/libs/Sound/BaseSound.ts:

    • In withMinimalExecutionTime, ensure that processQueue catches any promise rejection returned by nextFunc():
      const result = nextFunc();
      if (result instanceof Promise) {
          result.catch((error) => Log.warn('Error in queued execution', {error}));
      }
      

What alternative solutions did you consider?

  • Enabling shouldPlayInBackground: true in setAudioModeAsync: Rejected because in-app UI chimes should not play in the background or hijack external audio (system push notifications already handle background alert sounds).
  • Only catching the error without checking AppState: Rejected because attempting to initialize an audio player when already backgrounded is wasted native resources and guaranteed to fail on iOS.

RajGahoi avatar Nov 16 '26 11:11 RajGahoi

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 16 '26 11:11 melvin-bot[bot]

@MelvinBot, please open this for proposals

eVoloshchak avatar Nov 17 '26 10:11 eVoloshchak

Proposal

Please re-state the problem that we are trying to solve in this issue.

On iOS, playSound throws "Session activation failed" from player.play(). Nothing catches it, so Sentry records it as an unhandled promise rejection: 786 events from 307 users so far.

What is the root cause of that problem?

In expo-audio 57.0.3 the native play function begins with try activateSession(), which runs AVAudioSession.setActive(true) (node_modules/expo-audio/ios/AudioModule.swift, Function("play")). iOS refuses that call for an app in the background when the audio mode was set with shouldPlayInBackground: false. It also refuses while another session has priority, a phone call for example. Because play is a synchronous Expo function, the refusal arrives in JS as a plain throw from player.play().

Our native sound helper calls it with no guard, and it has no app state check right before playback:

https://github.com/Expensify/App/blob/b2233de911618a6019162f52868f344543be5f91/src/libs/Sound/index.native.ts#L37-L54

There are two ways the app can be in the background at that point. playSoundForMessageType checks Visibility.isVisible() first, but then waits on an async isChannelMuted Onyx read, and playSound itself waits on audioModeConfigured. The app can go to the background during either wait.

https://github.com/Expensify/App/blob/b2233de911618a6019162f52868f344543be5f91/src/libs/actions/User.ts#L780-L790

playSound is async, so the throw turns into a rejected promise. withMinimalExecutionTime calls nextFunc() and ignores what it returns, so nothing ever handles that rejection:

https://github.com/Expensify/App/blob/b2233de911618a6019162f52868f344543be5f91/src/libs/Sound/BaseSound.ts#L40-L50

I confirmed this by running current main against an expo-audio player whose play() throws the same error:

  • createAudioPlayer runs and the completion listener gets attached.
  • player.play() throws UnexpectedException: Session activation failed.
  • Jest reports it as an unhandled rejection at playSound (src/libs/Sound/index.native.ts:53:12), the same frame as the Sentry stack.
  • subscription.remove() and player.remove() never run, because cleanup only happens on didJustFinish. Every failed sound leaves a native player behind.
  • With AppState.currentState set to background, createAudioPlayer still runs, so the background case goes straight into the failing call.
flowchart TD
    A["Pusher message while app is going to background"] -->|"isChannelMuted / audioModeConfigured awaited"| B["AppState is now background"]
    B -->|"no state check in playSound"| C["createAudioPlayer + listener"]
    C -->|"activateSession throws"| D["player.play throws Session activation failed"]
    D -->|"async fn, nextFunc result ignored"| E["unhandled rejection in Sentry"]
    D -->|"didJustFinish never fires"| F["player never removed"]

What changes do you think we should make in order to solve the problem?

I'd fix it in src/libs/Sound/index.native.ts. That file covers every native caller (report, task, IOU and search flows), and web uses a separate implementation.

  1. After await audioModeConfigured, return early unless AppState.currentState === 'active'. This is the latest point before the native call, so it also covers a background switch during either wait.
  2. Wrap player.play() in try/catch. On failure, remove the subscription and the player, and log it. We still need this when the app is in the foreground, because a phone call or another app can hold the session.
     await audioModeConfigured;

+    if (AppState.currentState !== 'active') {
+        return;
+    }
+
     const player = createAudioPlayer(source);
     ...
-    player.play();
+    try {
+        player.play();
+    } catch (error) {
+        subscription.remove();
+        player.remove();
+        Log.hmmm('[sound] Play error:', {message: (error as Error).message});
+    }

The log uses the same [sound] Play error: prefix as the web implementation. I used hmmm instead of alert because this is an expected OS refusal.

I also added tests/unit/SoundNativeTest.ts. It fails on current main with the same unhandled rejection at line 53 and passes with this change. With the change, a throwing play() no longer leaks a rejection, both the subscription and the player get removed, and no player is created while the app is in the background. Normal foreground playback and its existing completion cleanup don't change.

What alternative solutions did you explore? (Optional)

I tried adding another visibility check only in playSoundForMessageType. That doesn't help the other native callers. It also leaves the audioModeConfigured wait inside playSound uncovered, and it can't help when a phone call holds the session.

I also tried making withMinimalExecutionTime pass the wrapped promise through. Most callers fire and forget the sound, so the rejection would still go unhandled one level up. The failure is expected on iOS, so it's better handled where the native player is created and can be released.

mukhrr avatar Nov 17 '26 10:11 mukhrr

Proposal

Please re-state the problem that we are trying to solve in this issue.

On iOS, playSound reports UnexpectedException: Session activation failed to Sentry as an unhandled rejection whenever iOS refuses to activate the audio session, and the failed player is never released.

What is the root cause of that problem?

player.play() became a call that can throw when we moved from react-native-sound to expo-audio in #80624, but our sound code still treats it as fire-and-forget at every layer.

1. The throw comes from expo-audio 57, and it is not wrapped. On iOS play is a sync native function and its first line activates the session:

expo-audio/ios/AudioModule.swift#L212-L216

Function("play") { player in
  try activateSession()
  let rate = player.currentRate > 0 ? player.currentRate : 1.0
  player.play(at: rate)
}

activateSession() rethrows the raw NSError from AVAudioSession.setActive(true):

expo-audio/ios/AudioModule.swift#L824-L826

private func activateSession() throws {
  try AVAudioSession.sharedInstance().setActive(true)
}

The same file wraps this error into AudioStateException in setIsAudioActive (L741-L752), but not here. That's why it reaches JS as a generic UnexpectedException from SyncFunctionDefinition.swift:96, the exact frame in Sentry. "Session activation failed" is the NSError text iOS returns when the app isn't active (we use .ambient with shouldPlayInBackground: false), and also in the foreground when a call, Siri or another non-mixable session has priority.

The old code had no such failure path, sound.play() only ran from the load callback and never threw (https://github.com/Expensify/App/commit/d3bb56b20f1).

2. playSound calls it with no guard, and since it is async the throw becomes a rejected promise. When it throws, the didJustFinish listener never fires, so player.remove() never runs and the AudioPlayer stays in expo's AudioComponentRegistry for the whole session:

https://github.com/Expensify/App/blob/3c2269297d3ce9213717989d75d01cf2963e6900/src/libs/Sound/index.native.ts#L39-L53

3. No caller can catch it. withMinimalExecutionTime drops the promise from nextFunc() and resolves the caller's promise right away, before the sound even ran. So await playSound(...) in any caller resolves fine while the real rejection goes to onunhandledrejection:

https://github.com/Expensify/App/blob/3c2269297d3ce9213717989d75d01cf2963e6900/src/libs/Sound/BaseSound.ts#L47-L49

This hits every playSound caller (addComment, Task.ts, PayMoneyRequest.ts, Split.ts, search bulk actions), not only the Pusher one. And the module-level setAudioModeAsync promise has no .catch either, so if it fails once every later await audioModeConfigured rejects the same way:

https://github.com/Expensify/App/blob/3c2269297d3ce9213717989d75d01cf2963e6900/src/libs/Sound/index.native.ts#L25

Why an app state check can't fix it by itself. playSoundForMessageType checks Visibility.isVisible() once, before the isChannelMuted promise, the 300ms queue and await audioModeConfigured:

https://github.com/Expensify/App/blob/3c2269297d3ce9213717989d75d01cf2963e6900/src/libs/actions/User.ts#L784-L790

Moving that check into playSound makes it later, but it's still a JS cache. AppState.currentState is only updated when native sends the appStateDidChange event and JS handles it, so right after willResignActive JS can still read active while iOS already refuses the session:

RCTAppState.mm#L115-L129

if (![newState isEqualToString:_lastKnownState]) {
  _lastKnownState = newState;
  [self sendEventWithName:@"appStateDidChange" body:@{@"app_state" : _lastKnownState}];
}

AppState.js#L87-L89

emitter.addListener('appStateDidChange', appStateData => {
  eventUpdated = true;
  this.currentState = appStateData.app_state;
});

So the check only skips calls we already know will fail. The real fix has to be handling the throw, because nothing in JS can predict every refusal (late AppState, a call, Siri).

What changes do you think we should make in order to solve the problem?

Bring back the contract we had with react-native-sound: a UI sound can fail silently, but it never throws and never leaks.

  1. In playSound (src/libs/Sound/index.native.ts), wrap play() and release the native player when it fails. This is the actual fix:
try {
    player.play();
} catch (error) {
    // A call or another app can still hold the session, so release the player
    subscription.remove();
    player.remove();
    Log.hmmm('[sound] Failed to play sound', {soundFile, message: error instanceof Error ? error.message : String(error)});
}

Log.hmmm and not Log.alert, a missed ding is expected iOS behavior and shouldn't go back to Sentry.

  1. Right after await audioModeConfigured, skip when the app is not active, reusing the native Visibility check we already have. It just avoids creating a player for a call we know will fail:
await audioModeConfigured;

// iOS refuses to activate the session when the app is not active
if (!Visibility.isVisible()) {
    return;
}
  1. Catch the module-level audio mode promise once, so one failed setAudioModeAsync doesn't reject every later sound:
const audioModeConfigured = setAudioModeAsync({...}).catch((error: unknown) => {
    Log.hmmm('[sound] Failed to configure audio mode', {message: error instanceof Error ? error.message : String(error)});
});
  1. In withMinimalExecutionTime (BaseSound.ts), stop dropping the result, so no queued sound (web or native) can become an unhandled rejection again. The 300ms spacing stays the same:
const [nextFunc, resolve] = next;
Promise.resolve()
    .then(nextFunc)
    .catch((error: unknown) => {
        Log.hmmm('[sound] Queued sound failed', {message: error instanceof Error ? error.message : String(error)});
    });
resolve();

Running it through .then also covers a sync throw, which today happens inside the caller's new Promise executor for the first queued call.

Branch with the fix and test: https://github.com/Expensify/App/compare/main...David-2002065:App:fix/106955-ios-sound-session-activation

What specific scenarios should we cover in automated tests to prevent reoccurrence?

tests/unit/SoundNativeTest.ts (on the branch) with expo-audio mocked:

  1. play() throws Session activation failed: no unhandled rejection, subscription.remove() and player.remove() are called once.
  2. App goes to the background before the queued sound runs: createAudioPlayer is never called.
  3. Normal foreground case: the sound plays and the player is kept until didJustFinish.

On main 1 and 2 fail (the first one with the same Session activation failed rejection), with the fix all 3 pass.

What alternative solutions did you explore? (Optional)

  1. Patch expo-audio in patches/ with the play part of expo/expo#48588 (start playback, then activate the session best-effort). That fixes it at the source, but it's a native patch to maintain until SDK 58 for a UI ding, and playSound would still drop errors through the queue, so I'd keep the JS fix.
  2. Only add the AppState check. It is racy because currentState is a JS cache, it doesn't cover a call or Siri in the foreground, and the player still leaks.
  3. Set shouldPlayInBackground: true. It was intentionally set to false in #81831 since the system already plays push sounds, so backgrounded dings would play twice.

David-2002065 avatar Nov 17 '26 10:11 David-2002065

Proposal

Please re-state the problem that we are trying to solve in this issue.

On iOS, playing an in-app notification sound can throw UnexpectedException: Session activation failed from player.play(), and nothing catches it, so Sentry reports it as an unhandled promise rejection (APP-NTH, 307 users / 786 events since 9.5.31). It mostly happens when a sound is requested while the app is no longer active — for example a Pusher message arriving seconds after the user backgrounds the app — and can also happen when a phone call or another app holds the audio session. The failed attempt also leaks the audio player it created.

What is the root cause of that problem?

Three layers combine to produce the unhandled rejection.

First, the native playSound is async and calls player.play() with no error handling:

https://github.com/Expensify/App/blob/d9d8c4e40ad7c431138355a337265bcb21a446c2/src/libs/Sound/index.native.ts#L41-L53

expo-audio's play() activates the iOS audio session, and the audio mode is configured with shouldPlayInBackground: false:

https://github.com/Expensify/App/blob/d9d8c4e40ad7c431138355a337265bcb21a446c2/src/libs/Sound/index.native.ts#L21-L25

so iOS refuses the activation when the app is not active and expo-audio throws "Session activation failed". Because playSound is async, the synchronous throw becomes a rejected promise. The playbackStatusUpdate listener never fires after a failed play, so the subscription and the native player are never removed — a resource leak on every failure.

Second, the queue wrapper discards the promise. withMinimalExecutionTime invokes nextFunc() and ignores its return value, so no downstream caller can ever catch the rejection:

https://github.com/Expensify/App/blob/d9d8c4e40ad7c431138355a337265bcb21a446c2/src/libs/Sound/BaseSound.ts#L39-L54

Third, the caller-side protections do not cover this. playSoundForMessageType checks Visibility.isVisible() (which on native is AppState.currentState === 'active') at the moment the Pusher update arrives:

https://github.com/Expensify/App/blob/d9d8c4e40ad7c431138355a337265bcb21a446c2/src/libs/actions/User.ts#L776-L785

but the sound actually plays later — after the async muted-channel check, the debounce, and the queue's 300 ms spacing — so the app can move to the background in between. Its try/catch only covers synchronous code, and the other playSound call sites (37 calls across 13 files in total, in the IOU, Task, and Report actions and search bulk actions) have no app-state check at all.

What changes do you think we should make in order to solve the problem?

Both changes go inside playSound in src/libs/Sound/index.native.ts, so every call site is covered at the moment the sound actually plays.

First, after awaiting the audio-mode configuration, return early when AppState.currentState (from react-native) is not active. Checking at play time — rather than at push-arrival time, as playSoundForMessageType does — closes the race for every caller. Skipping the sound is the intended behavior here: the audio mode already declares shouldPlayInBackground: false because background notification sounds are played by the system, and a backgrounded app cannot make its in-app sound heard anyway.

Second, wrap player.play() in a try/catch. On failure, remove the status-listener subscription, call player.remove() so the native player is released, and log the error. This mirrors how the web implementation already treats playback failures as log-and-continue through Howler's onplayerror callback:

https://github.com/Expensify/App/blob/d9d8c4e40ad7c431138355a337265bcb21a446c2/src/libs/Sound/index.ts#L41-L43

The catch still matters even with the app-state guard in place, because iOS can also refuse the session while the app is in the foreground (an ongoing phone call, or another app holding the audio session), and the catch is also what fixes the player leak.

No web change is needed: Howler already reports play errors through its callback instead of throwing.

Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/106955-ios-sound-session-activation?expand=1

What alternative solutions did you explore? (Optional)

Handling the rejection inside withMinimalExecutionTime by catching the promise returned from nextFunc(). That would silence every unhandled rejection from sound playback in one place, but it cannot release the player and subscription (those are local to playSound), and it would hide errors behind a generic handler far from the context that can clean up. It could complement the main fix but is not sufficient on its own.

Setting shouldPlayInBackground: true so the background activation succeeds. Rejected: background notification sounds are already played by the system, so users would hear doubled sounds, and it would keep an audio session active in the background unnecessarily.

Adding app-state guards or error handling at each call site. Rejected: there are 37 call sites across 13 files, and a caller-side guard stays racy because of the debounce and queue delay between the call and the actual playback.

wildan-m avatar Nov 17 '26 10:11 wildan-m

Proposal

What is the root cause of that problem?

In expo-audio 57, play is a synchronous JSI Function that activates the audio session before playback:

https://github.com/expo/expo/blob/3ab9847d257a770aafff26b2e641c1ce0f637145/packages/expo-audio/ios/AudioModule.swift#L211-L216

activateSession() is try AVAudioSession.sharedInstance().setActive(true) (same file, L823-L825); our playsInSilentMode: false + mixWithOthers resolves to .ambient:

https://github.com/expo/expo/blob/3ab9847d257a770aafff26b2e641c1ce0f637145/packages/expo-audio/ios/AudioModule.swift#L780-L787

.ambient has no background audio mode, so iOS refuses setActive(true) with '!pla' (561015905) unless the app is foreground-active; ExpoModulesCore rethrows it as UnexpectedException at SyncFunctionDefinition.swift:96 (the Sentry frame) — native never reached player.play(at:).

#80624 swapped react-native-sound, whose play() never threw, for createAudioPlayer(...).play(); #81831 made playSound async, so the throw is now a rejected promise:

https://github.com/Expensify/App/blob/cea8dd6fdf4f65b5243ce0f759264e348479686d/src/libs/Sound/index.native.ts#L25-L54

Nobody owns it — processQueue discards nextFunc()'s return and resolves the caller:

https://github.com/Expensify/App/blob/cea8dd6fdf4f65b5243ce0f759264e348479686d/src/libs/Sound/BaseSound.ts#L39-L54

The default export wraps playSound in that 300 ms queue, so callers get that fire-and-forget promise:

https://github.com/Expensify/App/blob/cea8dd6fdf4f65b5243ce0f759264e348479686d/src/libs/Sound/BaseSound.ts#L56-L65

Volume: addComment fires SOUNDS.DONE on every message sent:

https://github.com/Expensify/App/blob/cea8dd6fdf4f65b5243ce0f759264e348479686d/src/libs/actions/Report/index.ts#L1451-L1453

Execution path:

  1. addComment calls playSound(SOUNDS.DONE) (Report/index.ts:1452); the wrapper queues it and returns its own promise.
  2. A sound in the previous 300 ms left timerId set, so it waits on setTimeout(processQueue, 300) (BaseSound.ts:50).
  3. The user locks the device; AppState.currentState leaves 'active'.
  4. processQueue runs nextFunc() then resolve() (BaseSound.ts:48-49), discarding the promise on line 48.
  5. getIsMuted() passes, then await audioModeConfigured yields a microtask (index.native.ts:39).
  6. createAudioPlayer(source) registers it in AudioComponentRegistry; player.play() (index.native.ts:53) calls try activateSession() on a backgrounded .ambient session → '!pla'.
  7. The throw crosses JSI as an unhandled rejection, plus a leaked player.

8 of the 37 call sites read Visibility.isVisible() in playSoundForMessageType, but before isChannelMuted()'s Onyx read and the queue slot — stale by step 6:

https://github.com/Expensify/App/blob/cea8dd6fdf4f65b5243ce0f759264e348479686d/src/libs/actions/User.ts#L779-L790

The other 29 read nothing — hence in_foreground: false.

The player also leaks: it never started, so wasPlaying stays false and foreground resume skips it (AudioModule.swift L99-L117, L695-L711), while AudioComponentRegistry.add's entry keyed by player.id (AudioComponentRegistry.swift:16-20) pins it for the process lifetime.

Upstream removed try activateSession() in expo/expo#48588, but only in expo-audio 58.x (SDK 58); we pin 57.0.3, and 57.0.5 still has it at AudioModule.swift:213, so inheriting it means an SDK major bump:

https://github.com/Expensify/App/blob/cea8dd6fdf4f65b5243ce0f759264e348479686d/package.json#L147-L149

What changes do you think we should make in order to solve the problem?

All in src/libs/Sound/index.native.ts, covering all 37 call sites.

  1. Handle rejection on line 25's promise: setAudioModeAsync can throw from session.setCategory, today both an unhandled rejection at import and a poison pill for every later await.
const audioModeConfigured = setAudioModeAsync({playsInSilentMode: false, shouldPlayInBackground: false, interruptionMode: 'mixWithOthers'}).catch((error: unknown) => {
    Log.hmmm('[sound] Failed to configure the audio mode', {message: error instanceof Error ? error.message : String(error)});
});
  1. Re-read foreground state after the await — closing steps 3→6 — with Visibility.isVisible(), on native AppState.currentState === 'active':

https://github.com/Expensify/App/blob/cea8dd6fdf4f65b5243ce0f759264e348479686d/src/libs/Visibility/index.native.ts#L1-L9

and make play() non-throwing, with the finish listener's cleanup (index.native.ts:44-51):

    await audioModeConfigured;

    // The queue and the await above resolve after the caller's visibility check.
    if (!Visibility.isVisible()) {
        return;
    }

    const player = createAudioPlayer(source);
    const subscription = player.addListener('playbackStatusUpdate', (status) => { /* unchanged */ });

    try {
        player.play();
    } catch (error) {
        // iOS can still refuse activation if another app owns the session.
        subscription.remove();
        player.remove();
        Log.hmmm('[sound] Audio session activation failed, skipping the sound', {soundFile, message: error instanceof Error ? error.message : String(error)});
    }

The re-check removes the steps 1-6 path; the try/catch covers what no app-state read predicts, and player.remove() frees the registry entry. Log.hmmm follows precedent for a swallowed notification failure:

https://github.com/Expensify/App/blob/cea8dd6fdf4f65b5243ce0f759264e348479686d/src/libs/Notification/LocalNotification/BrowserNotifications.ts#L110-L113

Nothing audible is lost: .ambient is silenced when inactive.

Repro on iOS: send two messages back to back and lock within ~300 ms of the second — the DONE chime dequeues after willResignActive and setActive(true) returns '!pla'.

Test branch: https://github.com/Expensify/App/compare/main...trasnake87:App:fix/106955

Regression test

tests/unit/PlaySoundNativeTest.ts, run with npx jest tests/unit/PlaySoundNativeTest.ts:

  • without the change: Tests: 2 failed, 2 total
  • with the change: Tests: 2 passed, 2 total

trasnake87 avatar Nov 17 '26 10:11 trasnake87

Opened for proposals by adding the Help Wanted label.


view run

MelvinBot avatar Nov 17 '26 10:11 MelvinBot

🚨 Edited by proposal-police: This proposal was edited at 2026-11-18 00:31:18 UTC.

Proposal

Please re-state the problem that we are trying to solve in this issue.

On iOS, playSound sometimes throws UnexpectedException: Session activation failed from player.play(). Nothing catches it, so Sentry reports an unhandled promise rejection (APP-NTH), and the audio player created for that sound is never released.

What is the root cause of that problem?

1. player.play() can throw on iOS, and we call it with no guard.

In expo-audio 57.0.3 the native play is a synchronous function that activates the audio session first (node_modules/expo-audio/ios/AudioModule.swift, L212-L216 and L824-L826):

Function("play") { player in
  try activateSession() // AVAudioSession.sharedInstance().setActive(true)
  ...
}

Our audio mode (playsInSilentMode: false, mixWithOthers) maps to the .ambient category (same file, L781-L786). iOS does not let an app in the background activate an .ambient session, so play() throws. This matches the Sentry event, which came from an app in the background (in_foreground: false).

https://github.com/Expensify/App/blob/0ee1dc1d5f6a9746b56799f3ef3a8e78b0c72de8/src/libs/Sound/index.native.ts#L39-L53

2. The app can reach play() after it has left the foreground.

A sound does not play at the moment it is requested. Every call goes through a queue that spaces sounds 300 ms apart, and then waits on audioModeConfigured. For incoming messages, playSoundForMessageType does check Visibility.isVisible(), but that check runs before the async isChannelMuted read and before the queue, so it can be out of date when the sound plays:

https://github.com/Expensify/App/blob/0ee1dc1d5f6a9746b56799f3ef3a8e78b0c72de8/src/libs/actions/User.ts#L782-L790

The other call sites (IOU, Task, Report and Search bulk actions; 37 calls in 13 files in total) have no check at all. So a check at the call site cannot protect play(). The state has to be checked inside playSound, right before playing.

3. Nothing can catch the throw.

playSound is async, so the throw becomes a rejected promise. withMinimalExecutionTime calls nextFunc() and drops the promise it returns, so no caller ever sees the rejection. That includes the try/catch in playSoundForMessageType. The rejection reaches Sentry through onunhandledrejection.

https://github.com/Expensify/App/blob/0ee1dc1d5f6a9746b56799f3ef3a8e78b0c72de8/src/libs/Sound/BaseSound.ts#L47-L49

The player is only removed in the didJustFinish listener. That listener never fires when play() throws, so every failure leaves a player and a listener behind.

What changes do you think we should make in order to solve the problem?

Both changes go in playSound in src/libs/Sound/index.native.ts, so every caller is covered at the moment the sound really plays.

  1. After await audioModeConfigured, return early when AppState.currentState === 'background'. The user cannot hear an in-app sound there, and we avoid creating a player that will fail. I check for background and not !== 'active' because inactive is still the foreground (app switcher, Control Center, a system prompt), so that case stays as it is today.
  2. Wrap player.play() in try/catch. On failure, remove the listener and the player, and log with Log.hmmm. This covers any refusal the state check cannot see, such as the app state changing between the check and the native call. It also fixes the leak.
await audioModeConfigured;

if (AppState.currentState === 'background') {
    return;
}

const player = createAudioPlayer(source);
const subscription = player.addListener('playbackStatusUpdate', ...); // unchanged

try {
    player.play();
} catch (error) {
    subscription.remove();
    player.remove();
    Log.hmmm('[Sound] Failed to play sound', {soundFile, error: error instanceof Error ? error.message : String(error)});
}

Notes:

  • forwardLogsToSentry only forwards logs with a listed prefix, and [Sound] is not one of them. The error does not come back to Sentry in another form.
  • The file is .native.ts, so web is not touched. On Android the only change is that a sound requested while the app is in the background is skipped.
  • withMinimalExecutionTime stays as it is, so the 300 ms spacing does not change.

Tests

I added tests/unit/SoundTest.ts with expo-audio mocked:

  • play() throws Session activation failed: playSound resolves, the listener and the player are removed, and the failure is logged.
  • App state is background: no player is created.
  • App state is inactive: the sound still plays.
  • Normal playback: the player is released on didJustFinish.

I ran it. On current main the first two fail, the first one with the same Session activation failed rejection that Sentry shows. With the change all four pass.

How to reproduce on a device

The window between the request and play() is normally a few milliseconds, so it needs to be widened to hit it by hand:

  1. Temporarily change the queue spacing from 300 to 4000 on the last line of src/libs/Sound/index.native.ts.
  2. On a real iPhone (sounds not muted), open a chat and send two messages one right after the other.
  3. Go to the Home screen within about two seconds.
  4. The second sound fires about four seconds after the first, with the app in the background. The logs show an unhandled rejection with Session activation failed from playSound.

I have not confirmed these steps on a physical iPhone yet. The Simulator may not enforce the background audio rule.

What alternative solutions did you explore? (Optional)

  • Add a .catch to nextFunc() in withMinimalExecutionTime. This hides the Sentry event, but the player is not in scope there, so it cannot be released, and we would still create a player for every background attempt.
  • Only add the app state check. This leaves the gap between the check and the native call, and any other refusal from iOS would still be an unhandled rejection.

abbasifaizan70 avatar Nov 17 '26 10:11 abbasifaizan70

🤖 ProposalPolice™ is tracking duplicate proposals for this issue using an OpenAI Conversation. This comment stores that Conversation's ID and can be safely ignored.

github-actions[bot] avatar Nov 17 '26 10:11 github-actions[bot]

Proposal

What is the root cause of that problem?

On iOS, playSound in src/libs/Sound/index.native.ts calls player.play() with no error handling. expo-audio activates the audio session inside play(). When iOS refuses (the app is not active, or a call or another app holds the session), play() throws "Session activation failed".

The error then goes unhandled:

  1. playSound is async, so the throw becomes a rejected promise.
  2. withMinimalExecutionTime in src/libs/Sound/BaseSound.ts calls nextFunc() and drops the returned promise.
  3. The try/catch in playSoundForMessageType (src/libs/actions/User.ts) only covers synchronous code, so it never sees the rejection.

Sentry therefore reports an onunhandledrejection. Because the throw skips subscription.remove() and player.remove(), the player also stays in memory.

Refusal can happen even while the app is in the foreground (for example, during a phone call). That means a background check alone cannot remove the error, and the failure itself must be handled where it happens.

What changes do you think we should make in order to solve the problem?

  1. In src/libs/Sound/index.native.ts, playSound: wrap the player.play() call in try/catch. In the catch, call subscription.remove() and player.remove(), log the failure, and do not rethrow. A failed UI sound should never be an app error, and this removes both the unhandled rejection and the leaked player for every playSound caller.
try {
    player.play();
} catch (error) {
    subscription.remove();
    player.remove();
    // log the error here, do not rethrow
}
  1. In the same function, return early when AppState.currentState !== 'active', placed right before the player is created and after any await inside playSound. The sound can be queued for a while before it plays, so the app may have gone to the background in that time. This skips a pointless attempt and avoids creating a player that would immediately fail.

What alternative solutions did you explore? (Optional)

  • Adding a .catch on nextFunc() in withMinimalExecutionTime would silence the Sentry event for all sounds. It does not clean up the player, though, and it would hide other real failures in queued functions, so I prefer fixing playSound itself.
  • Only adding the AppState check, as the issue's first suggestion proposes, does not cover a call or another app holding the audio session.

Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

samranahm avatar Nov 17 '26 10:11 samranahm