Skip to content

Remove unsafe assertions from composer, paste, input, and tab navigation contracts - #103910

Open
KJ21-ENG wants to merge 3 commits into
Expensify:mainfrom
KJ21-ENG:seatbelt-v2/batch-20261013-run-2-0c446c40
Open

KJ21-ENG wants to merge 3 commits into
Expensify:mainfrom
KJ21-ENG:seatbelt-v2/batch-20261013-run-2-0c446c40

Conversation

@KJ21-ENG

@KJ21-ENG KJ21-ENG commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Replace asserted composer and DOM shapes with platform-specific ref contracts and DOM checks, and bind expense navigators to their supported tab names. Forwarding handles read the current input, DOM writes require a real DOM element, and browser IME confirmation is checked through its native keyboard event.

Changed files:

  • src/components/Composer/implementation/index.native.tsx
  • src/components/Composer/implementation/index.tsx
  • src/components/Composer/types.ts
  • src/hooks/useHtmlPaste/index.ts
  • src/hooks/useHtmlPaste/types.ts
  • src/hooks/useOdometerDraftHydrator.ts
  • src/hooks/useResetIOUType.ts
  • src/libs/ComponentUtils/index.native.ts
  • src/libs/ComponentUtils/index.ts
  • src/libs/InputUtils/index.ts
  • src/libs/InputUtils/types.ts
  • src/libs/Navigation/OnyxTabNavigator.tsx
  • src/libs/ReportActionComposeFocusManager.ts
  • src/libs/actions/InputFocus/index.ts
  • src/libs/actions/InputFocus/index.web.ts
  • src/libs/focusComposerWithDelay/types.ts
  • src/libs/preventTextInputFocusOnFirstResponderOnce/index.ios.ts
  • src/libs/preventTextInputFocusOnFirstResponderOnce/types.ts
  • src/libs/updateMultilineInputRange/types.ts
  • src/pages/home/ForYouSection/ConciergePromptBox.tsx
  • src/pages/inbox/report/ReportActionCompose/ComposerContext.ts
  • src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx
  • src/pages/inbox/report/ReportActionCompose/ReportActionComposeUtils.ts
  • src/pages/inbox/report/ReportActionCompose/Suggestions.tsx
  • src/pages/inbox/report/ReportActionCompose/getScrollPosition/types.ts
  • src/pages/inbox/report/ReportActionCompose/updateNativeTextInputValue/index.ios.ts
  • src/pages/inbox/report/ReportActionCompose/useComposerSubmit.ts
  • src/pages/inbox/report/ReportActionCompose/useComposerSuggestions.ts
  • src/pages/inbox/report/ReportActionCompose/useEditMessage.ts
  • src/pages/inbox/report/ReportActionItemMessageEdit.tsx
  • src/pages/iou/request/DistanceRequestStartPage.tsx
  • src/pages/iou/request/IOURequestStartPage.tsx
  • tests/ui/ComposerImperativeRefTest.tsx
  • tests/ui/DistanceRequestStartPageTest.tsx
  • tests/ui/IOURequestStartPageManualTabTest.tsx
  • tests/ui/OnyxTabNavigatorTest.tsx
  • tests/ui/hooks/useHtmlPasteTest/index.tsx
  • tests/unit/ComposerSelectionNotificationTest.tsx
  • tests/unit/InputUtilsTest.ts
  • tests/unit/focusComposerWithDelayTest.ts
  • tests/unit/hooks/useEditMessageComposerCommands.test.ts
  • tests/unit/useComposerSubmitClearValueTest.tsx
  • tests/unit/useResetIOUTypeTabSelectionTest.tsx

Fixed Issues

$ #94739
PROPOSAL: #94739 (comment)

Tests

Focused repository lint, formatting, spelling, and checked-in Jest tests passed, including all 15 selected suites and 154 tests.

QA Steps

  • 1. Composer lifecycle.

    • In a writable conversation, enter an overflowing multiline draft, move the caret and insert an emoji suggestion.
    • Expand/collapse, send, then send a second message.
    • Send an attachment with a comment through its preview, then send another plain message.
    • Expect correct text/caret behavior, one send per action and a usable composer after each return.
  • 2. Message editing.

    • Edit an owned multiline message, move the caret and save.
    • Edit again, empty the text, attempt to submit, cancel the Delete confirmation and continue typing.
    • Expect correct saved text and restored editing/focus after cancellation.
    • Check desktop inline editing and the narrow-layout editor.
  • 3. Paste and scroll.

    • Replace selected composer text using plain/formatted clipboard content.
    • With the composer mounted, paste into an expense Description instead.
    • Edit an overflowing Description, save/reopen and continue typing.
    • In Search, accept a long suggestion/filter, append a character and clear.
    • Expect paste to affect only the intended input, with usable scrolling, visible caret and correct text.
  • 4. Expense-tab persistence.

    • Open Create expense, switch Manual > Scan > Manual, focus/type in the active input, select Scan, leave with the App's Back control and reopen.
    • Expect the correct active tab to persist and inputs to remain usable without stale focus.

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Recordings (5)
01-composer-lifecycle-desktop.mp4
02-message-edit-desktop.mp4
03-message-edit-narrow.mp4
04-paste-scroll-desktop.mp4
05-manual-scan-persistence-desktop.mp4

Seatbelt-Operation: 2facc752-58f4-4853-995b-5cf055d3ff11
@codecov

codecov Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
...omponents/Composer/implementation/index.native.tsx 96.15% <100.00%> (+5.76%) ⬆️
src/components/Composer/implementation/index.tsx 73.83% <100.00%> (+73.83%) ⬆️
src/hooks/useHtmlPaste/index.ts 88.77% <100.00%> (+5.61%) ⬆️
src/hooks/useOdometerDraftHydrator.ts 69.56% <100.00%> (ø)
src/hooks/useResetIOUType.ts 100.00% <100.00%> (+2.77%) ⬆️
src/libs/ComponentUtils/index.native.ts 100.00% <100.00%> (ø)
src/libs/ComponentUtils/index.ts 100.00% <100.00%> (+100.00%) ⬆️
src/libs/InputUtils/index.ts 100.00% <100.00%> (+100.00%) ⬆️
src/libs/ReportActionComposeFocusManager.ts 61.11% <100.00%> (ø)
src/libs/actions/InputFocus/index.ts 50.00% <100.00%> (ø)
... and 15 more
... and 212 files with indirect coverage changes

@KJ21-ENG
KJ21-ENG marked this pull request as ready for review October 16, 2026 21:21
@KJ21-ENG
KJ21-ENG requested review from a team as code owners October 16, 2026 21:21
@melvin-bot
melvin-bot Bot requested review from ikevin127 and removed request for a team October 16, 2026 21:21
@melvin-bot

melvin-bot Bot commented Oct 16, 2026

Copy link
Copy Markdown

@ikevin127 Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot requested a review from dylanexpensify October 16, 2026 21:21
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T21:56:58.307888Z be44bfd Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@melvin-bot
melvin-bot Bot removed the request for review from a team October 16, 2026 21:21
@ikevin127

ikevin127 commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Screen.Recording.2026-10-16.at.18.35.11.mov

import React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
import {DeviceEventEmitter, StyleSheet} from 'react-native';

type WebMarkdownInput = HTMLDivElement & Pick<TextInput, 'clear' | 'isFocused'> & {value?: string};

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.

src/components/Composer/implementation/index.tsx L30 / L295

🟠 value?: string on WebMarkdownInput is what forces onClear to become (text: string | undefined) => void across types.ts, ComposerWithSuggestions and useComposerSubmit, and that's why validateAndSubmitDraft now has to throw by hand. Can we normalize it at the source instead ?

const currentText = textInputRef.current.value ?? '';

Then onClear can stay (text: string) => void everywhere, and the undefined branch plus the hand-written TypeError in useComposerSubmit can go.

Right now, a clear fired before live-markdown sets value still crashes the report screen. The only difference is that the crash is now deliberate.

Comment on lines +63 to +66
// Live-markdown may clear before it initializes value. Keep that failure before submission effects.
if (draftMessage === undefined) {
throw new TypeError("Cannot read properties of undefined (reading 'trim')");
}

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.

Compose/useComposerSubmit.ts` L63-66**

🟠 Throwing a hand-written TypeError that copies the V8 message ("Cannot read properties of undefined (reading 'trim')") to preserve a crash isn't something we want in the codebase. It also makes the stack trace in Sentry point at a fake error.

If we fix the value ?? '' above, this block goes away. Otherwise, return early here.

Comment on lines +20 to +23
// Preserve the failed focus invocation after Onyx records focus.
if (ref === null) {
throw new TypeError("Cannot read properties of null (reading 'focus')");
}

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.

src/libs/actions/InputFocus/index.web.ts L20-23

🟠 Same pattern here. If ref is null, throwing a hand-written TypeError from inside a useEffect in ReportActionItemMessageEdit takes down the edit row. Let's just do ref?.focus().

The test preserves the null TypeError after that update in ComposerImperativeRefTest should then assert that it doesn't throw.

Comment on lines +85 to +89
type ComposerWithSuggestionsRef = Pick<ComposerRef, 'clear' | 'blur' | 'isFocused'> & {
readonly setSelection: ComposerRef['setSelection'];
readonly setNativeProps: ComposerRef['setNativeProps'];
readonly preventFocusOnFirstResponderOnce: ComposerRef['preventFocusOnFirstResponderOnce'];
readonly scrollTop: number | undefined;

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.

src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx L84-89 / L960-1030

🟡 The only consumers of ComposerWithSuggestionsRef (ComposerProvider, useComposerFocus, useEditMessage, ComposerContext) use focus, blur, isFocused, clearWorklet, replaceSelectionWithText and resetHeight.

Nothing reads setSelection, setNativeProps, preventFocusOnFirstResponderOnce, scrollTop or clear from the outer handle, so the Object.defineProperties block is about 40 lines of dead getters.

Can we drop those from the type and the handle ?

useImperativeHandle(ref, (): ComposerWithSuggestionsRef => ({
    focus,
    replaceSelectionWithText,
    getCurrentText,
    clearWorklet,
    resetHeight,
    blur: () => composerRef.current?.blur(),
    isFocused: () => !!composerRef.current?.isFocused(),
}));

This also gets rid of the throw new TypeError('Composer ref is not available') wrappers. A side note in case someone wires the setNativeProps getter up later: it returns an unbound host-instance method, and ReactNativeElement.setNativeProps relies on this.

The old Proxy covered for that, but this plain object won't.

Comment on lines +44 to +45
defaultSelectedTab?: Extract<TTabName, string>;
onTabSelected?: (newTabName: Extract<TTabName, string> | undefined) => void;

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.

src/libs/Navigation/OnyxTabNavigator.tsx L44-45 / L399

🟡 Widening onTabSelected to | undefined spreads into useResetIOUType (where tabSelectedTypeRef is now IOURequestType | undefined | null) and useOdometerDraftHydrator.

Passing undefined into resetIOUTypeIfChanged would call initMoneyRequest with newIouRequestType: undefined and wipe the draft, so it shouldn't be possible through the public API.

Can we guard it in the navigator and keep the callback narrow ?

if (!newSelectedTab) {
    return;
}
Tab.setSelectedTab(id, newSelectedTab);
onTabSelected(newSelectedTab);
onTabSelected?: (newTabName: TTabName) => void;

Also, Extract<TTabName, string> is redundant since TTabName extends string already; plain TTabName is enough.

@ikevin127 ikevin127 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.

@KJ21-ENG I found no blockers. There are 5 actionable comments I'd like addressed though, and the two most important ones are the same problem: the PR adds hand-written crashes (throw new TypeError(...)) to copy the old null/undefined crashes, and adds new tests that lock them in.

The Composer and tab-navigator files are already identical to the PR head on this branch. To check that the createOnyxTabNavigator factory doesn't stop React Compiler from compiling OnyxTabNavigator, I ran Babel and OXC on the main and PR-head versions.

Both still compile and memoize it, so that's fine. The old Proxy forwarding on ComposerWithSuggestions doesn't break any current caller either: the outer handle is only used through focus, blur, isFocused, clearWorklet, replaceSelectionWithText and resetHeight, and setNativeProps is always called on the inner ref.

@dylanexpensify dylanexpensify 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.

refactor, product input not required

Seatbelt-Operation: reviewer-fix-103910-06791fa4-9c10-4ba3-8718-b35d312fac7c
Seatbelt-Operation: upstream-ci-repair-103910-0f9fc68a-d352-4633-96c8-b2525d1538d3

@ikevin127 ikevin127 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.

🟢 LGTM - Thanks for the changes! All five of your comments are fixed in code, and the only red CI check is a flaky Jest job (a worker killed by the CI host) that needs a re-run.

@melvin-bot
melvin-bot Bot requested a review from blimpich October 19, 2026 23:19
@blimpich

Copy link
Copy Markdown
Contributor

Jest tests seem to be failing?

This branch has not been deployed

No deployments
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.

4 participants