فهرست منبع

Render chat message images and profile avatars

The chat timeline now draws image attachments, GIFs and link-preview images inline, and message avatars and the New DM picker use the real profile picture (the initial is shown until it loads or when there is none).

- ucmd_chat.c: resolve picture/attachment URLs against the server, parse attachment/gif/preview images and authorPicture, lay out and blit the cached RGB565 bitmaps, and keep the timeline pinned at the bottom while image heights settle.  Pictures are fetched lazily through the existing uhttp connection and cookie jar, one per main-loop pass, then decoded by the image library.  Message images live in a 16-entry/6 MB LRU (480x320 max, 4 MB fetch); avatars in a 64-entry 32x32 cache.
- Makefile: link the image decoders and inflate into ucmd_chat.elf.
- tools/mock_chat.py, qmp_chat_test.py: avatar and attachment endpoints, a seeded image message, and checks that both are fetched.
- AGENTS.md and docs (network, graphics, userland) updated.

make test-chat and make test-chat-e2e pass; the e2e screenshot shows the image and real avatars.
Johannes Zellner 1 هفته پیش
والد
کامیت
397b6a6b31
8فایلهای تغییر یافته به همراه746 افزوده شده و 41 حذف شده
  1. 26 14
      AGENTS.md
  2. 4 2
      Makefile
  3. 3 2
      docs/graphics.html
  4. 11 0
      docs/network.html
  5. 1 1
      docs/userland.html
  6. 91 15
      tools/mock_chat.py
  7. 4 0
      tools/qmp_chat_test.py
  8. 606 7
      ucmd_chat.c

+ 26 - 14
AGENTS.md

@@ -1314,14 +1314,22 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   since the floppy needs IRQ 6.
 - **Chat client**: `ucmd_chat.c` (`chat [config-path]`, top-bar `Chat`
   button) is a native Cloudron Chat client on ngui: channel/DM sidebar with
-  unread badges, presence dots and previews; a timeline with initial-letter
-  avatars, author grouping, UTC times, day headers, reply snippets and an
-  attachments/thread/reaction line; a composer; browse/join and new-DM
-  pickers.  It talks to the Chat REST API (`/api/me`, `/api/channels`,
-  `/api/dms`, `/api/channels/public`, `/api/users`, messages with
-  `?limit=50`, `&before=` and `&after=`, POST messages with a `clientId`,
-  `/read`, `/join`, `/api/dms`) through one `struct uhttp` with a cookie
-  jar.  No WebSocket: the open conversation is polled every 2 s (5 s
+  unread badges, presence dots and previews; a timeline with profile-picture
+  avatars (initials until the picture loads, or when there is none), author
+  grouping, UTC times, day headers, reply snippets, inline image
+  attachments/link-preview images and an attachments/thread/reaction line;
+  a composer; browse/join and new-DM pickers.  It talks to the Chat REST API
+  (`/api/me`, `/api/channels`, `/api/dms`, `/api/channels/public`,
+  `/api/users`, messages with `?limit=50`, `&before=` and `&after=`, POST
+  messages with a `clientId`, `/read`, `/join`, `/api/dms`) through one
+  `struct uhttp` with a cookie jar.  Message images and avatars use the same
+  uhttp connection and cookie jar, are fetched one per main-loop pass, and
+  are decoded by the in-tree image library (PNG/JPEG/GIF first
+  frame/BMP/TGA/PNM/ICO/PAM).  They live in a 16-entry, 6 MB message-image
+  LRU plus a 64-entry avatar cache.  The fetch is capped at 4 MB and the
+  decoder at 4 MP / 12 MB of scratch.
+
+  No WebSocket: the open conversation is polled every 2 s (5 s
   unfocused), the directory every 12 s (20 s), polling waits 1 s after
   input, and errors back off 2/5/10/30 s.  An open TCP socket pauses the
   netkexec watcher (`tcp_client_count()`), so keep-alive is kept only while
@@ -1356,8 +1364,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `img_png.c`, `img_bmp.c`, `img_gif.c`, `img_jpeg.c`, `img_tga.c`,
   `img_pnm.c`, `img_file.c/h` — freestanding RGB565 decoders with an optional
   8-bit alpha plane.  The codecs are independent of the OS and ngui: they take
-  an input buffer plus a caller-provided `struct img_mem` arena, so a browser
-  can link the same objects and decode HTTP bodies.  `inflate.c/h` (DEFLATE,
+  an input buffer plus a caller-provided `struct img_mem` arena, so the browser
+  and the chat client can link the same objects and decode HTTP bodies.  `inflate.c/h` (DEFLATE,
   zlib, gzip, CRC32/Adler32) is shared with the boot pack.  Its whole-buffer
   helpers (`inflate_gzip_mem`/`_zlib_mem`/`_raw_mem`, used by `ramfs_init`
   and the image decoders) are a separate fast path: 10-bit Huffman lookup
@@ -1367,12 +1375,14 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   with a source/sink and progress hook) keeps the bit-at-a-time decoder.  `img_sniff()` is a
   cheap header probe; `img_decode()` returns `struct img_image`; `img_draw()`
   is a clipped, scaled (box-filter down, bilinear up) RGB565 blit with alpha
-  over a checkerboard or over the destination (for a browser).  Progressive
+  over a checkerboard or over the destination (for the browser and chat).  Progressive
   JPEG (successive approximation), EXIF orientation, ICO/CUR, PAM and
   animated GIF frames are supported as well; arithmetic JPEG/CMYK are not.
   The viewer, `ucmd_view.c`, owns a canvas window and reads its file through
   `SYS_READ_FILE`; it uses fit/1:1/zoom/pan, shows format/dimensions/size,
-  animates GIFs, and gives a clear error for unsupported variants.  Host
+  animates GIFs, and gives a clear error for unsupported variants.  The chat
+  client decodes fetched message images and avatars into a 480x320 / 32x32
+  cache and draws them with `img_draw()`.  Host
   tests: `make test-images` (`img_test.c`, corpus in `testdata/images/`,
   generator `tools/gen_img_tests.py`).
 - **Network service**: `sys_net.c/h` — the NIC and the stack stay in the
@@ -2271,8 +2281,10 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     says so), and the saved cookie in `/data/CHAT.CFG` (or
     `/share/chat.cfg` without a `/data` mount) is a bearer credential
     (persistent on `/data`, RAM-only on `/share`; concurrent chat windows
-    share the file).  No threads, reactions, polls, search,
-    attachments/images/GIFs, edits or deletes beyond what a reload shows;
+    share the file).  No threads, reactions, polls, search, edits or deletes
+    beyond what a reload shows; image attachments and link-preview images
+    render inline up to the 4 MB fetch / 4 MP decode caps (first GIF frame;
+    WebP/AVIF/SVG are not decoded), file attachments are still text-only,
     messages over 4 KB are truncated, history holds 240 messages, times are
     UTC and text is Latin-1.  Network calls block the UI for their duration.
 

+ 4 - 2
Makefile

@@ -763,6 +763,8 @@ gallery.elf: gallery.o ngui.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
 # viewer links them today; a browser can link the same objects later.
 IMGLIB_OBJS = img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o \
               img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o
+IMG_DECODE_OBJS = img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o \
+                  img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o
 
 $(IMGLIB_OBJS): %.o: %.c img.h img_internal.h inflate.h ucmd_lib.h syscall.h
 	$(CC) $(CFLAGS) $(SECTION_CFLAGS) -o $@ $<
@@ -805,10 +807,10 @@ ucmd_curl.elf: ucmd_curl.o uhttp.o uhttp_cookie.o $(TLSLIB_OBJS) ucmd.ld libc.a
 chat_login.o: chat_login.c chat_login.h ujson.h uhttp.h uhttp_cookie.h ucmd_lib.h
 	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -o $@ $<
 
-ucmd_chat.o: ucmd_chat.c ucmd_lib.h syscall.h wm_abi.h ngui.h uhttp.h uhttp_cookie.h ujson.h chat_login.h $(LIBC_HEADERS)
+ucmd_chat.o: ucmd_chat.c ucmd_lib.h syscall.h wm_abi.h ngui.h uhttp.h uhttp_cookie.h ujson.h chat_login.h img.h $(LIBC_HEADERS)
 	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
 
-ucmd_chat.elf: ucmd_chat.o chat_login.o ujson.o uhttp.o uhttp_cookie.o ngui.o font_8x16.o $(UFONT_OBJS) $(TLSLIB_OBJS) ucmd.ld libc.a
+ucmd_chat.elf: ucmd_chat.o chat_login.o ujson.o uhttp.o uhttp_cookie.o ngui.o font_8x16.o $(UFONT_OBJS) $(IMG_DECODE_OBJS) inflate.o $(TLSLIB_OBJS) ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 

+ 3 - 2
docs/graphics.html

@@ -369,13 +369,14 @@
 			The codecs are independent of the OS and the toolkit: each takes an
 			input buffer plus a caller-provided <code>struct img_mem</code> arena
 			and returns an RGB565 image with an optional 8-bit alpha plane. The
-			browser links the same objects and decodes HTTP bodies in memory.
+			browser and the chat client link the same objects and decode HTTP
+			bodies in memory.
 		</p>
 		<ul>
 			<li><strong>Formats.</strong> PNG, baseline and progressive JPEG, animated GIF, BMP, TGA, PNM, ICO/CUR and PAM.</li>
 			<li><strong>Drawing.</strong> <code>img_draw()</code> is a clipped, scaled RGB565 blit: box-filter downscale, bilinear upscale, alpha over a checkerboard or over the destination.</li>
 			<li><strong>Orientation.</strong> EXIF orientation is applied; arithmetic JPEG and CMYK are rejected.</li>
-			<li><strong>Cost.</strong> Downscaling runs on the CPU. The viewer caches one image; the browser keeps a display bitmap but still rescales on repaint.</li>
+			<li><strong>Cost.</strong> Downscaling runs on the CPU. The viewer caches one image; the browser keeps a display bitmap but still rescales on repaint; the chat client caches up to 480x320 message images and 32x32 avatars.</li>
 		</ul>
 	</section>
 

+ 11 - 0
docs/network.html

@@ -449,6 +449,17 @@
 			paste a <code>connect.sid</code> cookie from a signed-in browser
 			instead.
 		</p>
+		<p>
+			Message image attachments, link-preview images and profile
+			pictures are fetched through the same uhttp connection and
+			cookie jar, one per main-loop pass, and decoded by the in-tree
+			image library (PNG, JPEG, GIF first frame, BMP, TGA, PNM, ICO
+			and PAM).  Message images are scaled to at most 480x320 and
+			cached in a 16-entry, 6 MB LRU; avatars are 32x32 with a
+			64-entry cache and fall back to initials until they load or
+			when the account has no picture.  The fetch is capped at 4 MB
+			and the decoder at 4 MP / 12 MB of scratch.
+		</p>
 		<p>
 			There is no WebSocket: the open conversation is polled with
 			<code>GET /api/channels/:id/messages?after=&lt;newest&gt;</code> every

+ 1 - 1
docs/userland.html

@@ -340,7 +340,7 @@
 		<ul>
 			<li><strong>files</strong> — browser for the VFS; opens text in <code>edit</code>, images in <code>view</code>, HTML in <code>browser</code>. First user of ngui.</li>
 			<li><strong>gallery</strong> — live widget and primitive showcase; the real app ships in the pack.</li>
-			<li><strong>chat</strong> — native Cloudron Chat client (top-bar <em>Chat</em> button, or <code>chat [config-path]</code>): username/password/TOTP login through the Cloudron OIDC API or a pasted session cookie, channels and DMs with unread badges and presence, history with older paging, sending, REST polling, read markers, browse/join and new DM.  The session cookie (never the password) is saved in <code>/data/CHAT.CFG</code> when the persistent volume is mounted, or in the RAM-only <code>/share/chat.cfg</code> otherwise.  Keys: Enter sends, PgUp/PgDn scroll, Home at the top pages in older history, Ctrl+B browse, Ctrl+N new DM, Ctrl+R refresh, and with the composer unfocused (Esc) Up/Down switch conversations.  See <a href="network.html#chat">Network → Chat client</a>.</li>
+			<li><strong>chat</strong> — native Cloudron Chat client (top-bar <em>Chat</em> button, or <code>chat [config-path]</code>): username/password/TOTP login through the Cloudron OIDC API or a pasted session cookie, channels and DMs with unread badges and presence, history with older paging, inline image attachments and profile-picture avatars, sending, REST polling, read markers, browse/join and new DM.  The session cookie (never the password) is saved in <code>/data/CHAT.CFG</code> when the persistent volume is mounted, or in the RAM-only <code>/share/chat.cfg</code> otherwise.  Keys: Enter sends, PgUp/PgDn scroll, Home at the top pages in older history, Ctrl+B browse, Ctrl+N new DM, Ctrl+R refresh, and with the composer unfocused (Esc) Up/Down switch conversations.  See <a href="network.html#chat">Network → Chat client</a>.</li>
 			<li><strong>solitaire</strong> — Klondike with drag-and-drop, scoring and a win animation.</li>
 			<li><strong>mines</strong> — second ngui canvas app; shares the toolkit and event model.</li>
 			<li><strong>view</strong> — fit/1:1/zoom/pan image viewer, animated GIF playback.</li>

+ 91 - 15
tools/mock_chat.py

@@ -5,7 +5,8 @@ Two plain-HTTP origins on the host, reachable from a QEMU slirp guest as
 10.0.2.2:
 
   chat  (default port 18080): /auth/login, /auth/callback, /auth/return,
-        /auth/logout and the /api/* routes the client uses
+        /auth/logout and the /api/* routes the client uses, including
+        /api/avatars/<uid> and /api/attachments/<id> for pictures
   login (default port 18081): /openid/auth, /openid/interaction/<uid>
         (login page with cloudron-config JSON, consent page as a bare
         auto-submit form), POST .../login and .../confirm
@@ -28,19 +29,27 @@ import argparse
 import datetime
 import json
 import secrets
+import struct
 import threading
+import zlib
 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
 from urllib.parse import parse_qs, urlparse
 
 LOCK = threading.Lock()
 STATE = {
     "users": {
-        "u-test": {"id": "u-test", "username": "test", "name": "Test User"},
-        "u-alice": {"id": "u-alice", "username": "alice", "name": "Alice Example"},
-        "u-bob": {"id": "u-bob", "username": "bob", "name": "Bob Böhm"},
-        "u-carol": {"id": "u-carol", "username": "carol", "name": "Carol"},
-        "u-totp": {"id": "u-totp", "username": "totp", "name": "Totp User"},
-        "u-consent": {"id": "u-consent", "username": "consent", "name": "Consent User"},
+        "u-test": {"id": "u-test", "username": "test", "name": "Test User",
+                   "picture": ""},
+        "u-alice": {"id": "u-alice", "username": "alice", "name": "Alice Example",
+                    "picture": "/api/avatars/u-alice"},
+        "u-bob": {"id": "u-bob", "username": "bob", "name": "Bob Böhm",
+                  "picture": "/api/avatars/u-bob"},
+        "u-carol": {"id": "u-carol", "username": "carol", "name": "Carol",
+                    "picture": ""},
+        "u-totp": {"id": "u-totp", "username": "totp", "name": "Totp User",
+                   "picture": ""},
+        "u-consent": {"id": "u-consent", "username": "consent",
+                      "name": "Consent User", "picture": ""},
     },
     "channels": {},         # id -> {id,name,type,members:set,description}
     "messages": {},         # channel id -> [msg]
@@ -54,6 +63,59 @@ SEQ = [0]
 ARGS = None
 
 
+def png_chunk(tag, data):
+    return (struct.pack(">I", len(data)) + tag + data +
+            struct.pack(">I", zlib.crc32(tag + data) & 0xffffffff))
+
+
+def png_rgb(w, h, pixel):
+    raw = bytearray()
+    for y in range(h):
+        raw.append(0)
+        for x in range(w):
+            raw.extend(pixel(x, y))
+    return (b"\x89PNG\r\n\x1a\n" +
+            png_chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) +
+            png_chunk(b"IDAT", zlib.compress(bytes(raw), 6)) +
+            png_chunk(b"IEND", b""))
+
+
+AVATAR_PNGS = {}
+
+
+def avatar_png(uid):
+    if uid in AVATAR_PNGS:
+        return AVATAR_PNGS[uid]
+    h = sum(ord(c) for c in uid)
+    colors = [(208, 90, 90), (90, 154, 208), (90, 176, 112),
+              (192, 138, 58), (154, 106, 200), (58, 168, 168)]
+    r, g, b = colors[h % len(colors)]
+
+    def pixel(x, y):
+        # A coloured disc with a lighter centre, so the screenshot shows a
+        # real avatar rather than the initial fallback.
+        dx, dy = x - 15.5, y - 15.5
+        if dx * dx + dy * dy > 15.5 * 15.5:
+            return (32, 34, 38)
+        if 8 <= x <= 23 and 12 <= y <= 19:
+            return (245, 245, 245)
+        return (r, g, b)
+
+    AVATAR_PNGS[uid] = png_rgb(32, 32, pixel)
+    return AVATAR_PNGS[uid]
+
+
+def attachment_png():
+    def pixel(x, y):
+        if (x // 8 + y // 8) % 2:
+            return (240, 150, 40)
+        return (40, 90, 160)
+    return png_rgb(96, 64, pixel)
+
+
+ATTACHMENT_PNG = attachment_png()
+
+
 def note(line):
     STATE["log"].append(line)
     if ARGS and ARGS.verbose:
@@ -76,7 +138,9 @@ def add_message(cid, uid, body, client_id=None, reply_to=None, extra=None):
     msgs = STATE["messages"][cid]
     m = {"id": "m%05d" % (SEQ[0] + 1), "clientId": client_id, "channelId": cid,
          "userId": uid, "authorName": STATE["users"][uid]["name"],
-         "authorUsername": STATE["users"][uid]["username"], "body": body,
+         "authorUsername": STATE["users"][uid]["username"],
+         "authorPicture": STATE["users"][uid].get("picture", ""),
+         "body": body,
          "type": None, "parentId": None, "replyToId": reply_to, "replyTo": None,
          "createdAt": now_iso(), "deleted": False, "reactions": [],
          "attachments": [], "threadCount": 0, "readBy": [], "pinned": False}
@@ -109,10 +173,15 @@ def seed(n_general):
                 "NebOS chat timeline, because it keeps going and going with "
                 "plenty of words to test the greedy word wrapper.\nAnd a "
                 "second paragraph.", reply_to=first,
-                extra={"attachments": [{"id": "a1", "filename": "notes.txt",
-                                        "mime": "text/plain", "size": 12}],
-                       "threadCount": 2,
-                       "reactions": [{"emoji": "\U0001F44D", "count": 3}]})
+                extra={
+                    "attachments": [
+                        {"id": "a1", "filename": "notes.txt",
+                         "mime": "text/plain", "size": 12},
+                        {"id": "a2", "filename": "neb.png",
+                         "mime": "image/png", "size": len(ATTACHMENT_PNG),
+                         "url": "/api/attachments/a2"}],
+                    "threadCount": 2,
+                    "reactions": [{"emoji": "\U0001F44D", "count": 3}]})
     add_message("c-secret", "u-alice", "Private channel, only us two.")
     add_message("d-alice", "u-alice", "Hi Test, this is a direct message!")
     # test has read general up to the history; the rest is unread
@@ -136,7 +205,8 @@ def last_message(cid):
         return None
     m = msgs[-1]
     return {"id": m["id"], "body": m["body"][:160], "createdAt": m["createdAt"],
-            "userId": m["userId"], "authorName": m["authorName"], "authorPicture": ""}
+            "userId": m["userId"], "authorName": m["authorName"],
+            "authorPicture": m.get("authorPicture", "")}
 
 
 def channel_json(c, uid):
@@ -377,7 +447,7 @@ class ChatHandler(Base):
             if not uid:
                 return self.send(401, {"error": "Unauthorized"})
             if p == "/api/me":
-                return self.send(200, dict(STATE["users"][uid], email="", picture="",
+                return self.send(200, dict(STATE["users"][uid], email="",
                                            active=True))
             if p == "/api/channels":
                 return self.send(200, [channel_json(c, uid) for c in STATE["channels"].values()
@@ -391,9 +461,15 @@ class ChatHandler(Base):
                 return self.send(200, [dm_json(c, uid) for c in STATE["channels"].values()
                                        if c["type"] == "dm" and uid in c["members"]])
             if p == "/api/users":
-                return self.send(200, [dict(x, email="", picture="", active=True)
+                return self.send(200, [dict(x, email="", active=True)
                                        for x in STATE["users"].values()])
             parts = p.strip("/").split("/")
+            if len(parts) == 3 and parts[:2] == ["api", "avatars"]:
+                if parts[2] in STATE["users"]:
+                    return self.send(200, avatar_png(parts[2]), "image/png")
+            if len(parts) == 3 and parts[:2] == ["api", "attachments"]:
+                if parts[2] == "a2":
+                    return self.send(200, ATTACHMENT_PNG, "image/png")
             if len(parts) == 4 and parts[:2] == ["api", "channels"] and parts[3] == "messages":
                 c = STATE["channels"].get(parts[2])
                 if not c or uid not in c["members"]:

+ 4 - 0
tools/qmp_chat_test.py

@@ -285,6 +285,10 @@ def main():
         check("history loaded",
               wait_for(lambda: logged("/api/channels/c-general/messages?limit=50"),
                        30, "history"))
+        check("avatars fetched",
+              wait_for(lambda: logged("GET /api/avatars/"), 20, "avatars"))
+        check("message image fetched",
+              wait_for(lambda: logged("GET /api/attachments/a2"), 20, "image"))
         time.sleep(4.0)
         shot(s, workdir, out, "3-main")
         if not full:

+ 606 - 7
ucmd_chat.c

@@ -22,6 +22,7 @@
 #include "uhttp.h"
 #include "ujson.h"
 #include "chat_login.h"
+#include "img.h"
 
 #include <stdlib.h>
 #include <string.h>
@@ -39,6 +40,20 @@
 #define PAGE_SIZE      50
 #define LIVE_PAGE      50
 
+#define MSG_IMG_MAX    3
+#define CHAT_IMG_W     480
+#define CHAT_IMG_H     320
+#define CHAT_IMG_MAX   16
+#define CHAT_AVATAR_MAX 64
+#define CHAT_AVATAR    32
+#define CHAT_IMG_BUDGET (6u * 1024u * 1024u)
+#define CHAT_IMG_ARENA_MAX (12u * 1024u * 1024u)
+#define CHAT_IMG_FETCH_MAX (4u * 1024u * 1024u)
+#define CHAT_IMG_URL_MAX (UHTTP_HOST_MAX + UHTTP_PATH_MAX + 16)
+#define CHAT_PIC_QUEUED 0
+#define CHAT_PIC_READY  1
+#define CHAT_PIC_FAILED (-1)
+
 #define POLL_CONV_MS        2000
 #define POLL_CONV_IDLE_MS   5000
 #define POLL_DIR_MS         12000
@@ -78,10 +93,13 @@ struct msg {
 	char id[48];
 	char user_id[48];
 	char author[48];
+	char *author_pic;       /* profile picture URL, or NULL */
 	char created[32];       /* ISO 8601 UTC, sorts as text */
 	char reply[96];         /* "Name: snippet" */
 	char extra[112];        /* attachments / thread / reactions line */
 	char *body;             /* Latin-1, malloc'd */
+	char *img_url[MSG_IMG_MAX]; /* image attachments, malloc'd URLs */
+	unsigned char nimg;
 	unsigned char action;   /* type "me" */
 	int height;
 	int layout_w;
@@ -93,6 +111,7 @@ struct pick {
 	char id[48];
 	char name[64];
 	char sub[64];
+	char pic[256];
 };
 
 static struct ngui ui;
@@ -403,6 +422,7 @@ static void maybe_save_cookie(void)
 /* ---- HTTP / JSON plumbing ---- */
 
 static void paint_now(void);
+static int line_h(void);
 
 static void net_drop(void)
 {
@@ -436,6 +456,472 @@ static int parse_resp(void)
 	return root;
 }
 
+/* ---- message images and avatars ---- */
+
+struct chat_pic {
+	char *url;
+	struct img_image img;
+	unsigned int bytes;     /* RGB565 bytes in the message-image budget */
+	unsigned int last_used;
+	int state;              /* CHAT_PIC_* */
+};
+
+static struct chat_pic chat_images[CHAT_IMG_MAX];
+static int nchat_images;
+static unsigned int chat_image_bytes;
+static struct chat_pic chat_avatars[CHAT_AVATAR_MAX];
+static int nchat_avatars;
+static unsigned int chat_pic_clock;
+static unsigned char *chat_fetch_buf;
+static unsigned char *chat_arena;
+static unsigned int chat_arena_size;
+
+static void chat_pic_free(struct chat_pic *p)
+{
+	free(p->url);
+	free(p->img.px);
+	free(p->img.alpha);
+	memset(p, 0, sizeof(*p));
+}
+
+static struct chat_pic *chat_pic_find(struct chat_pic *arr, int n,
+				      const char *url)
+{
+	int i;
+
+	for (i = 0; i < n; i++)
+		if (arr[i].url && strcmp(arr[i].url, url) == 0)
+			return &arr[i];
+	return 0;
+}
+
+/* Pick a cache slot, evicting the least recently used entry when full.
+ * avatars: their images never change the timeline layout. */
+static struct chat_pic *chat_pic_slot(struct chat_pic *arr, int *count, int max,
+				      const char *url, int avatars)
+{
+	struct chat_pic *p = chat_pic_find(arr, *count, url);
+	unsigned int best = ~0u;
+	int i, victim = -1;
+
+	if (p)
+		return p;
+	if (*count < max) {
+		p = &arr[*count];
+		memset(p, 0, sizeof(*p));
+		p->url = strdup(url);
+		if (!p->url)
+			return 0;
+		(*count)++;
+	} else {
+		for (i = 0; i < *count; i++) {
+			if (arr[i].state == CHAT_PIC_QUEUED)
+				continue;
+			if (arr[i].last_used < best) {
+				best = arr[i].last_used;
+				victim = i;
+			}
+		}
+		if (victim < 0)
+			return 0;
+		p = &arr[victim];
+		if (!avatars) {
+			chat_image_bytes -= p->bytes;
+			msgs_gen++;
+		}
+		chat_pic_free(p);
+		p->url = strdup(url);
+		if (!p->url)
+			return 0;
+	}
+	p->state = CHAT_PIC_QUEUED;
+	p->last_used = ++chat_pic_clock;
+	return p;
+}
+
+static struct chat_pic *chat_image_slot(const char *url)
+{
+	return chat_pic_slot(chat_images, &nchat_images, CHAT_IMG_MAX, url, 0);
+}
+
+static struct chat_pic *chat_avatar_slot(const char *url)
+{
+	return chat_pic_slot(chat_avatars, &nchat_avatars, CHAT_AVATAR_MAX,
+			     url, 1);
+}
+
+static int chat_image_room(unsigned int need)
+{
+	while (chat_image_bytes + need > CHAT_IMG_BUDGET) {
+		unsigned int best = ~0u;
+		int i, victim = -1;
+
+		for (i = 0; i < nchat_images; i++) {
+			if (chat_images[i].state != CHAT_PIC_READY)
+				continue;
+			if (chat_images[i].last_used < best) {
+				best = chat_images[i].last_used;
+				victim = i;
+			}
+		}
+		if (victim < 0)
+			return -1;
+		chat_image_bytes -= chat_images[victim].bytes;
+		chat_pic_free(&chat_images[victim]);
+		msgs_gen++;
+	}
+	return 0;
+}
+
+static unsigned char *chat_pic_arena_get(unsigned int need)
+{
+	if (need <= chat_arena_size)
+		return chat_arena;
+	free(chat_arena);
+	chat_arena = (unsigned char *)malloc(need);
+	chat_arena_size = chat_arena ? need : 0;
+	return chat_arena;
+}
+
+static int chat_pic_store(struct chat_pic *p, unsigned int len, int avatar)
+{
+	struct img_info info;
+	struct img_options opt;
+	struct img_mem mem;
+	struct img_image decoded;
+	struct img_blit blit;
+	unsigned char *arena, *alpha = 0;
+	unsigned short *px;
+	unsigned int est, scale, dw, dh, sw, sh, i, need;
+	int r;
+
+	if (img_sniff(chat_fetch_buf, len, &info) != 0)
+		return -1;
+	est = img_estimate(&info);
+	if (est == 0xFFFFFFFFu || est > CHAT_IMG_ARENA_MAX)
+		return -1;
+	arena = chat_pic_arena_get(est);
+	if (!arena)
+		return -1;
+	img_mem_init(&mem, arena, est);
+	opt.max_pixels = 4u * 1024u * 1024u;
+	r = img_decode(chat_fetch_buf, len, &opt, &mem, &decoded);
+	if (r != 0 || !decoded.w || !decoded.h)
+		return -1;
+
+	if (avatar) {
+		sw = (CHAT_AVATAR << 16) / decoded.w;
+		sh = (CHAT_AVATAR << 16) / decoded.h;
+		scale = sw < sh ? sw : sh;
+		dw = dh = CHAT_AVATAR;
+	} else {
+		scale = 65536;
+		if (decoded.w > CHAT_IMG_W)
+			scale = (CHAT_IMG_W << 16) / decoded.w;
+		if (((decoded.h * scale) >> 16) > CHAT_IMG_H)
+			scale = (CHAT_IMG_H << 16) / decoded.h;
+		dw = (decoded.w * scale) >> 16;
+		dh = (decoded.h * scale) >> 16;
+		if (!dw)
+			dw = 1;
+		if (!dh)
+			dh = 1;
+		need = dw * dh * 2u;
+		if (chat_image_room(need) != 0)
+			return -1;
+	}
+	px = (unsigned short *)malloc(dw * dh * 2u);
+	if (!px)
+		return -1;
+	for (i = 0; i < dw * dh; i++)
+		px[i] = avatar ? 0xFFFF : ui.theme.bg;
+	if (avatar && decoded.alpha) {
+		alpha = (unsigned char *)malloc(dw * dh);
+		if (alpha)
+			memset(alpha, 255, dw * dh);
+	}
+	memset(&blit, 0, sizeof(blit));
+	blit.dst = px;
+	blit.dst_w = (int)dw;
+	blit.dst_h = (int)dh;
+	blit.clip_x = 0;
+	blit.clip_y = 0;
+	blit.clip_w = (int)dw;
+	blit.clip_h = (int)dh;
+	blit.x = avatar ? (int)(dw - ((decoded.w * scale) >> 16)) / 2 : 0;
+	blit.y = avatar ? (int)(dh - ((decoded.h * scale) >> 16)) / 2 : 0;
+	blit.scale = scale;
+	blit.bg = avatar ? 0xFFFF : ui.theme.bg;
+	blit.bg2 = blit.bg;
+	blit.dst_a = alpha;
+	blit.flags = alpha ? IMG_BLIT_SAVE_ALPHA :
+		     (decoded.alpha ? IMG_BLIT_OVER_DST : 0);
+	img_draw(&decoded, &blit);
+
+	p->img.format = decoded.format;
+	p->img.w = dw;
+	p->img.h = dh;
+	p->img.px = px;
+	p->img.alpha = alpha;
+	p->img.flags = 0;
+	p->bytes = avatar ? 0 : dw * dh * 2u;
+	if (!avatar)
+		chat_image_bytes += p->bytes;
+	return 0;
+}
+
+static void chat_pic_load(struct chat_pic *p, int avatar)
+{
+	unsigned int len = 0;
+	int st;
+
+	if (!chat_fetch_buf)
+		chat_fetch_buf = (unsigned char *)malloc(CHAT_IMG_FETCH_MAX);
+	if (!chat_fetch_buf) {
+		p->state = CHAT_PIC_FAILED;
+		return;
+	}
+	http.jar = &jar;
+	http.accept = "image/*,*/*";
+	st = chat_http(&http, 0, p->url, 0, (char *)chat_fetch_buf,
+		       CHAT_IMG_FETCH_MAX, &len);
+	if (st != 200 || len == 0 || chat_pic_store(p, len, avatar) != 0) {
+		p->state = CHAT_PIC_FAILED;
+	} else {
+		p->state = CHAT_PIC_READY;
+		p->last_used = ++chat_pic_clock;
+		if (!avatar) {
+			msgs_gen++;
+			if (at_bottom)
+				tl_scroll.offset = 1 << 28;
+		}
+	}
+	ngui_invalidate(&ui);
+}
+
+static void chat_media_tick(void)
+{
+	int i;
+
+	if (screen != SCR_MAIN || offline)
+		return;
+	for (i = 0; i < nchat_images; i++) {
+		if (chat_images[i].state == CHAT_PIC_QUEUED) {
+			chat_pic_load(&chat_images[i], 0);
+			return;
+		}
+	}
+	for (i = 0; i < nchat_avatars; i++) {
+		if (chat_avatars[i].state == CHAT_PIC_QUEUED) {
+			chat_pic_load(&chat_avatars[i], 1);
+			return;
+		}
+	}
+}
+
+static void chat_media_clear(void)
+{
+	int i;
+
+	for (i = 0; i < nchat_images; i++)
+		chat_pic_free(&chat_images[i]);
+	for (i = 0; i < nchat_avatars; i++)
+		chat_pic_free(&chat_avatars[i]);
+	nchat_images = 0;
+	nchat_avatars = 0;
+	chat_image_bytes = 0;
+	free(chat_fetch_buf);
+	chat_fetch_buf = 0;
+	free(chat_arena);
+	chat_arena = 0;
+	chat_arena_size = 0;
+}
+
+/* Refresh/Retry gives failed pictures another chance. */
+static void chat_media_retry(void)
+{
+	int i;
+
+	for (i = 0; i < nchat_images; i++)
+		if (chat_images[i].state == CHAT_PIC_FAILED)
+			chat_images[i].state = CHAT_PIC_QUEUED;
+	for (i = 0; i < nchat_avatars; i++)
+		if (chat_avatars[i].state == CHAT_PIC_FAILED)
+			chat_avatars[i].state = CHAT_PIC_QUEUED;
+	ngui_invalidate(&ui);
+}
+
+/* Resolve a picture URL; Cloudron's older profile-avatar path is rewritten
+ * to the /api/avatars/ route the current server serves. */
+static int chat_pic_url(const char *raw, char *out, unsigned int cap)
+{
+	static const char old_prefix[] = "/api/v1/profile/avatar/";
+	const char *p;
+	char tmp[CHAT_IMG_URL_MAX];
+	char *q;
+
+	if (!raw || !raw[0])
+		return -1;
+	p = strstr(raw, old_prefix);
+	if (p) {
+		s_copy(tmp, "/api/avatars/", sizeof(tmp));
+		s_cat(tmp, p + sizeof(old_prefix) - 1, sizeof(tmp));
+		q = strchr(tmp, '?');
+		if (q)
+			*q = '\0';
+		raw = tmp;
+	}
+	return uhttp_resolve(server, raw, out, cap);
+}
+
+static int chat_image_name(const char *mime, const char *filename)
+{
+	static const char *const ext[] = {
+		".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tga",
+		".ppm", ".pgm", ".pbm", ".ico", ".cur", ".pam"
+	};
+	unsigned int i;
+
+	if (mime && strncmp(mime, "image/", 6) == 0)
+		return 1;
+	if (!filename)
+		return 0;
+	for (i = 0; i < sizeof(ext) / sizeof(ext[0]); i++) {
+		unsigned int n = (unsigned int)strlen(ext[i]);
+		unsigned int j;
+		const char *s = filename + strlen(filename);
+
+		if ((unsigned int)strlen(filename) < n)
+			continue;
+		s -= n;
+		for (j = 0; j < n; j++) {
+			char a = s[j], b = ext[i][j];
+
+			if (a >= 'A' && a <= 'Z')
+				a = (char)(a - 'A' + 'a');
+			if (a != b)
+				break;
+		}
+		if (j == n)
+			return 1;
+	}
+	return 0;
+}
+
+/* Layout/draw dimensions for one message image.  *state is the cache state
+ * (a missing entry is treated as queued; draw queues it). */
+static void chat_image_measure(const char *url, int tw, int *dw, int *dh,
+			       unsigned int *scale, int *state)
+{
+	struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url);
+	unsigned int sc = 65536;
+
+	if (p && p->state == CHAT_PIC_READY) {
+		if ((int)p->img.w > tw)
+			sc = ((unsigned int)tw << 16) / p->img.w;
+		if (((p->img.h * sc) >> 16) > CHAT_IMG_H)
+			sc = (CHAT_IMG_H << 16) / p->img.h;
+		*dw = (int)((p->img.w * sc) >> 16);
+		*dh = (int)((p->img.h * sc) >> 16);
+		if (*dw < 1)
+			*dw = 1;
+		if (*dh < 1)
+			*dh = 1;
+		*scale = sc;
+		*state = CHAT_PIC_READY;
+		return;
+	}
+	*dw = tw < 320 ? tw : 320;
+	if (*dw < 40)
+		*dw = 40;
+	*dh = 120;
+	*scale = 65536;
+	*state = p ? p->state : CHAT_PIC_QUEUED;
+}
+
+static struct ngui_rect chat_clip_rect(void)
+{
+	if (ui.nclip > 0)
+		return ui.clip[ui.nclip - 1];
+	return (struct ngui_rect){ 0, 0, ui.w, ui.h };
+}
+
+static void chat_image_draw(const char *url, int x, int y, int tw)
+{
+	struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url);
+	struct ngui_rect clip = chat_clip_rect();
+	int dw, dh, state;
+	unsigned int scale;
+
+	if (!p)
+		p = chat_image_slot(url);
+	chat_image_measure(url, tw, &dw, &dh, &scale, &state);
+	if (p && p->state == CHAT_PIC_READY) {
+		struct img_blit blit;
+
+		memset(&blit, 0, sizeof(blit));
+		blit.dst = ui.px;
+		blit.dst_w = ui.w;
+		blit.dst_h = ui.h;
+		blit.clip_x = clip.x;
+		blit.clip_y = clip.y;
+		blit.clip_w = clip.w;
+		blit.clip_h = clip.h;
+		blit.x = x;
+		blit.y = y;
+		blit.scale = scale;
+		blit.bg = ui.theme.bg;
+		blit.bg2 = ui.theme.bg;
+		blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
+		img_draw(&p->img, &blit);
+		ngui_frame(&ui, (struct ngui_rect){ x, y, dw, dh },
+			   ui.theme.border);
+	} else {
+		struct ngui_rect box = { x, y, dw, dh };
+
+		ngui_fill_rect(&ui, box, ui.theme.panel_alt);
+		ngui_frame(&ui, box, ui.theme.border);
+		ngui_text_ellipsis(&ui, box, x + 8, y + (dh - line_h()) / 2,
+				   state == CHAT_PIC_FAILED ?
+				   "Image could not be loaded" :
+				   "Loading image...", ui.theme.text_dim);
+	}
+}
+
+static int chat_avatar_draw(const char *url, int x, int y, int size,
+			    unsigned short fallback)
+{
+	struct chat_pic *p;
+
+	if (!url || !url[0])
+		return 0;
+	p = chat_pic_find(chat_avatars, nchat_avatars, url);
+	if (!p)
+		p = chat_avatar_slot(url);
+	if (p && p->state == CHAT_PIC_READY) {
+		struct ngui_rect clip = chat_clip_rect();
+		struct img_blit blit;
+
+		memset(&blit, 0, sizeof(blit));
+		blit.dst = ui.px;
+		blit.dst_w = ui.w;
+		blit.dst_h = ui.h;
+		blit.clip_x = clip.x;
+		blit.clip_y = clip.y;
+		blit.clip_w = clip.w;
+		blit.clip_h = clip.h;
+		blit.x = x;
+		blit.y = y;
+		blit.scale = ((unsigned int)size << 16) / CHAT_AVATAR;
+		blit.bg = fallback;
+		blit.bg2 = fallback;
+		blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
+		img_draw(&p->img, &blit);
+		return 1;
+	}
+	return 0;
+}
+
 static void go_login(const char *why);
 
 /* Common error handling for API calls in the main screen.  Returns 1 when
@@ -562,8 +1048,47 @@ static int load_directory(void)
 
 static void msg_free(struct msg *m)
 {
+	int i;
+
 	free(m->body);
 	m->body = 0;
+	free(m->author_pic);
+	m->author_pic = 0;
+	for (i = 0; i < m->nimg; i++) {
+		free(m->img_url[i]);
+		m->img_url[i] = 0;
+	}
+	m->nimg = 0;
+}
+
+/* Resolve and remember one image URL; duplicates and overflowing messages
+ * are ignored. */
+static int msg_add_image(struct msg *m, const char *raw)
+{
+	char url[CHAT_IMG_URL_MAX];
+	int i;
+
+	if (!raw || !raw[0] || m->nimg >= MSG_IMG_MAX)
+		return 0;
+	if (uhttp_resolve(server, raw, url, sizeof(url)) != 0)
+		return 0;
+	for (i = 0; i < m->nimg; i++)
+		if (strcmp(m->img_url[i], url) == 0)
+			return 0;
+	m->img_url[m->nimg] = strdup(url);
+	if (!m->img_url[m->nimg])
+		return -1;
+	m->nimg++;
+	return 0;
+}
+
+static void msg_set_author_pic(struct msg *m, const char *raw)
+{
+	char url[CHAT_IMG_URL_MAX];
+
+	if (!raw[0] || chat_pic_url(raw, url, sizeof(url)) != 0)
+		return;
+	m->author_pic = strdup(url);
 }
 
 static void clear_messages(void)
@@ -597,16 +1122,21 @@ static void build_extra(struct msg *m, int o)
 	for (it = ujson_first(&json, ujson_get(&json, o, "attachments"));
 	     it >= 0; it = ujson_next(&json, it)) {
 		char name[64];
+		const char *mime = ujson_get_str(&json, it, "mime");
+		const char *fn = ujson_get_str(&json, it, "filename");
+		const char *url = ujson_get_str(&json, it, "url");
 
-		to_latin1_line(name, sizeof(name),
-			       ujson_get_str(&json, it, "filename"));
+		if (chat_image_name(mime, fn) && url[0])
+			continue;       /* drawn inline by the timeline */
+		to_latin1_line(name, sizeof(name), fn);
 		if (m->extra[0])
 			s_cat(m->extra, ", ", sizeof(m->extra));
 		else
 			s_cat(m->extra, "[file] ", sizeof(m->extra));
 		s_cat(m->extra, name, sizeof(m->extra));
 	}
-	if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT) {
+	if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT &&
+	    !ujson_get_str(&json, ujson_get(&json, o, "gif"), "url")[0]) {
 		if (m->extra[0])
 			s_cat(m->extra, "  ", sizeof(m->extra));
 		s_cat(m->extra, "[GIF]", sizeof(m->extra));
@@ -671,6 +1201,7 @@ static int msg_from_json(struct msg *m, int o)
 	if (!nm[0])
 		nm = ujson_get_str(&json, o, "authorUsername");
 	to_latin1_line(m->author, sizeof(m->author), nm[0] ? nm : "?");
+	msg_set_author_pic(m, ujson_get_str(&json, o, "authorPicture"));
 	s_copy(m->created, ujson_get_str(&json, o, "createdAt"),
 	       sizeof(m->created));
 	m->action = strcmp(ujson_get_str(&json, o, "type"), "me") == 0;
@@ -687,8 +1218,39 @@ static int msg_from_json(struct msg *m, int o)
 	while (len && (body[len - 1] == '\n' || body[len - 1] == ' '))
 		body[--len] = '\0';
 	m->body = strdup(body);
-	if (!m->body)
+	if (!m->body) {
+		msg_free(m);
 		return -1;
+	}
+	{
+		int it;
+		const char *mime, *fn;
+
+		for (it = ujson_first(&json,
+				      ujson_get(&json, o, "attachments"));
+		     it >= 0; it = ujson_next(&json, it)) {
+			mime = ujson_get_str(&json, it, "mime");
+			fn = ujson_get_str(&json, it, "filename");
+			if (chat_image_name(mime, fn) &&
+			    msg_add_image(m, ujson_get_str(&json, it, "url")) != 0) {
+				msg_free(m);
+				return -1;
+			}
+		}
+	}
+	if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT &&
+	    msg_add_image(m, ujson_get_str(&json, ujson_get(&json, o, "gif"),
+					   "url")) != 0) {
+		msg_free(m);
+		return -1;
+	}
+	if (ujson_type(&json, ujson_get(&json, o, "preview")) == UJSON_OBJECT &&
+	    msg_add_image(m, ujson_get_str(&json,
+					   ujson_get(&json, o, "preview"),
+					   "image")) != 0) {
+		msg_free(m);
+		return -1;
+	}
 	rt = ujson_get(&json, o, "replyTo");
 	if (ujson_type(&json, rt) == UJSON_OBJECT) {
 		char tmp[96];
@@ -1034,6 +1596,14 @@ static void load_picks(int dms)
 		s_copy(p->id, ujson_get_str(&json, it, "id"), sizeof(p->id));
 		if (!p->id[0])
 			continue;
+		p->pic[0] = '\0';
+		{
+			char url[CHAT_IMG_URL_MAX];
+
+			if (chat_pic_url(ujson_get_str(&json, it, "picture"),
+					 url, sizeof(url)) == 0)
+				s_copy(p->pic, url, sizeof(p->pic));
+		}
 		if (dms) {
 			if (strcmp(p->id, me_id) == 0)
 				continue;
@@ -1140,6 +1710,7 @@ static void go_login(const char *why)
 	uhttp_jar_clear(&jar);
 	saved_jar_changes = jar.changes;
 	saved_cookie[0] = '\0';
+	chat_media_clear();
 	screen = SCR_SERVER;
 	modal = MODAL_NONE;
 	clear_messages();
@@ -1461,6 +2032,7 @@ static void layout_msg(int i, int width)
 {
 	struct msg *m = &msgs[i];
 	int lh = line_h(), h, tw = width - TEXT_X - 12;
+	int k;
 
 	if (tw < 40)
 		tw = 40;
@@ -1472,6 +2044,14 @@ static void layout_msg(int i, int width)
 	if (m->reply[0])
 		h += lh + 2;
 	h += count_lines(m->body, tw) * lh;
+	for (k = 0; k < m->nimg; k++) {
+		int dw, dh, state;
+		unsigned int scale;
+
+		chat_image_measure(m->img_url[k], tw, &dw, &dh, &scale,
+				   &state);
+		h += dh + 6;
+	}
 	if (m->extra[0])
 		h += lh + 2;
 	h += 2;
@@ -1520,7 +2100,7 @@ static unsigned short avatar_color(const char *id)
 }
 
 static void draw_avatar(int x, int y, int size, const char *name,
-			const char *id)
+			const char *id, const char *pic)
 {
 	struct ngui_rect r = { x, y, size, size };
 	char ini[2];
@@ -1528,6 +2108,8 @@ static void draw_avatar(int x, int y, int size, const char *name,
 
 	ngui_fill_round_rect(&ui, r, size / 2, size / 2, size / 2, size / 2,
 			     avatar_color(id));
+	if (chat_avatar_draw(pic, x, y, size, avatar_color(id)))
+		return;
 	ini[0] = name[0] ? name[0] : '?';
 	if (ini[0] >= 'a' && ini[0] <= 'z')
 		ini[0] = (char)(ini[0] - 'a' + 'A');
@@ -1853,7 +2435,8 @@ static void draw_message(struct msg *m, int x, int y, int width)
 		int aw;
 
 		y += PAD_TOP;
-		draw_avatar(x + 10, y, AVATAR, m->author, m->user_id);
+		draw_avatar(x + 10, y, AVATAR, m->author, m->user_id,
+			    m->author_pic);
 		ngui_text_px(&ui, tx, y, m->author, (unsigned int)strlen(m->author),
 			     ui.theme.text, ui.font_px, 1, 0, 0);
 		aw = text_w(m->author, (unsigned int)strlen(m->author), 1);
@@ -1885,6 +2468,19 @@ static void draw_message(struct msg *m, int x, int y, int width)
 		pos += adv;
 		y += lh;
 	}
+	{
+		int k;
+
+		for (k = 0; k < m->nimg; k++) {
+			int dw, dh, state;
+			unsigned int scale;
+
+			chat_image_measure(m->img_url[k], tw, &dw, &dh,
+					   &scale, &state);
+			chat_image_draw(m->img_url[k], tx, y, tw);
+			y += dh + 6;
+		}
+	}
 	if (m->extra[0]) {
 		struct ngui_rect er = { tx, y + 2, tw, lh };
 
@@ -2088,7 +2684,8 @@ static void draw_modal(void)
 			ngui_fill_rect(&ui, (struct ngui_rect){ row.x, y + 43,
 						row.w, 1 }, ui.theme.border);
 			if (modal == MODAL_NEWDM)
-				draw_avatar(row.x + 8, y + 6, 30, p->name, p->id);
+				draw_avatar(row.x + 8, y + 6, 30, p->name, p->id,
+					    p->pic);
 			ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48, y,
 						 row.w - 160, lh + 4 },
 					   row.x + 48, y + 4,
@@ -2380,6 +2977,7 @@ static void run_action(void)
 	case ACT_RETRY:
 		backoff_ms = 0;
 		retry_at = 0;
+		chat_media_retry();
 		s_copy(busy, "Refreshing...", sizeof(busy));
 		paint_now();
 		busy[0] = '\0';
@@ -2519,6 +3117,7 @@ void _start(const char *arg)
 			run_action();
 		else
 			poll_tick();
+		chat_media_tick();
 		/* The offline retry countdown needs a once-a-second repaint. */
 		if (offline && screen == SCR_MAIN) {
 			static unsigned int last_tick;