Skip to content

[Due for payment 2026-08-25] [$250] Attachment - Video orientation changes after editing a message #94341

Closed

Description

@applause-bot

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: v9.4.17-0
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from BrowserStack: #93971
Email or phone of affected tester (no customers): n/a
Issue reported by: Applause Internal Team
Bug source: Exploratory - Significant User Experience Deterioration
Device used: Mav 15.4.1 Safari, Chrome
App Component: Chat Report View

Action Performed:

  1. Go to https://staging.new.expensify.com
  2. Go to any chat
  3. Upload a video in portrait orientation
  4. Edit that message and save.

Expected Result:

The video orientation should remain unchanged after editing a message

Actual Result:

Video orientation changes after editing a message

Workaround:

Unknown

Platforms:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome Safari

Screenshots/Videos

Bug7188138_1782176719190.Recording__2451.mp4

View all open jobs on GitHub

Applause Internal Information
Exported by: Murugesan Natarajan
Bug ID: 7188138

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @aimane-chnaif

Activity

  1. applause-bot commented on Jun 23, 2026

    @applause-bot
    Author

    While Applause doesn't embed attachments for this bug, here are the links for quick view:
    https://platform.applause.com/services/links/v1/external/b2cf7491b1c538d351672a70398027b8733ef07e8346cc7b69998b758598efcd

  2. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Jun 23, 2026
  3. MelvinBot commented on Jun 23, 2026

    @MelvinBot
    Contributor

    Proposal / Analysis

    Problem

    Editing (and saving) a chat message that contains an uploaded portrait video flips the video to landscape. Reproducible on web (Chrome/Safari), staging + production, v9.4.17-0.

    Root Cause

    A video's display orientation comes from its data-expensify-width / data-expensify-height attributes. Editing a message round-trips its HTML through Markdown and back to HTML — but the Markdown form of a video is only ![name](url.mp4), which cannot encode width/height. Those attributes survive an edit only via a side-channel videoAttributeCache keyed by the video source URL.

    When that cache lookup misses at save time, the rebuilt <video> tag has no width/height. VideoRenderer.tsx:23-24 then computes Number(undefined) → NaN, and useThumbnailDimensions.ts:19-20 falls back to NAN_ASPECT_RATIO: 1.5 — a 3:2 landscape ratio. So a portrait video renders landscape.

    This is a regression in the videoAttributeCache round-trip wiring (the area touched by #93971). The most likely trigger is a key mismatch: the cache is keyed by the HTML-encoded video source captured during htmlToMarkdown, while the markdown→html rebuild looks it up using an escaped/decoded source. For real attachment URLs (which contain & in query params/auth tokens), the keys diverge, the lookup misses, and dimensions are dropped — which is exactly why PR #93971's regression test passed (it used a clean URL https://example.com/video.mp4 with no special characters).

    Evidence chain (file:line)
    • Markdown can't hold dimensions; cache is the only preservation path. editReportComment rebuilds the edited HTML and threads the cache through: Report/index.ts:3199-3206 and :3242.
    • Cache populated on entering edit, keyed by video source: useDraftMessageVideoAttributeCache.ts:31-37; forwarded on save in useEditMessage.ts:92-103.
    • Serialization & lookup logic lives in expensify-common@2.0.181 ExpensiMark — the html→markdown video rule caches (videoSource, attrs) and the markdown→html rule re-attaches attrCache[videoSource]. The encode/decode/escape ordering between these two is where the key desyncs for URLs containing &.
    • Downstream fallback to landscape: VideoRenderer → NaN width/height → useThumbnailDimensions → NAN_ASPECT_RATIO: 1.5 (all linked above). On web the player can partially self-heal via onloadedmetadata re-measurement (VideoPlayerPreview/index.tsx), but the initial/thumbnail aspect ratio is already wrong, which is what the tester observed.

    Recommended Fix

    Make the video-attribute cache lookup encoding-insensitive so the key can't desync across the markdown↔html round trip — e.g. normalize the key (htmlDecode / sanitizeURL) on both the cacheVideoAttributes setter and the attrCache[videoSource] lookup. The canonical matching logic is in Expensify/expensify-common (ExpensiMark video rules), so the robust fix likely requires a change there (then a version bump in App). An App-side mitigation in the cache wiring (useDraftMessageVideoAttributeCache.ts / editReportComment) may also be possible.

    Regardless of the chosen path, the regression test should be strengthened to use a video URL containing &/query params and assert the rebuilt HTML still contains data-expensify-width/data-expensify-height.

    ⚠️ One thing to confirm before implementing: that the cache miss is caused by the &-encoding desync (vs. the module-singleton cache being cleared/clobbered by a concurrent mount). Both produce the identical NaN→landscape symptom. Inspecting a real saved Edit_Comment payload for a portrait video — does the post-edit HTML drop data-expensify-width/-height, and does the source URL contain &? — would settle it.

    Related issues

    None of the open issues matched this exact regression (the "orientation/landscape" matches were unrelated layout/a11y bugs).


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/94341) to create a draft PR.
    To refine: @MelvinBot <your feedback>
    To reject: Explain why you are rejecting Melvin's proposal.

  4. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Jun 23, 2026
  5. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on Jun 23, 2026
  6. MobileMage commented on Jun 23, 2026

    @MobileMage
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-06-23 17:24:43 UTC.

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    When a chat message that contains a portrait (e.g. 1080×1920) video attachment is edited and saved, the video re-renders with the wrong orientation/aspect ratio — a portrait clip is shown in a landscape (≈1.5) frame. The video itself is unchanged; only its on-screen dimensions flip after the edit round-trip. This reproduces on web (Chrome/Safari) and is independent of the actual edit text.

    What is the root cause of that problem?

    The orientation of a video preview is driven entirely by the data-expensify-width / data-expensify-height attributes that live on the stored <video> HTML. VideoRenderer reads them into videoDimensions={{width, height}} and hands them to useThumbnailDimensions. When either value is missing/NaN, useThumbnailDimensions does not fall back to the real ratio — it returns a fixed landscape ratio:

    if (!width || !height) {
        return {width: fixedDimension, aspectRatio: CONST.THUMBNAIL_IMAGE.NAN_ASPECT_RATIO}; // 1.5 → landscape
    }

    const thumbnailDimensionsStyles = useMemo(() => {
    if (!width || !height) {
    return {width: fixedDimension, aspectRatio: CONST.THUMBNAIL_IMAGE.NAN_ASPECT_RATIO};
    }

    So a portrait video that loses its width/height ends up rendered at 1.5:1. The question is why the edit drops those attributes. The edit write-path is editReportComment → handleUserDeletedLinksInHtml, which re-serializes the edited draft markdown back to HTML via getParsedMessageWithShortMentions with extras: {videoAttributeCache}. The draft markdown only carries ![name](source) — the dimensions are NOT in the markdown. They are re-attached purely by an in-memory cache lookup keyed on the video source string:

    const htmlForNewComment = getParsedMessageWithShortMentions({
    text: newCommentText,
    userEmailDomain,
    availableMentionLogins: allPersonalDetailLogins,
    parserOptions: {
    extras: {videoAttributeCache},
    },
    });

    I reproduced the full round-trip with the actual expensify-common parser. When the cache lookup misses (empty cache, or the draft's source string doesn't exactly match the key captured from data-expensify-source), the parser emits a <video> tag with no dimension attributes: <video data-expensify-source="…/w_hash.mp4" >Recording.mp4</video>. The edited action's HTML is then persisted without data-expensify-width/height, so on every subsequent render videoDimensions is {NaN, NaN} and the portrait clip is forced to the landscape NAN_ASPECT_RATIO. The cache is fragile because the value is re-built per edit by useDraftMessageVideoAttributeCache keyed on the raw source, and any divergence between that key and the source the parser sees in the draft markdown (query-string sources like ?encryptedAuthToken=…, HTML-entity escaping of & → &amp; under shouldEscapeText: true, or a not-yet-repopulated cache) silently drops the attributes. (Note: PR #93971 is the regression-test PR, but it only swapped allPersonalDetails for a threaded personalDetails arg in this same function — it did not touch the video-attribute path, and this bug reproduces in production where #93971 isn't shipped, so the cache fragility is pre-existing.)

    What changes do you think we should make in order to solve the problem?

    Make the write-path resilient so the edit can never strip dimensions that were already present on the original action. In editReportComment (src/libs/actions/Report/index.ts), we already have the original action HTML (originalCommentHTML from getReportActionHtml(originalReportAction)). Before building optimisticReportActions, re-apply any data-expensify-width/data-expensify-height/data-expensify-thumbnail-url/data-expensify-duration from the original <video> (matched by data-expensify-source) onto the freshly parsed htmlForNewComment for any <video> that lost them. Concretely, seed the cache from the original HTML as the source of truth rather than relying solely on the transient module-level draftMessageVideoAttributeCache:

    // Build a guaranteed cache from the persisted action HTML, then merge the draft cache on top
    const fallbackVideoCache: Record<string, string> = {};
    Parser.htmlToMarkdown(originalCommentHTML ?? '', {cacheVideoAttributes: (src, attrs) => (fallbackVideoCache[src] = attrs)});
    const mergedCache = {...fallbackVideoCache, ...videoAttributeCache};

    Passing mergedCache into handleUserDeletedLinksInHtml guarantees the dimension attributes are re-attached from the original action even when the draft cache is empty or keyed slightly differently, so the saved HTML keeps data-expensify-width/height and the portrait ratio is preserved. This is safe because it only adds attributes that already existed on the original action keyed by the exact same source, and it does not alter text/link/mention handling.

    What alternative solutions did you explore? (Optional)

    Hardening only the read side — making useThumbnailDimensions fall back to measuring the real video instead of the 1.5 NAN_ASPECT_RATIO — would mask the symptom but still persist HTML that has lost its dimensions, breaking native (which has no off-screen web measurement) and the attachment carousel; fixing the write-path keeps the stored HTML correct for every consumer.

  7. lorretheboy commented on Jun 23, 2026

    @lorretheboy
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-07-23 16:17:49 UTC.

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    A portrait video uploaded to a chat on web renders with a landscape (3:2) aspect ratio in the chat preview. The issue title frames this as an edit bug, but editing is only one of several triggers — it also reproduces when navigating away via the LHN and back, and on a plain page refresh, without ever touching the edit flow.

    What is the root cause of that problem?

    Uploaded attachment videos are persisted with zeroed dimension attributes. The server-stored report-action HTML looks like this (verified directly in Onyx for the repro report):

    <video data-expensify-source="https://staging.expensify.com/chat-attachments/.../w_....mov"
           data-expensify-width=0 data-expensify-height=0 data-expensify-duration=0 ...>ios-app-72.mov</video>

    VideoRenderer reads those attributes into videoDimensions, so it passes {width: 0, height: 0}:

    const {report, action} = useShowContextMenuState();

    With no valid stored dimensions, useThumbnailDimensions falls back to a hard-coded landscape ratio (NAN_ASPECT_RATIO: 1.5):

    const aspectRatio = (height && width / height) || 1;
    if (width > height) {

    So the real orientation is never carried by the stored attributes — it can only come from the web-only client-side measurement in VideoPlayerPreview, which probes the file with a throwaway <video> element and stores the result in webMeasuredDimensions:

    useEffect(() => {
    if (!videoUrl || getPlatform() !== CONST.PLATFORM.WEB) {
    return;
    }
    const video = document.createElement('video');
    video.onloadedmetadata = () => {
    if (video.videoWidth === videoDimensions.width && video.videoHeight === videoDimensions.height) {
    return;
    }
    setWebMeasuredDimensions({
    width: video.videoWidth,
    height: video.videoHeight,
    });
    };
    video.src = videoUrl;
    video.load();
    return () => {
    video.src = '';
    };
    }, [videoUrl, videoDimensions.width, videoDimensions.height]);

    That measurement is the single point of failure, and it breaks in two independent ways:

    1. The probe URL is unauthenticated. It sets video.src = videoUrl using the raw source. Real attachments live behind auth and require an encryptedAuthToken query param (the same way BaseVideoPlayer builds its source). For a protected attachment the request is rejected, onloadedmetadata never fires, webMeasuredDimensions stays null, and the preview falls back to videoDimensions {0, 0} → landscape. This is why the bug reproduces on a fresh load / refresh with no edit at all.

    2. webMeasuredDimensions is local React state. Any remount — editing and saving, LHN navigation and return, or a refresh — resets it to null. Even if the probe had succeeded before, the correct dimensions are gone after the remount and the preview snaps back to 1.5.

    Editing is therefore a trigger (it forces a re-render/remount), not the root cause. It only reproduces on web because the whole measurement block is web-only, which matches the reported platforms (Chrome / Safari desktop only).

    Note: this is not introduced by the referenced PR #93971 — that change only threads personalDetails into editReportComment / handleUserDeletedLinksInHtml and leaves the video path unchanged. The zeroed dimensions and the fragile web measurement predate it.

    Correction vs. the "override" theory

    An earlier reading blamed the measurement for overriding valid portrait attributes with a rotation-unaware landscape size, and proposed making the measurement a pure fallback. That does not hold up against the data:

    • The stored attributes are 0/0 (invalid), not valid portrait, so there is nothing valid to override — the code already falls through to the measurement.
    • Once the probe is authenticated, the browser returns the correct portrait size (measured 0.485876 / 1), i.e. it is not a rotation-unaware landscape value.

    Making the measurement a fallback is necessary but not sufficient: with stored dims at 0/0 the fallback is still null because the probe itself fails on the protected URL. That is why fallback-only proposals didn't fix the bug in practice.

    What changes do you think we should make in order to solve the problem?

    Fix it entirely in VideoPlayerPreview (no parser, edit-path, or useThumbnailDimensions changes) by making the measurement both authenticated and durable, and by treating valid stored dimensions as authoritative.

    1. Add src/components/VideoPlayerPreview/videoDimensionUtils.ts — a small module holding:

    • measuredVideoDimensionsCache: Map<string, Dimensions> — a module-level cache that survives remounts.
    • areVideoDimensionsValid(dims) — true only for finite, positive width and height (so 0 / NaN / Infinity are invalid).
    • getCachedVideoDimensions / cacheVideoDimensions — read/write the cache (never caches invalid dims).
    • getAuthenticatedVideoSourceURL(videoUrl, encryptedAuthToken) — mirrors BaseVideoPlayer: pass-through for blob: / file://, otherwise append the auth token, plus the #t=0.001 skip tag.

    2. Update src/components/VideoPlayerPreview/index.tsx:

    • Probe with the authenticated URL so onloadedmetadata fires for protected attachments:
      const metadataProbeURL = useMemo(() => getAuthenticatedVideoSourceURL(videoUrl, encryptedAuthToken), [videoUrl, encryptedAuthToken]);
    • Valid stored dimensions win; measurement is only a fallback when they're absent/invalid:
      const hasValidStoredDimensions = areVideoDimensionsValid(videoDimensions);
      const measuredDimensions =
          isWeb && videoUrl && !hasValidStoredDimensions && areVideoDimensionsValid(webMeasuredDimensions) ? webMeasuredDimensions : videoDimensions;
    • Seed webMeasuredDimensions from the cache on mount so a remount restores the orientation immediately (no landscape flash), and write successful measurements back to the cache (in both the probe's onloadedmetadata and onSourceLoaded). Skip the probe entirely when hasValidStoredDimensions.
    • Carry the measurement across the blob: → server-URL swap that happens when an upload finishes, so the just-measured portrait dims aren't lost. This is done during render (the recommended "adjust state on prop change" pattern) to avoid the react-hooks/set-state-in-effect lint rule.

    This keeps the original orientation across edits, LHN navigation, and refresh, while still letting the measurement supply dimensions for videos stored without them.

    What alternative solutions did you explore? (Optional)

    Fix it at the data level so the rebuilt comment carries real dimensions: have the edit round-trip in editReportComment restore data-expensify-width / height from draftMessageVideoAttributeCache, and/or persist non-zero dimensions server-side on upload. If the attributes were reliable, the preview would never need to measure. This is the deeper fix but touches the shared parse/cache path and doesn't help the non-edit triggers (LHN nav, refresh) or already-stored 0/0 videos, whereas the preview-level change above is web-isolated and stops every trigger.

  8. melvin-bot commented on Jun 23, 2026

    @melvin-bot

    Triggered auto assignment to Contributor-plus team member for initial proposal review - @ChavdaSachin (External)

  9. changed the title [-]Attachment - Video orientation changes after editing a message[/-] [+][$250] Attachment - Video orientation changes after editing a message[/+] on Jun 23, 2026
  10. melvin-bot commented on Jun 23, 2026

    @melvin-bot
  11. godzillaxbox19982014-lgtm commented on Jun 23, 2026

    @godzillaxbox19982014-lgtm

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    [$250] Attachment - Video orientation changes after editing a message

    What is the root cause of that problem?

    I traced this to the path that handles the issue-specific state:

    • src/pages/inbox/report/ReportActionCompose/useAttachmentPicker.ts:53 (useFilesValidation): const {validateFiles, PDFValidationComponent, ErrorModal} = useFilesValidation(onFilesValidated);
    • src/pages/inbox/report/ReportActionCompose/useAttachmentPicker.ts:97 (useAttachmentPicker): return {pickAttachments, PDFValidationComponent, ErrorModal};
    • src/pages/inbox/report/actionContents/ChatMessageContent.tsx:48 (attachmentContextValue): const attachmentContextValue = isOnSearch ? {type: CONST.ATTACHMENT_TYPE.SEARCH} : {reportID, type: CONST.ATTACHMENT_TYPE.REPORT};
    • The local evidence matches this recurring failure shape: the composer visibility gate and recipient lookup are derived from different Onyx selector states. Here, src/pages/inbox/report/ReportActionCompose/useAttachmentPicker.ts:53 and src/pages/inbox/report/ReportActionCompose/useAttachmentPicker.ts:97 do not agree on the same the issue-specific state value, so the user-visible path can show a missing or stale state even though nearby data already has the needed context.

    What changes do you think we should make in order to solve the problem?

    • Update src/pages/inbox/report/ReportActionCompose/useAttachmentPicker.ts:53 to derive the issue-specific state from the report/transaction source that owns this flow before the value is consumed.
    • Carry the same normalized value through src/pages/inbox/report/ReportActionCompose/useAttachmentPicker.ts:97; that follows the safer family move to derive the recipient accountID once, then let both the eligibility selector and recipient selector use that same ID, so the write/optimistic/read paths agree instead of only changing the visible component.
    • Keep the change inside the Chat Report, Composer, Recipient Local Time surface and avoid changing chat composer rendering, Onyx selector churn.

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    1. Add or update a regression in tests/unit/ComposerLocalTimeTest.tsx for the exact issue flow: [$250] Attachment - Video orientation changes after editing a message.
    2. Cover the counter-case near src/pages/inbox/report/ReportActionCompose/useAttachmentPicker.ts:53 so valid existing the issue-specific state behavior still works.
    3. Manually repeat the issue steps after the patch and confirm the visible state/action is no longer stale.

    What alternative solutions did you explore? (Optional)

    • I would not add a broad new condition outside these referenced paths; the safer fix is to keep the issue-specific state consistent at the first read/write boundary shown above.
  12. aswin-s commented on Jun 23, 2026

    @aswin-s
    Contributor

    🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

  13. 82 remaining items

  14. MelvinBot commented on Aug 18, 2026

    @MelvinBot
    Contributor

    Short answer: it's not the linked PR (#93971). The web-only regression was introduced by the expo-av → expo-video migration — originally #66793, and currently in production via the re-landed #75270 ("Expo-av to expo-video migration after revert", merged 2026-01-27).

    Why not #93971: that's the BrowserStack/regression PR the report auto-linked — it only threads personalDetails into editReportComment/handleUserDeletedLinksInHtml and never touches the video path. The bug also reproduces in production, where a day-old PR isn't deployed. It surfaced the bug during exploratory testing; it didn't cause it.

    What the migration changed (the actual mechanism): On web, VideoPlayerPreview measures the video's real dimensions and overrides the stored ones. Before the migration (≤ v pre-expo-video), that measurement came from the mounted, authenticated player via its onReadyForDisplay/srcElement event — so it worked. The migration replaced it with a separate offscreen probe that loads the raw, unauthenticated URL:

    • VideoPlayerPreview/index.tsx:80 creates document.createElement('video') and :90 sets video.src = videoUrl — the raw source, without the encryptedAuthToken that BaseVideoPlayer appends. For a protected chat attachment the request is rejected, onloadedmetadata never fires, and webMeasuredDimensions stays null.
    • The result is held in transient local state (:67), so any remount — editing, LHN navigation, or a plain refresh — resets it. With no valid stored dimensions to fall back on, useThumbnailDimensions returns the hard-coded landscape NAN_ASPECT_RATIO: 1.5, flipping a portrait video to landscape.

    Editing is therefore a trigger (it forces a remount), not the root cause — which is consistent with the proposals reporting the same flip on refresh/LHN-nav with no edit at all.

    Git-history evidence for the bisection

    One caveat to confirm: at least one proposal inspected Onyx and found the stored attributes are literally data-expensify-width=0 data-expensify-height=0 (zeroed at upload). If that's server-side, it's a contributing factor independent of App — but the web-only symptom (only reproduces on desktop Chrome/Safari) points squarely at the migration's unauthenticated-probe measurement path above, since that block is the only web-gated code in the flow.

  15. melvin-bot commented on Aug 21, 2026

    @melvin-bot

    @nkdengineer Whoops! This issue is 2 days overdue. Let's get this updated quick!

  16. melvin-bot commented on Aug 24, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  17. melvin-bot commented on Aug 24, 2026

    @melvin-bot

    Payment Summary

    Resolving PRs:

    BugZero Checklist (@mallenexpensify)

    • I have confirmed assignees, roles, and Upwork contracts look correct
    • I have paid out Upwork contracts / manual NewDot requests
    • [BugZero Assignee] I have created a GH issue for creating/updating the regression test once above steps have been agreed upon
  18. mallenexpensify commented on Aug 26, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor: @nkdengineer due $250 via NewDot
    Contributor+: @aimane-chnaif due $250 via NewDot

  19. garrettmknight commented on Sep 14, 2026

    @garrettmknight
    Contributor

    $250 approved for @aimane-chnaif

  20. twisterdotcom commented on Sep 18, 2026

    @twisterdotcom
    Contributor

    $250 approved for @nkdengineer in Report ID: R004MP3TQTwm.

    Zapier Logs Run ID: 00040eee-a90e-a63f-d73f-433ff725f1a4

    SO: https://stackoverflowteams.com/c/expensify/questions/7582

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

Metadata

Metadata

Labels

Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions