Skip to content

fix: Attachment - Edit comment option is shown for .doc file#90203

Merged
stitesExpensify merged 16 commits into
Expensify:mainfrom
TaduJR:fix-Attachment-Edit-comment-option-is-shown-for-.doc-file
May 29, 2026
Merged

fix: Attachment - Edit comment option is shown for .doc file#90203
stitesExpensify merged 16 commits into
Expensify:mainfrom
TaduJR:fix-Attachment-Edit-comment-option-is-shown-for-.doc-file

Conversation

@TaduJR

@TaduJR TaduJR commented May 11, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

Fixes the "Edit comment" option incorrectly appearing for .doc/.pdf attachment-only messages after navigating away and back, plus the related (pre-edit) styling/LHN misclassification.

Two interacting failures in the original code:

  1. isReportMessageAttachment returned false for .doc attachment-only messages after the OpenReport response. The server returns message.text = "filename URL" for documents (instead of "[Attachment]" like it does for images), so the existing text === "[Attachment]" and Str.isVideo(text) checks both missed it — cascading into wrong styling (TextCommentFragment instead of AttachmentCommentFragment) and wrong LHN text.

  2. canEditReportAction had two guards that both got bypassed: !isReportMessageAttachment(message) (from 1) and ((!isAttachmentWithText && !isAttachmentOnly) || !isOptimisticAction)isOptimisticAction is cleared to null by successData, so !null = true rendered the isAttachmentOnly check meaningless after sync.

Changes (6 files):

  • src/libs/isReportMessageAttachment.ts — replaced the brittle text-based logic with structural detection:

    • Fast path 1: if the HTML doesn't contain the data-expensify-source=" token (precise — leading space + =" so a URL query param isn't a false positive), it's not an attachment. Skips the parser for the vast majority of messages.
    • Fast path 2: a present source attribute + text === "[Attachment]" → attachment-only (covers standard image/video). Only .doc/.pdf (text = "filename URL") reach the parser.
    • htmlparser2 parse (already used in extractAttachments.ts, SelectionScraper, ReportActionFollowupUtils): attachment-only = one or more attachment tags and nothing else; any text/element outside them → attachment+text. A depth counter ensures markup nested inside an <a>/<video> (filename, formatting) isn't counted as user content.
    • WeakMap memoization keyed by the immutable Onyx Message object: list re-renders pass the same object, so the parser runs at most once per message rather than once per render.
  • src/libs/ReportUtils.ts (canEditReportAction) — removed isReportMessageAttachment from edit gating (it's a display/LHN signal, not a permission gate — conflating them was the root cause) and replaced the flawed flags check with a single isOptimisticAttachment guard. Per the agreed product behavior, all attachments are editable after sync; only block during the optimistic upload window.

  • cspell.json — whitelist ontext (htmlparser2 callback, alongside existing onopentag/onclosetag).

  • tests/unit/isReportMessageAttachmentTest.ts (19 cases) & tests/unit/ReportUtilsTest.ts (+5 canEditReportAction cases) — cover doc/pdf/video/image attachment-only & attachment+text, the two codex-bot regression guards (leading user link, trailing caption), nested markup, translationKey ≠ ATTACHMENT, undefined/empty input, and the optimistic-vs-synced edit matrix.

  • tests/perf-test/isReportMessageAttachment.perf-test.ts (new) — Reassure benchmark over a 10k-message chat history (the hot path situchan flagged).

Performance: measured vs the original regex (≈ what's on main): the final fast-path + memoized version is −69.5% 🟢🟢 on the 10k-message pass — i.e., faster than main on the realistic hot path (list re-renders of stable objects), and correct everywhere.

Fixed Issues

$ #74031
PROPOSAL: #74031 (comment)

Tests

  1. Open a chat, upload a .doc file (no text)
  2. Long-press it before upload completes → "Edit comment" is NOT shown
  3. Wait for upload to finish, go to LHN, reopen the chat
  4. Long-press the .doc → "Edit comment" IS shown
  5. Verify the .doc renders with its attachment border + icon (not plain text)
  6. Verify LHN preview for the chat shows [Attachment]
  7. Tap "Edit comment", type something, save → message updates without errors
  • Verify that no errors appear in the JS console

Offline tests

Same as tests

QA Steps

// TODO: These must be filled out, or the issue title must include "[No QA]."
Same as tests

  • Verify that no errors appear in the JS console

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
    • MacOS: Desktop
  • 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 verified there are no new alerts related to the canBeMissing param for useOnyx
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • 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 shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • 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)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • 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)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • 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 a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • 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

Android: Native
Android-Native.mp4
Android: mWeb Chrome
Android-mWeb.mp4
iOS: Native
iOS-Native.mp4
iOS: mWeb Safari
iOS-Safari.mp4
MacOS: Chrome / Safari
Mac-Chrome.mp4

@TaduJR
TaduJR requested review from a team as code owners May 11, 2026 14:21
@melvin-bot
melvin-bot Bot requested review from flaviadefaria and situchan and removed request for a team May 11, 2026 14:21
@melvin-bot

melvin-bot Bot commented May 11, 2026

Copy link
Copy Markdown

@situchan 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 removed the request for review from a team May 11, 2026 14:21

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: aa1b8bcdb8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/isReportMessageAttachment.ts Outdated
@TaduJR
TaduJR marked this pull request as draft May 11, 2026 14:27
@codecov

codecov Bot commented May 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Looks like you've decreased code coverage for some files. Please write tests to increase, or at least maintain, the existing level of code coverage. See our documentation here for how to interpret this table.

Files with missing lines Coverage Δ
src/libs/ReportUtils.ts 82.88% <100.00%> (-0.03%) ⬇️
src/libs/isReportMessageAttachment.ts 100.00% <100.00%> (+15.38%) ⬆️
... and 9 files with indirect coverage changes

@TaduJR
TaduJR marked this pull request as ready for review May 15, 2026 19:12

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 21b9a79815

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/isReportMessageAttachment.ts Outdated
@TaduJR

TaduJR commented May 15, 2026

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d42f03f154

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/ReportUtils.ts
@MelvinBot

Copy link
Copy Markdown
Contributor

Code Review

Overall: Solid fix with good test coverage. The root cause analysis is correct — isReportMessageAttachment was broken for .doc/.pdf because the server returns "filename URL" as message.text instead of "[Attachment]", and the canEditReportAction guard was bypassed once isOptimisticAction was cleared to null by successData. The approach of switching to HTML-structure-based detection and simplifying the edit guard is sound.

All CI checks pass. A few items to consider:

isReportMessageAttachment.ts — HTML parser approach

The rewrite from string/regex matching to htmlparser2 streaming is a meaningful improvement. htmlparser2 is already a dependency (v10.0.0) used elsewhere (extractAttachments.ts, SelectionScraper), so no new dep.

Minor concern — per-call parser instantiation: A new HtmlParser is created on every call. This function is called in hot paths: PureReportActionItem (list renders), ReportActionItemFragment, OptionsListUtils (LHN). For typical volumes this is fine — the codebase already accepts this pattern in extractAttachments.ts — but worth noting for future perf profiling if list-heavy chats feel slow.

Edge case clarity: Multiple attachments with no surrounding text → attachmentCount > 0 && !hasOtherContent → returns true. This seems intentionally correct (still attachment-only), but worth a brief comment or test case if multi-attachment-only messages are expected in practice.

ReportUtils.ts — Simplified canEditReportAction

The new guard isOptimisticAttachment = isOptimisticAction && (isAttachmentOnly || isAttachmentWithText) is correct:

  • isOptimisticAction is set to true in buildOptimisticAddCommentReportAction and cleared to null in successData
  • isAttachmentOnly / isAttachmentWithText persist after sync
  • Non-attachment optimistic actions explicitly set isAttachmentOnly: false

This correctly blocks editing only during upload and allows it after sync. Clean improvement over the old two-part guard that was leaking through !null === true.

Tests

Good coverage of both the isReportMessageAttachment behavioral changes and the canEditReportAction lifecycle (optimistic vs. synced). The regression guards for user URLs with data-raw-href and captions after attachments are particularly valuable.

Nitpick

The openAttachmentTag variable name could be slightly more descriptive (e.g., insideAttachmentTag) since it's tracking "are we inside an attachment element's text content" rather than "which tag is open," but this is minor.


Verdict: Looks good. The fix is well-scoped and the test coverage is thorough.

Comment thread src/libs/isReportMessageAttachment.ts Outdated
let attachmentCount = 0;
let hasOtherContent = false;
// Skip the filename text inside an open <a>/<video> so it isn't counted as user content.
let openAttachmentTag: string | null = null;

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.

isInsideAttachmentTag makes more sense.

Also do perf regression test with very long chat history.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

@situchan

situchan commented May 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
    • MacOS: Desktop
  • 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 there are no new alerts related to the canBeMissing param for useOnyx
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • 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 shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • 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)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • 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)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • 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
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • 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 any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • 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 a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • 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

Android: HybridApp
android.mov
Android: mWeb Chrome
iOS: HybridApp
ios.mov
iOS: mWeb Safari
msafari.mov
MacOS: Chrome / Safari
web.mov

@situchan

Copy link
Copy Markdown
Contributor

This happens in production so out of scope but preview changes to normal text even after renaming file only.
I'd expect this to be still an attachment preview with just file name update.

bug.mov

// Skip the filename text inside an open <a>/<video> so it isn't counted as user content.
let openAttachmentTag: string | null = null;

const parser = new HtmlParser({

@situchan situchan May 17, 2026

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.

Minor concern — per-call parser instantiation: A new HtmlParser is created on every call. This function is called in hot paths: PureReportActionItem (list renders), ReportActionItemFragment, OptionsListUtils (LHN). For typical volumes this is fine — the codebase already accepts this pattern in extractAttachments.ts — but worth noting for future perf profiling if list-heavy chats feel slow.

@MelvinBot suggest changes for code optimization to reduce performance impact.
Especially, early return if possible to avoid calling HtmlParser unnecessarily.

@MelvinBot

Copy link
Copy Markdown
Contributor

Two optimizations that avoid the HtmlParser for the majority of calls:

1. Early return when html doesn't contain data-expensify-source

Non-attachment messages will never have this attribute. A simple substring check rejects them before parser instantiation:

if (!message.html.includes(CONST.ATTACHMENT_SOURCE_ATTRIBUTE)) {
    return false;
}

This should go right after the existing translationKey early return (isReportMessageAttachment.ts:18). Most messages in chat are plain text/mentions/links without attachments, so this fast path would skip parsing for the vast majority of calls.

2. Early return for [Attachment] text without translationKey

After the server drops translationKey on sync, image-only messages still come back with text === "[Attachment]" and valid data-expensify-source HTML. For these, the parser will always return true anyway. You could add:

if (message.text === CONST.ATTACHMENT_MESSAGE_TEXT && message.html.includes(CONST.ATTACHMENT_SOURCE_ATTRIBUTE)) {
    return true;
}

This preserves the old fast path for images/common attachments while only falling through to the parser for .doc/.pdf cases where text !== "[Attachment]".

Together these two checks would eliminate parser instantiation for ~95%+ of calls (all non-attachment messages + standard image attachments), limiting the HtmlParser to only the .doc/.pdf edge cases this PR is fixing.

…ent-Edit-comment-option-is-shown-for-.doc-file

# Conflicts:
#	Mobile-Expensify
#	android/app/build.gradle
#	ios/NewExpensify/Info.plist
#	ios/NotificationServiceExtension/Info.plist
#	ios/ShareViewController/Info.plist
#	package-lock.json
#	package.json
#	patches/react-native-onyx/details.md
#	patches/react-native-onyx/react-native-onyx+3.0.69.patch
#	src/ROUTES.ts
#	src/SCREENS.ts
#	src/components/Icon/DefaultBotAvatars.ts
#	src/hooks/useParticipantSubmission.ts
#	src/languages/de.ts
#	src/languages/en.ts
#	src/languages/es.ts
#	src/languages/fr.ts
#	src/languages/it.ts
#	src/languages/ja.ts
#	src/languages/nl.ts
#	src/languages/pl.ts
#	src/languages/pt-BR.ts
#	src/languages/zh-hans.ts
#	src/libs/API/parameters/index.ts
#	src/libs/API/types.ts
#	src/libs/Avatars/PresetAvatarCatalog.types.ts
#	src/libs/ChronosUtils.ts
#	src/libs/Navigation/AppNavigator/ModalStackNavigators/index.tsx
#	src/libs/Navigation/linkingConfig/RELATIONS/SETTINGS_TO_RHP.ts
#	src/libs/Navigation/linkingConfig/config.ts
#	src/libs/Navigation/types.ts
#	src/libs/PolicyUtils.ts
#	src/libs/actions/Agent.ts
#	src/libs/actions/IOU/MoneyRequest.ts
#	src/libs/actions/IOU/index.ts
#	src/libs/actions/connections/index.ts
#	src/pages/iou/request/step/IOURequestStepAmount.tsx
#	src/pages/iou/request/step/IOURequestStepCategory.tsx
#	src/pages/iou/request/step/IOURequestStepCategoryCreate.tsx
#	src/pages/iou/request/step/IOURequestStepDestination.tsx
#	src/pages/iou/request/step/IOURequestStepDistance.tsx
#	src/pages/iou/request/step/IOURequestStepDistanceOdometer.tsx
#	src/pages/iou/request/step/IOURequestStepDistanceRate.tsx
#	src/pages/iou/request/step/IOURequestStepHours.tsx
#	src/pages/iou/request/step/IOURequestStepPerDiemWorkspace.tsx
#	src/pages/iou/request/step/IOURequestStepReport/hooks/useReportSelectionActions.ts
#	src/pages/iou/request/step/IOURequestStepTaxAmountPage.tsx
#	src/pages/iou/request/step/IOURequestStepTimeWorkspace.tsx
#	src/pages/iou/request/step/IOURequestStepUpgrade.tsx
#	src/pages/settings/Agents/AddAgentPage.tsx
#	src/pages/settings/Agents/AgentsPage.tsx
#	src/pages/settings/Agents/EditAgentPage.tsx
#	src/pages/settings/InitialSettingsPage.tsx
#	src/pages/settings/Profile/ProfilePage.tsx
#	src/pages/workspace/WorkspaceInitialPage.tsx
#	src/pages/workspace/travel/WorkspaceTravelInvoicingSection.tsx
#	src/types/onyx/AgentPrompt.ts
#	tests/actions/IOU/IOUSettersTest.ts
#	tests/actions/IOUTest.ts
#	tests/unit/AgentActionTest.ts
#	tests/unit/pages/settings/EditAgentPageTest.tsx
@TaduJR

TaduJR commented May 17, 2026

Copy link
Copy Markdown
Contributor Author

This happens in production so out of scope but preview changes to normal text even after renaming file only.
I'd expect this to be still an attachment preview with just file name update.

@situchan

Should we tackle it here since we got familiar with the flow for this issue?

@situchan

situchan commented May 17, 2026

Copy link
Copy Markdown
Contributor

This happens in production so out of scope but preview changes to normal text even after renaming file only.
I'd expect this to be still an attachment preview with just file name update.

@situchan

Should we tackle it here since we got familiar with the flow for this issue?

No, follow-up if needed. This also requires approval from product team.
Backend update might be required too since data-expensify-source attribute doesn't exist anymore after edit.

TaduJR added 5 commits May 17, 2026 23:37
…ent-Edit-comment-option-is-shown-for-.doc-file

# Conflicts:
#	Mobile-Expensify
#	android/app/build.gradle
#	ios/NewExpensify/Info.plist
#	ios/NotificationServiceExtension/Info.plist
#	ios/ShareViewController/Info.plist
#	package-lock.json
#	package.json
@TaduJR
TaduJR requested a review from situchan May 18, 2026 15:10
@MelvinBot

Copy link
Copy Markdown
Contributor

Updated Code Review (post May 17 changes)

Since the initial review, the PR addressed all feedback — renaming openAttachmentTagdepth, adding fast-path optimizations with WeakMap memoization, and expanding test coverage. All CI checks pass.

What changed since last review:

  • 791171f — Fast-path + memoize: added the two early returns I suggested (no data-expensify-source token → false, text === "[Attachment]"true) plus WeakMap caching keyed on the immutable Onyx Message object. This eliminates parser instantiation for ~95%+ of calls.
  • fabe04b — Renamed variable per situchan's feedback + added multi-attachment-only test case.
  • 4edca7a — Extended test matrix: translationKey semantics, undefined/empty input guards, image/video attachment+text cases.
  • Perf test added (isReportMessageAttachment.perf-test.ts) — 10k-message benchmark confirms −69.5% vs the regex baseline.

Review of current state:

The implementation is clean and well-structured. The layered fast-paths (translationKey → substring check → text === "[Attachment]" → parser) ensure minimal overhead for common cases. The depth counter correctly scopes inner content of attachment tags so filenames/nested markup aren't misclassified as user content.

The canEditReportAction simplification to isOptimisticAttachment is correct — the old guard was fundamentally broken because !null === true neutralized the isAttachmentOnly check after sync. The new logic cleanly expresses the intended behavior: block during upload, allow after sync.

No issues found. Looks good to merge.

@MelvinBot

Copy link
Copy Markdown
Contributor

Regression Analysis

I investigated all callers of the two modified functions (isReportMessageAttachment — 6 call sites, canEditReportAction — all consumers) and the WeakMap memoization safety.

TL;DR: No data-corruption regressions found. All isReportMessageAttachment behavioral changes are bug fixes (.doc/.pdf correctly classified). Two UX items worth confirming are intentional.


No regressions found (all positive behavioral changes)

Every caller that now receives true for .doc/.pdf attachment-only messages benefits from the fix:

Caller Old behavior (broken) New behavior (fixed)
ReportActionItemFragment.tsx:124 Rendered via TextCommentFragment (raw "filename URL") Renders via AttachmentCommentFragment (proper attachment UI)
OptionsListUtils/index.ts:739 LHN showed raw "filename URL" LHN shows "[Attachment]"
ReportActionsUtils.ts:1468 getLastVisibleMessage returned raw text Returns "[Attachment]"
ContextMenuActions.tsx:810 "Copy Message" visible (copied raw text) Correctly hidden for attachment-only
ContextMenuActions.tsx:1298 "Download" missing for .doc/.pdf Now shows Download — getAttachmentDetails correctly parses <a data-expensify-source>
Thread names (ReportUtils.ts:5798, ReportNameUtils.ts:825) Raw "filename URL" "[Attachment]"

WeakMap memoization: safe

Onyx's fastMerge never mutates objects in place — it creates new destination objects. Arrays (like message) are replaced entirely, not merged element-by-element. The successData for AddComment only merges {pendingAction: null, isOptimisticAction: null} without touching the message field, so the same Message references survive with correct cached values. No code path in the codebase directly mutates Message object properties.

Items to confirm are intentional (not regressions per se)

  1. Up-arrow shortcut now lands on attachment-only messages. useLastEditableAction.ts:41 uses canEditReportAction — since synced attachments are now editable, pressing up-arrow could open the edit composer on an attachment-only message showing raw markdown (!(url)). The PR description says this is product-approved behavior, so flagging for awareness only.

  2. Edit composer shows raw attachment markdown. When editing an attachment-only .doc/.pdf, the composer displays !(https://...) via Parser.htmlToMarkdown. Users could accidentally clear this and trigger message deletion (empty edit → deleteReportComment). Again, the PR states this is intentionally allowed post-sync.


Next Steps: Reply with @MelvinBot <your feedback> if you'd like me to dig deeper into any of these areas.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3b2d71d8a9

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/ReportUtils.ts
Comment thread src/libs/isReportMessageAttachment.ts
@situchan

Copy link
Copy Markdown
Contributor

Please merge main

@MelvinBot

Copy link
Copy Markdown
Contributor

Regression Analysis

I reviewed the diff and traced all call sites. Here are the potential regressions, ranked by severity:


1. translationKey guard relaxed — false-positive risk for attachment-only detection

Old behavior: When translationKey was set, required both text === "[Attachment]" AND translationKey === "common.attachment".
New behavior: Only checks translationKey === "common.attachment" — ignores text entirely.

If a message ever has translationKey: "common.attachment" with text !== "[Attachment]" (e.g. attachment+text during optimistic phase), it would be incorrectly classified as attachment-only. This affects:

Severity: Medium. In practice the client sets both text and translationKey consistently during optimistic creation, and the server drops translationKey after sync. But if any code path sets translationKey on an attachment+text message, this would silently eat user content in the display.


2. WeakMap caching ineffective at the OptionsListUtils call site

OptionsListUtils/index.ts:786 constructs a new ad-hoc Message object on every call:

isReportMessageAttachment({text: report?.lastMessageText ?? '', html: report?.lastMessageHtml, type: ''})

Since the WeakMap is keyed by object identity, a fresh object on every render means the cache never hits here. The HTML parser runs on every LHN render for every report whose last message contains data-expensify-source. On a high-traffic account with many attachment messages, this could add up.

Severity: Low-Medium. The perf test covers the hot path for stable objects (list re-renders), but doesn't cover this ad-hoc-object pattern. Worth verifying with the LHN specifically on high-traffic accounts.


3. Case-sensitivity change in attribute matching

Old: Regex with /i flag (case-insensitive).
New: html.includes( data-expensify-source=") — case-sensitive.

If the server ever emits DATA-EXPENSIFY-SOURCE or mixed casing, the new code would miss it. HTML attributes are canonically lowercase, so this is very unlikely.

Severity: Low.


4. canEditReportAction now allows editing synced attachments — intentional but behavioral change

The old code blocked editing when isReportMessageAttachment(message) returned true, regardless of sync state. The new code only blocks during optimistic upload (isOptimisticAction && (isAttachmentOnly || isAttachmentWithText)).

This is explicitly intentional per the PR description, and the old guard was already partially broken (isOptimisticAction cleared to null by successData made the check meaningless for .doc files). The two affected call sites:

Severity: Low (intentional fix, well-tested).


Summary

# Issue Severity Functional risk
1 translationKey check no longer validates text Medium Could misclassify attachment+text as attachment-only
2 WeakMap cache miss on OptionsListUtils ad-hoc objects Low-Medium Perf regression on LHN for high-traffic accounts
3 Case-sensitive attribute matching Low Unlikely server casing mismatch
4 Synced attachments now editable Low Intentional, matches product intent

No showstoppers found. Item #1 is the most worth guarding against — a unit test for {text: "user text", translationKey: "common.attachment", html: "<a data-expensify-source=...>file</a>"} would confirm whether the current behavior is intentional or a gap.

…ent-Edit-comment-option-is-shown-for-.doc-file

# Conflicts:
#	Mobile-Expensify
#	android/app/build.gradle
#	cspell.json
#	ios/NewExpensify/Info.plist
#	ios/NotificationServiceExtension/Info.plist
#	ios/ShareViewController/Info.plist
#	package-lock.json
#	package.json
#	src/components/HTMLEngineProvider/HTMLRenderers/VictoryChartRenderer/components/VictoryChartBar.tsx
#	src/components/HTMLEngineProvider/HTMLRenderers/VictoryChartRenderer/components/VictoryChartLine.tsx
#	src/components/MoneyReportHeaderPrimaryAction/SubmitPrimaryAction.tsx
#	src/libs/Navigation/AppNavigator/Navigators/TabNavigatorBar.tsx
#	src/libs/ReportUtils.ts
#	src/libs/actions/IOU/MoneyRequestBuilder.ts
#	src/pages/TransactionDuplicate/DuplicateTransactionItem.tsx
@TaduJR

TaduJR commented May 25, 2026

Copy link
Copy Markdown
Contributor Author

#90203 (comment)

Invalid

@melvin-bot
melvin-bot Bot requested a review from stitesExpensify May 26, 2026 05:58
@stitesExpensify
stitesExpensify merged commit 445d68a into Expensify:main May 29, 2026
39 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🚧 @stitesExpensify has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@OSBotify

OSBotify commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/stitesExpensify in version: 9.3.90-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

@MelvinBot

Copy link
Copy Markdown
Contributor

Help site review: no documentation changes required

I reviewed the changes in this PR against the help articles under App/docs/articles and no help site updates are needed.

Why: This is an internal bug fix to attachment-detection and edit-gating logic. It changes no user-facing labels, tabs, buttons, settings, or workflows, and it adds no new feature:

  • Code touched is logic-onlyisReportMessageAttachment.ts (structural attachment detection), canEditReportAction in ReportUtils.ts (edit gating), cspell.json, and tests. No UI strings (Edit comment / Delete comment) changed.
  • The documented workflow still matches the UI. The relevant article — Chat Features and Moderation ToolsEdit or Delete Messages — describes right-click / long-press → Edit comment, which is unchanged by this PR.
  • No existing doc is now inaccurate. The only related claim, "You can only edit or delete your own messages," remains correct. No article states that .doc/.pdf attachment messages can't be edited, so there is nothing to correct.

The fix restores the already-agreed product behavior (attachments are editable after sync; only blocked during the optimistic upload window) and corrects the styling/LHN misclassification — none of which alters documented behavior.

Because no changes are required, I did not create a draft help site PR. If you'd like the Edit or Delete Messages section expanded to explicitly call out that attachment messages can be edited after they finish uploading, let me know with @MelvinBot and I'll draft that addition.

@TaduJR, please confirm you agree no help site changes are needed for this PR. If you'd like a docs PR drafted anyway, reply and I'll create one.

@OSBotify

OSBotify commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/lakchote in version: 9.3.90-3 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

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.

5 participants