Skip to content

fix(mobile): a granted microphone tap launches no permission activity, and an aborted start says so - #22150

Merged
Jinwoo-H merged 4 commits into
mainfrom
ota-fu-dictation-start-abort
Sep 22, 2026
Merged

Jinwoo-H merged 4 commits into
mainfrom
ota-fu-dictation-start-abort

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​380 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​374
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​87 $\color{#cf222e}{\Huge{\mathbf{−}}}$​34 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​53

A granted microphone tap must not launch the permission activity

Two halves of one defect from the 2026-09-22 device run (followup-device-c7-9.md §7,
device-run-20260922T0037Z/enginefix/report.md): every mic tap on Android raised
GrantPermissionsActivity although RECORD_AUDIO was already granted, and the resume behind it
ended 2 of 4 tapped starts at idle with no toast, no banner and no error.

Fix 1 — the module asks only when it has to

ExpoTwoWayAudioModule.requestMicrophonePermissionsAsync called
Permissions.askForPermissionsWithPermissionsManager unconditionally. Expo's Android service takes
that straight to the activity: askForPermissionsWithPromise → askForPermissions →
askForManifestPermissions → delegateRequestToActivity → currentActivity.requestPermissions(...),
with no granted check anywhere on the way. The translucent activity lives 50–115 ms and drives
onUserLeaveHint → onHostPause → onHostResume through the React host.

Before, RECORD_AUDIO already granted

requestMicrophonePermissionsAsync
  → Permissions.askForPermissionsWithPermissionsManager
  → PermissionsService.askForPermissionsWithPromise
  → askForPermissions            (no WRITE_SETTINGS, so straight through)
  → askForManifestPermissions
  → delegateRequestToActivity    ── addToAskedPermissionsCache(RECORD_AUDIO)
  → currentActivity.requestPermissions(...)   ── START GrantPermissionsActivity
       ⋯ onUserLeaveHint / onHostPause ⋯ user-invisible dialog ⋯ onHostResume ⋯
  → PermissionsResponseListener
  → getPermissionsWithPromise
  → resolve { expires: 'never', status: 'granted', canAskAgain: true, granted: true }

After, RECORD_AUDIO already granted

requestMicrophonePermissionsAsync
  → appContext.permissions.hasGrantedPermissions(RECORD_AUDIO)  → true
  → Permissions.getPermissionsWithPermissionsManager
  → PermissionsService.getPermissionsWithPromise
  → resolve { expires: 'never', status: 'granted', canAskAgain: true, granted: true }

Same resolved bundle, no activity, no host pause, and no write to the asked-permissions cache. When
the permission is not granted the call is byte-for-byte the old one, so a first-run prompt and a
re-prompt after a denial are unchanged. A null permissions manager also keeps its old answer: the
?. leaves the ask arm, which rejects with E_NO_PERMISSIONS.

iOS: not the same shape, so not changed

MicrophonePermissionRequester.swift has no granted check either, but it does not need one.
EXPermissionsService.askForPermissionUsingRequesterClass reads the current status first and
returns onResult(permission) before it ever reaches the requester when the status is granted. The
requester's AVAudioApplication.requestRecordPermission is never called on a granted tap, and no
activity equivalent exists on that path.

There is no Kotlin test harness in this module (android/src/ holds main only), which is why the
call sequences above stand in for one.

Fix 2 — a tapped start that stops before recording says so

canSend is the hook's enabled, and it is
activeHandle != null && tabType is a terminal's && connState === 'connected' && clientId != null.

Established

The arm that returned a tapped start to idle in silence is cancel() from the !enabled Effect.
cancel() is also the user's own cancel: it bumped the generation, ended the capture, set idle
and cleared the error, and nothing distinguished the two. The downstream arms then correctly stayed
quiet, because the generation had moved — start()'s post-open check releasing the capture, and
cancelStaleStart in the desktop start.

connState does not move across a short background. A connected relay is retained under
RELAY_BACKGROUND_GRACE_MS (30 s), the nudge router only probes a healthy relay on resume, and the
terminal foreground recovery is gated to iOS. clientId is the entry's device token and does not
move either.

Still open: what flips canSend on that resume

activeHandle is the remaining input, and this change does not establish what clears it. A tabs
reconciliation that has not yet answered is ruled out. use-mobile-session-tabs-reconciliation.ts
does subscribe AppState and force refresh(true) on every 'active', but an in-flight or
omitting snapshot cannot null the handle: resolveActiveSessionTab returns null for empty tabs
(active-session-tab.ts:27,62) and both clearing arms test active first
(use-mobile-session-tab-application.ts:180,199), so a null active falls through and the handle is
retained — which is what the comment at :198 guards. The handle is nulled only when the snapshot
names a real active tab carrying no handle: :181 a terminal tab whose terminal is not a string,
:199 a non-terminal tab. Both persist while that tab stays active, and on the device run the
active tab was a terminal with a live handle. So a healthy resume snapshot would not have cleared
it, and the trigger needs its own evidence.

The fix does not depend on that answer. It is pinned at the hook level: whatever flips enabled, a
start the user tapped now reports instead of ending in silence.

The change

The hook now separates the user's cancel from an abort it did not ask for.
abandonDictation(reason) is the one abort path; reason === null is the user's cancel and stays
silent, and anything else reaches onError when a start or a recording was actually underway. The
!enabled Effect passes MOBILE_DICTATION_INPUT_CLOSED_ERROR_MESSAGE, which the composer already
renders through its onError toast. A disable arriving while idle still says nothing.

Both device shapes are covered by the one change, because the report survives what follows it: the
post-open release and cancelStaleStart both only reset the status while the generation is still
theirs, and the abort moved it.

Device evidence this matches

tap trace reading
22:39:24 focus requested @b526fa +0 ms, abandoned +599 ms with no re-request tearDown(), whose only JS caller is capture.release()
22:47:54 wake lock released, focus @67e07ee retained, no toggleRecording(true) capture.end() without a teardown

capture.end() without a teardown is closeDictationAudio(), which the abort runs; the teardown
case is the post-open release that follows an abort that moved the generation.

Not changed, and why

  • onInterruption still routes through the silent cancel(). Another app taking the microphone is
    the same class of involuntary stop, but no device evidence reaches it on this path and it has its
    own tests; it is a separate follow-up.
  • A disable landing while stop() is in flight (processing) still discards the recording quietly.
    That is a stop the user tapped, not a start, and it is outside this change.

Lead verification

Lead gate on 6e394ac033 against b9643365ba: tsc 0, ratchet 0, all lint gates 0, changed-code quality passed, React Doctor 0; config/scripts 251 files passed; mobile 809 files passed; no machine paths. The Kotlin arm has no unit harness; it is the same shape the phone-verified engine fix (#22132) took, and the next device run's dictation step is its proof.

Round 2 — two stale writes after an await

Both review bots found the same class of defect: a write that resumes after an await and lands on
a dictation that is no longer the one it belongs to. Both are reproduced by
mobile-dictation-stale-abort.test.tsx and both predate this branch.

abandonDictation, the post-await write

wasUnderway and the branch it picks are read before await dictationSessionCancel.request(...),
which is a full desktop round trip. A fresh start() that lands inside it reaches recording, and
then the held cancel resolves into a stale abort.

Red, the reporting branch:

expected [ Array(1) ] to deeply equal []
+ [ "Voice dictation stopped because this session is no longer accepting input. Try again." ]

A toast over a live recording. The silent branch is the same shape one step milder: a user cancel
whose response arrives late idled the recording that replaced it, expected 'idle' to be 'recording'.

The abort now captures the generation it bumps to and returns if the generation moved while the
cancel was in flight — the guard isCurrentMobileDictationFinish and the desktop-session start
already use.

capture.open()'s catch, the unguarded reset

If enabled goes false while the open is pending, the disable reports the closure and bumps the
generation. A late rejection from that open then ran applyStatus('idle') and rethrew, wiping the
closure the user had just been shown: expected 'idle' to be 'error'.

The catch now makes the same check the arm below it already made,
generationRef.current !== generation || !enabledRef.current, and returns. It does not rethrow on
that path either: the composer toasts whatever start rejects with, so a stale refusal would land
on top of the closure. That matches shouldReport in the desktop start, which returns false
rather than throwing once its start is no longer current.

Both predate this branch

Probed against b9643365ba with the same cases. A user cancel whose response arrived after a newer
recording started idled it (expected 'idle' to be 'recording'), and a late open rejection did the
same. This branch did not introduce either race. What it added was a reporting branch through the
first one, which turns a silent wrong reset into a visible wrong toast.

Lead gate on 51c664d against b964336 (gate-dictation-51c664de23.log): tsc 0, ratchet 0, changed-code quality 0, react-doctor 0, anti-slop 0, max-lines 0, root-oxlint 0 (5 files), config/scripts 251 passed / 2 skipped, mobile 810 passed, machine-paths 0.

…activity

Every Android mic tap raised GrantPermissionsActivity although RECORD_AUDIO
was granted: Expo's askForPermissions path has no granted check and goes
straight to delegateRequestToActivity. The activity pauses and resumes the
React host for 50-115 ms.

The module now answers from getPermissionsWithPermissionsManager when the
permission is already held. iOS needs nothing: EXPermissionsService returns
on a granted status before it reaches the requester.

The resume behind that activity forces a tabs reconciliation, which can
transiently clear the active handle and so flip canSend, the hook's `enabled`.
That reached cancel() through the !enabled Effect -- the same cancel the user's
own has -- so a tapped start ended at idle with nothing shown. abandonDictation
now carries a reason: null is the user's cancel and stays silent, anything else
reaches onError when a start or a recording was underway.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 2f8e44f1-1d0c-41d9-b980-30f26781d0b2

📥 Commits

Reviewing files that changed from the base of the PR and between 6e394ac and 51c664d.

📒 Files selected for processing (2)
  • mobile/src/hooks/mobile-dictation-stale-abort.test.tsx
  • mobile/src/hooks/use-mobile-dictation.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • mobile/src/hooks/use-mobile-dictation.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

The Android audio module now returns existing microphone permission state before requesting permission. The mobile dictation hook distinguishes user cancellation from input closure. It preserves closure errors when asynchronous operations finish late and ignores stale operations that could alter a newer dictation session. New tests cover pending starts, cancellation, input closure, and stale aborts.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 51c66

Android permission handling avoids redundant prompts, and dictation closure and stale asynchronous operations preserve the current session state. No actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides detailed context, implementation changes, scope, race-condition coverage, and verification results. It does not provide the required linked issue, visual proof or an explicit … Add an issue reference after Fixes #. Add before-and-after visual proof, or write N/A with a brief reason if no visual or interaction change applies. Complete the testing and checklist items, and document any inapplicable sections.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies both main fixes: avoiding the Android permission activity when microphone access is already granted and reporting aborted dictation starts.
Full details: Description check

Explanation

The description provides detailed context, implementation changes, scope, race-condition coverage, and verification results. It does not provide the required linked issue, visual proof or an explicit N/A statement, completed testing checkboxes, or completed checklist items.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 77d0d2ae-656f-4992-af7e-898ea793628d

📥 Commits

Reviewing files that changed from the base of the PR and between b964336 and 6e394ac.

📒 Files selected for processing (5)
  • mobile/packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/ExpoTwoWayAudioModule.kt
  • mobile/src/hooks/mobile-dictation-input-closed-mid-start.test.tsx
  • mobile/src/hooks/mobile-dictation-session-state.ts
  • mobile/src/hooks/use-mobile-dictation-source.test.ts
  • mobile/src/hooks/use-mobile-dictation.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

One real race in the new abort path: abandonDictation writes status and fires onError after awaiting the cancel RPC, without checking whether a newer start has taken over. A stale abort can therefore paint error and emit a toast over an active recording. Details inline.

Reviewed changes

  • Android permission fast path — requestMicrophonePermissionsAsync now checks hasGrantedPermissions(RECORD_AUDIO) and resolves via getPermissionsWithPermissionsManager when already granted, so a granted tap no longer launches GrantPermissionsActivity. Verified against [email protected]: the granted branch resolves the same bundle (granted: true, canAskAgain: true) with no activity and no asked-permissions-cache write; a null manager still rejects with E_NO_PERMISSIONS.
  • Abort reporting in useMobileDictation — cancel() is split into abandonDictation(reason); the !enabled Effect passes the new MOBILE_DICTATION_INPUT_CLOSED_ERROR_MESSAGE so a start the composer disables no longer ends in silence, while the user's own cancel stays silent. A statusRef mirrors status for aborts between commit and passive effects.
  • Tests — new mobile-dictation-input-closed-mid-start.test.tsx drives both halves (disable reports, user cancel silent); use-mobile-dictation-source.test.ts slices updated. Both verified passing, and the new case does fail against the pre-change code.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

…laced it

abandonDictation read what it would report before awaiting the desktop cancel,
and nothing re-checked identity after it resumed. A start landing inside that
round trip reaches recording, then the stale abort reported the closure over it
or idled it. It now captures the generation it bumps to and returns if the
generation moved, the guard the finish check and the desktop start already use.

capture.open()'s catch had the same hole: a rejection arriving after a disable
had already reported the closure ran applyStatus('idle') and rethrew, wiping it.
The catch now makes the same check the arm below it makes, and returns without
rethrowing, because the composer toasts whatever start rejects with.

Both races predate this branch; probed against b964336 with the same cases.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

The delta since the prior pullfrog review (6e394ac033) is commit 51c664de23, which closes the stale post-await write races both review bots had flagged.

  • Guarded abandonDictation after its cancel await — it now captures the generation it bumps to and returns if a newer operation moved it, so a disable or a user cancel that resolves late no longer reports over, or idles, the start that replaced it.
  • Guarded capture.open()'s catch — returns when the generation moved or the composer is disabled, so a late microphone refusal neither resets a reported closure back to idle nor rethrows into the composer's toast.
  • Added mobile-dictation-stale-abort.test.tsx — drives the stale disable report, the stale user cancel, and the late open rejection; each assertion fails against the pre-fix code.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit 5769eb6 into main Sep 22, 2026
24 checks passed
@Jinwoo-H
Jinwoo-H deleted the ota-fu-dictation-start-abort branch September 22, 2026 05:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant