Records Feature record

FDR-008

File Attachments & Video Processing

Active Last reviewed 2026-11-12 Source file

Overview

Users can attach files to messages — images, videos, documents — via drag-and-drop, paste, or file picker. Images are dimensioned and resizable on the fly via signed URLs. When video processing is enabled, new videos are processed into adaptive HLS streams; animated GIFs and historical processed videos retain the MP4 path.

Behavior

  • Reply attribution shows the original message text when it has non-whitespace text. Otherwise, one attachment shows an icon and its translated type label (Image, Video, Audio, or File). Multiple attachments show a paperclip icon and the translated attachment count. The label uses loaded message metadata and does not load thumbnails.
  • Text attachments with a text/* file type open automatically in the large file viewer as selectable monospace text. Line breaks and indentation stay intact, and long lines wrap. HTML keeps its consent step, and Markdown keeps its formatted preview. Text content cannot execute markup or load linked resources. The viewer requests only the attachment from its server or configured asset storage; that system can see the viewer's IP address. It cancels pending reads when the selection changes or the viewer closes, and uses the existing URL refresh and retry controls. Other file types keep their existing preview or download fallback.
  • In the iOS Home Screen app, Download prepares the selected original file. Select Save or share… to open the system share sheet and choose Save to Files or another destination. Chatto shares the file with its original name. The access ticket stays in Chatto. File types that the device cannot share use the download link.
  • PDF attachments open automatically in the browser's native PDF viewer when the browser reports inline PDF support. The file type must be PDF; a .pdf filename alone does not enable the preview. Browsers without this capability show the download fallback without loading the document. Native controls vary by browser. Download stays available when a document cannot render because the browser does not reliably report these failures to Chatto. Preview requests use the attachment server and its configured storage, with no external document-viewer service.
  • The composer accepts files via drag-and-drop, paste, and a file picker button when the viewer has message.attach.
  • A message can have up to 10 attachments. The composer adds only the valid files that fit and shows a warning when it skips extra files. Files still being prepared count toward this limit. A draft change discards unfinished preparation from the previous draft. Changing between the visual and Markdown editors keeps the same draft, including files still being prepared.
  • Draft attachments persist across room switches inside the same session.
  • Message attachments are uploaded through chatto.api.v1.AssetUploadService before message creation. The browser sends bounded unary chunks with SHA-256 checksums, then calls MessageService.CreateMessage with completed attachment asset IDs.
  • A completed asset can be attached only by its uploader and to one exact message. Reusing another member's asset ID, or reusing one's own already-attached asset ID, is rejected.
  • While a message's attachments are being prepared and uploaded, the bundled composer keeps their previews visible, reports committed upload progress for each file, and disables editing and composer actions until the send finishes. A failed send keeps the submitted text and attachments available for correction or retry.
  • A member can add one plain-text description to each message attachment before send. The composer keeps the description in memory and sends it only after the upload returns an asset ID. Descriptions can contain line breaks. Chatto trims outer whitespace, limits each value to 1,000 Unicode characters, and treats an empty value as removal.
  • Message authors can change attachment descriptions during the message-edit window. Effective message.manage permission bypasses the time limit and permits changes to other members' descriptions. A change marks the message as edited and refreshes current message views through the existing bodyless message-edited signal.
  • In messages, hovering over an image, video, audio player, or file card shows its description in a native browser tooltip when a description exists. Attachment action buttons keep their action labels. Keyboard and touch users can read descriptions in the attachment viewer.
  • Image descriptions are alt text, with the filename as fallback. In the shared attachment viewer, static images have a Details panel that starts closed to give the image more space. The panel shows the selected image's description, type, and size beside the image on desktop and below it on smaller screens. The description remains available to assistive technology while the panel is closed. Other file descriptions stay visible beside or below the preview, including before HTML preview consent. Long descriptions scroll without hiding Download or Close. Video, audio, and file controls expose descriptions to assistive technology.
  • One upload size limit applies to all files, including GIFs and videos. The default is 25 MB, set with core.assets.max_upload_size. Video upload enablement is independent of this limit.
  • The deprecated video.max_upload_size setting is a migration input. When set, the larger of that value and the general limit applies to all files. If the general limit is absent, its 25 MB default participates in this comparison. Operators must set the desired general limit and remove the deprecated setting. The old implicit 100 MB video default no longer applies.
  • ServerRuntimeConfig.max_upload_size reports the effective limit. Its deprecated max_video_upload_size alias reports the same value. Client upload validation uses the general limit for all file types.
  • The experimental composer automatically compresses videos above the server upload limit on the device, without contacting another service. The attachment tile appears immediately and shows queued or compression progress in the same area later used for upload progress. Removing the tile cancels processing. The source file stays unchanged; only the compressed copy is uploaded. The primary audio track is retained. A failed preparation stays visible and blocks sending until the member removes that tile. Changing drafts cancels unfinished work; a retained draft shows its cancelled tile as failed. The result must pass the current server upload policy before it becomes sendable.
  • This compression experiment accepts SDR sources up to 3840×2160 pixels and produces at most 100 MiB. It requires browser support for decoding the source and encoding a compatible video/audio pair. Output resolution falls with the video bitrate budget: longest-side caps are 1920 pixels at 2.5 Mbps or more, 1280 at 1.2 Mbps, 854 at 600 kbps, 640 at 300 kbps, and 426 below 300 kbps. Smaller sources are not enlarged; aspect ratio is retained with even output dimensions. These experimental thresholds reduce blocking at low bitrates but do not guarantee visual quality. Very long videos may not fit at the minimum quality budget. HDR conversion, background processing, and guaranteed support across browsers remain open work. Server-side video processing still runs after upload. Suitable outputs can be reused without another video encode; fallback transcoding can still reduce quality.
  • Video uploads require server-side video processing to be enabled. When it is disabled, the composer rejects video/* files immediately and the message-post API rejects them before storage.
  • When video processing is enabled, GIF attachment uploads can exceed the image-decoder frame-count and cumulative-pixel limits. The upload byte, canvas-size, and per-frame pixel limits still apply. Without video processing, the image animation limits still apply. Image transforms keep these limits even for GIFs accepted for video conversion.
  • Thumbnail URLs for GIFs routed to video processing use the generated video thumbnail. They are absent before a thumbnail is available, after processing fails, or when processing completes without a thumbnail. Message previews and room file lists do not request an image transform of these GIFs. Static GIFs and GIFs kept as images retain image thumbnail URLs.
  • Images are inspected for dimensions at upload time and can be resized at render time via URL parameters (width, height, fit mode). Public attachment and avatar APIs expose transform parameters; public server branding images expose canonical URLs only.
  • The room timeline loads attachment images within 960×400 bounds, while the lightbox loads a separate derivative within 2048×2048 bounds. The untouched upload remains available through the viewer’s Download action.
  • The attachment viewer opens and closes with a short zoom and fade. Reduced motion disables the effect.
  • Right-clicking an image attachment in a message opens the message menu with Copy Image. It copies the displayed image as PNG. Other message menu actions remain available. The image URL is not offered as a copy action because it contains a temporary access ticket.
  • When enabled, videos and animated GIFs are processed as durable background jobs. The processing marker commits atomically with the owning message, so a rejected message cannot create work and an accepted message remains queued while workers are offline. Workers may run inside chatto run or as separate chatto asset-processing processes.
  • Processing status: durable STARTED / COMPLETED / FAILED outcomes are stored as asset aggregate events (evt.asset.{assetId}.*) and delivered through the normal live EVT subscription path after room-membership authorization and the applicable message-read check for the owning thread. There is no separate video_processed live event or new runtime KV state for video progress; failed videos keep the original message visible and show a processing-failed state, while the retained original remains available through the attachment's original/download action.
  • Processed video dimensions are display dimensions used for layout, not necessarily raw encoded storage pixels. Non-square-pixel and rotated sources should render in their intended orientation and aspect ratio. The room timeline displays every posted video uncropped at its measured aspect ratio, including unusual near-square dimensions and converted animated GIF loops. The player canvas is bounded to the available timeline width and a maximum height; for ratios beyond 9:16 or 16:9, it uses letterboxing so playback controls remain usable without cropping the video. Video previews include a picture-in-picture control when the browser supports it. Preview actions use the shared corner pill described below. Google Cast, PiP, and fullscreen stay inside the video player. Video previews have no separate viewer opener. Readers without description or delete permission see no pill. Viewing, description, and delete commands stay directly accessible as icons.
  • A thumbnail is generated from an early video frame using the same display dimensions, so non-square-pixel sources do not persist squished or pillarboxed poster images.
  • For newly processed ordinary videos, the public attachment view exposes a signed HLS master-playlist URL. The durable processing manifest stores HLS rendition metadata and no MP4 variant. Existing processed videos are not backfilled; when HLS metadata is absent, the new client continues through their historical MP4 path.
  • Opaque static attachment derivatives use JPEG quality 75. Derivatives that require transparency or animation use lossless WebP, and resized results can be held in the auto-expiring server cache.
  • Browser media uses direct signed asset URLs. Relative attachment URLs are resolved against the server that owns the message or room-file item, so remote-server images, audio, and video can load without cross-site cookies or bearer headers. Chatto-streamed NATS objects are full, non-seekable responses; S3-backed passive media redirects to object storage for byte-range delivery.
  • Playing audio and video attachments stay mounted when their messages scroll out of view in a room or thread timeline. Buffering and seeking keep this protection. Pause, playback end, or a media error releases it. A video in picture-in-picture stays mounted until picture-in-picture ends, so its window stays controllable after a pause. Converted GIF loops do not keep their messages mounted. Retention ends when the attachment, message, or timeline is removed; it does not extend playback across navigation.
  • Clients refresh expiring attachment URL fields through room-scoped AssetService.GetAsset / BatchGetAssets, or by refetching the relevant timeline or room attachment-list page. The timeline, previews, lightbox, downloads, and room-files surfaces refresh before expiry and retry after media load errors.
  • Every message attachment opens in the shared attachment viewer, with a filename header, file type and size, Download, and Close. Static images have a larger dark stage. Viewers can zoom from Fit to 1600% with controls, a wheel or trackpad, double-click, or touch pinch, then drag to pan. Zoom and pan reset when they select another image. The zoom controls stay visible during gallery navigation. They are disabled while the next image preview is unavailable, including after a failed URL refresh. The image keeps its native context menu for right-click, macOS Control-click, and touch press-and-hold, so viewers can copy or save it in the browser or desktop app. Images in the same message form a gallery with previous/next controls and arrow-key navigation that wraps. Gallery selection changes the preview, metadata, and download target within one history entry. Back or Escape closes the viewer and restores focus. The viewer fills small screens and keeps its controls outside the pan surface. Images use bounded derivatives, audio and video use media players, Markdown uses a rendered document preview, and unsupported files show a download-only fallback. Inline audio and video controls remain available in the timeline. Audio has a separate viewer button; video uses its player fullscreen control.
  • Click an image or a converted GIF preview to open the attachment viewer. Converted GIFs have no separate opener icon and show only the frame when the reader has no management actions. Audio attachments have an icon button to open the viewer, with no filename row below the media. The tooltip and accessible label include the filename. Every attachment preview (image, GIF, video, audio, and file) puts its actions in a small pill in the top end corner of its frame. Viewing actions come before permitted management actions. No preview has an action footer. With a mouse or trackpad, the pill shows only when the pointer is on the preview or an action has keyboard focus. With touch input, the pill is always visible. On audio and file cards, the pill ends the card's row, centred on the player or filename. In narrow messages it wraps below the audio player. Unavailable actions leave no gap. Delete uses a trash icon; its confirmation dialog uses the destructive style. Audio attachments use a compact card, like ordinary file cards. Opening the viewer from an audio opener pauses that attachment's inline playback.
  • Ordinary file cards keep the filename as the viewer action. Delete and Edit description use the same corner pill as media attachments.
  • Markdown attachments open a rendered preview automatically. The viewer recognises Markdown document types and .md or .markdown files with a plain-text, generic, or missing type. The preview uses message Markdown formatting, keeps mentions as plain text, and does not run HTML or load embedded images. Document links open only when selected. Long documents scroll while Download and Close stay available. Download saves the original file. A failed preview offers Retry.
  • HTML and XHTML attachments use Download and Show preview controls in this shared viewer. The document stays unloaded until the user selects Show preview. A notice explains that external websites can see the viewer's IP address if the document loads their content. Consent applies only to the current opening. Download saves the original file without enabling the preview. The viewer shows the document type and original file size before and after consent. File size comes from an authenticated metadata read that does not fetch the document. If that read fails, the viewer shows an unavailable size and keeps preview and download available.
  • Original attachments use a browser sandbox unless their type is on a short list of passive types: common raster images, video, audio, plain text, and PDF. Uploaded scripts cannot run as trusted Chatto application code. Chatto stores and sends only canonical content types. A missing or malformed declared type becomes application/octet-stream.
  • The room sidebar Files panel lists current accessible attachments from both root messages and thread replies, grouped by date as Today, Yesterday, This week, This month, then older calendar months. Date groups use the same separated, collapsible sidebar-section treatment as room navigation and remember their expanded state per room. Rows show a thumbnail or file-type icon, filename, and upload time. Selecting a file opens only that file in the shared attachment viewer. Closing the viewer returns to the same list position. A separate circle-arrow button goes to the upload message: it brings a root message into view, or opens the thread pane and highlights a thread reply. These separate actions let users view files without losing their place in the conversation.
  • The Files panel is virtualized in the same way as the room member list (FDR-025). The client mounts only the date headings and rows near the visible part of the list. The next page loads when the end of the full list comes into view.
  • Each room's Files list starts empty and is loaded only when that panel is first opened. Once loaded, incoming message, edit, deletion, and processing updates keep the cached rows current without reloading the whole list; rooms whose Files panel has never opened make no attachment-list request.
  • Deleting a message-owned attachment durably revokes access first, then removes its source/derivative bytes and transform-cache entries. Shared durable-consumer replicas retry failed physical deletion after process restart or replica handover.

Design Decisions

1. Attachment uploads use chunked ConnectRPC sessions

Decision: Public message attachment uploads use AssetUploadService: CreateUpload, UploadChunk, GetUpload, CompleteUpload, and CancelUpload. Chunks are bounded unary ConnectRPC requests instead of browser client-streaming RPCs. Each upload declares the final file size and lowercase SHA-256 digest, each chunk carries its offset and chunk SHA-256, and CompleteUpload verifies the assembled digest before creating the durable asset. CreateMessage accepts only completed, live, room-matching asset IDs uploaded by the caller and atomically attaches each asset exclusively to the message. New sessions accept chunks up to 10 MiB. The client starts at 256 KiB or the server's maximum, whichever is smaller. It adjusts the next chunk toward 15 seconds per request, including server wait time, with at most twofold growth after each success. It uses at least 64 KiB unless the server's maximum is smaller. The final chunk can be smaller. This lets slow connections commit progress frequently while fast connections use larger chunks.

Each chunk request has a 60-second client deadline. After a timeout, the client reduces the attempted chunk size to one quarter, down to its minimum. This permits recovery from a sharp bandwidth drop within the retry budget. Before it sends more bytes after a transient failure, it checks the server's committed offset. It retries transient chunk, status, and completion failures up to four times with increasing, randomized delays. Authorization failures stop the upload. Recovery stays in the same upload session; a page reload does not resume it automatically. The client does not retry session creation because a lost creation response leaves it without the session ID.

Why: Attachments should remain inside the protobuf/ConnectRPC API surface instead of introducing a second REST upload endpoint. Unary chunks work with the current browser Connect stack and give resumable progress through the committed offset. Tradeoff: Clients must hash the full file before completion and issue several RPCs for larger files. Small initial chunks add acknowledgement waits on fast connections. Request duration includes storage and queue time, so a busy server can reduce the chosen chunk size. Extremely slow connections can still exceed the deadline at the minimum chunk size, and prolonged outages exhaust the retry budget. Temporary chunks and open sessions need cleanup if the browser disappears before completion. Retrying a send after the first attempt actually committed must hydrate the created message rather than attach the same asset to a second message.

2. Dual storage backends (NATS ObjectStore + S3)

Decision: Attachments can be stored in NATS ObjectStore (default, good for development and small deployments) or in an S3-compatible bucket (production-grade). Each asset records its storage backend and logical key at upload time; S3 deployments may add a configurable object-key prefix that is applied only at the S3 client boundary. Why: Self-hosters running a single binary shouldn't have to spin up S3 just to send a screenshot. Larger operators need durable, replicated object storage. Supporting both lets us serve both ends of the spectrum. See ADR-021. Tradeoff: Migration between backends or S3 prefixes is operator-managed. Stored asset keys remain prefix-free so moving objects between S3 base paths does not require rewriting Chatto metadata. Ordinary NATS-backed files still use complete non-seekable responses, but processed videos use bounded HLS segments and are seekable on either backend.

3. Video processing uses durable background jobs

Decision: Accepted message work survives restart and worker outages. Media processing uses the shared job system. It can run inside the server process or in a standalone media process. A terminal attachment outcome completes its job, including a failed conversion or deletion. See ADR-123 and FDR-056. Why: Common queue controls let operators inspect and recover worker failures. Tradeoff: Media retries without a limit until it reaches a terminal outcome, so a missing tool or storage outage delays processing instead of failing it. Media has its own worker capacity. Interrupted attempts can repeat processing, so the existing terminal asset rules still control the published result.

4. Animated GIFs go through the video pipeline

Decision: When video processing is enabled, animated GIFs are detected at upload and routed to the video transcoder rather than served as raw images. When video processing is disabled, GIFs remain allowed as image uploads. Why: Animated GIF files are typically much larger than equivalent MP4s, and they're inefficient to decode in browsers. Transcoding to MP4 produces smaller, smoother playback. Tradeoff: A static thumbnail is shown until processing finishes, even for GIFs that would have rendered immediately as-is. Worth it for the playback experience and bandwidth savings.

5. New processed videos persist HLS segments only

Decision: The server inspects uploaded media before it chooses whether to encode the highest rendition. Compatible H.264 MP4 uploads with square pixels, progressive SDR video, and optional stereo AAC-LC audio can retain their source resolution up to a 1920-pixel longest side and a 1080-pixel shortest side. This includes suitable 1080p uploads. The server checks actual media, not a client processing flag. Conservative codec, frame-rate, bitrate, timestamp, and rotation checks exclude uncertain inputs. It packages the source without re-encoding and checks that each segment decodes independently, seek intervals are bounded, and lower renditions share the same presentation timeline and segment boundaries. Lower renditions follow source keyframes without inserting periodic encoder keyframes. Reused and encoded renditions use the same stereo audio layout. Late reuse failures are logged with an asset ID and a bounded reason code; raw media metadata is not included. Any failed reuse check returns to the normal encoding ladder before video segments are uploaded. Thumbnail generation, original retention, authorization, and durable processing outcomes use the same paths.

Normal transcoding temporarily produces H.264 MP4 renditions whose target resolutions are derived from the source display resolution. A 1080p source might yield 720p and 480p; a 480p source skips the higher tiers. Video audio is encoded as AAC stereo so every independently loaded MPEG-TS segment carries a browser-compatible channel layout, including when the upload has quad or another unusual multichannel layout. The normal encoding path forces aligned six-second keyframes, then ffmpeg packages each temporary file into MPEG-TS segments without another encode. Only the thumbnail and segments are uploaded. The terminal manifest records rendition dimensions, peak bandwidth, and each segment's asset ID and exact duration. Chatto generates master and media playlists from that manifest on every authorised request. Animated GIF loops continue using one durable MP4 derivative directly. Why: Reusing a suitable source avoids an unnecessary lossy encode and preserves its detail. Bounded HLS segments provide duration, seeking, and adaptive rendition switching even when the asset backend can only stream complete objects. Generating small playlists on demand avoids storing duplicate MP4 media or request-specific playlist URLs. Generated segments and MP4 derivatives stream to storage without a user upload size limit. A segment can exceed the upload limit if the source requires it; storage capacity and the processing time budget still apply. Tradeoff: Source validation decodes copied segments and can add work before a fallback encode. Reuse is deliberately conservative; rotated, HDR, reordered-frame, and other unsupported sources still use normal transcoding. HLS packaging or segment upload failure is a failed processing outcome for a new ordinary video. The processor publishes that terminal outcome with an independent bounded context, then uses a separate bounded context to tombstone and delete partial derivatives. Cleanup interrupted before every tombstone is written can leave unused storage orphaned until durable failed-generation cleanup replaces this best-effort path. A success append with an ambiguous result is checked by exact event ID. If confirmation also fails, Chatto retains the output rather than risk deleting assets referenced by a committed manifest, which can also leave orphaned storage if the success did not commit. An uncommitted derivative creation has no canonical storage fact and likewise relies on bounded prompt compensation. A processing attempt that exceeds its fixed 30-minute worker budget becomes a terminal failure rather than repeating the same expensive work forever; worker shutdown remains retryable. Historical processed videos are not backfilled; their manifests omit HLS and the new client continues using their MP4 variants. Older clients cannot play new HLS-only manifests, which is an accepted pre-1.0 compatibility break. During a server rollout, every replica behind one endpoint must understand HLS before new HLS-only videos are created: an older replica cannot expose the HLS metadata or serve playlist and segment routes. An older replica can also ignore HLS child IDs while deleting a source; the durable asset-cleanup consumer on a newer replica re-reads the source manifest and tombstones any still-live HLS segments. Videos whose meaningful content occupies only part of the encoded canvas retain that empty space because the player does not guess which parts are safe to crop.

6. Attachments are declared content; derivative manifests are durable events

Decision: AssetCreatedEvent records each uploaded or generated binary as a first-class Asset on evt.asset.{assetId}.asset_created. Asset carries inline storage and flat media metadata such as dimensions, duration, and bitrate; room scope, uploader, and derivative context live on AssetCreatedEvent. Uploaded assets awaiting attachment also record SHA-256, expiry, and video-processing hints. Message posting atomically appends an AssetAttachedEvent for every attachment and an AssetProcessingStartedEvent for newly uploaded video/animated-GIF assets. Durable runtime-unit workers consume the processing facts. After transcoding succeeds, the original upload is retained as source content, and generated thumbnails and HLS segments—or the MP4 derivative for an animated GIF—are appended as derivative AssetCreatedEvents whose owner points at the original asset. Durable failed/unavailable outcomes are recorded with AssetProcessingFailedEvent.failure_code and are mapped to stable client-facing failure reasons. Beta histories remain readable through the asset projection's legacy subscription lanes, with the first surviving message-body reference authored by the recorded uploader treated as owner. Why: Attachments and video derivatives are content metadata, not runtime state. Making assets their own aggregates gives projections a single asset graph (message -> original asset -> derivative assets), keeps binary lifecycle facts out of the room aggregate, and lets future uploads exist outside messages without a parallel asset model. Keeping the original allows future re-encoding, and storing processing outcomes in EVT lets processed playback survive projection rebuilds and storage-boundary cleanup. Tradeoff: Retaining originals costs more storage than the old replace-after-transcode behavior. Processing execution is at least once: the durable Started fact survives crashes, but ffmpeg and storage work may repeat before one terminal event wins. Every write-serving replica must be upgraded together for exclusive attachment to be a security boundary; an older replica neither enforces nor understands AssetAttachedEvent and can reopen attachment aliasing during a mixed-version rollout. Moving new writes from room aggregates to asset aggregates means older beta binaries must not be rolled back after new asset-subject writes have occurred; compatibility is maintained by this and later versions reading both subject shapes, not by rewriting history.

7. Attachment URLs are per-user signed capabilities

Decision: Public attachment APIs expose attachment media as stable asset paths plus per-user access tickets: /assets/files/{assetId}?access={ticket} for originals and /assets/files/{assetId}/image/{width}x{height}/{fit}?access={ticket} for image derivatives. HLS uses a domain-separated, source-video-scoped ticket on /assets/hls/{assetId}/master.m3u8; Chatto generates each playlist with authorised child routes and checks every requested segment against the durable derivative manifest. Attachment, thumbnail, video thumbnail, HLS master, and historical variant URLs expose the ticket expiry so the client can refresh before or after a lazy-load miss. Every fetch verifies that the signed user is still a room member and has broad message.read, or message.read-interactions with a relationship to the asset's owning thread. Why: Cross-origin <img> tags (used when the SPA loads attachments from a remote registered server) can't carry session cookies (SameSite) or Authorization headers. A signed per-user access ticket lets browsers load remote attachments directly, while current membership and applicable permission checks revoke access after an access boundary changes. Tradeoff: The access ticket is a bearer capability — anyone holding it can fetch until the expiry passes, the signed user loses room membership, or the signed user loses applicable channel-room message-read authority. Tickets use hourly issuance buckets and retain 23–24 hours of validity, so repeated reads within a bucket return the same URL while normal rendering, lazy loading, deferred media startup, and lightbox use remain reliable across long-lived room views. Timeline, preview, and room-files clients use the exposed expiry to refresh shortly before it; the attachment viewer refreshes images on opening, refreshes expired URLs before preview or download, and retries media failures once before showing an error. Late refresh results cannot change a closed viewer or a different gallery selection. Media load errors also trigger refreshes. Protected asset responses use private, no-store, so browser-visible protected bytes are not reused as authorization state. HLS segments stream through Chatto on both backends, while short-lived S3 redirects remain reserved for heavy passive originals such as video, audio, and large files of passive types. Rotating [core.assets].signing_secret invalidates all outstanding access tickets.

Decision: HTML and XHTML attachments use a large modal with an initially disabled preview. The user can download the original file immediately or select Show preview after a notice about external connections. Consent is not saved. The preview uses an iframe with no sandbox permissions and sends no referrer. All original attachment responses include nosniff. Responses for all types except a passive allowlist (PNG, JPEG, GIF, WebP, AVIF, video, audio, plain text, and PDF) also include a CSP sandbox. Chatto normalizes the declared content type at upload and again when it serves the file. A missing or malformed type becomes application/octet-stream, so the browser never gets a type that it reads differently from Chatto. Only passive types can redirect to a presigned S3 URL. All other S3-backed attachments stream through Chatto, so the same response policy applies. Why: Users need both viewing and downloading. External document resources can reveal the viewer's IP address, so preview loading requires an explicit choice. Uploaded active content must not become trusted Chatto application code. A sandbox without same-origin privileges preserves the viewing use case while preventing the easiest same-origin stored-XSS path. An earlier denylist of active types missed malformed types such as text/html,. It also missed valid types that can run scripts, such as text/xsl. The policy now allows only known passive types. PDF stays outside the sandbox because Chromium's PDF viewer does not render in sandboxed documents. Tradeoff: Scripts, forms, top-level navigation, and same-origin APIs are restricted inside uploaded active documents. Keyboard events inside the sandbox do not reach the viewer. Users can select Close or move focus to the viewer controls before pressing Escape. S3 deployments also lose the zero-copy redirect fast path for all types except passive types. This includes large archives. Heavy passive originals can still use a short-lived S3 redirect after Chatto authorizes the request.

9. Room Files panel is a read projection, not durable attachment state

Decision: Room.attachments exposes a paginated list of current message attachments for a room. The read uses the Room Timeline projection's compact attachment index to select a page before it loads current message bodies from EVT. It includes thread replies, preserves attachment order within each message, and sorts by newest message first. The bundled client owns one lazy file cache per room in its server-scoped state: opening Files hydrates it once, after which authoritative timeline message snapshots reconcile attachment rows already in the cache and newly posted attachments are inserted directly. Why: Files should disappear from the sidebar when their message body is retracted or the attachment is removed. The frontend shares bounded message reads across timelines, Files, and pins. Each affected message supplies the current attachment data to all loaded views, including Files when a reply's thread is closed. This keeps the views consistent without separate message reads for each panel or repeated full-list reads. Tradeoff: There is no search or media filtering in this iteration. Hydrated room caches consume client memory for the server session, and attachment changes beyond a partially loaded page converge when that page is loaded.

10. Displayed images use bounded derivatives

Decision: Timeline images fit within 960×400 bounds and lightbox images fit within 2048×2048 bounds. Opaque static derivatives use JPEG quality 75, while transparency and animation continue to use lossless WebP. Original uploads remain unchanged and available separately. Why: Timeline frames are much smaller than typical camera and screenshot uploads, and even full-screen viewing rarely benefits from transferring the source resolution. Separate display sizes reduce bandwidth without sacrificing the original file-sharing behavior. Tradeoff: Opaque displayed images are lossy and capped in resolution. Transparent and animated images may see smaller savings because preserving their behavior requires lossless encoding.

11. Message-owned asset deletion is replayable

Decision: A message or attachment delete may tombstone an asset and touch its backing objects only when AssetAttachedEvent names that exact room and message. Historical duplicate references are removed from the aliasing message without deleting the canonical owner's asset. Request paths still attempt immediate NATS/S3 and transform-cache deletion, while shared chatto-asset-cleanup-v1 durable-consumer replicas process canonical AssetDeletedEvent facts and retry each idempotent cleanup independently. The asset ID locates the same aggregate's durable AssetCreatedEvent, which supplies storage metadata even after the in-memory projection drops it. Beta room-scoped histories without a canonical asset creation aggregate are skipped rather than probing guessed object keys. Why: A committed deletion must remain recoverable when immediate storage cleanup fails, the process exits, or another replica committed the event. Resolving the immutable creation fact preserves that guarantee without duplicating storage metadata in the deletion event or depending on a mutable projection. Tradeoff: Each cleanup requires an aggregate-history lookup, and a fresh worker replays prior deletion facts idempotently. Beta room-scoped events cannot gain the same guarantee without a migration or unsafe backend-key inference, and server branding/avatar cleanup remains outside this message-owned worker.

12. Durable worker health is shared and owner-visible

Decision: Owner-only admin diagnostics derive asset cleanup and the other known durable-worker queue states directly from JetStream. The System tab reports inactive, healthy, working, unconfirmed, stalled, or unavailable state plus queue depth, ack-pending deliveries, unresolved redeliveries, and delivery progress. It does not expose asset IDs, filenames, storage keys, raw errors, or a reclaimed-byte estimate. Why: Automatic retry is only operationally useful when self-hosters can tell whether the worker is available and whether durable work remains. Shared consumer state makes that answer consistent regardless of which replica serves the admin request. Tradeoff: Broker state is point-in-time. Waiting pulls demonstrate availability, but an ack-pending delivery without a waiter may be actively handled or awaiting recovery after a crash, so diagnostics report that state as unconfirmed. The unresolved-redelivery count resets as messages are acknowledged and does not identify which current item retried; the consumer also does not expose the age of its oldest pending delivery. Counts describe queued and unacknowledged work, not historical deletion totals, and idempotent cleanup cannot reliably attribute reclaimed bytes.

13. Attachment descriptions are encrypted message metadata

Decision: MessageBody stores one encrypted description envelope per described attachment, keyed by asset ID. Each envelope records its encryption version, the original author's message-body DEK epoch, nonce, and ciphertext. Its authenticated data is domain-separated and binds the description to the room, canonical message, body event, author, asset, key epoch, and description purpose. Every body replacement decrypts descriptions transiently and encrypts them again for the new body event, including linked channel echoes. Obsolete body events use the existing secure-delete process. AssetAttachedEvent remains the permanent asset-to-message ownership link and contains no description. Asset, upload-session state, snapshots, logs, realtime event payloads, and search indexes do not contain description plaintext.

Why: A description can identify a person or disclose message context. It must follow message editing, retraction, secure deletion, and author-key shredding. It describes one use of an asset in one message, so it is not intrinsic file metadata. Permanent asset lifecycle evidence must remain useful after message PII is deleted.

Tradeoff: Hydrating a message or room-file row must decrypt the current description. Editing any message-body field encrypts every retained description again because the body-event ID is part of authenticated data. Existing messages need no migration and return no description. All message-writing replicas must understand this metadata before clients create it. A rollback to an older writer after descriptions exist is not supported.

14. Attachment types share one viewer shell

Decision: Message attachments use one history-backed viewer shell. The shell owns the filename, file metadata, gallery controls, and download action. On desktop, a side panel holds the description, metadata, gallery controls, and Download. Smaller screens place these below the preview. Images use a subtle background without an outline and fit without cropping. Preview components use the existing image and media paths. HTML keeps its per-opening consent gate. Files without a supported preview show a download action without loading their bytes. Gallery navigation stays local to one opening and unmounts the previous media. The dialog fills viewports below 640 CSS pixels and uses a large framed layout on wider screens, with controls outside the preview. Why: Every file needs an accessible download action and consistent dismissal. A shared shell keeps mobile layout and keyboard behavior consistent while preserving image galleries and HTML privacy controls. Tradeoff: Images in one message form a gallery; other attachments open individually. PDF previews depend on native browser support. Plain text, archives, and other unsupported formats have no built-in preview. PDF support adds no document parser, external service, protocol field, or stored-data migration.

15. All attachments share one upload size limit

Decision: GIFs, images, videos, and other files share one configured byte limit. Video upload enablement and processing limits remain separate controls. During migration, an explicitly set legacy video limit can raise the common limit; remove it after setting the desired general limit. Why: Users should not need to convert an animation to another file format to get a larger upload allowance. One setting gives operators and clients one clear policy. Tradeoff: A larger allowance also permits larger documents and images. Image dimensions, frame counts, and processing time still have independent bounds. Operators who relied on the old implicit 100 MB video default must set the general limit explicitly to keep that allowance.

16. Upload and image memory has per-process bounds

Decision: Each server process applies these bounds to uploads and image transforms:

  • CompleteUpload joins the chunks in a temporary file and streams the file to storage. Thus, its memory use does not increase with the file size. For an image, it reads only the image headers to get the dimensions and frame count. It does not decode pixels. Image derivatives from workers use the same header check.
  • GIF attachment uploads use a separate header-only admission check when video processing is enabled. This check does not retain frames, so it does not apply the frame-count or cumulative-pixel limits of image decoders. The video processor keeps its processing time limit and loop controls. Ordinary image checks and worker-generated image derivatives keep the image-decoder limits.
  • At most four UploadChunk requests are in progress, and at most two for one user. Each bot counts as a separate user. Other chunk requests wait before the server reads their body. A request that holds a slot must send its body within five minutes.
  • Concurrent requests for the same image derivative share one transform, and only one of them reads the source. At most two distinct transforms read or hold source files at once. Other transforms wait before opening their source; cancellation ends this wait without a source read. An admitted transform holds its slot through reading, waiting for pixels, and transformation. Success, failure, or cancellation while waiting for pixels releases the slot. A separate budget of 40 million pixels limits decoding work. A large image waits until enough pixels are free, and transforms that start to wait for pixels later wait behind it.
  • When the GOMEMLIMIT environment variable is not set, chatto run sets the Go memory limit to 90% of the cgroup memory limit of the container.

Why: A full decode of a 40 megapixel image needs approximately 160 MB. In a small container, the kernel can stop the process during uploads or when many clients load a new image together. Go does not read the container memory limit, so without a limit the heap can grow to twice the live data before Go frees memory.

Tradeoff: An image with valid headers but damaged pixel data is accepted at upload. Its derivatives fail when a client requests them, and the original stays available for download. Chunk uploads and transforms can wait during peaks, and a client on a link slower than approximately 0.3 Mbit/s cannot send a full 10 MiB chunk. Only two distinct transforms can run concurrently, even for small images. An admitted transform waiting for pixels holds its source bytes, but later requests cannot accumulate an unbounded number of source buffers. This limits concurrent source files rather than total memory: file sizes, pixel formats, output buffers, and results retained by callers vary. An animated GIF counts as at most 40 million pixels although its frames together can have more. The bounds apply to each process, not to the cluster.

17. HEIC attachments keep their original bytes

Decision: The server accepts HEIC still images through both the public and Operator upload APIs. It keeps the original bytes, filename, and content type for download, and generates JPEG or WebP previews on request. Import tools do not need to convert HEIC files before upload.

Why: Imports must preserve the source file and checksum while browsers need a supported display format.

Tradeoff: HEIC image sequences are rejected because their decode cost is not covered by the still-image pixel limit. The bundled frontend retains its upload conversion for older servers.

Permissions

Posting an attachment requires room membership, the relevant message-posting permission (message.post or message.post-in-thread), and message.attach. The message.attach permission is configurable at server, group, and room scope and only gates message attachments; server branding uploads, user avatars, link previews, and attachment deletion use their existing checks.

Reading attachment metadata or bytes requires room membership. Reads also require broad message.read, or message.read-interactions with a relationship to the asset's owning thread. This check applies again when a client uses an existing signed or ticketed asset URL.

Fresh servers seed message.attach for everyone so new deployments keep uploads enabled by default. Existing servers are not automatically backfilled after upgrade; operators should grant message.attach manually or through their chosen RBAC maintenance flow if existing rooms should keep allowing uploads.

  • ADRs: ADR-123, ADR-007 (per-user encryption and crypto-shredding), ADR-021 (dual asset storage), ADR-023 (HMAC-signed image transform URLs), ADR-032 (self-describing signed attachment URLs), ADR-036 (runtime state in RUNTIME_STATE), ADR-041 (runtime units for optional processes), ADR-045 (public API stability tiers), ADR-047 (direct ticketed asset URLs), ADR-066 (durable asset processing runtime unit), ADR-067 (Electron desktop packaging), ADR-069 (explicit durable consumer lifecycle), ADR-080 (explicit message-read permissions), ADR-082 (derived thread interactions), ADR-090 (EVT timeline payload hydration)
  • FDRs: FDR-002 (Replies & Threads), FDR-004 (Message Editing & Deletion), FDR-034 (Chatto Desktop), FDR-039 (Message Access & Interactions)

Records that name this record

Esc