Repository navigation
Description
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:
playSoundinsrc/libs/Sound/index.native.tsisasync, so the throw fromplayer.play()becomes a rejected promise.withMinimalExecutionTimeinsrc/libs/Sound/BaseSound.tscallsnextFunc()and ignores the promise it returns.- The
try/catchinplaySoundForMessageTypeonly 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
- Skip the sound when the app is not active (
AppState.currentState !== 'active'). The user cannot hear an in-app sound in the background. - Wrap
player.play()in atry/catch. On failure, log it and callsubscription.remove()andplayer.remove().
Reproduction
Not confirmed. Likely steps on an iOS HybridApp build:
- Log in on iOS and make sure sounds are not muted.
- Send the app to the background.
- Within a few seconds, mention this account in a chat from another account.
- 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
- Upwork Job URL: https://www.upwork.com/jobs/~022122187481936413737
- Upwork Job ID: 2122187481936413737
- Last Price Increase: 2026-11-17
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsSUBISSUE
Activity
expensify-chore-bot commentedon Nov 16, 2026
Triggered auto assignment to Contributor-plus team member for initial proposal review - @eVoloshchak (
External)[-][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[/+]expensify-chore-bot commentedon Nov 16, 2026
Job added to Upwork: https://www.upwork.com/jobs/~022122187481936413737
Stephen3453 commentedon Nov 16, 2026
Proposal
What is the root cause of that problem?
playSoundinsrc/libs/Sound/index.native.ts(line ~53) callsplayer.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). BecauseplaySoundisasync, the throw becomes a rejected promise.withMinimalExecutionTimeinsrc/libs/Sound/BaseSound.ts(nextFunc();insideprocessQueue) discards that promise, and thetry/catchinplaySoundForMessageType(src/libs/actions/User.ts, ~line 793) only covers synchronous code, so nothing handles it and it surfaces asonunhandledrejection.The
AppStatecheck is already there, but too early:playSoundForMessageTypechecksVisibility.isVisible()(native:AppState.currentState === 'active',src/libs/Visibility/index.native.ts) beforeawait isChannelMuted(...), thenplaySoundwaits foraudioModeConfiguredand the 300 ms queue. The app can go to the background in between, so that guard does not protect theplay()call. The player is also never removed whenplay()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:AppState.currentState !== 'active'right beforecreateAudioPlayer, after the awaits.player.play()intry/catch; incatch, callsubscription.remove()andplayer.remove(), and log withLog.hmmminstead of rethrowing. A failed notification sound should never be an app error.This fixes the cause once for every
playSoundcaller, not just the Pusher path. Test: a unit test intests/unit/that mocksexpo-audiosoplay()throws, and assertsplaySoundresolves,player.removeis called, and no unhandled rejection occurs; plus one whereAppState.currentState = 'background'assertscreateAudioPlayeris not called.What alternative solutions did you explore? (Optional)
playSoundForMessageTypeand still races, and it does not cover a phone call or another app holding the session.withMinimalExecutionTime(.catchonnextFunc()) would also silence the error but leaves the leaked player and hides other failures.cocvn157 commentedon Nov 16, 2026
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) throwsUnexpectedException: Session activation failedfromexpo-audio'splayer.play()when iOS refusesAVAudioSession.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). BecauseplaySoundisasyncandwithMinimalExecutionTimeignores its returned Promise, the exception escapes as an unhandled promise rejection (onunhandledrejectionin SentryAPP-NTH) and leaks theAudioPlayerinstance.What is the root cause of that problem?
player.play()(src/libs/actions/User.ts:793->src/libs/Sound/BaseSound.ts:44->src/libs/Sound/index.native.ts:27-53):playSoundForMessageTypechecksVisibility.isVisible()upfront, it subsequentlyawaitsisChannelMuted(...)and then enqueuesplaySoundthroughwithMinimalExecutionTime(playSound, 300)(src/libs/Sound/BaseSound.ts:32-60), which spaces out executions by300msviasetTimeout.playSound(SOUNDS.DONE,SOUNDS.SUCCESS,SOUNDS.ATTENTION) do not checkVisibility.isVisible()/AppState.currentStatebefore or after the queue delay.playSoundactually runs and resumes afterawait audioModeConfigured, the app may already be in the background (AppState.currentState !== 'active'), whereshouldPlayInBackground: falsecauses iOS to rejectAVAudioSession.setActive(true).async playSoundand resource leak (src/libs/Sound/index.native.ts:40-53):player.play()synchronously calls the nativeExpoModulesCoreSyncFunctionDefinition(activateSession()->player.play()). When iOS rejects session activation (either due to background state or an active phone call / Siri / exclusive audio session),player.play()throwsUnexpectedException: Session activation failed.playSoundisasync, that throw rejects the returned Promise, skippingsubscription.remove()andplayer.remove()(leaking both the listener and the nativeAudioPlayer), whilewithMinimalExecutionTime(src/libs/Sound/BaseSound.ts:44) callsnextFunc()without.catch(...), turning the rejection into an unhandled promise rejection.src/libs/Sound/index.native.ts:25),const audioModeConfigured = setAudioModeAsync(...)has no.catch(...), so ifsetAudioModeAsyncever rejects,await audioModeConfiguredwould also reject every subsequentplaySoundcall.What changes do you think we should make in order to solve the problem?
In
src/libs/Sound/index.native.ts:audioModeConfiguredwith.catch(...)so a failure configuring audio mode logs viaLog.hmmminstead of permanently rejectingaudioModeConfigured.AppState.currentState !== 'active'(or!Visibility.isVisible()) both at the start ofplaySoundand immediately afterawait audioModeConfiguredbefore creating the player, since the app state can change while waiting in the 300ms throttle queue or awaitingaudioModeConfigured.player.play()in atry / catchblock. In thecatchblock, clean upsubscription.remove()andplayer.remove(), and log the non-fatal audio session refusal viaLog.hmmm:Add unit tests (
tests/unit/SoundTest.ts):AppState.currentStateis'background'or'inactive',playSoundreturns early without callingcreateAudioPlayer.player.play()throwsError('UnexpectedException: Session activation failed'),playSoundcatches the error without rejecting, callssubscription.remove()andplayer.remove(), and logs viaLog.hmmm.What alternative solutions did you explore? (Optional)
AppState.currentState === 'active'without wrappingplayer.play()intry/catch: Insufficient because iOS can also refuseAVAudioSession.setActive(true)while the app is in the foreground (e.g., during an active phone call, FaceTime, or Siri session). Both theAppStateguard andtry/catchwithplayer.remove()cleanup are required.dankezo commentedon Nov 16, 2026
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:
No background guard where the session is activated.
playSoundinsrc/libs/Sound/index.native.tsawaits the module-levelaudioModeConfiguredpromise (thesetAudioModeAsynccall made at importtime), then calls
createAudioPlayer(source)andplayer.play(). There isno 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.
The one guarded caller cannot close the race.
playSoundForMessageType(
src/libs/actions/User.ts:777) checksVisibility.isVisible() && Visibility.hasFocus()at line 782, but that check runs BEFORE the asyncisChannelMuted(reportID, ...).then(...)boundary, andplaySoundonlyruns 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) callplaySoundwith no visibility check at all.Failures surface as unhandled rejections. The module-level
audioModeConfiguredpromise has no.catch, so a rejectedsetAudioModeAsyncis itself an unhandled rejection, and every laterawait audioModeConfiguredthrows. AndwithMinimalExecutionTime(
src/libs/Sound/BaseSound.ts:35) callsnextFunc()with no try/catch andno catch handler on the returned promise, so a rejected
playSoundbecomesan unhandled promise rejection - which is exactly the Sentry noise in this
issue.
Changes
src/libs/Sound/index.native.ts- guard at activation time. At the topof
playSound, after the existing mute check, return silently when the appis not active:
if (!Visibility.isVisible()) { return; }.Visibility.isVisible()on native isAppState.currentState === 'active'(
src/libs/Visibility/index.native.ts), so this is a synchronous check madeat 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.
src/libs/Sound/index.native.ts- a failed configuration must not throwforever. Attach a catch handler to
audioModeConfiguredthat logs oncewith
Log.hmmmand resolves, so asetAudioModeAsyncfailure degrades to"no sound" instead of an unhandled rejection plus a throw on every play.
src/libs/Sound/index.native.ts- contain playback failures. WrapcreateAudioPlayerandplayer.play()in try/catch. On error, remove theplayback listener and the player, log with
Log.hmmm, and return.Log.hmmm,not
Log.alert: a sound that cannot play while backgrounded is expectedbehaviour, not an error worth a Sentry event - the Sentry noise is the bug
being fixed.
src/libs/Sound/BaseSound.ts- the wrapper must not leak rejections.In
withMinimalExecutionTime'sprocessQueue, wrapnextFunc()intry/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 mutelogic (
getIsMuted), the sound assets, and every call site - no caller needsto 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), mockingexpo-audioand AppState:backgroundorinactive:playSoundresolves, andsetAudioModeAsync/createAudioPlayer/player.playare never called.setAudioModeAsyncrejects:playSoundstill resolves, nothing is thrown,no unhandled rejection is raised.
createAudioPlayerthrows (orplaythrows): the listener is removed, theplayer is removed,
playSoundresolves.active: the sound plays (regression control).withMinimalExecutionTime: a wrapped function that rejects does not producean unhandled rejection, and the queue still processes the next call.
Alternatives considered
with no guard today, and the guarded one still races across its async
boundary. The check belongs where the session is activated.
is precisely that these expected, harmless failures reach Sentry.
setAudioModeAsyncwhen backgrounded only. Rejected: the failurealso comes from
player.play()activating the session; both calls sitbehind the same guard in this proposal, which is simpler and complete.
audioModeConfiguredawait. Rejected: foreground playbackrelies on the ambient/mixWithOthers configuration; the fix keeps it and only
stops it from throwing.
melvin-bot commentedon Nov 16, 2026
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
dankezo commentedon Nov 16, 2026
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:
No background guard where the session is activated.
playSoundinsrc/libs/Sound/index.native.tsawaits the module-levelaudioModeConfiguredpromise (thesetAudioModeAsynccall made at importtime), then calls
createAudioPlayer(source)andplayer.play(). There isno 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.
The one guarded caller cannot close the race.
playSoundForMessageType(
src/libs/actions/User.ts:777) checksVisibility.isVisible() && Visibility.hasFocus()at line 782, but that check runs BEFORE the asyncisChannelMuted(reportID, ...).then(...)boundary, andplaySoundonlyruns 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) callplaySoundwith no visibility check at all.Failures surface as unhandled rejections. The module-level
audioModeConfiguredpromise has no.catch, so a rejectedsetAudioModeAsyncis itself an unhandled rejection, and every laterawait audioModeConfiguredthrows. AndwithMinimalExecutionTime(
src/libs/Sound/BaseSound.ts:35) callsnextFunc()with no try/catch andno catch handler on the returned promise, so a rejected
playSoundbecomesan 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?
src/libs/Sound/index.native.ts- guard at activation time. At the topof
playSound, after the existing mute check, return silently when the appis not active:
if (!Visibility.isVisible()) { return; }.Visibility.isVisible()on native isAppState.currentState === 'active'(
src/libs/Visibility/index.native.ts), so this is a synchronous check madeat 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.
src/libs/Sound/index.native.ts- a failed configuration must not throwforever. Attach a catch handler to
audioModeConfiguredthat logs oncewith
Log.hmmmand resolves, so asetAudioModeAsyncfailure degrades to"no sound" instead of an unhandled rejection plus a throw on every play.
src/libs/Sound/index.native.ts- contain playback failures. WrapcreateAudioPlayerandplayer.play()in try/catch. On error, remove theplayback listener and the player, log with
Log.hmmm, and return.Log.hmmm,not
Log.alert: a sound that cannot play while backgrounded is expectedbehaviour, not an error worth a Sentry event - the Sentry noise is the bug
being fixed.
src/libs/Sound/BaseSound.ts- the wrapper must not leak rejections.In
withMinimalExecutionTime'sprocessQueue, wrapnextFunc()intry/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 mutelogic (
getIsMuted), the sound assets, and every call site - no caller needsto 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), mockingexpo-audioand AppState:backgroundorinactive:playSoundresolves, andsetAudioModeAsync/createAudioPlayer/player.playare never called.setAudioModeAsyncrejects:playSoundstill resolves, nothing is thrown,no unhandled rejection is raised.
createAudioPlayerthrows (orplaythrows): the listener is removed, theplayer is removed,
playSoundresolves.active: the sound plays (regression control).withMinimalExecutionTime: a wrapped function that rejects does not producean unhandled rejection, and the queue still processes the next call.
What alternative solutions did you explore? (Optional)
with no guard today, and the guarded one still races across its async
boundary. The check belongs where the session is activated.
is precisely that these expected, harmless failures reach Sentry.
setAudioModeAsyncwhen backgrounded only. Rejected: the failurealso comes from
player.play()activating the session; both calls sitbehind the same guard in this proposal, which is simpler and complete.
audioModeConfiguredawait. Rejected: foreground playbackrelies on the ambient/mixWithOthers configuration; the fix keeps it and only
stops it from throwing.
25 remaining items
jpereyra243-byte commentedon Nov 17, 2026
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 failedfromexpo-audio'splayer.play()when iOS refusesAVAudioSession.setActive(true)(e.g. when the app is backgrounded or during active phone calls / Siri / other audio sessions holding exclusive control). BecauseplaySoundisasyncand its returned promise is unhandled by callers and the throttle queue, this escapes as an unhandled promise rejection (onunhandledrejectionin SentryAPP-NTH) and leaks the nativeAudioPlayerinstance and listener.What is the root cause of that problem?
player.play()(src/libs/actions/User.ts:793->src/libs/Sound/BaseSound.ts:44->src/libs/Sound/index.native.ts:27-53):playSoundForMessageType,Visibility.isVisible()is checked upfront, but it subsequentlyawaitsisChannelMutedand enqueuesplaySoundthroughwithMinimalExecutionTime(playSound, 300), which delays execution viasetTimeout.SOUNDS.DONE,SOUNDS.SUCCESS,SOUNDS.ATTENTION) do not perform any visibility or AppState check.src/libs/Sound/index.native.ts,playSoundawaitsaudioModeConfigured. By the time execution resumes, the app can be backgrounded (AppState.currentState !== 'active'). BecauseshouldPlayInBackgroundis explicitlyfalse(background sounds are handled by system push notifications), iOS rejectsAVAudioSession.setActive(true)whenplayer.play()is invoked.src/libs/Sound/index.native.ts:40-53):createAudioPlayercreates the native player andplayer.addListener('playbackStatusUpdate', ...)registers a subscription that is only removed whenstatus.didJustFinishfires.player.play()calls nativeactivateSession()which throws synchronously on iOS when activation fails.subscription.remove()andplayer.remove()are never called, causing nativeAudioPlayerinstances and listeners to leak in memory.src/libs/Sound/BaseSound.ts:44-48):withMinimalExecutionTimeinvokesnextFunc();without chaining.catch(...). BecauseplaySoundisasync, 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?
In
src/libs/Sound/index.native.ts:AppStatefromreact-native.Logfrom@libs/Log.AppStateguard afterawait audioModeConfiguredright before creating the player:try...catchblock.player.play()or player setup throws, immediately clean up native resources and log withLog.hmmm:In
src/libs/Sound/BaseSound.ts:withMinimalExecutionTime(processQueue), safeguard the promise execution so no queued sound function can escape as an unhandled rejection:Automated Unit Tests (
tests/unit/SoundNativeTest.ts):AppState.currentState === 'background',createAudioPlayeris never called andplaySoundresolves cleanly.player.play()throws an error (e.g.Session activation failed),subscription.remove()andplayer.remove()are called,Log.hmmmis invoked, and no unhandled promise rejection occurs.player.play()and cleans up ondidJustFinish.What alternative solutions did you explore? (Optional)
Visibility.isVisible()/AppStateonly at the call sites: Rejected because callers execute asynchronously (e.g. afterawait isChannelMuted), queue throttling adds a 300ms delay, and other callers (DONE,SUCCESS) do not check visibility. Checking right before playback inindex.native.tsprovides universal protection for all callers.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.BaseSound.tswithout try/catch inindex.native.ts: Rejected because it leaves the nativeAudioPlayerand subscription leaked in memory wheneverplay()fails.melvin-bot commentedon Nov 17, 2026
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
TassioSales commentedon Nov 17, 2026
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
playSoundinsrc/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,playSoundinstantiates an audio player fromexpo-audioand directly invokesplayer.play():On iOS,
expo-audioexecutesAVAudioSession.sharedInstance().setActive(true)synchronously in native code (AudioModule.swift). iOS strictly refuses audio session activation when:AppState.currentState !== 'active'), which frequently happens when Pusher delivers a message notification right after the user backgrounds the app or locks their device.Because
player.play()is invoked without atry/catchor error handler around the synchronous/promise boundary, iOS's rejection propagates upward intoonunhandledrejection, 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?
src/libs/Sound/index.native.ts:AppStateso that background incoming socket/notification events do not attempt to activate an audio session when the app is inactive:player.play()with atry/catchblock to handle transient native audio activation refusals (such as mid-call interruptions) gracefully without crashing or surfacing Sentry exceptions:player.release()is safely called in afinallyblock or when playback ends.What alternative solutions did you explore? (Optional)
Configuring
AVAudioSessionCategoryPlaybackwithmixWithOthersin native app configuration, but checkingAppState.currentState === 'active'and adding error containment inindex.native.tsis purely JavaScript-level, completely cross-platform safe, and prevents unnecessary audio session interruptions while the user is outside the app.kevinjosh10 commentedon Nov 18, 2026
Proposal
Please re-state the problem that we are trying to solve in this issue?
On iOS HybridApp builds,
playSoundthrows an unhandled promise rejection in Sentry (APP-NTH:UnexpectedException: Session activation failed (at ExpoModulesCore/SyncFunctionDefinition.swift:96)). This occurs whenexpo-audio'splayer.play()attempts to activate the audio session viaAVAudioSession.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 nativeAudioPlayerand 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:Racy background audio playback (
src/libs/Sound/index.native.ts:27-53):src/libs/actions/User.ts:782,playSoundForMessageTypechecksVisibility.isVisible()upfront, but then asynchronously awaitsisChannelMuted(reportID).playSoundis exported throughwithMinimalExecutionTime(playSound, 300)(src/libs/Sound/BaseSound.ts:35-65), which throttles executions with a 300ms delay, followed byawait audioModeConfiguredinsrc/libs/Sound/index.native.ts:39.Task.ts,PayMoneyRequest.ts,Split.ts, etc.) invokeplaySounddirectly without checking visibility orAppState.shouldPlayInBackground: false(src/libs/Sound/index.native.ts:25), iOS rejectsAVAudioSession.setActive(true), causingplayer.play()to throwUnexpectedException: Session activation failed.Missing error handling & native resource leak (
src/libs/Sound/index.native.ts:41-53):player.play()throws synchronously inside theasync playSoundfunction, which converts the throw into a rejected promise.withMinimalExecutionTimecallsnextFunc()(src/libs/Sound/BaseSound.ts:48) without handling or.catch()-ing the returned promise, allowing it to bubble up as an unhandled promise rejection.player.play()throws before playback finishes, theplaybackStatusUpdatelistener never receivesstatus.didJustFinish, sosubscription.remove()andplayer.remove()are never executed. This leaks the nativeAudioPlayerinstance in memory on every failure.setAudioModeAsyncat module scope (src/libs/Sound/index.native.ts:25) has no.catch()handler, so any failure during initial audio mode configuration would permanently rejectaudioModeConfiguredand all subsequentplaySoundcalls.What changes do you think we should make in order to solve the problem?
In
src/libs/Sound/index.native.ts:setAudioModeAsyncrejections: Attach a.catch()handler logging viaLog.hmmmso an initial audio mode configuration failure does not permanently break playback or unhandled rejection handlers.AppState.currentState !== 'active'both before and afterawait audioModeConfiguredto prevent creating players and requesting audio sessions when the app is inactive or backgrounded.play()intry / catchwith guaranteed cleanup: WrapcreateAudioPlayer, listener registration, andplayer.play()in atry / catchblock. Ifplayer.play()or session activation throws:subscription?.remove()andplayer?.remove()immediately to release native audio resources.Log.hmmminstead 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.What alternative solutions did you explore? (Optional)?
AppState.currentState === 'active'withouttry / 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).withMinimalExecutionTimeonly:While adding
.catch()insidewithMinimalExecutionTimesilences unhandled promise rejections, it does not prevent the native memory leak (player.remove()would never be called ifplayer.play()threw). Both the state guard and cleanup insidetry / catchare necessary.What specific scenarios should we cover in automated tests to prevent reoccurrence?
Add a new unit test suite
tests/unit/SoundTest.tsmockingexpo-audioandreact-native'sAppState:AppState.currentStateis'background'or'inactive', verify that callingplaySound(SOUNDS.RECEIVE)returns early without callingcreateAudioPlayer.AppState.currentStatetransitions to'background'while awaitingaudioModeConfigured, verify thatcreateAudioPlayeris not called.player.play()throwsError('UnexpectedException: Session activation failed'), verify that:playSoundresolves cleanly without throwing or rejecting.subscription.remove()andplayer.remove()are invoked to prevent native memory leaks.Log.hmmmis called with the error details.getIsMuted()is true,createAudioPlayeris not called.playbackStatusUpdatefires withdidJustFinish: true,subscription.remove()andplayer.remove()are called.Contributor details
theroimasters1-dev commentedon Nov 18, 2026
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 atsrc/libs/Sound/index.native.ts:53when callingplayer.play().What is the root cause of that problem?
In
src/libs/Sound/index.native.ts,playSoundcallsplayer.play().On iOS,
expo-audio's native implementation callsAVAudioSession.setActive(true)upon starting playback. However:AVAudioSession.audioModeConfiguredspecifiesshouldPlayInBackground: false, iOS denies session activation and throwsUnexpectedException: Session activation failed.src/libs/Sound/index.native.ts,player.play()is invoked synchronously without atry...catchblock to handle platform session activation refusals, causing an unhandled native exception / rejection. Furthermore, whenplayer.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?
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 inspectAppState.currentState === 'active'(orVisibility.isVisible()): if the app is in the background, skip sound playback immediately since system notifications already handle background alerts.player.play()in atry...catchblock insideplaySound:player.play()throws, bothsubscription.remove()andplayer.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
AppStatelisteners withouttry/catch. However, combining bothAppState.currentState !== 'active'guard AND thetry...catchsafety net is strictly required because race conditions can occur between JavaScript receiving a Pusher message and iOS transitioning into inactive/background state.yuvrajangadsingh commentedon Nov 18, 2026
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
playbegins withtry activateSession(), a bareAVAudioSession.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 innode_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
playSoundcalls it unguarded inside anasyncfunction, so the throw becomes a rejected promise:App/src/libs/Sound/index.native.ts
Lines 41 to 53 in 76a83b9
The queue calls that function and drops the promise it returns, so no caller can catch the rejection:
App/src/libs/Sound/BaseSound.ts
Lines 47 to 49 in 76a83b9
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
playreturns early when the ringer is on silent or vibrate and the audio mode hasplaysInSilentMode: 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
App/src/libs/Sound/index.native.ts
Lines 21 to 25 in 76a83b9
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:
App/src/libs/actions/Report/index.ts
Lines 1452 to 1454 in 76a83b9
The listener closure references the player, so neither can be garbage collected.
I ran the current
playSoundunder Jest with the repo's expo-audio mock. Withplay()throwing the Sentry error, the promise rejects and neither the listener nor the player is removed. Withplay()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.
playSoundForMessageTypechecksVisibility.isVisible()and then waits onisChannelMuted. After that the sound waits for its 300ms queue slot and foraudioModeConfigured. The app can be in the background by then, which is the state the Sentry event was captured in (in_foreground: false).App/src/libs/actions/User.ts
Lines 782 to 790 in 76a83b9
What changes do you think we should make in order to solve the problem?
The three changes are inside
playSoundin the native sound file. Callers, the queue and web stay as they are.1. Catch the throw.
Wrap
player.play()intry/catchand release the player in thecatch. Log the same[sound] Play error:line web logs, but withLog.hmmm, because a refused sound is expected, for example during a call.App/src/libs/Sound/index.ts
Lines 48 to 50 in 76a83b9
2. Release the player even when the sound doesn't finish.
The
didJustFinishlistener stays. I'd add areleasehelper that thecatchcalls 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.3. Check visibility again right before creating the player.
After the
audioModeConfiguredawait, return whenVisibility.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.App/src/libs/Sound/index.native.ts
Line 39 in 76a83b9
App/src/libs/Visibility/index.native.ts
Line 7 in 76a83b9
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:App/tests/unit/SoundTest.ts
Line 8 in 76a83b9
App/__mocks__/expo-audio.ts
Lines 3 to 11 in 76a83b9
play()throws "Session activation failed":playSoundresolves, the listener and the player are removed, the failure is loggedplay()does nothing and no finish event arrives: the listener and the player are removed after the timeoutWhat alternative solutions did you explore? (Optional)
playswallows the activation error. The native sound file is the one place undersrcthat 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.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.withMinimalExecutionTime. It stops the Sentry event, but the player and the listener aren't in scope there.RajGahoi commentedon Nov 18, 2026
github-actions commentedon Nov 18, 2026
RajGahoi commentedon Nov 18, 2026
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS HybridApp,
player.play()inexpo-audiocallsAVAudioSession.setActive(true)which iOS refuses when the app is backgrounded or when another app holds the audio session. The resultingError: Session activation failedis an unhandled rejection (the calling chain never awaits or catches). Additionally, theplayer.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:
withMinimalExecutionTimeinsrc/libs/Sound/BaseSound.tscallsnextFunc()withoutawaitand without catching its rejection.playSoundinsrc/libs/Sound/index.native.tsdoes not guard againstAppState.currentState !== 'active'.try/catchinplaySoundForMessageTypeonly 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.tsplayer.play(), checkAppState.currentState === 'active'. If not active, callplayer.remove()and return early — no sound should play in background.player.play()in atry/catch. On error, callsubscription.remove()andplayer.remove(), then log withLog.warn(notLog.hmmmto avoid Sentry noise). Do NOT rethrow — the caller does not need the rejection.File 2 —
src/libs/Sound/BaseSound.tswithMinimalExecutionTime, changenextFunc()toawait nextFunc()and wrap intry/catchso promise rejection does not escape.No other files need changes. The issue is entirely within the Sound library.
What specific scenarios should we test?
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.
knowaguy4u-cell commentedon Nov 19, 2026
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.playSoundis async, so the synchronous throw fromplayer.play()(src/libs/Sound/index.native.ts:53) rejects a promise that no code ever observes. Thetry/catchinplaySoundForMessageTypecannot 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
setAudioModeAsyncpromise (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 whenplay()throws, thedidJustFinishlistener is the only placeplayer.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:784vssrc/libs/Sound/index.native.ts:39-53), which is how a backgrounded app still attempts playback withshouldPlayInBackground: 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:
src/libs/Sound/BaseSound.ts— MakewithMinimalExecutionTimeadopt 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.src/libs/Sound/index.native.ts— Make the exported sound operation a non-rejecting boundary:player.play()together; on any failure, log it and run one idempotent cleanup that attemptssubscription.remove()andplayer.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 afinallyright afterplay()— playback is asynchronous and the existingdidJustFinishcompletion cleanup stays.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.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)
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 theUser.tschain detached. The Sentry class would recur from the next sound-path failure.playSoundinplaySoundForMessageType: ineffective until the wrapper propagates results (today it resolves independently of playback), and it leaves the other fire-and-forget callers inReport/index.tsexposed.shouldPlayInBackground: changes the product's stated sound policy (push sounds are the system's job) and fixes none of the promise/cleanup defects.melvin-bot commentedon Nov 19, 2026
📣 @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:
Format:
github-actions commentedon Nov 19, 2026
devcrafta commentedon Nov 19, 2026
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 failedfromplayer.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 callsAVAudioSession.setActive(true)first. That call throws when iOS refuses to turn the session on (node_modules/expo-audio/ios/AudioModule.swift,Function("play")):A player created without
keepAudioSessionActivealso 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 setsshouldPlayInBackground: false. It can also refuse when a phone call or another app holds the audio session:App/src/libs/Sound/index.native.ts
Line 25 in 5c27272
2. The error is never caught.
playSoundisasyncand callsplayer.play()without atry/catch, so the throw becomes a rejected promise:App/src/libs/Sound/index.native.ts
Lines 41 to 53 in 5c27272
withMinimalExecutionTimecallsnextFunc(), ignores the promise it returns, and resolves straight away. Callers can't catch the error even if theyawait:App/src/libs/Sound/BaseSound.ts
Lines 47 to 49 in 5c27272
3. The caller's checks run too early.
playSoundForMessageTypechecksVisibility.isVisible()when the Pusher update arrives:App/src/libs/actions/User.ts
Line 784 in 5c27272
The sound plays later, after the async
isChannelMutedcheck,await audioModeConfiguredand the 300 ms queue gap. By then the app may be in the background. The otherplaySoundcallers (IOU, Task, Report actions) don't check app state at all.4. The player leaks.
createAudioPlayerregisters the player inexpo-audio's native registry (self.registry.add(player)). Only thedidJustFinishlistener removes it, and that listener never fires whenplay()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
playSoundinsrc/libs/Sound/index.native.ts, so all callers are covered at the moment the sound actually plays:await audioModeConfiguredand beforecreateAudioPlayer, return early whenAppState.currentState !== 'active'. The check comes after theawaitso 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.player.play()in atry/catch. On failure, callsubscription.remove()andplayer.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.Log.hmmm('[sound] Session activation failed', {message}), not theLog.alertthe webonplayerroruses. This failure is expected iOS behavior, so an alert would move the noise from Sentry into server alerts..catchthat logs to the module-levelsetAudioModeAsync(...)promise. As written, if it ever rejects, every laterawait audioModeConfiguredrethrows that rejection and no sound plays for the rest of the session.Tests: extend the existing
__mocks__/expo-audio.tsand addtests/unit/SoundTest.ts, with each case documented with// Given / // When / // Thencomments:play()throws: no unhandled rejection, andplayer.remove()plussubscription.remove()are called;AppStateisbackground:createAudioPlayeris not called;AppStateisactiveandplay()succeeds: the player is released afterdidJustFinish.What alternative solutions did you explore? (Optional)
keepAudioSessionActive: trueon 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 themixWithOthers/ "don't interrupt other audio" intent noted in the code.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.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 insideplaySound, so the native leak stays. It's fine as an extra safety net.ignoreErrors). Rejected: it hides the report without fixing the leak or the wasted activation attempts.expo-audiowithpatch-packageto swallow the error natively. Rejected: the fix belongs in our code, and patching would hide real errors from everyexpo-audiouser in the app.Contributor details
Your Expensify account email: alfonso.ortega.upwork@gmail.com
Upwork Profile Link: https://www.upwork.com/freelancers/~01732a1c6c797326dd
melvin-bot commentedon Nov 19, 2026
✅ Contributor details stored successfully. Thank you for contributing to Expensify!