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
Issue OwnerCurrent Issue Owner: @mukhrr

Activity

  1. self-assigned this
    on Nov 16, 2026
  2. added
    External
    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 (#106955 (comment)), 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. 41 remaining items

  12. expensify-chore-bot commented on Nov 20, 2026

    @expensify-chore-bot

    @eVoloshchak, @mountiny Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

  13. mountiny commented on Nov 21, 2026

    @mountiny
    ContributorAuthor

    Bump

  14. brahim1070 commented on Nov 21, 2026

    @brahim1070

    Proposal

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

    An iOS notification sound can fail to start when the app loses its audio session. This leaves a rejected playback promise and can leave the player allocated.

    What is the root cause of that problem?

    In src/libs/Sound/index.native.ts, playback waits for audio-mode setup. The app can become inactive during that wait. Once the player and listener exist, cleanup depends on a completion event that may never arrive if play() throws. The scheduling wrapper also resolves its caller without observing that playback promise.

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

    Earlier proposals already identify the visibility race and cleanup. My contribution is a regression check for ownership of the player: after audio setup, check iOS activity immediately before allocation. Once allocated, release the player exactly once on completion, listener registration failure, or playback failure. Log the playback failure. A late completion callback after cleanup should be harmless.

    In an AI-assisted Node harness exercising the native playback block with mocked audio and app state, one of five cases passed on the original code and all five passed with the patch. The cases were backgrounding during setup, activation refusal followed by late completion, listener registration failure, normal playback with repeated completion, and preserving the Android background path. Physical iPhone and full-app validation are still outstanding.

    What alternative solutions did you explore?

    A visibility check alone cannot handle a foreground activation refusal. Catching the rejection only in the shared queue would still leave cleanup to a completion event that may never fire.

  15. melvin-bot commented on Nov 21, 2026

    @melvin-bot

    📣 @brahim1070! 📣
    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>
    
  16. eVoloshchak commented on Nov 22, 2026

    @eVoloshchak
    Contributor

    @mukhrr's proposal looks good to me!

    🎀👀🎀 C+ reviewed!

  17. expensify-chore-bot commented on Nov 22, 2026

    @expensify-chore-bot

    Current assignee @mountiny is eligible for the choreEngineerContributorManagement assigner, not assigning anyone new.

  18. phenstyle commented on Nov 22, 2026

    @phenstyle

    Contributor details
    Your Expensify account email: phenstyleiswinstyle@gmail.com
    Upwork Profile Link: https://www.upwork.com/freelancers/~0169ceedd79de285b6

    Proposal

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

    On iOS HybridApp, calling playSound() in src/libs/Sound/index.native.ts throws Error: UnexpectedException: Session activation failed from expo-audio's player.play() when iOS refuses to activate AVAudioSession (such as when the app has moved to the background or another app/call holds the audio session). Because playSound is async and invoked fire-and-forget by withMinimalExecutionTime, the thrown error becomes an unhandled promise rejection reported to Sentry (APP-NTH) and leaks the allocated native AudioPlayer and its playbackStatusUpdate listener.

    What is the root cause of that problem?

    1. Missing AppState guard around native playback (src/libs/Sound/index.native.ts): setAudioModeAsync configures shouldPlayInBackground: false (.ambient category on iOS), so AVAudioSession.sharedInstance().setActive(true) inside expo-audio's Function("play") (AudioModule.swift:212-216, 824-826) fails whenever the app is not in the active foreground state. Even callers that check Visibility.isVisible() (e.g. playSoundForMessageType in src/libs/actions/User.ts:784) do so before an async isChannelMuted read and withMinimalExecutionTime's 300 ms queue delay (src/libs/Sound/BaseSound.ts:35-66), and playSound itself also yields on await audioModeConfigured.
    2. Eager module-load setAudioModeAsync rejection caching (src/libs/Sound/index.native.ts:25): Calling setAudioModeAsync(...) eagerly at module import time risks an unhandled rejection on background wake and permanently caches any rejected promise for the rest of the session.
    3. Uncaught synchronous throws and resource leaks (src/libs/Sound/index.native.ts:41-53): player.play() (as well as createAudioPlayer / addListener) runs outside try/catch. Inside an async function called without .catch() by withMinimalExecutionTime, any throw becomes an unhandled rejection and skips subscription.remove() and player.remove().

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

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

    1. Lazily configure audio mode with retry on failure (ensureAudioModeConfigured): Call setAudioModeAsync({playsInSilentMode: false, shouldPlayInBackground: false, interruptionMode: 'mixWithOthers'}) on first active foreground playback instead of module import, clearing the cached promise in .catch() before rethrowing so transient failures never permanently poison the session and concurrent callers share the in-flight promise.
    2. Guard playback on AppState.currentState === 'active' before and after awaiting audio mode setup: Return early if getIsMuted() || AppState.currentState !== 'active' at entry, and re-check if (getIsMuted() || AppState.currentState !== 'active') immediately after await ensureAudioModeConfigured().
    3. Catch playback errors and safely release resources (releasePlaybackResources): Wrap ensureAudioModeConfigured(), createAudioPlayer(), addListener(), and player.play() in try/catch. Share a releasePlaybackResources(player, subscription) helper between didJustFinish and catch that wraps subscription?.remove() and player?.remove() in independent try {} catch {} blocks so cleanup on a broken/detached native SharedObject can neither skip player.remove() nor re-throw as an unhandled rejection. Log playback failures with Log.hmmm('[sound] Failed to play sound', {soundFile, message}).
    4. Add unit test coverage (tests/unit/SoundNativeTest.ts): Verify lazy audio-mode setup and caching, didJustFinish resource cleanup, 'background'/'inactive' skips, backgrounding mid-await, Session activation failed handling with listener+player cleanup and Log.hmmm, cleanup-throw resilience, addListener failure teardown, concurrent failing setAudioModeAsync sharing and retry, createAudioPlayer error handling, and muted skips.

    What alternative solutions did you explore? (Optional)

    • Swallowing rejections inside withMinimalExecutionTime (src/libs/Sound/BaseSound.ts): Rejected as the primary fix because it would hide unhandled errors without preventing unnecessary background AudioPlayer allocations or leaking native players/listeners when player.play() throws. Handling failures and lifecycle cleanup directly in src/libs/Sound/index.native.ts fixes the root cause cleanly without altering shared web/native throttling semantics.
    • Using Log.alert instead of Log.hmmm: Rejected because iOS refusing audio session activation during background transitions or active phone calls is an expected transient OS condition rather than an alert-worthy error.
  19. melvin-bot commented on Nov 22, 2026

    @melvin-bot

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

  20. removed
    Help Wanted
    on Nov 23, 2026
  21. mountiny commented on Nov 23, 2026

    @mountiny
    ContributorAuthor

    @mukhrr can you prioritize the pr please?

  22. added
    Reviewing
    Weekly
    and removed
    Daily
    on Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

ExternalReviewingWeekly

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions