Skip to content

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

Open

Description

@mountiny

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

Activity

  1. self-assigned this
    on Nov 16, 2026
  2. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Nov 16, 2026
  3. expensify-chore-bot commented on Nov 16, 2026

    @expensify-chore-bot

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

  4. changed the title [-][Sentry: APP-NTH] iOS sound playback throws "Session activation failed" in playSound[/-] [+][$175] [Sentry: APP-NTH] iOS sound playback throws "Session activation failed" in playSound[/+] on Nov 16, 2026
  5. expensify-chore-bot commented on Nov 16, 2026

    @expensify-chore-bot
  6. Stephen3453 commented on Nov 16, 2026

    @Stephen3453

    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.
  7. cocvn157 commented on Nov 16, 2026

    @cocvn157

    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.
  8. dankezo commented on Nov 16, 2026

    @dankezo

    Contributor details
    Your Expensify account email: dannyphan190@gmail.com
    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.
  9. melvin-bot commented on Nov 16, 2026

    @melvin-bot

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

  10. dankezo commented on Nov 16, 2026

    @dankezo

    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: dannyphan190@gmail.com
    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.
  11. 25 remaining items

  12. jpereyra243-byte commented on Nov 17, 2026

    @jpereyra243-byte

    Contributor details
    Your Expensify account email: jpereyra2433@gmail.com
    Upwork Profile Link: https://www.upwork.com/freelancers/~01f6ba4c6dde3d0fbb

    Proposal

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

    On iOS HybridApp production builds, playing an in-app sound throws UnexpectedException: Session activation failed from expo-audio's player.play() when iOS refuses AVAudioSession.setActive(true) (e.g. when the app is backgrounded or during active phone calls / Siri / other audio sessions holding exclusive control). Because playSound is async and its returned promise is unhandled by callers and the throttle queue, this escapes as an unhandled promise rejection (onunhandledrejection in Sentry APP-NTH) and leaks the native AudioPlayer instance and listener.

    What is the root cause of that problem?

    1. Asynchronous race gap before player.play() (src/libs/actions/User.ts:793 -> src/libs/Sound/BaseSound.ts:44 -> src/libs/Sound/index.native.ts:27-53):
      • In playSoundForMessageType, Visibility.isVisible() is checked upfront, but it subsequently awaits isChannelMuted and enqueues playSound through withMinimalExecutionTime(playSound, 300), which delays execution via setTimeout.
      • Other callers (SOUNDS.DONE, SOUNDS.SUCCESS, SOUNDS.ATTENTION) do not perform any visibility or AppState check.
      • Inside src/libs/Sound/index.native.ts, playSound awaits audioModeConfigured. By the time execution resumes, the app can be backgrounded (AppState.currentState !== 'active'). Because shouldPlayInBackground is explicitly false (background sounds are handled by system push notifications), iOS rejects AVAudioSession.setActive(true) when player.play() is invoked.
    2. Unguarded synchronous throw and native resource leak (src/libs/Sound/index.native.ts:40-53):
      • createAudioPlayer creates the native player and player.addListener('playbackStatusUpdate', ...) registers a subscription that is only removed when status.didJustFinish fires.
      • player.play() calls native activateSession() which throws synchronously on iOS when activation fails.
      • The throw halts execution before any listener fires, so subscription.remove() and player.remove() are never called, causing native AudioPlayer instances and listeners to leak in memory.
    3. Promise rejection discard in execution queue (src/libs/Sound/BaseSound.ts:44-48):
      • withMinimalExecutionTime invokes nextFunc(); without chaining .catch(...). Because playSound is async, the thrown error causes the returned promise to reject without an unhandled rejection handler, surfacing directly to Sentry.

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

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

      • Import AppState from react-native.
      • Import Log from @libs/Log.
      • Add an AppState guard after await audioModeConfigured right before creating the player:
        // Do not activate audio session or play in-app sounds if the app is not active (backgrounded/inactive)
        if (AppState.currentState !== 'active') {
            return;
        }
      • Wrap player creation, subscription, and playback inside a try...catch block.
      • If player.play() or player setup throws, immediately clean up native resources and log with Log.hmmm:
        let player: AudioPlayer | null = null;
        let subscription: EventSubscription | null = null;
        
        try {
            player = createAudioPlayer(source);
        
            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 due to audio session activation failure', {soundFile, error});
        }
    2. In src/libs/Sound/BaseSound.ts:

      • In withMinimalExecutionTime (processQueue), safeguard the promise execution so no queued sound function can escape as an unhandled rejection:
        const [nextFunc, resolve] = next;
        Promise.resolve(nextFunc())
            .catch((error) => {
                Log.hmmm('[Sound] Error in sound execution queue', {error});
            })
            .finally(resolve);
    3. Automated Unit Tests (tests/unit/SoundNativeTest.ts):

      • Add unit tests for native sound playback:
        • Verify that when AppState.currentState === 'background', createAudioPlayer is never called and playSound resolves cleanly.
        • Verify that when player.play() throws an error (e.g. Session activation failed), subscription.remove() and player.remove() are called, Log.hmmm is invoked, and no unhandled promise rejection occurs.
        • Verify normal playback flow still calls player.play() and cleans up on didJustFinish.

    What alternative solutions did you explore? (Optional)

    • Checking Visibility.isVisible() / AppState only at the call sites: Rejected because callers execute asynchronously (e.g. after await isChannelMuted), queue throttling adds a 300ms delay, and other callers (DONE, SUCCESS) do not check visibility. Checking right before playback in index.native.ts provides universal protection for all callers.
    • Setting shouldPlayInBackground: true: Rejected because push notification sounds are handled by iOS system banners, and enabling background audio would cause duplicate sounds and require background audio entitlement.
    • Only catching in BaseSound.ts without try/catch in index.native.ts: Rejected because it leaves the native AudioPlayer and subscription leaked in memory whenever play() fails.
  13. melvin-bot commented on Nov 17, 2026

    @melvin-bot

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

  14. TassioSales commented on Nov 17, 2026

    @TassioSales

    Proposal

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

    On iOS HybridApp production builds, playing in-app UI sound effects (via playSound in src/libs/Sound/index.native.ts) intermittently throws an unhandled rejection: UnexpectedException: Session activation failed (Sentry issue APP-NTH), primarily when push/socket events trigger sound playback while the application is in the background or during audio interruptions (e.g., active phone calls, Siri, or screen lock).

    What is the root cause of that problem?

    In src/libs/Sound/index.native.ts, playSound instantiates an audio player from expo-audio and directly invokes player.play():

    player.play();

    On iOS, expo-audio executes AVAudioSession.sharedInstance().setActive(true) synchronously in native code (AudioModule.swift). iOS strictly refuses audio session activation when:

    1. The app is in the background or transition state (AppState.currentState !== 'active'), which frequently happens when Pusher delivers a message notification right after the user backgrounds the app or locks their device.
    2. The audio session is interrupted or locked by another prioritized system audio stream (phone call, FaceTime, Siri).

    Because player.play() is invoked without a try/catch or error handler around the synchronous/promise boundary, iOS's rejection propagates upward into onunhandledrejection, generating Sentry errors for non-critical, fire-and-forget UI feedback chimes.

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

    1. In src/libs/Sound/index.native.ts:
      • Add a foreground check via AppState so that background incoming socket/notification events do not attempt to activate an audio session when the app is inactive:
      import {AppState} from 'react-native';
      
      if (AppState.currentState !== 'active') {
          return;
      }
      • Guard player.play() with a try/catch block to handle transient native audio activation refusals (such as mid-call interruptions) gracefully without crashing or surfacing Sentry exceptions:
      try {
          player.play();
      } catch (error) {
          Log.warn('[Sound] Failed to play sound due to audio session state:', error);
      }
      • In the event cleanup / listener removal, ensure player.release() is safely called in a finally block or when playback ends.

    What alternative solutions did you explore? (Optional)

    Configuring AVAudioSessionCategoryPlayback with mixWithOthers in native app configuration, but checking AppState.currentState === 'active' and adding error containment in index.native.ts is purely JavaScript-level, completely cross-platform safe, and prevents unnecessary audio session interruptions while the user is outside the app.

  15. kevinjosh10 commented on Nov 18, 2026

    @kevinjosh10

    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

  16. theroimasters1-dev commented on Nov 18, 2026

    @theroimasters1-dev

    Proposal

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

    On iOS HybridApp production builds, Sentry reports unhandled promise rejections / exceptions:
    Error: UnexpectedException: Session activation failed (at ExpoModulesCore/SyncFunctionDefinition.swift:96) occurring at src/libs/Sound/index.native.ts:53 when calling player.play().

    What is the root cause of that problem?

    In src/libs/Sound/index.native.ts, playSound calls player.play().
    On iOS, expo-audio's native implementation calls AVAudioSession.setActive(true) upon starting playback. However:

    1. When the app is in the background or during app state transitions (e.g. background Pusher event arriving right as the user locks the screen or switches apps), iOS strictly forbids non-background audio apps from activating AVAudioSession.
    2. Because audioModeConfigured specifies shouldPlayInBackground: false, iOS denies session activation and throws UnexpectedException: Session activation failed.
    3. In src/libs/Sound/index.native.ts, player.play() is invoked synchronously without a try...catch block to handle platform session activation refusals, causing an unhandled native exception / rejection. Furthermore, when player.play() fails, the player instance and listener subscription are never removed, leaking audio resources.

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

    1. In src/libs/Sound/index.native.ts, check whether the app is currently in the active foreground state before attempting to play notification sounds. We can inspect AppState.currentState === 'active' (or Visibility.isVisible()): if the app is in the background, skip sound playback immediately since system notifications already handle background alerts.
    2. Wrap player.play() in a try...catch block inside playSound:
        try {
            player.play();
        } catch (error) {
            subscription.remove();
            player.remove();
            Log.info('[Sound] Failed to play audio notification', {error});
        }
    1. Ensure that if player.play() throws, both subscription.remove() and player.remove() are cleanly called in the catch block to prevent memory and audio player resource leaks.

    What alternative solutions did you explore? (Optional)

    Handling the session activation failure purely via AppState listeners without try/catch. However, combining both AppState.currentState !== 'active' guard AND the try...catch safety net is strictly required because race conditions can occur between JavaScript receiving a Pusher message and iOS transitioning into inactive/background state.

  17. yuvrajangadsingh commented on Nov 18, 2026

    @yuvrajangadsingh
    Contributor

    Proposal

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

    On iOS, player.play() throws "Session activation failed" when iOS won't start the audio session. Nothing catches it, so Sentry gets an unhandled rejection, and the player created for that sound is not released.

    What is the root cause of that problem?

    1. play() can throw and nothing handles it.

    In expo-audio, the iOS play begins with try activateSession(), a bare AVAudioSession.setActive(true). It is a sync function, so an iOS refusal reaches JS as a plain throw. The linked file is byte-identical to the 57.0.3 in node_modules.

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

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

    playSound calls it unguarded inside an async function, so the throw becomes a rejected promise:

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

    The queue calls that function and drops the promise it returns, so no caller can catch the rejection:

    const [nextFunc, resolve] = next;
    nextFunc();
    resolve();

    2. The player is released from didJustFinish, and that event doesn't come when playback doesn't start.

    On iOS the end-of-playback observer is installed inside play(at:), which a failed activation skips:

    https://github.com/expo/expo/blob/3ab9847d257a770aafff26b2e641c1ce0f637145/packages/expo-audio/ios/AudioPlayer.swift#L102-L109

    Android has the same hole without any error, so Sentry doesn't show it. Its play returns early when the ringer is on silent or vibrate and the audio mode has playsInSilentMode: false, which is the mode the native sound file sets:

    https://github.com/expo/expo/blob/3ab9847d257a770aafff26b2e641c1ce0f637145/packages/expo-audio/android/src/main/java/expo/modules/audio/AudioModule.kt#L467-L481

    // 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'});

    So on an Android phone set to vibrate, each sound request creates a player and a listener that nothing removes. Sending a chat message is one of those requests:

    if (shouldPlaySound) {
    playSound(SOUNDS.DONE);
    }

    The listener closure references the player, so neither can be garbage collected.

    I ran the current playSound under Jest with the repo's expo-audio mock. With play() throwing the Sentry error, the promise rejects and neither the listener nor the player is removed. With play() doing nothing and no finish event, both are still there after 60 seconds of fake time.

    3. The visibility check is stale by the time the sound plays.

    playSoundForMessageType checks Visibility.isVisible() and then waits on isChannelMuted. After that the sound waits for its 300ms queue slot and for audioModeConfigured. The app can be in the background by then, which is the state the Sentry event was captured in (in_foreground: false).

    const reportID = reportActionsOnly
    .map((value) => value.key.split('_').at(1))
    .find((reportKey) => reportKey === Navigation.getTopmostReportId() && Visibility.isVisible() && Visibility.hasFocus());
    if (!reportID) {
    return;
    }
    isChannelMuted(reportID, currentUserAccountID).then((isSoundMuted) => {

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

    The three changes are inside playSound in the native sound file. Callers, the queue and web stay as they are.

    1. Catch the throw.

    Wrap player.play() in try/catch and release the player in the catch. Log the same [sound] Play error: line web logs, but with Log.hmmm, because a refused sound is expected, for example during a call.

    onplayerror: (_id: number, error: unknown) => {
    Log.alert('[sound] Play error:', {message: getErrorMessage(error)});
    },

    2. Release the player even when the sound doesn't finish.

    The didJustFinish listener stays. I'd add a release helper that the catch calls right away and a fallback timer calls after 5 seconds. The longest sound, success.mp3, is 1.56s. If the player is already released, the timer's removes do nothing.

    const release = () => {
        subscription.remove();
        player.remove();
    };
    
    // Playback does not always start (Android skips play() in silent mode), so completion can't be the only way to release
    setTimeout(release, RELEASE_TIMEOUT);
    
    try {
        player.play();
    } catch (error) {
        // iOS throws when it refuses to activate the audio session
        release();
        Log.hmmm('[sound] Play error:', {message: error instanceof Error ? error.message : String(error)});
    }

    3. Check visibility again right before creating the player.

    After the audioModeConfigured await, return when Visibility.isVisible() is false. It is the check the message path already does, moved to play time, so a queued sound isn't started for an app that has left.

    await audioModeConfigured;

    const isVisible: IsVisible = () => AppState.currentState === 'active';

    It is an early exit, not the fix. A call can hold the session while the app is active, so change 1 still handles the refusal.

    Tests: Not run on a device. I ran the cases below as a scratch Jest probe and they pass. With the PR I'd add them in a new SoundNativeTest.ts, loading the native file the way the web test does and using the existing expo-audio mock:

    const {default: playSound, clearSoundAssetsCache, SOUNDS} = jest.requireActual<typeof SoundModule>('@libs/Sound/index.ts');

    const mockPlayer = {
    play: jest.fn(),
    pause: jest.fn(),
    replace: jest.fn(),
    remove: jest.fn(),
    addListener: jest.fn(() => ({remove: jest.fn()})),
    };
    const createAudioPlayer = jest.fn(() => mockPlayer);

    • play() throws "Session activation failed": playSound resolves, the listener and the player are removed, the failure is logged
    • play() does nothing and no finish event arrives: the listener and the player are removed after the timeout
    • the sound finishes: the listener and the player are removed right away
    • the app is not visible: no player is created

    What alternative solutions did you explore? (Optional)

    • A patch-package patch so the native play swallows the activation error. The native sound file is the one place under src that imports expo-audio, so a patch protects no other caller. With the throw gone, JS can't tell that the sound didn't start, so it still needs change 2, and the Android case stays.
    • One long-lived player per sound, replayed with seekTo(0). There is nothing to release per play, but two quick sounds of the same type would cut each other off instead of overlapping, and four native players would stay alive for the whole session. That is more behavior change than this issue needs.
    • Catching in withMinimalExecutionTime. It stops the Sentry event, but the player and the listener aren't in scope there.
  18. RajGahoi commented on Nov 18, 2026

    @RajGahoi
  19. github-actions commented on Nov 18, 2026

    @github-actions
    Contributor

    ⚠️ @RajGahoi Thanks for your interest. To be considered for this job, please post a proposal following the proposal template (note the mandatory sections). Comments claiming the job without one are not reviewed.

  20. RajGahoi commented on Nov 18, 2026

    @RajGahoi

    Proposal

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

    On iOS HybridApp, player.play() in expo-audio calls AVAudioSession.setActive(true) which iOS refuses when the app is backgrounded or when another app holds the audio session. The resulting Error: Session activation failed is an unhandled rejection (the calling chain never awaits or catches). Additionally, the player.remove() cleanup is never called on failure, causing a memory leak. First seen in 9.5.31 when the Sentry SDK upgrade started surfacing it.

    What is the root cause of that problem?

    Three layered gaps:

    1. withMinimalExecutionTime in src/libs/Sound/BaseSound.ts calls nextFunc() without await and without catching its rejection.
    2. playSound in src/libs/Sound/index.native.ts does not guard against AppState.currentState !== 'active'.
    3. The try/catch in playSoundForMessageType only wraps synchronous dispatch, not the async sound chain.

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

    File 1 — src/libs/Sound/index.native.ts

    • Before calling player.play(), check AppState.currentState === 'active'. If not active, call player.remove() and return early — no sound should play in background.
    • Wrap player.play() in a try/catch. On error, call subscription.remove() and player.remove(), then log with Log.warn (not Log.hmmm to avoid Sentry noise). Do NOT rethrow — the caller does not need the rejection.

    File 2 — src/libs/Sound/BaseSound.ts

    • In withMinimalExecutionTime, change nextFunc() to await nextFunc() and wrap in try/catch so promise rejection does not escape.

    No other files need changes. The issue is entirely within the Sound library.

    What specific scenarios should we test?

    1. App in foreground → sound plays normally (regression test).
    2. App sent to background, incoming message notification → no crash, no Sentry event, player cleaned up.
    3. Another app holds audio session (e.g. phone call in progress) → same as above.
    4. Normal app lifecycle: open app → send/receive chat → verify sound plays once per message.

    Are there any concerns with your approach?

    None. Silently skipping background audio is the correct UX (the user is not in the app). The fix is surgical — only 2 files, no logic changes to upstream callers.

  21. knowaguy4u-cell commented on Nov 19, 2026

    @knowaguy4u-cell

    Proposal

    What is the root cause of that problem?

    On iOS, playing an in-app sound can throw "Session activation failed" from player.play() when iOS refuses to activate the audio session (e.g. the app has just been backgrounded while a Pusher message arrives). Nothing in the chain handles that failure, so it reaches Sentry as an unhandled promise rejection (307 users, 786 events), and the audio player is never released.

    The throw itself is only the trigger. The defect that turns it into an unhandled rejection is in withMinimalExecutionTime (src/libs/Sound/BaseSound.ts:47-58): it invokes the wrapped function, discards the promise it returns, and resolves its own promise unconditionally. playSound is async, so the synchronous throw from player.play() (src/libs/Sound/index.native.ts:53) rejects a promise that no code ever observes. The try/catch in playSoundForMessageType cannot help — it wraps synchronous code and never awaits the sound call, and its own .then() chain is discarded without a catch (src/libs/actions/User.ts:790-863).

    Two related defects ride along: the module-scope setAudioModeAsync promise (index.native.ts:25) has no rejection handler and is never recreated, so one configuration failure is both unhandled and permanent for the session; and when play() throws, the didJustFinish listener is the only place player.remove() is called, so the failed player has no release path. Finally, app visibility is checked before the debounce/mute/queue delays, never at playback time (src/libs/actions/User.ts:784 vs src/libs/Sound/index.native.ts:39-53), which is how a backgrounded app still attempts playback with shouldPlayInBackground: false.

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

    Fix all three layers, so this class of failure cannot recur silently:

    1. src/libs/Sound/BaseSound.ts — Make withMinimalExecutionTime adopt the wrapped function's result: settle the caller's promise from the inner promise's fulfillment/rejection (including synchronous throws), while keeping queue progression and the 300 ms spacing independent of success or failure.
    2. src/libs/Sound/index.native.ts — Make the exported sound operation a non-rejecting boundary:
      • Initialize audio configuration lazily inside the protected operation (or immediately convert the module-scope promise into a handled success/failure outcome), and allow re-initialization after a failure instead of reusing a permanently rejected promise.
      • Re-check app state at execution time — after the config await, immediately before creating the player — and skip playback when the app is not active.
      • Wrap configuration, player creation, listener registration, and player.play() together; on any failure, log it and run one idempotent cleanup that attempts subscription.remove() and player.remove() independently (one throwing must not block the other). Playback that starts but never completes gets the same cleanup path. I will not remove the player in a finally right after play() — playback is asynchronous and the existing didJustFinish completion cleanup stays.
    3. src/libs/actions/User.ts — Give the mute-lookup/playback chain a terminal catch so a failure anywhere in it is contained instead of surfacing as an unhandled rejection.
    4. Web (src/libs/Sound/index.ts) shares the wrapper but detaches its own cache/blob promises internally (:55-80); I will scope the rejection guarantee to native and call that out explicitly in the PR rather than silently changing web behavior.

    What alternative solutions did you explore? (Optional)

    • AppState guard + try/catch around player.play() only (the commonly proposed fix): stops the most visible trigger, but leaves the wrapper discarding every future rejection, the module-scope config promise unhandled and permanently poisoned after one failure, and the User.ts chain detached. The Sentry class would recur from the next sound-path failure.
    • Await playSound in playSoundForMessageType: ineffective until the wrapper propagates results (today it resolves independently of playback), and it leaves the other fire-and-forget callers in Report/index.ts exposed.
    • Enable shouldPlayInBackground: changes the product's stated sound policy (push sounds are the system's job) and fixes none of the promise/cleanup defects.
  22. melvin-bot commented on Nov 19, 2026

    @melvin-bot

    📣 @knowaguy4u-cell! 📣
    Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork.
    Please follow these steps:

    1. Make sure you've read and understood the contributing guidelines.
    2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
    3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
    4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
      Screen Shot 2022-11-16 at 4 42 54 PM
      Format:
    Contributor details
    Your Expensify account email: <REPLACE EMAIL HERE>
    Upwork Profile Link: <REPLACE LINK HERE>
    
  23. github-actions commented on Nov 19, 2026

    @github-actions
    Contributor

    ⚠️ @knowaguy4u-cell Thanks for your proposal. Please update it to follow the proposal template, as proposals are only reviewed if they follow that format (note the mandatory sections).

  24. devcrafta commented on Nov 19, 2026

    @devcrafta

    Proposal

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

    On iOS, an in-app notification sound can throw UnexpectedException: Session activation failed from player.play(). Nothing catches it, so Sentry records an unhandled promise rejection (APP-NTH, 300+ users). Each failure also leaves an audio player behind in memory.

    What is the root cause of that problem?

    1. Every sound has to turn the iOS audio session back on.
    In expo-audio, play() always calls AVAudioSession.setActive(true) first. That call throws when iOS refuses to turn the session on (node_modules/expo-audio/ios/AudioModule.swift, Function("play")):

    Function("play") { player in
      try activateSession()

    A player created without keepAudioSessionActive also turns the session off when its sound finishes (onPlaybackComplete → deactivateSession()). We never pass that option, so every notification sound starts with the session off and has to turn it on again. iOS refuses that when the app isn't active, because our audio mode sets shouldPlayInBackground: false. It can also refuse when a phone call or another app holds the audio session:

    const audioModeConfigured = setAudioModeAsync({playsInSilentMode: false, shouldPlayInBackground: false, interruptionMode: 'mixWithOthers'});

    2. The error is never caught.
    playSound is async and calls player.play() without a try/catch, so the throw becomes a rejected promise:

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

    withMinimalExecutionTime calls nextFunc(), ignores the promise it returns, and resolves straight away. Callers can't catch the error even if they await:

    const [nextFunc, resolve] = next;
    nextFunc();
    resolve();

    3. The caller's checks run too early.
    playSoundForMessageType checks Visibility.isVisible() when the Pusher update arrives:

    .find((reportKey) => reportKey === Navigation.getTopmostReportId() && Visibility.isVisible() && Visibility.hasFocus());

    The sound plays later, after the async isChannelMuted check, await audioModeConfigured and the 300 ms queue gap. By then the app may be in the background. The other playSound callers (IOU, Task, Report actions) don't check app state at all.

    4. The player leaks.
    createAudioPlayer registers the player in expo-audio's native registry (self.registry.add(player)). Only the didJustFinish listener removes it, and that listener never fires when play() throws, so the native player and the JS subscription stay in memory after every failure.

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

    Every change goes in playSound in src/libs/Sound/index.native.ts, so all callers are covered at the moment the sound actually plays:

    1. Check app state just before playing. After await audioModeConfigured and before createAudioPlayer, return early when AppState.currentState !== 'active'. The check comes after the await so it sees the latest state. It comes before the player is created so a skipped sound doesn't allocate a native player. A backgrounded app can't play an in-app sound anyway, and the system plays the push notification sound.
    2. Catch the play error and clean up. Wrap player.play() in a try/catch. On failure, call subscription.remove() and player.remove(). iOS can still refuse while the app is in the foreground (a phone call or another app holding the session), so the catch is needed even with step 1.
    3. Log without alerting. Use Log.hmmm('[sound] Session activation failed', {message}), not the Log.alert the web onplayerror uses. This failure is expected iOS behavior, so an alert would move the noise from Sentry into server alerts.
    4. Guard the audio mode setup. Add a .catch that logs to the module-level setAudioModeAsync(...) promise. As written, if it ever rejects, every later await audioModeConfigured rethrows that rejection and no sound plays for the rest of the session.

    Tests: extend the existing __mocks__/expo-audio.ts and add tests/unit/SoundTest.ts, with each case documented with // Given / // When / // Then comments:

    • play() throws: no unhandled rejection, and player.remove() plus subscription.remove() are called;
    • AppState is background: createAudioPlayer is not called;
    • AppState is active and play() succeeds: the player is released after didJustFinish.

    What alternative solutions did you explore? (Optional)

    1. keepAudioSessionActive: true on the player. This keeps the session on between sounds, so most sounds would skip the activation call. Rejected: the first sound, and any sound after a phone call, still activates the session and can still fail. It would also keep our session on after the sound ends, against the mixWithOthers / "don't interrupt other audio" intent noted in the code.
    2. shouldPlayInBackground: true. The activation in the background would succeed. Rejected: users would hear our sound on top of the system's push notification sound, and the app would keep an audio session running in the background.
    3. Catch the rejection in withMinimalExecutionTime (Promise.resolve(nextFunc()).catch(...)). This stops the unhandled rejection in one shared place. Rejected as the only fix: it can't reach the player and subscription inside playSound, so the native leak stays. It's fine as an extra safety net.
    4. Add guards at each call site. Rejected: there are many callers, and a check at the call is still too early because of the async mute check and the queue delay.
    5. Filter the error in Sentry (ignoreErrors). Rejected: it hides the report without fixing the leak or the wasted activation attempts.
    6. Patch expo-audio with patch-package to swallow the error natively. Rejected: the fix belongs in our code, and patching would hide real errors from every expo-audio user in the app.

    Contributor details
    Your Expensify account email: alfonso.ortega.upwork@gmail.com
    Upwork Profile Link: https://www.upwork.com/freelancers/~01732a1c6c797326dd

  25. melvin-bot commented on Nov 19, 2026

    @melvin-bot

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

DailyKSv2ExternalAdded to denote the issue can be worked on by a contributorHelp WantedApply this label when an issue is open to proposals by contributorsOverdue

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions