Skip to content

[Due for payment 2026-07-16] [$250] web-Attachment-Attach image offline and refresh page, the attachment fails to load #93375

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.6-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: https://test-management.browserstack.com/projects/2219752/test-runs/60273287/folder/13176710/41236949/1481940979
Email or phone of affected tester (no customers): lekima20+66106@gmail.com
Issue reported by: Applause Internal Team
Bug source: Regression TC Execution
Device used: Win 11/Chrome
App Component: Chat Report View

Action Performed:

  1. Open https://staging.new.expensify.com
  2. Disable the internet connection in the device
  3. Navigate to a chat and upload an attachment
  4. Verify that image preview appears in the chat immediately
  5. Refresh the page
  6. Enable the internet connection in the device and refresh the page

Expected Result:

Image should appear in the chat without reduced opacity.

Actual Result:

Image is blank. Click on image, it shows "Attachment not found"

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

Bug7178471_1781229316442.Recording__2202.mp4

View all open jobs on GitHub

Applause Internal Information
Exported by: Mita Rachim
Bug ID: 7178471

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @mallenexpensify

Activity

  1. added
    Daily
    Bug
    on Jun 12, 2026
  2. MelvinBot commented on Jun 12, 2026

    @MelvinBot
    Contributor

    Proposal

    What is the root cause of that problem?

    When an attachment is uploaded offline, the optimistic message embeds the file's in-memory blob: URL (web) / file:// URI (native) as the image source, and the AddAttachment request carries the raw File object. Neither survives a page reload, so after a refresh the image points at a dead URL and the upload request is gone — the attachment is permanently stranded.

    The two layers that drop the data:

    1. The optimistic HTML hard-codes the volatile local URI as the canonical source. getUploadingAttachmentHtml builds <img src="${file.uri}" data-expensify-source="${file.uri}" .../> where file.uri is a blob:/file: URL. This HTML is persisted to Onyx via buildOptimisticAddCommentReportAction. The report action survives the reload, but a blob: URL is only valid for the lifetime of the page that created it — after refresh it is dangling, so AttachmentView fails to load it and shows "Attachment not found".

    2. The request queue intentionally cannot persist File/Blob objects. shouldPersistOngoingRequest returns false whenever request.data contains a File/Blob, and the code comment acknowledges this is a hard limitation: "IndexedDB cannot clone native File objects (DataCloneError). These requests cannot survive a crash anyway since File references are lost on restart." So the queued upload is never replayed when the user comes back online.

    The user sees a silent blank image (not a red-brick failure) because the optimistic action keeps pendingAction: 'add' forever while its underlying upload request has silently vanished.

    Failure timeline
    1. Offline — pick file → optimistic action stored with src="blob:..."; API.write('AddAttachment', {file, ...}) pushes a request whose data.file is a File object.
    2. The File is not structured-cloneable, so the persisted queue copy loses the binary (or the persist is skipped entirely).
    3. Refresh (still offline) — Onyx rehydrates the optimistic action (plain JSON, dead blob: src), but the upload request's file is gone.
    4. Back online + refresh — queue flushes whatever remains; the upload never replays. Image is blank → click → "Attachment not found".

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

    Make the offline attachment durable across a reload by persisting the file bytes (not the volatile File/blob: reference):

    • When an attachment is queued offline, write the file contents to a reload-safe store (e.g. read into an ArrayBuffer/base64 and store it under a dedicated Onyx key keyed by the optimistic attachmentID). On app start, reconstruct a File/Blob from that stored data and re-hydrate both the queued AddAttachment request's data.file and a fresh object URL for the optimistic action's source, so the upload replays and the preview renders.
    • Clean up the stored bytes once the server confirms the upload (the real AddAttachment response replaces the optimistic source with the server URL).

    Minimum viable alternative if full persistence is out of scope: detect on app start that an optimistic attachment action exists whose source is a now-invalid blob:/file: URL with no replayable upload request, and mark it failed (errored pendingAction) so the user gets a clear retry affordance instead of a silently broken image.

    What alternative solutions did you explore? (Optional)

    • Storing the attachment in IndexedDB as a Blob directly (IndexedDB can store Blobs; the current limitation is specifically Onyx's JSON/structured-clone path on the request queue) and looking it up by attachmentID on reload.
    • Blocking/queuing the optimistic preview behind a "will upload when online" state and surfacing a non-destructive pending indicator that survives reload.

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

  3. added
    External
    on Jun 12, 2026
  4. added
    Help Wanted
    on Jun 12, 2026
  5. lorretheboy commented on Jun 12, 2026

    @lorretheboy
    Contributor

    Proposal

    What is the root cause of that problem?

    When an attachment is uploaded offline, the optimistic comment is built with an <img src> that points at a local blob: (web) / file: URI:

    App/src/libs/ReportUtils.ts

    Lines 6037 to 6050 in 23e38e8

    const dataAttributes = [
    `${CONST.ATTACHMENT_OPTIMISTIC_SOURCE_ATTRIBUTE}="${file.uri}"`,
    `${CONST.ATTACHMENT_SOURCE_ATTRIBUTE}="${file.uri}"`,
    `${CONST.ATTACHMENT_ORIGINAL_FILENAME_ATTRIBUTE}="${file.name}"`,
    attachmentID && `${CONST.ATTACHMENT_ID_ATTRIBUTE}="${attachmentID}"`,
    'width' in file && `${CONST.ATTACHMENT_THUMBNAIL_WIDTH_ATTRIBUTE}="${file.width}"`,
    'height' in file && `${CONST.ATTACHMENT_THUMBNAIL_HEIGHT_ATTRIBUTE}="${file.height}"`,
    ]
    .filter((x) => !!x)
    .join(' ');
    // file.type is a known mime type like image/png, image/jpeg, video/mp4 etc.
    if (file.type?.startsWith('image')) {
    return `<img src="${file.uri}" alt="${file.name}" ${dataAttributes} />`;

    In parallel, addActions saves the real bytes into a persistent cache (CacheStorage on web, the filesystem on native) keyed by attachmentID:

    if (file) {
    // When we are adding an attachment we will call AddAttachment.
    // It supports sending an attachment with an optional comment and AddComment supports adding a single text comment only.
    commandName = WRITE_COMMANDS.ADD_ATTACHMENT;
    const attachment = buildOptimisticAddCommentReportAction({text, file, reportID, attachmentID, delegateAccountIDParam: delegateAccountID});
    attachmentAction = attachment.reportAction;
    cacheAttachment({attachmentID, uri: file.uri ?? '', mimeType: file.type});
    }

    The problem is the read-back. The optimistic action (with its blob: src) is persisted in Onyx, so it survives a reload — but the browser revokes every blob: object URL when the page unloads, so after a refresh that src resolves to nothing. The inline thumbnail goes blank, and opening it hands the same dead blob: URL to the attachment modal → "Attachment not found".

    The cache has a retrieval half built exactly for this — getCachedAttachment, which rebuilds a fresh object URL from the cached bytes for a given attachmentID:

    async function getCachedAttachment({attachmentID, attachment, currentSource}: GetCachedAttachmentProps): Promise<string> {
    const isStale = attachment ? attachment?.remoteSource && attachment.remoteSource !== currentSource : false;
    if (isStale) {
    // Only re-cache the [markdown-attachment] if it is outdated (updated)
    cacheAttachment({attachmentID, uri: currentSource});
    return currentSource;
    }
    const cachedAttachment = await CacheAPI.get(CONST.CACHE_API_KEYS.ATTACHMENTS, attachmentID);
    const isUncached = !cachedAttachment;
    if (isUncached) {
    return currentSource;
    }
    try {
    const attachmentFile = await cachedAttachment.blob();
    return URL.createObjectURL(attachmentFile);
    } catch (error) {
    Log.warn('[AttachmentCache] Failed to get attachment', {error});
    return currentSource;
    }
    }

    …but it is exported and never called anywhere in the app. The bytes get cached on upload, yet nothing ever reads them back, so the dead blob: URI is all that remains after reload.

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

    Wire getCachedAttachment into source resolution. When an attachment carries an attachmentID and its current source is a local blob:/file: URI (or fails to load), resolve the displayed source from the cache via getCachedAttachment(attachmentID, …) and render the returned object URL instead of the stale src.

    Do it at the shared point both render paths read from — best as a small hook (e.g. useCachedAttachmentSource(attachmentID, source)) used in:

    • the inline chat thumbnail, where ImageRenderer currently passes only the raw blob: src to ThumbnailImage and never forwards attachmentID:

      const previewSource = tryResolveUrlFromApiRoot(htmlAttribs.src);
      // The backend always returns these thumbnails with a .jpg extension, even for .png images.
      // As a workaround, we remove the .1024.jpg or .320.jpg suffix only for .png images,
      // For other image formats, we retain the thumbnail as is to avoid unnecessary modifications.
      const processedPreviewSource = typeof previewSource === 'string' ? previewSource.replaceAll(/\.png\.(1024|320)\.jpg$/g, '.png') : previewSource;
      const source = tryResolveUrlFromApiRoot(isAttachmentOrReceipt ? attachmentSourceAttribute : htmlAttribs.src);
      const alt = htmlAttribs.alt;
      const imageWidth = (htmlAttribs['data-expensify-width'] && parseInt(htmlAttribs['data-expensify-width'], 10)) || undefined;
      const imageHeight = (htmlAttribs['data-expensify-height'] && parseInt(htmlAttribs['data-expensify-height'], 10)) || undefined;
      const imagePreviewModalDisabled = htmlAttribs['data-expensify-preview-modal-disabled'] === 'true';
      const fileType = getFileType(attachmentSourceAttribute);
      const fallbackIcon = fileType === CONST.ATTACHMENT_FILE_TYPE.FILE ? icons.Document : icons.GalleryNotFound;
      const theme = useTheme();
      let fileName = htmlAttribs[CONST.ATTACHMENT_ORIGINAL_FILENAME_ATTRIBUTE] || getFileName(`${isAttachmentOrReceipt ? attachmentSourceAttribute : htmlAttribs.src}`);
      const fileInfo = splitExtensionFromFileName(fileName);
      if (!fileInfo.fileExtension) {
      fileName = `${fileInfo?.fileName || CONST.DEFAULT_IMAGE_FILE_NAME}.jpg`;
      }
      const thumbnailImageComponent = (
      <ThumbnailImage
      previewSourceURL={processedPreviewSource}
      style={styles.webViewStyles.tagStyles.img}
      isAuthTokenRequired={isAttachmentOrReceipt}
      fallbackIcon={fallbackIcon}
      imageWidth={imageWidth}
      imageHeight={imageHeight}
      isDeleted={isDeleted}
      altText={alt}
      fallbackIconBackground={theme.highlightBG}
      fallbackIconColor={theme.border}
      />
      );

    • the opened attachment, where AttachmentView already receives attachmentID but still renders the raw source:

      attachmentID,
      source,

    This fixes both the blank preview and the "Attachment not found" modal from the one cache lookup.

    What alternative solutions did you explore? (Optional)

    On web, also persist a stable source for the attachment (mirroring how the native cache stores a source filepath) and read that back on render. But the bytes are already in CacheStorage, so simply calling the existing getCachedAttachment is the smaller, single-source-of-truth change.

  6. melvin-bot commented on Jun 12, 2026

    @melvin-bot

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

  7. ahmdshrif commented on Jun 12, 2026

    @ahmdshrif
    Contributor

    🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

  8. melvin-bot commented on Jun 12, 2026

    @melvin-bot
  9. changed the title [-]web-Attachment-Attach image offline and refresh page, the attachment fails to load[/-] [+][$250] web-Attachment-Attach image offline and refresh page, the attachment fails to load[/+] on Jun 12, 2026
  10. github-actions commented on Jun 12, 2026

    @github-actions
    Contributor

    ⚠️ @ahmdshrif Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

  11. github-actions commented on Jun 12, 2026

    @github-actions
    Contributor

    ⚠️ @lorretheboy Thanks for your proposal. Please update it to follow the proposal template, as proposals are only reviewed if they follow that format (note the mandatory sections).

  12. 78 remaining items

  13. added
    Daily
    Awaiting Payment
    on Jul 15, 2026
  14. melvin-bot commented on Jul 15, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  15. melvin-bot commented on Jul 15, 2026

    @melvin-bot

    Payment Summary

    Upwork Job

    BugZero Checklist (@mallenexpensify)

    • I have verified the correct assignees and roles are listed above and updated the necessary manual offers
    • I have verified that there are no duplicate or incorrect contracts on Upwork for this job (https://www.upwork.com/ab/applicants/2065274209562742465/hired)
    • I have verified the PR was not reverted
    • I have applied any discounts due to bugs/regressions introduced by this PR
    • I have paid out the Upwork contracts or cancelled the ones that are incorrect
    • I have verified the payment summary above is correct
  16. mallenexpensify commented on Jul 17, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor: @lorretheboy paid $250 via Upwork
    Contributor+: @ZhenjaHorbach due $250 via NewDot

    @lorretheboy can you please accept the job below? Please reply here and tag me once you have.
    If you're not sent an offer in Upwork when you're assigned to an issue, please tag me. If an Upwork job exists, please submit a proposal.
    https://www.upwork.com/jobs/~022078257864148756245

    ^ Test case created. Thx

  17. lorretheboy commented on Jul 18, 2026

    @lorretheboy
    Contributor

    @mallenexpensify Thanks. I accepted the job

  18. mallenexpensify commented on Jul 20, 2026

    @mallenexpensify
    Contributor

    @lorretheboy paid, summary updated above. Thx.

  19. garrettmknight commented on Aug 4, 2026

    @garrettmknight
    Contributor

    $250 approved for @ZhenjaHorbach

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

Metadata

Metadata

Labels

Awaiting PaymentBugDailyExternal

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions