Skip to content

fix(platform): decode Gmail bodies and render synced mail content - #3987

Merged
larryro merged 5 commits into
mainfrom
fix/gmail-body-utf8-decode
Sep 30, 2026
Merged

larryro merged 5 commits into
mainfrom
fix/gmail-body-utf8-decode

Conversation

@larryro

@larryro larryro commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Two Inbox defects on mail synced from Gmail (the second also affects Outlook):

  1. Garbled bodies. Any non-ASCII text arrives as mojibake: 你今天怎么样 reads ä½ ä»å¤©æä¹æ ·, Grüße reads GrüÃe. Subjects are fine, because Gmail decodes RFC 2047 headers itself.
  2. Attachments can't be opened. Each one shows as a chip with a name and size, but there is no download and no inline cid: image. Outlook messages show no attachments at all.
  3. Inline images render broken even once stored. EmailPreview resolved cid: parts to their signed storage link first, then routed every non-same-origin image through /api/image-proxy. That route has answered 404 since feat(platform): rewrite the AI backend on a minimal YAML-config core #2857 dropped it along with the Convex HTTP router ("re-registers with the chat rebuild"; it never did).
  4. No remote image in any email renders (newsletters, signatures, logos), for the same dead route.

Causes

  1. decodeBase64Url in backend/core/conversations/ingest/normalize_email.ts returned atob(...) directly. That yields one character per byte (Latin-1), so the UTF-8 bytes Gmail sends were never decoded. Gmail's format=full transcodes every text part's body.data to UTF-8 but keeps the original charset label, so the fix decodes UTF-8 and ignores the label. The bug dates from feat: workflow automation templates and integration-linked automations #805 (v0.2.7).
  2. sync_mailbox.fetchOneBody called get_message with { messageId } only, and unwrapFetchedMessage kept only output.message. The Gmail and Outlook connectors download and store attachments only with includeAttachments: true, and no caller ever passed it. Graph lists no attachments on the message itself, so Outlook ingested none. IMAP is unaffected, since it carries bytes inline.

Change

  • Decode: base64url bytes go through TextDecoder as UTF-8. An invalid body is logged instead of dropped silently.
  • Attachments, sync side:
    • When a fetched Gmail or Outlook message has attachments (Gmail lists its parts; Graph raises hasAttachments) and is not already ingested with them settled, the sync fetches it once more with includeAttachments: true.
    • That response is used whole. Each stored fileId becomes the matching part's storageId by id, because Gmail mints attachment ids per fetch. Outlook's attachments come from the connector's list.
    • Existing binding, indexing and read-time presigning then serve the download and the inline images unchanged.
  • Re-fetch guard: the message on the sync cursor is re-fetched every poll. settledAttachmentsOfIngested (in reuse_stored_attachments.ts) hands back the stored references of a message whose parts are all settled (stored, or truncated), so nothing is downloaded or stored twice. reuseStoredAttachments skips its lookup when every part is already settled.
  • Failures: a failed download keeps the metadata-only chips and the mail is still ingested.
  • Gmail size cap: ctx.http carries at most 5 MiB, and Gmail sends attachment bytes base64url inside JSON. A larger part used to fail the whole action, after the parts before it were already stored. get_message and get_attachments now list a part over 3.5 MB as truncated (IMAP's term) instead of fetching it.
  • Inline images (@tale/ui email-preview.tsx): remote images are rewritten to the proxy first and cid: parts resolved after, so an inline part loads straight from its signed link. The stale "Convex storage" line in the rewrite's comment is gone.
  • Image proxy restored (backend/domains/image_proxy/): GET /api/image-proxy again.
    • Session-gated, and charged per person on a new security:image-proxy lane (token bucket: 300 a minute, burst 600).
    • Fetches through safeFetchBinary with a new credentialless option. With no credential to leak, plaintext http: and redirects onto another public host are admitted. Every hop is still resolved, checked and pinned; private and metadata addresses stay refused; a credential header on such a request throws.
    • 10 MB cap, 5 redirects, 10 s timeout, at most 16 fetches in flight per process (bounds memory under a burst).
    • Serves only a raster type detected from the bytes (file-type). SVG and anything else answer 415 whatever the host claims.
    • Responses carry Content-Security-Policy: default-src 'none'; sandbox, private caching, no-referrer and CORP same-origin.
    • Refusals come as coded envelopes: INVALID_IMAGE_URL, IMAGE_HOST_REFUSED, IMAGE_TOO_LARGE, NOT_AN_IMAGE, IMAGE_FETCH_FAILED, IMAGE_FETCH_TIMEOUT (registered in error-codes.md). The path has its own metrics route class.
  • Non-ASCII image URLs: rewriteExternalImageSrcs passed the raw src to btoa, which throws outside Latin-1, so one image URL with a Chinese file name took the whole preview down. It now encodes the parsed href.
  • Docs and manual tests: one sentence on attachments and the Gmail limit in Built-in automations, and one on how remote images load (and what does not appear) on the Home page, each in EN/DE/FR. Manual boxes CONV-F35 and CONV-F36 plus their rows in reference/automation.md.

Not in this PR

  • Stored rows are not repaired. Messages already ingested keep their garbled text and metadata-only chips; sync dedupes by Message-ID and does not re-fetch them. The message on the cursor heals on its next pass.
  • Sent mail: its attachments are stored but not bound to the conversation (as for IMAP today). The shipped packs sync with includeSent: false.
  • Outlook size cap: a message whose attachments total more than 5 MiB still fails the connector's attachment listing, so it keeps no chips.
  • Truncated chips: such a chip shows no reason in the UI (existing gap, IMAP too).

Verification

  • Every new test fails on the old code:
    • normalize_email.test.ts: the old decoder produces the exact string from the report.
    • sync_mailbox.test.ts: six cases (Gmail new, already settled, legacy chip, truncated, failed download; Outlook).
    • reuse_stored_attachments.test.ts: five cases.
    • shipped-connectors.test.ts: runs the real Gmail get_message / get_attachments bodies on the in-process runner.
  • @tale/platform test: 960 files, 80306 tests pass. @tale/docs test: 200 pass. Platform typecheck and lint green; lint:manual and check-guide green on the suite.
  • @tale/ui test: 274 files, 2676 tests pass; the updated email-preview.test.tsx case fails on the old ordering. Platform conversation UI tests: 248 pass.
  • Image proxy: service, route and safe-fetch suites (25 + 53 cases) green, every new case red on the old code. SAST on the new files: 0 findings. Full @tale/platform test: 962 files, 80334 tests pass.
  • Real remote images through fetchProxiedImage (the route's own fetch path, run from a scratch script) for every remote image URL in the dev inbox:
    • 27 of 28 load: PNG, WebP (HubSpot labels it .png), JPEG, and LinkedIn's GIF tracking pixels.
    • The one failure is HubSpot's read-time tracker, which redirects to itself endlessly; it is refused after 5 hops, as intended.
    • http://github.com/fluidicon.png (plaintext plus a cross-host redirect) loads. An SVG answers 415. 169.254.169.254 and 127.0.0.1 answer 403.
    • The route itself needs a backend restart on the dev stack before CONV-F36 can be judged in the browser.
  • Observed live on the dev stack (backend restarted onto this branch): a new QQ Mail → Gmail message with Chinese text and an inline PNG synced, and its body reads 你好啊. The inline part was stored with a storageId by the gated second fetch. The fixed EmailPreview, given that message's real HTML and its presigned link in Chromium, rendered the image (2244×943) straight from the store, not through the proxy. The in-page render used a fresh module import, because this session's git stash had cost Vite its watch on the file. A PDF attachment's Download has not yet been clicked through live (CONV-F35).

Gmail's format=full returns every text part's body.data transcoded to
UTF-8 while keeping the part's original charset label. The normalizer
decoded it with atob alone, which yields one character per byte, so any
non-ASCII body landed in the Inbox as mojibake (你好 → ä½ å¥½). Decode
the bytes as UTF-8 instead, and log an invalid base64url body rather
than dropping it silently.

Already-ingested messages keep their stored text; this fixes new mail.
The mailbox sync fetched Gmail and Outlook messages without
includeAttachments and kept only the message, so every attachment
landed as a metadata-only chip: no stored file, no download, no inline
cid image. Outlook messages showed no attachments at all, since Graph
lists them only through the connector.

When a fetched message has attachments and is not already ingested
with them settled, fetch it once more with includeAttachments and put
each stored fileId on the matching part of that same response (Gmail
mints attachment ids per fetch). The message on the sync cursor is
re-fetched every poll, so a settled one keeps its stored references
instead of storing another copy. A failed download keeps the
metadata-only chips and still ingests the mail.

Gmail sends attachment bytes base64url inside JSON, and ctx.http
carries at most 5 MiB, so a larger part failed the whole action after
storing the parts before it. get_message and get_attachments now list a
part over 3.5 MB as truncated instead of fetching it.
@larryro larryro changed the title fix(platform): decode Gmail message bodies as UTF-8 fix(platform): decode Gmail bodies and store synced mail attachments Sep 30, 2026
EmailPreview resolved cid: references to the caller's signed storage
links first and then routed every remote-looking image through
/api/image-proxy, so an inline image became a proxied fetch of the
platform's own blob store. That route has answered 404 since the
Convex HTTP router was retired, so every inline image rendered broken.

Rewrite remote images to the proxy first and resolve cid: parts after,
so an inline part loads straight from its signed link.
@larryro larryro changed the title fix(platform): decode Gmail bodies and store synced mail attachments fix(platform): decode Gmail bodies and show synced mail attachments Sep 30, 2026
EmailPreview routes every remote image an email draws through
/api/image-proxy, but the route went with the Convex HTTP router in
#2857 and was never registered on the new backend, so it answered 404
and no remote image in any email has rendered since.

GET /api/image-proxy is back as a session-gated door, charged per
person on a new security:image-proxy lane. It fetches through the
SSRF-safe client with a new credentialless option: with no credential
to leak, plaintext http and redirects onto another public host are
admitted, while every hop is still resolved, checked and pinned and
private and metadata addresses stay refused. It caps an image at
10 MB, runs at most 16 fetches at once per process, and serves only a
raster type detected from the bytes; SVG and anything else are refused
whatever the host claims. Responses carry a sandboxing CSP and private
caching.
rewriteExternalImageSrcs passed the raw src to btoa, which throws on
any character outside Latin-1, so one image URL with a Chinese file
name or an internationalized host took the whole email preview down.
Encode the parsed URL's href instead: punycode host, percent-encoded
path, always ASCII.
@larryro larryro changed the title fix(platform): decode Gmail bodies and show synced mail attachments fix(platform): decode Gmail bodies and render synced mail content Sep 30, 2026
@larryro
larryro merged commit 8d39333 into main Sep 30, 2026
69 checks passed
@larryro
larryro deleted the fix/gmail-body-utf8-decode branch September 30, 2026 12:28
yannickmonney added a commit that referenced this pull request Oct 1, 2026
CHAT-F52 now follows the header's Create task and the one-step start.
CHAT-F53 to CHAT-F55, CHAT-B20 and CHAT-A8 cover the task's live row
and its states, the reply's hand-over steps, a hand-over with no agent
anywhere, and the keyboard and screen reader; TASK-F59 covers Create
and start agent on the board. The automation reference names the specs
that own the rest, and the readme counts are current, including the
conversations suite's two boxes from #3987.
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.

1 participant