Skip to content

[Test branch] Keep an edited attachment name from collapsing to the form field name - #101756

Closed
MelvinBot wants to merge 3 commits into
mainfrom
claude-attachmentNameResetOnOfflineEdit
Closed

MelvinBot wants to merge 3 commits into
mainfrom
claude-attachmentNameResetOnOfflineEdit

Conversation

@MelvinBot

Copy link
Copy Markdown

Explanation of Change

This is a test branch requested on the linked issue, not a finished fix.

Keep a file attachment intact when its comment is edited was reverted from main in d805f83 while the linked issue was being triaged. This branch re-lands it and then hardens the attachment rename path that the issue reported, so both the original feature and the reported bug can be tested together.

Two commits, kept separate so the second is reviewable on its own:

  1. Re-apply PR Keep a file attachment intact when its comment is edited #99385 — a plain revert of the revert, no other changes.
  2. Harden the rename path — four changes:
    • editReportComment decided whether an edit renamed the attachment by comparing the draft's markdown label against the data-name attribute, but applyLabelToUploadingAttachmentHtml only rewrote the anchor's inner text. Once those two disagreed, every later edit re-renamed the queued file from whatever the label happened to be. The comparison now uses the tag's own current label (new getUploadingAttachmentLabel helper), which makes it idempotent, and applyLabelToUploadingAttachmentHtml keeps data-name in sync so the tag no longer contradicts itself.
    • renameQueuedAttachment now returns the file untouched when the label is empty. A multipart part sent without a filename is stored under the form field name, which is how an attachment ends up called file.
    • renameQueuedAttachment rebuilds a File to change its name, which silently dropped the non-standard uri and source properties the app hangs off file objects. prepareRequestPayload/index.native.ts reads source to find the file on disk, so losing it changes the native upload path. They are now carried across the rebuild.
    • prepareRequestPayload/index.native.ts falls back to the source basename so a part is never appended unnamed.

Unit tests were added for the idempotence of the label comparison, for uri/source surviving the rebuild, and for an empty label leaving the queued filename alone.

Caveat for the reviewer: the analysis behind this pinned the mechanism to the rename path with medium confidence. Walking a first, text-only edit by hand, the draft label and the tag label are equal, so the rename should not fire at all — which means either the label diverges somewhere in the native live-markdown edit composer, or the multipart filename arrives blank and the server falls back to the field name. These changes close both routes, but the repro should be re-run on a device to confirm which one it was.

Fixed Issues

$ #101744
PROPOSAL: #101744 (comment)

Tests

// TODO: The human co-author must fill out the tests you ran before marking this PR as "ready for review".
// Please describe what tests you performed that validate your change worked.

  • Verify that no errors appear in the JS console

Offline tests

// TODO: The human co-author must fill out the offline tests you ran before marking this PR as "ready for review".

QA Steps

// TODO: These must be filled out, or the issue title must include "[No QA]."
// TODO: The human co-author must fill out the QA tests before marking this PR as "ready for review".

  • 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
  • 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.
  • 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.

AI Tests

Run locally by MelvinBot on this branch:

Check Result
npm test -- tests/unit/RequestConflictUtilsTest.ts ✅ 83 passed
npm test -- tests/unit/ReportUtilsTest.ts ✅ 1396 passed
npm test -- tests/actions/ReportTest.ts tests/unit/getAttachmentDetailsTest.ts tests/unit/FileUtilsTest.ts ✅ 363 passed
npm run typecheck ✅ passed
npm run lint-changed ✅ passed
npm run spell-changed ✅ 19 files, 0 issues

Not run: npm run storybook -- --smoke-test --ci and the full npm test suite. Direct npx eslint on src/libs/ReportUtils.ts and src/libs/actions/Report/index.ts reports only pre-existing violations grandfathered by the seatbelt ratchet; none fall on the changed lines.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

MelvinBot and others added 2 commits September 21, 2026 15:32
This reverts commit d805f83, restoring PR #99385
so the follow-up commit can harden the attachment rename path it introduced.

Co-authored-by: Shubham Agrawal <shubham1206agra@users.noreply.github.com>
Compare a draft label against the attachment tag it came from rather than the
original filename, so an edit that leaves the label alone never renames the
queued file, and keep data-name in sync when a rename is applied.

Also stop the rename from blanking a name or dropping the uri and source the
native upload path reads off the file, and fall back to the source basename so
a multipart part is never sent unnamed.

Co-authored-by: Shubham Agrawal <shubham1206agra@users.noreply.github.com>
@codecov

codecov Bot commented Sep 21, 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/ONYXKEYS.ts 100.00% <ø> (ø)
...TMLEngineProvider/HTMLRenderers/AnchorRenderer.tsx 73.91% <100.00%> (+0.38%) ⬆️
src/libs/ExportOnyxState/common.ts 80.95% <ø> (ø)
src/libs/fileDownload/FileUtils.ts 44.98% <100.00%> (+0.64%) ⬆️
src/libs/fileDownload/getAttachmentDetails.ts 100.00% <100.00%> (ø)
...orAttachmentsOnly/BaseAnchorForAttachmentsOnly.tsx 0.00% <0.00%> (ø)
src/libs/ReportUtils.ts 87.52% <97.77%> (+0.10%) ⬆️
src/libs/actions/Report/index.ts 72.56% <95.45%> (+0.79%) ⬆️
src/libs/prepareRequestPayload/index.native.ts 71.05% <0.00%> (ø)
src/libs/actions/RequestConflictUtils.ts 98.30% <80.00%> (-1.70%) ⬇️
... and 2 more
... and 10 files with indirect coverage changes

Wrap the data-name replace() call across lines to match oxfmt's output so the
Oxfmt check no longer reports a diff.

Co-authored-by: Shubham Agrawal <shubham1206agra@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Author

Fixed and pushed. The only real failure was Oxfmt check — src/libs/ReportUtils.ts:6957 had a replace() call on one long line that oxfmt wants wrapped across three. npm run fmt produced the wrap; that's the whole change. Oxfmt is now green.

The other red check, Check independent approval, isn't a code problem — it needs a reviewer approval, not a commit.

Details

Failure output:

> oxfmt --write .
Finished in 1127ms on 9490 files using 4 threads.
src/libs/ReportUtils.ts
Error: Oxfmt diff detected! Please run `npm run fmt` and commit the changes.

Diff (whitespace only):

-    const labelledHtml = uploadingAttachmentHtml.replace(new RegExp(`${CONST.ATTACHMENT_ORIGINAL_FILENAME_ATTRIBUTE}="[^"]*"`, 'i'), `${CONST.ATTACHMENT_ORIGINAL_FILENAME_ATTRIBUTE}="${label}"`);
+    const labelledHtml = uploadingAttachmentHtml.replace(
+        new RegExp(`${CONST.ATTACHMENT_ORIGINAL_FILENAME_ATTRIBUTE}="[^"]*"`, 'i'),
+        `${CONST.ATTACHMENT_ORIGINAL_FILENAME_ATTRIBUTE}="${label}"`,
+    );

AI tests re-run locally on the fix commit:

Check Result
npm run fmt (re-run, idempotent) ✅ no further diff
npm run typecheck ✅ passed
npm run lint src/libs/ReportUtils.ts ✅ passed
npm test -- tests/unit/ReportUtilsTest.ts ✅ 1396 passed

npm run lint-changed couldn't run in this environment (git merge-base failed against the shallow origin/main clone), so I linted the changed file directly instead.

@MelvinBot

MelvinBot commented Sep 21, 2026 •

Copy link
Copy Markdown
Author

🤖 Android test steps verification results: ⚠️ partial

Steps 1-4 pass on standalone Android NewDot: the offline text+attachment message sends as one pending message, long-press offers Edit comment, and the edit keeps both the new text and the attachment under its original name. Step 5 fails — after going back online the queued AddTextAndAttachment request never uploads. It throws TypeError: Cannot assign to property 'name' which has only a getter, retries 10 times, gives up, and the message rolls back to "Unexpected error posting the comment." A control run with no edit fails identically, so the upload failure is not caused by the edit.

Control message 'Control no edit' sent offline with no edit fails with the identical error

Step Status
1. A chat report opens and the composer is usableOpened the self DM "Melvin Tester (you) / Your space" via Search. is visible 'label="Write something..."' and is editable both exit 0; snapshot shows a [text-field] "Write something..." [editable] plus Emoji and Send buttons.
Self DM 'Your space' open with an editable composer
✅
2. Offline: type text, attach a .csv, send as one messageForce offline ON (snapshot contains "You appear to be offline."). Typed "Original caption text", then + → Choose file → melvin-test-report.csv. A single pending report action appeared containing [button] "melvin-test-report.csv" and an attachment-loading spinner. Attachment name before the edit is the original filename.
Offline pending message 'Original caption text' with attachment named melvin-test-report.csv
✅
3. Long-pressing the pending message opens a context menu with "Edit comment"Long-press on the comment node produced a 24-node menu snapshot including [button] "Edit comment" alongside Reply in thread / Mark as unread / Copy message / Copy link / Delete.
Context menu on the pending message showing Edit comment
✅
4. Editing the text and saving keeps both the edited text and the attachmentEdit composer read back as Original caption text\n\n[melvin-test-report.csv](file:///...Receipts-Upload/melvin-test-report_5543271697811769596.csv). Replaced the first line with "Edited caption text", kept the markdown attachment reference, pressed Save changes. Post-save: "Edited caption text  (edited)" with [button] "melvin-test-report.csv" still rendered as a file attachment, still offline/pending.
Still offline after the edit: 'Edited caption text' with the attachment still named melvin-test-report.csv
✅
5. After going back online the attachment uploads and keeps its ORIGINAL file name (not "file"), rendered as a file attachment not a bare linkForce offline OFF; the offline indicator disappeared and the queue flushed, but the request never reached the server. logcat: [Network] Making API request - {"command":"AddTextAndAttachment"} immediately followed by [alrt] ENSURE_BUGBOT unknown API request error caught while processing request - {"message":"Cannot assign to property 'name' which has only a getter"}, then [SequentialQueue] Request failed with error - {"command":"AddTextAndAttachment","errorName":"TypeError"}, retried to "Retry count: 10", then "Request failed too many times, giving up". The optimistic edit rolled back to "Original caption text" with the red "Unexpected error posting the comment." banner. The label stayed melvin-test-report.csv only because nothing ever uploaded — the post-upload name could not be observed. CONTROL: the same flow offline with a second file and NO edit produced the identical TypeError and banner, so this failure is independent of the edit and blocks the step-5 assertion.
Back online: edit rolled back to 'Original caption text' with 'Unexpected error posting the comment'
Control message 'Control no edit' sent offline with no edit fails with the identical error
❌
Notes for the author

Scope: standalone Android NewDot (developmentDebug APK, emulator), App checked out on claude-attachmentNameResetOnOfflineEdit at f4a5e97. Offline was driven with Settings → Troubleshoot → Force offline. The session arrived parked mid-onboarding, so onboarding was completed before the run.

The PR's rename path was never exercised. The attachment label was left unchanged, so renamedAttachmentLabel resolved to undefined and renameQueuedAttachment was never called. The conflict resolver did behave as intended — logcat shows [SequentialQueue] Conflict resolution: REPLACE - {"command":"UpdateComment","replaceIndex":5,"replacementRequest":"AddTextAndAttachment"}, and the replacement carried reportComment: 'Edited caption text' with file.name: 'melvin-test-report.csv' intact.

The blocker is in the send path, not the edit path, and it reproduces with no edit at all. Lead (not confirmed root cause): the queued file is rehydrated from disk as a plain object, so the key === 'file' && initiatedOffline branch in src/libs/prepareRequestPayload/index.native.ts calls readFileAsync, which constructs new File([blob], …). RN's File constructor does this.data.name = name while name is a getter-only accessor on File.prototype — the only .name assignment in reach. readFileAsync fetches the file:// URI through the globally installed react-native-nitro-fetch polyfill, so its Response.blob() result is what gets wrapped.

Also worth a look for the original "renamed to file" symptom: react-native-nitro-fetch's serializeFormData() uses fileName: part.fileName ?? part.name ?? 'file', and RN's FormData.getParts() returns {...value, headers, fieldName} — spreading a File drops name because it lives on the prototype as a getter, landing exactly on the 'file' default.

Test residue: two failed pending messages remain in the test account's self DM.


view run · view recording

@MelvinBot

MelvinBot commented Sep 21, 2026 •

Copy link
Copy Markdown
Author

🤖 Web test steps verification results: ⚠️ partial

Only step 1 passed. Steps 2-5 could not be run on web: the harness's browser driver documents file uploads as out of scope, so the attachment at the centre of this repro could never be added, and the report-action context menu was unreachable (right-click and long-press both return UNSUPPORTED_OPERATION, and hover surfaced no toolbar). A Playwright fallback also failed — standalone sign-in is hard-blocked by an email-provider suspension on the test account, and attaching to the live session ended with that browser being torn down. The PR's fix is not verified in either direction on web.

Session after browser teardown: blank page, agent-device snapshot returns 0 nodes

Step Status
1. A chat report opens and the composer is usableFinished the pending onboarding, opened the Concierge chat and the self DM "Melvin Tester (you)". Snapshot exposed [text-field] "Write something..." [editable] with Send / Emoji / Open actions menu; fill read back as [text-field] "Melvin test message" and Send activated.
Chat report open with text typed into the composer and Send enabled
✅
2. Offline: type text, attach a .csv, send as one messageThe offline half worked: Force offline ON, "You appear to be offline." rendered, and a text-only message sent in the self DM stayed pending. The attachment half never completed. The composer "+" menu exposes "Add attachment", but clicking it opens the native OS file chooser, which the driver cannot service — uploads are documented as out of scope and no command can set a file input. Playwright over CDP got further (typed into #composer, enumerated 4 input[type=file] nodes) but the actions popover never rendered under its forced click, so waitForEvent('filechooser') timed out at 20s and setInputFiles was never exercised.
Composer actions menu showing the Add attachment entry
Troubleshoot page with Force offline enabled
Pending text-only message sent while offline
Standalone Playwright sign-in blocked: email provider has temporarily suspended emails to the test account
Playwright attached over CDP to the live session: self DM, offline banner, pending message
❌
3. Context menu on the pending message offers "Edit comment"Not reachable. There was no attachment message to act on, and the affordance is unavailable on web regardless: click --button secondary and longpress both return UNSUPPORTED_OPERATION, and hovering the report action by coordinates, by ref and by label with --settle added no nodes and rendered no toolbar — so Edit comment could not be surfaced even for the plain-text pending message.
Pending message hovered - no mini context menu toolbar rendered
❌
4. Editing the text and saving keeps both the edited text and the attachmentNot executable — depends on steps 2 and 3, both blocked. No before-edit or after-edit attachment-name capture exists.
❌
5. After going back online the attachment keeps its ORIGINAL file name (not "file"), rendered as a file attachment not a bare linkNot executable. This is the actual bug check and it is NOT verified in either direction. The session browser was torn down (user-data-dir removed, blank page, snapshot returns 0 nodes) before any attachment existed. Neither reopening the session (lifecycle-gated) nor re-signing-in (email suspended) was available.
Session after browser teardown: blank page, agent-device snapshot returns 0 nodes
❌
What this means, and what would actually verify it

Be clear about the status: this run produced no evidence for or against the fix on web. Do not read the ❌ marks as the bug reproducing — they mark steps that could not be executed.

The repro needs a browser the test harness fully owns, so Playwright can both setInputFiles on the composer input and open the report-action context menu without contending with the CI-owned browser. Two workable routes: a Playwright run against a freshly minted dev account (new accounts join without a magic code, so the email suspension does not apply), or a Jest/RTL-level test over the offline edit path.

Two harness gaps this surfaced, worth fixing if web testing of attachment flows is meant to work at all:

  • The web driver cannot upload files, which rules out every attachment-composer flow.
  • Right-click, long-press, and hover-gated menus are unavailable on web, which rules out every report-action context-menu flow.

The attempt to work around the first gap by attaching Playwright to the live session is the most likely cause of the browser teardown. That went beyond the driver's documented scope and cost the session.

For what it's worth, the Android run did exercise this. On [Test branch] Keep an edited attachment name from collapsing to the form field name I reported earlier that steps 1-4 pass on Android but the queued AddTextAndAttachment never uploads — it throws TypeError: Cannot assign to property 'name' which has only a getter and gives up after 10 retries, and a control run with no edit fails identically. That blocker is in the send path, not the edit path, and it will likely need clearing before step 5 can be judged on any platform.


view run · no recording available

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Melvin-Test-Android Melvin-Test-Web Triggers Melvin to run the testing steps of the PR on web

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants