mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
The iOS emoji picker's custom emoji downloaded again every time the
picker opened, and animated emoji showed only their first frame.
Now each custom emoji downloads once per install and plays its
animation:
- The native picker gets image bytes from Flutter through the same path
as the rest of the app's images: the in-memory custom emoji cache, then
the persistent media disk cache, then one download through the shared
media HTTP client. Relay media is cached as immutable.
- Swift decodes every frame (no Swift-side cache) and shows the image in
a `UIImageView`, since SwiftUI `Image` draws only the first frame of an
animated `UIImage`. With Reduce Motion on, it shows the first frame,
following the setting live.
- At most four picker downloads run at once, and an emoji scrolled off
screen before its turn never starts. Emoji already saved on disk skip
the queue, so reopening a large set stays instant.
- A picker load joins any download of the same image already in flight
elsewhere in the app. A saved copy that fails to decode is evicted and
downloaded again, and only bytes that decoded are kept in memory.
- Swift decodes at most four emoji at once, including ones from cached
bytes. An emoji whose cell scrolls away gives up its place and stops
decoding between frames, and a cell that leaves the screen keeps only
its first frame.
- Each animation frame keeps its own delay. UIKit spaces animated frames
evenly, so a frame repeats for its share of the loop, and a GIF that
holds its last frame for 3 s still does.
### Why it refetched
The native picker loaded images itself with `URLSession.shared` and an
`NSCache` keyed on the whole request. Every request carried a freshly
signed media auth header, so the key never matched and nothing was
cached on disk.
### Validation
Relay media downloads for the 48 custom emoji matching "nod" (local
relay, iPhone 17 Pro simulator):
| Step | main | this PR |
| --- | --- | --- |
| First open | 48 | 48 |
| Leave and re-enter the channel, reopen | 48 | 0 |
| Relaunch the app, reopen | 48 | 0 |
| Reinstall the app, reopen | not measured | 0 |
Before (main): every reopen downloads again, and animated emoji are
still.
https://github.com/user-attachments/assets/7a43dd6a-61e0-495d-abed-6c11f7d4f965
After (this PR): reopening shows cached emoji immediately, and animated
emoji play.
https://github.com/user-attachments/assets/bf45a5c0-77ef-4501-8843-6f42e15de389
Automated app run: signed in to a local relay, opened a channel,
long-pressed a message, opened the full picker, searched, closed, left
and re-entered the channel, reopened, relaunched and reopened. Repeated
on the final head (359fdc8) with a warm cache: 0 downloads across open,
re-entering the channel and relaunch, all emoji rendered. The run used
the simulator only; device and hosted-relay behavior were not exercised.
Added tests:
- `media_disk_cache_test.dart`: encoded bytes for a native surface
download once, survive a relaunch, and bytes that never decode are not
saved.
- `emoji_picker_test.dart`: the native sheet's `mediaBytes` call returns
authorized bytes, a second call makes no request, and a cancelled call
fails.
- `emoji_picker_test.dart`: at most four loads run at once, a queued
load cancelled before it starts never downloads, and a saved emoji
doesn't wait for a slot.
- `media_disk_cache_test.dart`: a damaged saved copy (including a
truncated PNG) is evicted and downloaded again.
- `media_image_test.dart`: encoded-bytes requests share one download
with simultaneous image loads, and only decoded bytes reach observers.
- `NativeMessageImageLoaderTests.swift`: a GIF with uneven delays keeps
each frame's share, a cancelled decode returns nothing, and the decode
gate admits four in order and drops a cancelled waiter.
Removed `NativeEmojiRedirectPolicyTests` and the native concurrency test
along with the Swift loader they covered.
### Regressions
- Network: fewer requests. Cold loads keep the old picker's
four-at-a-time limit, so on a slow HTTP/1.1 origin queued requests don't
time out waiting for a connection. Downloads use the shared media HTTP
client, the same one other app images use, which on iOS now runs over
HTTP/2 since [#8897 iOS
HTTP/2](https://github.com/block/buzz/pull/8897).
- Memory: the picker keeps no image cache of its own. Each view decodes,
downsampled to 84 px and at most four at a time, from bytes Flutter
already holds in memory or on disk.
- Disk: emoji go into the existing 250 MB LRU media cache.
---------
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
288 lines
12 KiB
Swift
288 lines
12 KiB
Swift
import UIKit
|
|
import XCTest
|
|
@testable import Buzz
|
|
|
|
final class NativeMessageImageLoaderTests: XCTestCase {
|
|
private func loader(limit: Int = 1) -> NativeMessageImageLoader {
|
|
let configuration = URLSessionConfiguration.ephemeral
|
|
configuration.protocolClasses = [MessageImageProtocol.self]
|
|
return NativeMessageImageLoader(configuration: configuration, maximumConcurrent: limit)
|
|
}
|
|
|
|
@MainActor func testRejectsDeclaredOversizeWithoutFinishingBody() async {
|
|
let done = expectation(description: "rejected")
|
|
MessageImageProtocol.start = { transport in
|
|
transport.client?.urlProtocol(transport, didReceive: HTTPURLResponse(
|
|
url: transport.request.url!, statusCode: 200, httpVersion: nil,
|
|
headerFields: ["Content-Length": "\(NativeMessageImageLoader.maximumBytes + 1)", "Content-Type": "image/png"]
|
|
)!, cacheStoragePolicy: .notAllowed)
|
|
// Let URLProtocol deliver its headers without finishing the body. A
|
|
// completion-handler byte check would hang here, rather than reject.
|
|
transport.client?.urlProtocol(transport, didLoad: Data(count: 1024))
|
|
}
|
|
let loader = loader()
|
|
_ = loader.load(URLRequest(url: URL(string: "https://example.com/declared")!)) { image in
|
|
XCTAssertNil(image)
|
|
done.fulfill()
|
|
}
|
|
await fulfillment(of: [done], timeout: 2)
|
|
}
|
|
|
|
@MainActor func testRejectsChunkedOversizeWithoutWaitingForCompletion() async {
|
|
let done = expectation(description: "stream cancelled")
|
|
MessageImageProtocol.start = { transport in
|
|
transport.client?.urlProtocol(transport, didReceive: HTTPURLResponse(
|
|
url: transport.request.url!, statusCode: 200, httpVersion: nil, headerFields: nil
|
|
)!, cacheStoragePolicy: .notAllowed)
|
|
transport.client?.urlProtocol(transport, didLoad: Data(count: NativeMessageImageLoader.maximumBytes))
|
|
transport.client?.urlProtocol(transport, didLoad: Data([0]))
|
|
// No finish callback: the streaming byte guard must terminate the load.
|
|
}
|
|
let loader = loader()
|
|
_ = loader.load(URLRequest(url: URL(string: "https://example.com/chunked")!)) { image in
|
|
XCTAssertNil(image)
|
|
done.fulfill()
|
|
}
|
|
await fulfillment(of: [done], timeout: 2)
|
|
}
|
|
|
|
@MainActor func testDeduplicatesAndCancellationReleasesAdmission() async {
|
|
let first = expectation(description: "first admitted")
|
|
let second = expectation(description: "second admitted after cancellation")
|
|
var started = [String]()
|
|
MessageImageProtocol.start = { transport in
|
|
DispatchQueue.main.async {
|
|
started.append(transport.request.url!.path)
|
|
if started.count == 1 { first.fulfill() } else { second.fulfill() }
|
|
}
|
|
}
|
|
let loader = loader()
|
|
let request = URLRequest(url: URL(string: "https://example.com/shared")!)
|
|
let cancelFirst = loader.load(request) { _ in XCTFail("cancelled subscriber called") }
|
|
let cancelDuplicate = loader.load(request) { _ in XCTFail("cancelled duplicate called") }
|
|
let cancelQueued = loader.load(URLRequest(url: URL(string: "https://example.com/queued")!)) { _ in
|
|
XCTFail("cancelled queued subscriber called")
|
|
}
|
|
let cancelNext = loader.load(URLRequest(url: URL(string: "https://example.com/next")!)) { _ in }
|
|
await fulfillment(of: [first], timeout: 2)
|
|
XCTAssertEqual(started, ["/shared"])
|
|
cancelFirst()
|
|
cancelQueued()
|
|
// One subscriber remains: cancelling the first must not cancel its peer.
|
|
let turn = expectation(description: "cancellation processed")
|
|
DispatchQueue.main.async { turn.fulfill() }
|
|
await fulfillment(of: [turn], timeout: 2)
|
|
XCTAssertEqual(started, ["/shared"])
|
|
cancelDuplicate()
|
|
await fulfillment(of: [second], timeout: 2)
|
|
XCTAssertEqual(started, ["/shared", "/next"])
|
|
cancelNext()
|
|
}
|
|
|
|
@MainActor func testCachesDecodedImages() async {
|
|
let done = expectation(description: "decoded")
|
|
let image = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)).pngData { _ in }
|
|
var requests = 0
|
|
MessageImageProtocol.start = { transport in
|
|
requests += 1
|
|
transport.client?.urlProtocol(transport, didReceive: HTTPURLResponse(
|
|
url: transport.request.url!, statusCode: 200, httpVersion: nil, headerFields: nil
|
|
)!, cacheStoragePolicy: .notAllowed)
|
|
transport.client?.urlProtocol(transport, didLoad: image)
|
|
transport.client?.urlProtocolDidFinishLoading(transport)
|
|
}
|
|
let loader = loader()
|
|
let request = URLRequest(url: URL(string: "https://example.com/cached")!)
|
|
_ = loader.load(request) { image in XCTAssertNotNil(image); done.fulfill() }
|
|
await fulfillment(of: [done], timeout: 2)
|
|
var cached = false
|
|
_ = loader.load(request) { image in cached = image != nil }
|
|
XCTAssertTrue(cached)
|
|
XCTAssertEqual(requests, 1)
|
|
}
|
|
}
|
|
|
|
final class NativeMessageImageLoaderDecodeTests: XCTestCase {
|
|
/// A 1x1 GIF with one frame per delay, in centiseconds.
|
|
private func gif(_ delays: [Int]) -> Data {
|
|
var bytes: [UInt8] = Array("GIF89a".utf8)
|
|
bytes += [1, 0, 1, 0, 0x80, 0, 0] // 1x1, two-colour global table
|
|
bytes += [0, 0, 0, 0xff, 0xff, 0xff]
|
|
for delay in delays {
|
|
bytes += [0x21, 0xf9, 4, 0, UInt8(delay & 0xff), UInt8(delay >> 8), 0, 0] // frame delay
|
|
bytes += [0x2c, 0, 0, 0, 0, 1, 0, 1, 0, 0] // 1x1 image
|
|
bytes += [2, 2, 0x44, 1, 0] // one pixel
|
|
}
|
|
bytes.append(0x3b)
|
|
return Data(bytes)
|
|
}
|
|
|
|
func testShowsFramesOfTenMillisecondsOrLessForOneHundred() throws {
|
|
// Browsers and the Flutter timeline show 0 and 1 cs frames for 100 ms;
|
|
// longer frames keep their own delay.
|
|
let image = try XCTUnwrap(NativeMessageImageLoader.decode(gif([0, 1, 2, 5])))
|
|
XCTAssertEqual(holds(image), [10, 10, 2, 5])
|
|
XCTAssertEqual(image.duration, 0.1 + 0.1 + 0.02 + 0.05, accuracy: 0.001)
|
|
}
|
|
|
|
func testUnevenDelaysKeepEachFramesShare() throws {
|
|
// UIKit spaces frames evenly, so a held frame repeats for its share.
|
|
let image = try XCTUnwrap(NativeMessageImageLoader.decode(gif([10, 10, 300])))
|
|
XCTAssertEqual(holds(image), [1, 1, 30])
|
|
XCTAssertEqual(image.duration, 3.2, accuracy: 0.001)
|
|
}
|
|
|
|
func testCancelledDecodeReturnsNil() {
|
|
XCTAssertNil(NativeMessageImageLoader.decode(gif([5, 5]), isCancelled: { true }))
|
|
}
|
|
|
|
func testStillImageIsNotAnimated() throws {
|
|
let image = try XCTUnwrap(NativeMessageImageLoader.decode(gif([5])))
|
|
XCTAssertNil(image.images)
|
|
}
|
|
|
|
/// How many consecutive entries each decoded frame fills.
|
|
private func holds(_ image: UIImage) -> [Int] {
|
|
var runs: [(frame: UIImage, count: Int)] = []
|
|
for frame in image.images ?? [] {
|
|
if let last = runs.last, last.frame === frame {
|
|
runs[runs.count - 1].count += 1
|
|
} else {
|
|
runs.append((frame, 1))
|
|
}
|
|
}
|
|
return runs.map(\.count)
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
final class NativeEmojiDecodeGateTests: XCTestCase {
|
|
func testAdmitsFourAndHandsSlotsOnInOrder() async throws {
|
|
for _ in 0..<NativeEmojiDecodeGate.limit { try await NativeEmojiDecodeGate.acquire() }
|
|
var admitted: [Int] = []
|
|
// Let each waiter queue before the next one starts.
|
|
func waiter(_ number: Int) async -> Task<Void, Error> {
|
|
let task = Task { try await NativeEmojiDecodeGate.acquire(); admitted.append(number) }
|
|
for _ in 0..<10 { await Task.yield() }
|
|
return task
|
|
}
|
|
let fifth = await waiter(5)
|
|
let sixth = await waiter(6)
|
|
let seventh = await waiter(7)
|
|
XCTAssertEqual(admitted, [])
|
|
|
|
// A waiter whose cell left gives up its place.
|
|
sixth.cancel()
|
|
do {
|
|
try await sixth.value
|
|
XCTFail("a cancelled waiter must not be admitted")
|
|
} catch is CancellationError {}
|
|
|
|
NativeEmojiDecodeGate.release()
|
|
try await fifth.value
|
|
NativeEmojiDecodeGate.release()
|
|
try await seventh.value
|
|
XCTAssertEqual(admitted, [5, 7])
|
|
|
|
for _ in 0..<NativeEmojiDecodeGate.limit { NativeEmojiDecodeGate.release() }
|
|
}
|
|
}
|
|
|
|
private final class MessageImageProtocol: URLProtocol {
|
|
static var start: ((MessageImageProtocol) -> Void)?
|
|
override class func canInit(with request: URLRequest) -> Bool { true }
|
|
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
|
|
override func startLoading() { Self.start?(self) }
|
|
override func stopLoading() {}
|
|
}
|
|
|
|
|
|
final class NativeReactionDetailsTests: XCTestCase {
|
|
@MainActor func testInlineEmojiAvatarRendersEmojiAndBackground() {
|
|
let controller = NativeReactionDetailsViewController(data: [
|
|
"reactions": [["emoji": "❤️", "label": "Heart", "users": ["person"]]],
|
|
"profiles": ["person": ["name": "Kenny", "avatarEmoji": "😊", "avatarColor": NSNumber(value: UInt32(0xFFFF6B9A))]],
|
|
])
|
|
let cell = controller.tableView(UITableView(), cellForRowAt: IndexPath(row: 0, section: 0))
|
|
let row = cell.contentView.subviews.compactMap { $0 as? UIStackView }.first!
|
|
let avatar = row.arrangedSubviews[0] as! NativeMessageGlyph
|
|
XCTAssertEqual(avatar.subviews.compactMap { $0 as? UILabel }.first?.text, "😊")
|
|
XCTAssertEqual(avatar.backgroundColor, UIColor(red: 1, green: 107.0 / 255, blue: 154.0 / 255, alpha: 1))
|
|
controller.updateProfiles(["person": ["name": "Kenny", "avatarEmoji": "🎉", "avatarColor": NSNumber(value: UInt32(0xFFFFE75C))]])
|
|
let updated = controller.tableView(UITableView(), cellForRowAt: IndexPath(row: 0, section: 0))
|
|
let updatedRow = updated.contentView.subviews.compactMap { $0 as? UIStackView }.first!
|
|
XCTAssertEqual(updatedRow.arrangedSubviews[0].subviews.compactMap { $0 as? UILabel }.first?.text, "🎉")
|
|
}
|
|
|
|
@MainActor func testShortcodeReactionWithoutImageNeverShowsText() {
|
|
let glyph = NativeMessageGlyph(
|
|
data: ["emoji": ":ghost:", "isShortcode": true], size: 26, isReaction: true)
|
|
XCTAssertNil(glyph.subviews.compactMap { $0 as? UILabel }.first?.text)
|
|
XCTAssertNotNil(glyph.subviews.compactMap { $0 as? UIImageView }.first?.image)
|
|
}
|
|
|
|
@MainActor func testTogglesListEveryReactorAndRelabelUpdatedProfiles() {
|
|
let controller = NativeReactionDetailsViewController(data: [
|
|
"reactions": [
|
|
["emoji": "❤️", "label": "Heart", "count": 2, "users": ["human", "agent"]],
|
|
["emoji": "🔥", "label": "Fire", "count": 1, "users": ["agent"]],
|
|
],
|
|
"profiles": ["human": ["name": "Honey"], "agent": ["name": "Honey (agent)"]],
|
|
])
|
|
var toggled: [String] = []
|
|
controller.onToggle = { toggled.append($0) }
|
|
controller.loadViewIfNeeded()
|
|
let table = UITableView()
|
|
func labels() -> [String] {
|
|
(0..<controller.tableView(table, numberOfRowsInSection: 0)).map {
|
|
controller.tableView(table, cellForRowAt: IndexPath(row: $0, section: 0)).accessibilityLabel ?? ""
|
|
}
|
|
}
|
|
func descendants(_ view: UIView) -> [UIView] {
|
|
view.subviews.flatMap { [$0] + descendants($0) }
|
|
}
|
|
func tap(_ label: String) {
|
|
let button = descendants(controller.view).compactMap { $0 as? UIButton }
|
|
.first { $0.accessibilityLabel == label }
|
|
XCTAssertNotNil(button, label)
|
|
button?.sendActions(for: .primaryActionTriggered)
|
|
}
|
|
XCTAssertEqual(labels(), ["Honey, Heart", "Honey (agent), Heart", "Honey (agent), Fire"])
|
|
tap("Fire 1")
|
|
tap("Heart 2")
|
|
XCTAssertEqual(toggled, ["🔥", "❤️"])
|
|
controller.updateProfiles(["agent": ["name": "Helper (agent)"]])
|
|
XCTAssertEqual(labels(), ["Honey, Heart", "Helper (agent), Heart", "Helper (agent), Fire"])
|
|
}
|
|
}
|
|
|
|
|
|
final class NativeMessageLayoutTests: XCTestCase {
|
|
private func descendants(_ view: UIView) -> [UIView] {
|
|
view.subviews.flatMap { [$0] + descendants($0) }
|
|
}
|
|
|
|
@MainActor func testReactionFiltersFitAccessibilityText() {
|
|
let parent = UIViewController()
|
|
let controller = NativeReactionDetailsViewController(data: [
|
|
"reactions": [["emoji": "❤️", "label": "Heart", "count": 12345, "users": ["a"]]],
|
|
])
|
|
parent.addChild(controller)
|
|
parent.setOverrideTraitCollection(UITraitCollection(preferredContentSizeCategory: .accessibilityExtraExtraExtraLarge), forChild: controller)
|
|
parent.view.addSubview(controller.view)
|
|
controller.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
|
controller.view.setNeedsLayout()
|
|
controller.view.layoutIfNeeded()
|
|
let filter = descendants(controller.view).compactMap { $0 as? UIButton }
|
|
.first { $0.accessibilityLabel == "Heart 12345" }
|
|
XCTAssertNotNil(filter)
|
|
let viewport = descendants(controller.view).compactMap { $0 as? UIScrollView }
|
|
.first { !($0 is UITableView) }
|
|
XCTAssertNotNil(viewport)
|
|
let needed = filter?.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height ?? 0
|
|
XCTAssertGreaterThan(needed, 48)
|
|
XCTAssertGreaterThanOrEqual(viewport?.bounds.height ?? 0, needed)
|
|
XCTAssertGreaterThanOrEqual(filter?.bounds.height ?? 0, needed)
|
|
}
|
|
}
|