[$175] [Sentry: APP-P53] NotAllowedError: Failed to execute 'writeText' on 'Clipboard' (unhandled rejection)
Sentry
https://expensify.sentry.io/issues/APP-P53
Impact
- 1 user, 1 event since first seen: 2026-11-12 17:41 UTC
- Platform: web, Edge on Windows, standalone
- Release:
9.5.36 - Route:
/workspaces/:policyID/connections/two-factor-auth - View:
Dynamic_Settings_TwoFactorAuth_Root - Mechanism: unhandled rejection (
onunhandledrejection)
Error
NotAllowedError: Failed to execute 'writeText' on 'Clipboard': Document is not focused.
Top first-party frames
src/libs/Clipboard/index.ts:139 — setString
DynamicTwoFactorAuthPage.tsx:165 — onPress
PressableWithDelayToggle.tsx:107 — updatePressState
Root cause
The browser legitimately rejects clipboard writes when the document is unfocused. Our clipboard wrapper delegates to a dependency that neither returns nor catches the navigator.clipboard.writeText() Promise, allowing the rejection to escape unhandled.
The 2FA handler also marks recovery codes as copied and announces “Copied” without confirming the write succeeded.
Suggested fix
Handle clipboard write failures centrally and expose success/failure to callers. Only mark recovery codes as copied and announce success after a successful write; otherwise allow retry without claiming success.
A synchronous try/catch around the existing wrapper will not catch this asynchronous rejection.
Add tests verifying rejected clipboard writes are handled and do not trigger success feedback.
Existing issues
No matching tracking issue found in Expensify/App or Expensify/Expensify. App#93837 discusses clipboard rejection in comments but tracks a different error.
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022121304566909824244
- Upwork Job ID: 2121304566909824244
- Last Price Increase: 2026-11-13
Issue Owner
Current Issue Owner: @FitseTLT
Triggered auto assignment to Contributor-plus team member for initial proposal review - @FitseTLT (External)
Job added to Upwork: https://www.upwork.com/jobs/~022121304566909824244
Proposal
What is the root cause of that problem?
-
Unhandled Asynchronous Promise in
Clipboard.setStringandClipboard.setHtml:- In
src/libs/Clipboard/index.ts:138-140:const setString: SetString = (text) => { Clipboard.setString(text); };setStringdelegates to@react-native-clipboard/clipboard's web implementation, which callsnavigator.clipboard.writeText(text)without awaiting, catching, or returning the promise. - When the document is unfocused (or clipboard permission is refused by the browser),
navigator.clipboard.writeText(text)rejects with aNotAllowedError. Because there is no.catch()handler attached to the promise and the wrapper does not return the promise to the caller, the rejection escapes as an unhandled promise rejection (window.onunhandledrejection), causing the Sentry error. - Similarly, in
src/libs/Clipboard/index.ts:125-131,setHtmlcallsnavigator.clipboard.write([...])without a.catch()handler, allowing the sameNotAllowedErrorto escape unhandled.
- In
-
Premature Success Feedback in
DynamicTwoFactorAuthPage&PressableWithDelayToggle:- In
src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:208-213:onPress={() => { Clipboard.setString(account?.recoveryCodes ?? ''); setError(''); setCodesAreCopied(); announceStatus(translate('common.copied')); }}setCodesAreCopied()andannounceStatus(translate('common.copied'))execute synchronously without awaiting or confirming whether the clipboard write actually succeeded. - In
src/components/Pressable/PressableWithDelayToggle.tsx:102-108,updatePressStateunconditionally callstemporarilyDisableInteractions()(which switches the button to the "Copied" checkmark state) regardless of whether the copy operation succeeded.
- In
What changes do you think we should make in order to solve the problem?
-
Centralize Clipboard Write Error Handling & Return Status in
src/libs/Clipboard/index.ts:- In
src/libs/Clipboard/types.ts, updateSetStringandSetHtmlto returnPromise<boolean>. - In
src/libs/Clipboard/index.ts:- In
setString, useasync/awaitaroundnavigator.clipboard.writeText(text):- If
navigator?.clipboard?.writeTextsucceeds, returntrue. - If
navigator.clipboard.writeTextrejects (e.g.NotAllowedError), catch the error, log a warning withLog.warn, and attempt the existing fallbacksetHTMLSync('', text)(usingdocument.execCommand('copy')). If fallback succeeds, returntrue; otherwise returnfalse.
- If
- In
setHtml, wrapnavigator.clipboard.write([...])in atry/catch: if it rejects, catch the error, log a warning, and fall back tosetHTMLSync(html, text).
- In
- In
src/libs/Clipboard/index.native.ts, wrapClipboard.setString(text)in atry/catchand returnPromise.resolve(true)on success andPromise.resolve(false)on failure.
- In
-
Only Announce and Mark Copied on Success in
DynamicTwoFactorAuthPage.tsx:- In
src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:208-213, update theonPresscallback to check the result ofClipboard.setString:onPress={async () => { const success = await Clipboard.setString(account?.recoveryCodes ?? ''); if (!success) { return false; } setError(''); setCodesAreCopied(); announceStatus(translate('common.copied')); return true; }}
- In
-
Update
PressableWithDelayToggle.tsxto RespectonPressReturn Value:- In
src/components/Pressable/PressableWithDelayToggle.tsx:102-108, updateupdatePressState:- If
onPressreturns a Promise, await it (or chain.then(success => ...)): only calltemporarilyDisableInteractions()if the result is notfalse. - If
onPressreturns synchronousfalse, do not calltemporarilyDisableInteractions(). - If
onPressreturnsvoid/undefined, calltemporarilyDisableInteractions()as before to maintain backward compatibility with existing synchronous buttons.
- If
- In
-
Add Unit & UI Tests:
- In
tests/unit/ClipboardTest.ts:- Verify that when
navigator.clipboard.writeTextrejects withNotAllowedError,Clipboard.setStringcatches the error, attempts fallback, and resolves tofalsewithout triggering an unhandled rejection.
- Verify that when
- In
tests/ui/DynamicTwoFactorAuthPageTest.tsx:- Add a test verifying that when
Clipboard.setStringfails,setCodesAreCopiedis not called, and the status announcement is not triggered.
- Add a test verifying that when
- In
What alternative solutions did you explore? (Optional)
- Wrapping
Clipboard.setStringin a synchronoustry/catchinsideDynamicTwoFactorAuthPage.tsx: Rejected becausenavigator.clipboard.writeTextreturns a Promise that rejects asynchronously in a later event loop tick; a synchronoustry/catchwill not catch the rejection. - Using only
document.execCommand('copy')on web: Rejected becausedocument.execCommandis deprecated and the modern asynchronous Clipboard API is the preferred web standard.
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
What is the root cause of that problem?
The code supports the issue’s diagnosis, with one additional problem: the copy button displays “Copied” before the clipboard operation succeeds.
The web clipboard dependency discards the Promise returned by navigator.clipboard.writeText(). Consequently, the browser’s focus-related rejection escapes unhandled. Meanwhile, the recovery-code handler immediately records the codes as copied and announces success.
Code evidence
- The locked clipboard dependency is version 1.16.3. Its web implementation neither returns nor catches the browser write Promise.
- Clipboard/index.ts:135–140 delegates to that dependency without exposing completion.
- DynamicTwoFactorAuthPage.tsx:203–220 unconditionally records and announces success.
- PressableWithDelayToggle.tsx:102–123 independently activates checked text and accessibility feedback before invoking the handler. Awaiting inside the handler alone would therefore leave false success feedback.
Confidence: Medium. The current code explains the reported rejection and premature success feedback. The production event and release-specific behavior were not independently reproduced; why the document lost focus remains unknown.
What changes do you think we should make in order to solve the problem?
- Handle browser clipboard writes centrally in App, observing the actual browser Promise and returning a non-rejecting success/failure result. Merely awaiting the existing dependency is insufficient.
- Preserve the legacy copy fallback, checking its result and cleaning up temporary elements even on failure.
- Make the recovery-code control success-aware: show and announce “Copied,” and record acknowledgement, only after success. Separate pending/disabled state from successful checked state.
- On failure, provide retryable failure feedback without logging recovery codes. Preserve the independent Download flow and any previous successful acknowledgement.
- Keep existing callers compatible and explicitly account for native clipboard APIs that do not confirm completion.
Regression coverage
Test delayed success, rejected writes—including the reported focus error—synchronous exceptions, fallback failure, and successful retry. Verify there is no unhandled rejection or premature copied state, announcement, checkmark, or acknowledgement. Exercise the real pressable behavior rather than mocking away its immediate state transition.
What alternative solutions did you explore? (Optional)
- Synchronous
try/catchor awaiting the current wrapper: cannot catch a Promise already discarded by the dependency. - Only delaying the page’s announcement: leaves the button’s independent “Copied” feedback incorrect.
- Forcing focus: does not address other legitimate clipboard failures.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106888) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On web (such as Edge standalone on /workspaces/:policyID/connections/two-factor-auth), clicking Copy codes on the 2FA recovery codes step when the document lacks focus causes navigator.clipboard.writeText() to reject with NotAllowedError: Failed to execute 'writeText' on 'Clipboard': Document is not focused., escaping as an unhandled Promise rejection (onunhandledrejection). At the same time, both PressableWithDelayToggle and DynamicTwoFactorAuthPage unconditionally report success—displaying Copied!, announcing "Copied!" to screen readers, setting codesAreCopied: true in Onyx (unlocking the Verify step without copied codes), and throttling retries for 1800ms—even though nothing was written to the clipboard.
What is the root cause of that problem?
-
Unhandled Promise rejection in
src/libs/Clipboard/index.ts:src/libs/Clipboard/index.ts:138-140delegatessetStringto@react-native-clipboard/clipboard(v1.16.3), whose web implementation callsnavigator.clipboard.writeText(text)without returning or.catch()ing the Promise, and only falls back todocument.execCommand('copy')whennavigator.clipboarditself is undefined—never whenwriteText()rejects due to focus or permission restrictions.src/libs/Clipboard/index.ts:125-131(setHtml) likewise invokesnavigator.clipboard.write([...])without returning or catching its Promise, andcanSetHtml(lines 26-30) returns a nested closure() => (...args) => ...that is always truthy even whennavigator.clipboard?.writeorClipboardItemis unavailable.- Existing
setHTMLSync(lines 34-100) cannot be reused as-is for plain-text fallback because: (a) it appendsnodetodocument.body(line 49) before the earlyif (selection === null) return;(lines 53-55) and withouttry / finally, leaking DOM nodes containing sensitive text on early exit or selection errors; (b) it ignores thebooleanreturn value ofdocument.execCommand('copy')(line 81), which returnsfalsewithout throwing when user activation has expired after an async rejection; and (c) it unconditionally writese.clipboardData?.setData('text/html', html)(line 46), so passinghtml = ''writes an empty'text/html'payload that pastes blank into rich-text editors.
-
Unconditional pre-completion success UI in
PressableWithDelayToggleandDynamicTwoFactorAuthPage:- In
src/components/Pressable/PressableWithDelayToggle.tsx:102-108,updatePressStatecallstemporarilyDisableInteractions()beforeonPress?.(). FlippingisActivetofalseimmediately switches the label totextChecked("Copied!"), icon toCheckmark, andaccessibilityLabeltocheckedAccessibilityLabel(lines 110-126, 163-168) while blocking retries for1800ms, regardless of async completion or failure. - In
src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:208-213,onPresssynchronously callssetCodesAreCopied()(which setscodesAreCopied: trueandtwoFactorAuthSetupInProgress: trueinONYXKEYS.ACCOUNT, satisfyingTwoFactorAuthWrapper'sVERIFYgate) andannounceStatus(translate('common.copied'))without awaiting confirmation that the clipboard write succeeded.
- In
What changes do you think we should make in order to solve the problem?
-
Centralize non-rejecting clipboard writes with a leak-safe fallback in
src/libs/Clipboard/:- In
src/libs/Clipboard/types.ts, updateSetStringto(text: string) => Promise<boolean>,SetHtmlto(html: string, text: string) => Promise<boolean>, andCanSetHtmlto() => boolean. - In
src/libs/Clipboard/index.ts:- Fix
canSetHtmlto returnBoolean((navigator?.clipboard?.write && typeof ClipboardItem !== 'undefined') || Browser.getBrowser() === CONST.BROWSER.SAFARI). - Replace
setHTMLSyncwithcopyWithExecCommand(text: string, html?: string): booleanthat checksdocument.bodyandwindow?.getSelection()before appending the temporary<span>, only sets'text/html'whenhtml !== undefined(preserving rich-text paste compatibility for plain-text fallbacks), checks bothdocument.execCommand('copy')andcopy-eventclipboardDatapopulation, and restores selection + callsnode.remove()inside afinallyblock. - Implement
setStringdirectly againstnavigator?.clipboard?.writeText(text)insideasync / try / catch: returntruewhenwriteTextresolves; on rejection or missingwriteText, attemptcopyWithExecCommand(text), log sanitized error metadata (error.name/error.messageviaLog.warn—never loggingtext, which holds 2FA recovery codes, TOTP secrets, or card CVVs) only if the fallback also fails, and resolve toboolean. Apply the sametry / catch+copyWithExecCommand(text, html)fallback tosetHtml.
- Fix
- In
src/libs/Clipboard/index.native.ts, wrapClipboard.setString(text)intry / catchreturningPromise.resolve(true)/Promise.resolve(false)(accounting for React Native's synchronous fire-and-forget bridge) and returnPromise.resolve(false)fromsetHtml.
- In
-
Decouple in-flight press protection from checked success state in
PressableWithDelayToggle.tsx:- In
src/components/Pressable/PressableWithDelayToggle.tsx, widenonPressviaOmit<PressableProps, 'onPress'>to acceptboolean | void | Promise<boolean | void>. - Track in-flight async presses with a synchronous
isPendingRef(plusisPendingstate forstyles.cursorDefaultandisMountedReffor unmount safety) so neither nestedPressableWithoutFeedbackbubbling (lines 143, 196) nor rapid clicks can fire duplicateonPresscalls while a Promise is pending, while keepingisActive === true(no premature"Copied!"text, checkmark, or checked accessibility label). - Call
temporarilyDisableInteractions()only whenonPressreturns synchronously!== falseor resolves to!== false; if it returnsfalse, resolves tofalse, or rejects, catch internally and resetisPendingimmediately so the user can retry without waiting1800ms. - In
src/components/CopyTextToClipboard.tsx:41-43, returnClipboard.setString(urlToCopy || text || '')fromcopyToClipboardso it (alongsideDynamicVerifyPageandTwoFactorAuthSecretDisplay) also withholds"Copied!"on failed writes.
- In
-
Gate recovery-code acknowledgement & surface retryable error feedback in
DynamicTwoFactorAuthPage.tsx:- In
src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:208-213, makeonPressasync(guarded byisMountedRefso late resolutions afterquitAndNavigateBackcannot re-dirtyONYXKEYS.ACCOUNT):onPress={async () => { setError(''); const didCopy = await Clipboard.setString(account?.recoveryCodes ?? ''); if (!isMountedRef.current) { return false; } if (!didCopy) { setError(translate('twoFactorAuth.errorCopyCodes')); return false; } setCodesAreCopied(); announceStatus(translate('common.copied')); return true; }} - On failure,
setCodesAreCopied()andannounceStatus(translate('common.copied'))are not called (preserving any priorcodesAreCopied: truefrom an earlier Copy or Download without resetting it, and leaving the independent Download flow intact), while the existing<FormHelpMessage isError message={error} />(lines 240-246) displays and assertively announcestwoFactorAuth.errorCopyCodes(src/languages/*.ts).
- In
-
Add regression tests:
tests/unit/ClipboardTest.ts: test webClipboard.setString/setHtmlfor resolved writes,NotAllowedErrorunfocused-document rejections (no unhandled rejection, DOM<span>cleaned up, secret text never logged, resolvesfalsewhen fallback fails andtruewith'text/plain'-only when fallback succeeds), and synchronous exceptions.tests/ui/DynamicTwoFactorAuthPageTest.tsx: exercise the realPressableWithDelayTogglebutton (CONST.SENTRY_LABEL.TWO_FACTOR_AUTH.COPY_CODES) for pending writes (no premature"Copied!"orsetCodesAreCopied), rejected writes (shows error, keeps"Copy codes"active for immediate retry, preserves pre-existingcodesAreCopied), and successful retry.
What alternative solutions did you explore? (Optional)
- Calling existing
setHTMLSync('', text)as thesetStringfallback: Rejected becausesetHTMLSyncwrites an empty'text/html'clipboard item that causes rich-text editors to paste blank, ignoresdocument.execCommand('copy')'sbooleanresult, and can leak the temporary DOM node on early exit. - Delaying
temporarilyDisableInteractions()inPressableWithDelayTogglewithout an in-flight ref guard: Rejected becauseisActiveremainstruewhilenavigator.clipboard.writeText()is pending, allowing rapid clicks or nested pressable events to trigger concurrentonPressexecutions.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~014898525b9c53fc32
Proposal
Please re-state the problem that we are trying to solve in this issue.
When copying recovery codes on Web while the document is not focused, navigator.clipboard.writeText rejects with NotAllowedError: Document is not focused. Because Clipboard.setString does not catch or return the browser Promise, an unhandled rejection Sentry error is thrown. Simultaneously, the copy button and 2FA handler immediately show "Copied!" and announce success despite the clipboard write failing.
What is the root cause of that problem?
- Unhandled asynchronous promise in
Clipboard.setStringandClipboard.setHtml(src/libs/Clipboard/index.ts:125-140):setStringdelegates to@react-native-clipboard/clipboard's Web implementation, which callsnavigator.clipboard.writeText(text)without returning or catching the Promise. When the document is unfocused or clipboard permissions are denied, the rejection escapes as an unhandled promise rejection (window.onunhandledrejection). Similarly,setHtmlcallsnavigator.clipboard.write(...)without catching rejections. - Premature success state in
PressableWithDelayToggle.tsx:102-108:updatePressStateimmediately triggerstemporarilyDisableInteractions(), flippingisActivetofalseand displayingtextChecked("Copied!") regardless of whether the clipboard operation succeeds or is still pending. - Unchecked success in
DynamicTwoFactorAuthPage.tsx:208-213: TheonPresscallback executessetCodesAreCopied()andannounceStatus(translate('common.copied'))synchronously without confirming that the clipboard write succeeded.
What changes do you think we should make in order to solve the problem?
-
Centralize clipboard error handling & return boolean success in
src/libs/Clipboard/index.ts:- In
src/libs/Clipboard/types.ts: UpdateSetStringandSetHtmlsignatures to returnPromise<boolean>. - In
src/libs/Clipboard/index.ts:- In
setString:- If
navigator?.clipboard?.writeTextis available, wrap the call in atry/catch. If it resolves, returntrue. - If it rejects (e.g.
NotAllowedError), catch the error, log a warning viaLog.warn, and attempt legacy fallback usingdocument.execCommand('copy')withtext/plainonly (using a clean temporary<span>element cleaned up in afinallyblock). Returntrueif fallback succeeds,falseotherwise. (Do not callsetHTMLSyncfor plain text, as that creates an emptytext/htmlitem that corrupts paste in external rich text editors).
- If
- In
setHtml: Wrapnavigator.clipboard.write(...)in atry/catch. If it rejects, log a warning and fall back tosetHTMLSync(html, text).
- In
- In
src/libs/Clipboard/index.native.ts: WrapClipboard.setString(text)in atry/catchand returnPromise.resolve(true).
- In
-
Make
PressableWithDelayToggle.tsxasync-aware and gate checked state on success:- Widen
onPressprop to acceptboolean | void | Promise<boolean | void>. - Introduce an
isPendingstate / ref so that rapid clicks while a Promise is in flight are ignored without prematurely flipping totextChecked("Copied!"). - Call
temporarilyDisableInteractions()only ifonPressresolves to!== false. If it returns or resolves tofalse, resetisPendingimmediately so the user can retry without waiting the 1800ms throttle.
- Widen
-
Gate recovery codes confirmation in
DynamicTwoFactorAuthPage.tsx:208-213:- Make
onPressasync. const success = await Clipboard.setString(account?.recoveryCodes ?? '');- If
!success, displaysetError(translate('twoFactorAuth.errorCopyCodes'))and returnfalse. - Only call
setCodesAreCopied()andannounceStatus(translate('common.copied'))whensuccess === true.
- Make
-
Automated tests:
tests/unit/ClipboardTest.ts: Test WebClipboard.setStringresolving, rejecting withNotAllowedError(asserting no unhandled rejection and correct fallback behavior), and returningboolean.tests/ui/DynamicTwoFactorAuthPageTest.tsx: Test that a rejected clipboard write keeps the button active for immediate retry, does not announce "Copied", does not setcodesAreCopied, and displays the error message.
What alternative solutions did you explore? (Optional)
- Falling back to
setHTMLSync('', text)forsetString: Rejected becausesetHTMLSyncwrites an emptytext/htmlMIME type into the system pasteboard, which causes rich-text editors (Slack, Google Docs) to paste empty text. - Wrapping with a synchronous
try/catch: Rejected becausenavigator.clipboard.writeText()is asynchronous and a synchronoustry/catchdoes not intercept unhandled Promise rejections.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
📣 @RS-ITACHI! 📣 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:
- Make sure you've read and understood the contributing guidelines.
- 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.
- 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.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
What is the root cause of that problem?
The web clipboard wrapper delegates to @react-native-clipboard/clipboard. Its version 1.16.3 web setter calls navigator.clipboard.writeText() without returning or catching the promise. When the browser rejects an unfocused document's write, that rejection escapes unhandled. App's HTML copy path also discards a browser write promise.
Success feedback happens before either write completes. PressableWithDelayToggle switches to its checked state before calling the handler. The recovery-code handler immediately records the codes as copied and announces success. Both places need to wait for the result.
What changes do you think we should make in order to solve the problem?
- Have the shared web setters observe the actual browser promise and return
Promise<boolean>. Catch synchronous exceptions and asynchronous rejections centrally, including calls whose results are ignored. MakecanSetHtmlreturn a boolean capability check. - Reuse the existing span and copy-event fallback, checking
execCommand('copy')'s result. Remove the temporary node and restore selection infinally. Preserve Safari's whitespace behavior, HTML/plain text clipboard data, mention normalization and composer selection. Plain text copies must omit an empty HTML representation. Apply the existing FullStory mask before putting clipboard contents in the temporary node. - Let
PressableWithDelayToggleaccept boolean or asynchronous results through anOmitoverride ofonPress. A pending ref prevents duplicate and nested presses. Show checked feedback only after success; allow immediate retry afterfalse, a throw or a rejection. Keep synchronous successful handlers immediate and handle StrictMode effect replay correctly. - Await copying on the recovery-code page before acknowledgement or announcement. On failure, display the existing localized error. Ignore results after unmount, blur/refocus or replacement of the recovery codes. Preserve previous successful acknowledgement and the independent Download flow.
- Return the clipboard result from
CopyTextToClipboard, and adapt the three menu callbacks whose return types otherwise become incompatible. On native, report whether the synchronous bridge call succeeded; that does not confirm later OS clipboard persistence.
Local verification passed 95 Jest tests across nine suites, followed by 39 focused tests after the privacy mask change. Seven checks passed in an actual Chrome clipboard harness, including clipboard readback, fallback cleanup and controlled denial. TypeScript, lint, React Compiler, formatting and spelling checks passed; the staged standards review reported no violations.
A controlled local before/after recording exercises the real 2FA page with test recovery codes, stubbed server responses and an injected clipboard denial. The original build acknowledges the failed copy and emits an unhandled rejection. The patched build keeps failure retryable and confirms a subsequent copy through native clipboard readback. The exact production focus-loss condition remains unconfirmed. Safari's fallback branch was exercised in Chromium; actual Safari and iOS/Android device checks remain outstanding.
What alternative solutions did you explore? (Optional)
A synchronous catch around the existing dependency cannot observe the promise it discards. Updating only the page leaves the pressable's premature checkmark and accessible success label. Forcing browser focus would still leave other legitimate clipboard denials unhandled.
https://github.com/user-attachments/assets/b621e0e8-21e9-4097-a4df-f5546860ae10
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01e25967395e54eb3f
Proposal
Please re-state the problem that we are trying to solve in this issue.
On Web (e.g., Edge on Windows at /workspaces/:policyID/connections/two-factor-auth), pressing Copy codes on the 2FA recovery codes step when the document is unfocused causes navigator.clipboard.writeText() to reject with NotAllowedError: Failed to execute 'writeText' on 'Clipboard': Document is not focused., escaping as an unhandled Promise rejection (onunhandledrejection). At the same time, the button and page immediately mark the recovery codes as copied (setCodesAreCopied()) and display/announce "Copied" even though the clipboard write failed.
What is the root cause of that problem?
- Unhandled Promise rejection in
src/libs/Clipboard/index.ts:- In
src/libs/Clipboard/index.ts:144-146,setStringdelegates directly to@react-native-clipboard/clipboard(Clipboard.setString(text)), whose web implementation invokesnavigator.clipboard.writeText(text)without returning or catching the resultingPromise. When the document lacks focus, the browser rejects thatPromisewithNotAllowedError, escaping as an unhandled rejection. - Similarly,
setHtml(src/libs/Clipboard/index.ts:131-137) callsnavigator.clipboard.write([...])without catching rejections.
- In
- Unconditional success state in
DynamicTwoFactorAuthPage.tsx(src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:207-212):onPresssynchronously callsClipboard.setString(account?.recoveryCodes ?? '')and immediately runssetError(''),setCodesAreCopied(), andannounceStatus(translate('common.copied'))without confirming whether the clipboard write succeeded.
- Premature
"Copied"toggle inPressableWithDelayToggle.tsx(src/components/Pressable/PressableWithDelayToggle.tsx:101-107):updatePressStatecallstemporarilyDisableInteractions()synchronously beforeonPress?.()resolves. That immediately flipsisActivetofalse, renderingtextChecked={translate('common.copied')}, the checkmark icon, andaccessibilityLabelChecked—and throttling retries—even when the clipboard write fails.
What changes do you think we should make in order to solve the problem?
-
Handle web clipboard writes centrally and return
Promise<boolean>(src/libs/Clipboard/types.ts,src/libs/Clipboard/index.ts,src/libs/Clipboard/index.native.ts):- Update
SetStringinsrc/libs/Clipboard/types.tsto(text: string) => Promise<boolean>. - In
src/libs/Clipboard/index.ts, implementsetStringusingnavigator.clipboard?.writeText(text)when available, catching any rejection (includingNotAllowedError) and falling back to a synchronousdocument.execCommand('copy')helper that cleans up its temporary<textarea>in afinallyblock and returnstrue/falsewithout ever throwing or leaving an unhandled rejection:function setStringSync(text: string): boolean { if (typeof document === 'undefined' || !document.body) { return false; } const node = document.createElement('textarea'); node.value = text; node.setAttribute('readonly', ''); node.style.all = 'unset'; node.style.opacity = '0'; node.style.position = 'absolute'; node.style.left = '-9999px'; document.body.appendChild(node); node.select(); try { return document.execCommand('copy'); } catch { return false; } finally { document.body.removeChild(node); } } const setString: SetString = async (text) => { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { try { await navigator.clipboard.writeText(text); return true; } catch { return setStringSync(text); } } return setStringSync(text); }; - Also attach
.catch(() => setHTMLSync(html, text))tonavigator.clipboard.write(...)insetHtml(src/libs/Clipboard/index.ts:131-137) so HTML copies cannot trigger unhandled rejections when unfocused. - In
src/libs/Clipboard/index.native.ts, returnPromise.resolve(true)afterClipboard.setString(text).
- Update
-
Make
PressableWithDelayTogglerespect asynconPresssuccess/failure (src/components/Pressable/PressableWithDelayToggle.tsx):- Allow
onPressonPressableWithDelayTogglePropsto returnvoid | boolean | Promise<void | boolean>. - Guard in-flight async calls with an
isPendingRefref and only calltemporarilyDisableInteractions()(which switches the button to the checked"Copied"state) whenresult !== false:const updatePressState = () => { if (!isActive || isPendingRef.current) { return; } const result = onPress?.(); if (result instanceof Promise) { isPendingRef.current = true; result .then((didSucceed) => { if (didSucceed !== false) { temporarilyDisableInteractions(); } }) .catch(() => {}) .finally(() => { isPendingRef.current = false; }); return; } if (result !== false) { temporarilyDisableInteractions(); } };
- Allow
-
Gate 2FA recovery code acknowledgement and announcement on clipboard success (
src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:207-212):- Update the Copy codes
onPresshandler to awaitClipboard.setString(account?.recoveryCodes ?? '')and returnfalsewithout callingsetCodesAreCopied()or announcing"Copied"if the write fails:onPress={async () => { const didCopy = await Clipboard.setString(account?.recoveryCodes ?? ''); if (!didCopy) { return false; } setError(''); setCodesAreCopied(); announceStatus(translate('common.copied')); return true; }}
- Update the Copy codes
-
Add unit/UI tests:
- Add unit tests in
tests/unit/ClipboardTest.tsverifying that whennavigator.clipboard.writeTextrejects withNotAllowedErrorand fallback copy fails,Clipboard.setStringresolves tofalsewith no unhandled rejection. - Add UI tests in
tests/ui/DynamicTwoFactorAuthPageTest.tsxverifying that a rejected clipboard write does not callsetCodesAreCopied, does not announce"Copied", and does not toggle the button to"Copied", while a subsequent retry succeeds.
- Add unit tests in
What alternative solutions did you explore? (Optional)
- Wrapping
Clipboard.setStringin a synchronoustry/catchinsideDynamicTwoFactorAuthPage: Rejected becausenavigator.clipboard.writeTextrejects asynchronously on a microtask; synchronoustry/catchcannot catch it, and@react-native-clipboard/clipboarddiscards the underlyingPromise. - Only updating
DynamicTwoFactorAuthPagewithout updatingPressableWithDelayToggle: Rejected becausePressableWithDelayToggletoggles its own label and accessibility state to"Copied"beforeonPresscompletes.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
On Web (e.g. Edge/Chrome on Windows at Because the clipboard wrapper does not catch or return the Promise from Unhandled Asynchronous Promise in Our web wrapper delegates to Similarly, in Premature Success Feedback in In The 2FA screen synchronously clears errors, marks codes as copied ( Centralize Clipboard Write Error Handling and Return a Make Benefit: Existing callers returning Gate 2FA Success State on Clipboard Confirmation:
In Proposal
Proposal
Please re-state the problem that we are trying to solve in this issue.
/workspaces/:policyID/connections/two-factor-auth), clicking Copy codes when the document is not focused causes navigator.clipboard.writeText() to asynchronously reject with NotAllowedError: Failed to execute 'writeText' on 'Clipboard': Document is not focused..writeText, this rejection escapes into the microtask queue and triggers window.onunhandledrejection (Sentry APP-P53). Additionally, the UI prematurely announces "Copied" and marks recovery codes as copied even if the clipboard write failed.What is the root cause of that problem?
Clipboard.setString and Clipboard.setHtml:
In src/libs/Clipboard/index.ts:138-140:const setString: SetString = (text) => {
Clipboard.setString(text);
};
@react-native-clipboard/clipboard. On web, @react-native-clipboard/clipboard calls navigator.clipboard.writeText(text) but neither returns the Promise nor attaches a .catch() handler. When the browser rejects the operation (e.g. Document is not focused, permission denied, or cross-origin iframe restriction), the floating Promise rejects in the microtask queue, which any synchronous try/catch wrapper in caller code cannot catch.setHtml (lines 125–132), navigator.clipboard.write([...]) returns a Promise without a .catch(), leaving another unhandled rejection path.PressableWithDelayToggle and DynamicTwoFactorAuthPage:
In src/components/Pressable/PressableWithDelayToggle.tsx:102-108:const updatePressState = () => {
if (!isActive) {
return;
}
temporarilyDisableInteractions();
onPress?.();
};
temporarilyDisableInteractions() is invoked immediately upon click, prematurely flipping the button to "Copied" and displaying the checkmark icon regardless of whether the underlying write succeeded.src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:146-151:onPress={() => {
Clipboard.setString(account?.recoveryCodes ?? '');
setError('');
setCodesAreCopied();
announceStatus(translate('common.copied'));
}}
setCodesAreCopied()), and triggers screen reader announcement without awaiting clipboard confirmation.What changes do you think we should make in order to solve the problem?
Promise<boolean>:
src/libs/Clipboard/types.ts:
type SetString = (text: string) => Promise<boolean>;
type SetHtml = (html: string, text: string) => Promise<boolean>;
src/libs/Clipboard/index.ts:
Directly handle navigator.clipboard.writeText with try / catch and add a fallback to document.execCommand('copy') (matching the existing setHTMLSync approach already used in this file for Safari):
In function copyTextSync(text: string): boolean {
const node = document.createElement('textarea');
node.value = text;
node.style.all = 'unset';
node.style.position = 'fixed';
node.style.opacity = '0';
document.body.appendChild(node);
node.focus();
node.select();
try {
return document.execCommand('copy');
} catch {
return false;
} finally {
document.body.removeChild(node);
}
}
const setString: SetString = async (text: string): Promise<boolean> => {
if (navigator?.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch (error) {
Log.warn('[Clipboard] Failed to write text via navigator.clipboard.writeText, attempting sync fallback', {error});
return copyTextSync(text);
}
}
return copyTextSync(text);
};
setHtml (lines 125–132), catch rejection on navigator.clipboard.write and fall back to setHTMLSync:
try {
await navigator.clipboard.write([
new ClipboardItem({
/* eslint-disable @typescript-eslint/naming-convention */
'text/html': new Blob([htmlNonClosingTags], {type: 'text/html'}),
'text/plain': new Blob([text], {type: 'text/plain'}),
}),
]);
return true;
} catch (error) {
Log.warn('[Clipboard] Failed to write HTML via navigator.clipboard.write, falling back to sync copy', {error});
setHTMLSync(html, text);
return true;
}
src/libs/Clipboard/index.native.ts:
Update setString to return Promise.resolve(true):
const setString: SetString = (text) => {
Clipboard.setString(text);
return Promise.resolve(true);
};
PressableWithDelayToggle Await onPress Before Switching to "Copied":
In src/components/Pressable/PressableWithDelayToggle.tsx:
Allow onPress to return Promise<boolean | void> | void. In updatePressState:const updatePressState = async () => {
if (!isActive) {
return;
}
const result = onPress?.();
if (result instanceof Promise) {
const success = await result;
if (success === false) {
return;
}
}
temporarilyDisableInteractions();
};
void continue to work with zero breaking changes. Callers that return a Promise can signal failure by resolving false, which leaves the button active and immediately clickable for retry.src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:146-151:onPress={async () => {
const success = await Clipboard.setString(account?.recoveryCodes ?? '');
if (!success) {
return false;
}
setError('');
setCodesAreCopied();
announceStatus(translate('common.copied'));
return true;
}}
What alternative solutions did you explore? (Optional)
try/catch wrapping Clipboard.setString at caller sites: Rejected because navigator.clipboard.writeText rejects asynchronously in the microtask queue; a synchronous try/catch block does not intercept the rejection.window.addEventListener('unhandledrejection') global suppression: Rejected because masking unhandled rejections globally hides legitimate errors and does not provide proper retry UX to users.Test Plan
tests/unit/libs/ClipboardTest.ts):
Clipboard.setString succeeds and returns true when navigator.clipboard.writeText resolves.navigator.clipboard.writeText rejecting with new DOMException('Document is not focused.', 'NotAllowedError'):
copyTextSync is executed.Clipboard.setString returns false if copyTextSync also fails.Clipboard.setHtml handles rejection from navigator.clipboard.write and falls back to setHTMLSync.
PressableWithDelayToggle, verify that an onPress returning Promise.resolve(false) does not enter the disabled/checked state and keeps the button interactive.DynamicTwoFactorAuthPage, simulate a failed clipboard write: verify setCodesAreCopied is not called, "Copied" announcement is not made, and the button does not display "Copied".setCodesAreCopied is called, "Copied" announcement is made, and the button displays "Copied" with the checkmark.
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0105126232377c4c5c
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@FitseTLT can you please review the proposals?
Proposal
What is the root cause of that problem?
On web, Clipboard.setString hands the text to @react-native-clipboard/clipboard (L135-L140). The package's web setString calls navigator.clipboard.writeText() and drops the promise (v1.16.3 L22-L33), so when the browser refuses the write, nothing handles it. This started with #29119, which moved web setString from react-native-web's synchronous execCommand copy to this package.
The 2FA page then marks the codes as copied and announces "Copied" without knowing the result (L203-L213). PressableWithDelayToggle also switches to "Copied!" before it calls onPress (L102-L108).
I reproduced the exact error on staging 9.5.39-2 (Chromium, 1440px and 390px). The event came from the Xero connect flow on Connections; I opened the same Dynamic_Settings_TwoFactorAuth_Root screen from Settings > Security, because Connections isn't available on my test workspace.
- With the window unfocused (
document.hasFocus()is false), a click event on Copy codes gives an unhandledNotAllowedError: Failed to execute 'writeText' on 'Clipboard': Document is not focused.The button still shows "Copied!",account.codesAreCopiedbecomestrue, and the clipboard keeps its old content. - A real pointer click focuses the document first, so it copies normally (the clipboard then holds the codes). The event needs a click that reaches the button while the window isn't focused, such as an assistive-tech or scripted click. A retry with a normal click works.
What changes do you think we should make in order to solve the problem?
- Web
setString: callnavigator.clipboard.writeText()ourselves and returnPromise<boolean>. It resolvestrueon success. On rejection it logs withLog.hmmm(without the text) and resolvesfalse, so it never rejects, likehandleSearchErrorin Search.ts. Browsers without the async API keep the package call. Native resolvestrue. DynamicTwoFactorAuthPage: callsetCodesAreCopied()and announce "Copied" only when it resolvestrue, and return the result.PressableWithDelayToggle: whenonPressreturns a promise, switch to the checked state only if it resolvestrue; everything else works as today.ContextMenuItemalready notes this idea (L94). On failure the button stays "Copy codes", so the user can click again.- Once
setStringreturns a promise,no-misused-promisesflags the 3ContextMenuItemcallers that return it from a one-line arrow (Share code, workspace share, referral; checked with lint). They get a block body, with no behaviour change.
I don't add an execCommand fallback (most of the earlier proposals do). On staging, with the document unfocused, every fallback I tried returned false and left the clipboard unchanged: setHTMLSync('', text), a span holding the text, and the package's textarea. With focus, setHTMLSync('', text) returns true but copies nothing, because the span is empty and the copy event never reaches its listener. So a fallback can't copy here, and it could report a false success.
Tests: ClipboardWebTest runs the package's real web code with writeText rejecting with the measured error, and DynamicTwoFactorAuthPageTest gets two cases.
- On main, 3 fail, and jest reports the same "Document is not focused." rejection.
- With the change, both pass (14/14), and all 11 clipboard/copy suites pass (92/92).
- Lint and oxfmt are clean.
What alternative solutions did you explore? (Optional)
- Patching the package to return the promise: our wrapper would still need to handle it, so doing it in the wrapper is smaller.
setHtml(clipboard.write) has the same pattern. Draft #106742 already adds a catch there that falls back tosetString; with this change, that fallback resolvesfalseinstead of raising this same error. If #106742 doesn't land first, I can givesetHtmlthe same handling.
@MelvinBot draft the pr
🤖 Web test steps verification results: ❌ fail
Blocked on dev NewDot web: the existing session displays a blank page. No recovery-code behavior could be verified.
| Step | Status |
|---|---|
Recovery-code Copy success, failure/retry, and pending-write behaviorBoth snapshots returned zero nodes. Browser verification was blocked; no product regression was established.![]() |
❌ |
Created draft PR: Handle clipboard failures before acknowledging recovery codes, assigned to FitseTLT.
48 focused tests passed, alongside lint and typechecking. Full-suite, Storybook, and tooling limitations are documented in the draft.
view run · no recording available