From 3cceb302bb48595797d7377d9c729242e48a7cac Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Fri, 31 Jul 2026 15:33:05 -0700 Subject: [PATCH] perf(ios): recycle native transcript rows --- .../Features/Chat/ThreadDetailView.swift | 688 +++++++++++++++--- 1 file changed, 603 insertions(+), 85 deletions(-) diff --git a/apps/swift-ios/Features/Chat/ThreadDetailView.swift b/apps/swift-ios/Features/Chat/ThreadDetailView.swift index ad45d13752..e4804ef2e7 100644 --- a/apps/swift-ios/Features/Chat/ThreadDetailView.swift +++ b/apps/swift-ios/Features/Chat/ThreadDetailView.swift @@ -1,6 +1,9 @@ +import ImageIO import SwiftUI +import UIKit public struct ThreadDetailView: View { + @SwiftUI.Environment(\.dynamicTypeSize) private var dynamicTypeSize @SwiftUI.Environment(\.horizontalSizeClass) private var horizontalSizeClass @Bindable var model: FeatureRootModel @@ -295,76 +298,56 @@ public struct ThreadDetailView: View { } private func timeline(_ detail: FeatureThreadDetail) -> some View { - ScrollViewReader { proxy in - ScrollView { - LazyVStack(alignment: .leading, spacing: 22) { - if detail.messages.isEmpty { - ContentUnavailableView( - "Ready for a task", - systemImage: "sparkles", - description: Text("Tell the agent what you want to build.") - ) - .frame(maxWidth: .infinity) - .padding(.top, 80) - } - - ForEach(detail.messages) { message in - FeatureMessageView(message: message) - .id(message.id) - } - - Color.clear.frame(height: 1).id("timeline-bottom") - } - .padding(.horizontal, 18) - .padding(.top, 18) - .padding(.bottom, 14) - .frame(maxWidth: T3Metrics.readingWidth) - .frame(maxWidth: .infinity) - } - .scrollDismissesKeyboard(.interactively) - .task(id: thread.id) { - await Task.yield() - proxy.scrollTo("timeline-bottom", anchor: .bottom) - } - .onChange(of: detail.messages.last?.id) { - withAnimation(.easeOut(duration: 0.18)) { - proxy.scrollTo("timeline-bottom", anchor: .bottom) - } - } - .safeAreaInset(edge: .bottom, spacing: 0) { - FeatureComposerView( - text: $draft, - selection: $selection, - attachments: $attachments, - providers: model.snapshot.providers, - threadSelection: currentSelection, - isSending: isSending, - isWorking: detail.thread.state == .working || detail.thread.state == .queued, - focused: $composerFocused, - onSend: send, - onStop: { - Task { await model.cancelTurn(threadID: thread.id) } - }, - runtimeMode: currentThread.runtimeMode, - interactionMode: currentThread.interactionMode, - onRuntimeModeChange: { mode in - Task { await model.setRuntimeMode(thread.id, mode: mode) } - }, - onInteractionModeChange: { mode in - Task { await model.setInteractionMode(thread.id, mode: mode) } - }, - pendingApprovals: detail.approvals, - pendingUserInputs: detail.userInputs, - isResolvingRequest: model.isPerformingAction, - onApprovalDecision: { id, decision in - Task { await model.resolveApproval(id, decision: decision) } - }, - onUserInputSubmit: { id, answers in - Task { await model.resolveUserInput(id, answers: answers) } - } + Group { + if detail.messages.isEmpty { + ContentUnavailableView( + "Ready for a task", + systemImage: "sparkles", + description: Text("Tell the agent what you want to build.") + ) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + FeatureTranscriptCollectionView( + threadID: thread.id, + messages: detail.messages, + renderUpdate: model.detailRenderUpdates[thread.id], + dynamicTypeSize: dynamicTypeSize ) } } + .safeAreaInset(edge: .bottom, spacing: 0) { + FeatureComposerView( + text: $draft, + selection: $selection, + attachments: $attachments, + providers: model.snapshot.providers, + threadSelection: currentSelection, + isSending: isSending, + isWorking: detail.thread.state == .working || detail.thread.state == .queued, + focused: $composerFocused, + onSend: send, + onStop: { + Task { await model.cancelTurn(threadID: thread.id) } + }, + runtimeMode: currentThread.runtimeMode, + interactionMode: currentThread.interactionMode, + onRuntimeModeChange: { mode in + Task { await model.setRuntimeMode(thread.id, mode: mode) } + }, + onInteractionModeChange: { mode in + Task { await model.setInteractionMode(thread.id, mode: mode) } + }, + pendingApprovals: detail.approvals, + pendingUserInputs: detail.userInputs, + isResolvingRequest: model.isPerformingAction, + onApprovalDecision: { id, decision in + Task { await model.resolveApproval(id, decision: decision) } + }, + onUserInputSubmit: { id, answers in + Task { await model.resolveUserInput(id, answers: answers) } + } + ) + } } private func send() { @@ -425,6 +408,550 @@ private enum FeatureThreadToolSurface: String, Identifiable { var id: String { rawValue } } +/// A recycled transcript surface. SwiftUI still owns each message's rendering, +/// while UIKit keeps offscreen messages out of the active view hierarchy. +private struct FeatureTranscriptCollectionView: UIViewRepresentable { + private enum Section: Hashable { + case transcript + } + + let threadID: String + let messages: [FeatureMessage] + let renderUpdate: FeatureDetailRenderUpdate? + let dynamicTypeSize: DynamicTypeSize + + func makeCoordinator() -> Coordinator { + Coordinator() + } + + func makeUIView(context: Context) -> UICollectionView { + let collectionView = BottomAnchoredTranscriptCollectionView( + frame: .zero, + collectionViewLayout: Self.makeLayout() + ) + collectionView.backgroundColor = .black + collectionView.alwaysBounceVertical = true + collectionView.keyboardDismissMode = .interactive + collectionView.contentInsetAdjustmentBehavior = .never + collectionView.isPrefetchingEnabled = true + collectionView.accessibilityIdentifier = "thread-transcript" + context.coordinator.connect(to: collectionView) + return collectionView + } + + func updateUIView(_ collectionView: UICollectionView, context: Context) { + context.coordinator.update( + threadID: threadID, + messages: messages, + renderUpdate: renderUpdate, + dynamicTypeSize: dynamicTypeSize, + in: collectionView + ) + } + + private static func makeLayout() -> UICollectionViewLayout { + UICollectionViewCompositionalLayout { _, environment in + let width = environment.container.effectiveContentSize.width + let sideInset = max(18, (width - T3Metrics.readingWidth) / 2) + let itemSize = NSCollectionLayoutSize( + widthDimension: .fractionalWidth(1), + heightDimension: .estimated(120) + ) + let item = NSCollectionLayoutItem(layoutSize: itemSize) + let group = NSCollectionLayoutGroup.vertical( + layoutSize: itemSize, + subitems: [item] + ) + let section = NSCollectionLayoutSection(group: group) + section.interGroupSpacing = 22 + section.contentInsets = NSDirectionalEdgeInsets( + top: 18, + leading: sideInset, + bottom: 14, + trailing: sideInset + ) + return section + } + } + + @MainActor + final class Coordinator: NSObject, UICollectionViewDataSourcePrefetching, UICollectionViewDelegate { + private struct MarkdownPrefetch { + let revision: MarkdownContentRevision + let task: Task + } + + private var dataSource: UICollectionViewDiffableDataSource? + private var messagesByID: [String: FeatureMessage] = [:] + private var orderedIDs: [String] = [] + private var currentThreadID: String? + private var currentDetailRevision: UInt64? + private var currentDynamicTypeSize: DynamicTypeSize? + private var markdownPrefetches: [String: MarkdownPrefetch] = [:] + + deinit { + markdownPrefetches.values.forEach { $0.task.cancel() } + } + + func connect(to collectionView: UICollectionView) { + let registration = UICollectionView.CellRegistration { + [weak self] cell, _, messageID in + guard let message = self?.messagesByID[messageID] else { + cell.contentConfiguration = nil + return + } + + cell.contentConfiguration = UIHostingConfiguration { + FeatureMessageView(message: message) + } + .margins(.all, 0) + cell.backgroundConfiguration = UIBackgroundConfiguration.clear() + cell.accessibilityIdentifier = "message-cell-\(messageID)" + } + + dataSource = UICollectionViewDiffableDataSource( + collectionView: collectionView + ) { collectionView, indexPath, messageID in + collectionView.dequeueConfiguredReusableCell( + using: registration, + for: indexPath, + item: messageID + ) + } + collectionView.prefetchDataSource = self + collectionView.delegate = self + } + + func update( + threadID: String, + messages: [FeatureMessage], + renderUpdate: FeatureDetailRenderUpdate?, + dynamicTypeSize: DynamicTypeSize, + in collectionView: UICollectionView + ) { + guard let dataSource else { return } + + let threadChanged = currentThreadID != threadID + let typeSizeChanged = currentDynamicTypeSize != dynamicTypeSize + let revisionChanged = currentDetailRevision != renderUpdate?.revision + guard threadChanged || typeSizeChanged || revisionChanged else { return } + + let incremental = !threadChanged + ? incrementalState(messages: messages, renderUpdate: renderUpdate) + : nil + let state = incremental ?? fullState(messages: messages) + let newIDs = state.ids + let idsChanged = state.idsChanged + let changedIDs = typeSizeChanged + ? newIDs + : state.changedIDs + + currentDetailRevision = renderUpdate?.revision + currentDynamicTypeSize = dynamicTypeSize + guard threadChanged || idsChanged || !changedIDs.isEmpty else { return } + + if threadChanged { + cancelAllMarkdownPrefetches() + } else { + var invalidatedIDs = Set(changedIDs) + if idsChanged, !state.isAppendOnly { + invalidatedIDs.formUnion(Set(orderedIDs).subtracting(newIDs)) + } + cancelMarkdownPrefetches(for: invalidatedIDs) + } + + let wasNearBottom = isNearBottom(collectionView) + let lastIDChanged = orderedIDs.last != newIDs.last + let isInitialLoad = currentThreadID == nil || threadChanged + let previousIDs = orderedIDs + + currentThreadID = threadID + if let replacementMessagesByID = state.replacementMessagesByID { + messagesByID = replacementMessagesByID + } + orderedIDs = newIDs + (collectionView as? BottomAnchoredTranscriptCollectionView)?.maintainsBottomAnchor = + isInitialLoad || wasNearBottom + + var snapshot: NSDiffableDataSourceSnapshot + if !threadChanged, !idsChanged { + snapshot = dataSource.snapshot() + } else if !threadChanged, state.isAppendOnly { + snapshot = dataSource.snapshot() + snapshot.appendItems(state.appendedIDs, toSection: .transcript) + } else if !threadChanged, newIDs.starts(with: previousIDs) { + snapshot = dataSource.snapshot() + snapshot.appendItems(Array(newIDs.dropFirst(previousIDs.count)), toSection: .transcript) + } else { + snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([.transcript]) + snapshot.appendItems(newIDs, toSection: .transcript) + } + let appendedIDSet = Set(state.appendedIDs) + snapshot.reconfigureItems(changedIDs.filter { !appendedIDSet.contains($0) }) + + let shouldFollowBottom = isInitialLoad || wasNearBottom + dataSource.apply(snapshot, animatingDifferences: false) { + [weak self, weak collectionView] in + guard shouldFollowBottom, let self, let collectionView else { return } + DispatchQueue.main.async { + self.scrollToBottom( + collectionView, + animated: !isInitialLoad && lastIDChanged + ) + } + } + } + + private struct MessageState { + let ids: [String] + let replacementMessagesByID: [String: FeatureMessage]? + let changedIDs: [String] + let appendedIDs: [String] + let idsChanged: Bool + let isAppendOnly: Bool + } + + private func incrementalState( + messages: [FeatureMessage], + renderUpdate: FeatureDetailRenderUpdate? + ) -> MessageState? { + guard let currentDetailRevision, + let renderUpdate, + renderUpdate.baseRevision == currentDetailRevision, + case let .delta(delta) = renderUpdate.change, + messages.count == orderedIDs.count + delta.appendedMessageIDs.count else { + return nil + } + + let appendedIDs = delta.appendedMessageIDs + guard Set(appendedIDs).count == appendedIDs.count, + appendedIDs.allSatisfy({ messagesByID[$0] == nil }) else { + return nil + } + + let appendedIDSet = Set(appendedIDs) + let changedMessageIDs = Set(delta.changedMessages.map(\.id)) + guard appendedIDs.allSatisfy(changedMessageIDs.contains), + delta.changedMessages.allSatisfy({ + messagesByID[$0.id] != nil || appendedIDSet.contains($0.id) + }) else { + return nil + } + + var changedIDs: [String] = [] + changedIDs.reserveCapacity(delta.changedMessages.count) + for message in delta.changedMessages { + if messagesByID[message.id] != message { + changedIDs.append(message.id) + } + messagesByID[message.id] = message + } + + return MessageState( + ids: appendedIDs.isEmpty ? orderedIDs : orderedIDs + appendedIDs, + replacementMessagesByID: nil, + changedIDs: changedIDs, + appendedIDs: appendedIDs, + idsChanged: !appendedIDs.isEmpty, + isAppendOnly: !appendedIDs.isEmpty + ) + } + + private func fullState(messages: [FeatureMessage]) -> MessageState { + var seenMessageIDs = Set() + let uniqueMessages = Array(messages.reversed().filter { + seenMessageIDs.insert($0.id).inserted + }.reversed()) + let ids = uniqueMessages.map(\.id) + let updatedMessages = uniqueMessages.reduce(into: [String: FeatureMessage]()) { + $0[$1.id] = $1 + } + return MessageState( + ids: ids, + replacementMessagesByID: updatedMessages, + changedIDs: ids.filter { messagesByID[$0] != updatedMessages[$0] }, + appendedIDs: [], + idsChanged: orderedIDs != ids, + isAppendOnly: false + ) + } + + func collectionView( + _ collectionView: UICollectionView, + prefetchItemsAt indexPaths: [IndexPath] + ) { + for indexPath in indexPaths where orderedIDs.indices.contains(indexPath.item) { + let messageID = orderedIDs[indexPath.item] + guard markdownPrefetches[messageID] == nil, + let message = messagesByID[messageID], + !message.text.isEmpty, + message.state != .streaming, + message.role == .user || message.role == .assistant else { + continue + } + + let revision = MarkdownContentRevision(message.text) + guard MarkdownRenderCache.shared.cachedDocument(for: revision) == nil else { + continue + } + + let task = Task { [weak self] in + guard !Task.isCancelled else { return } + _ = await MarkdownRenderCache.shared.document(for: revision) + guard !Task.isCancelled else { return } + self?.finishMarkdownPrefetch(messageID: messageID, revision: revision) + } + markdownPrefetches[messageID] = MarkdownPrefetch( + revision: revision, + task: task + ) + } + } + + func collectionView( + _ collectionView: UICollectionView, + cancelPrefetchingForItemsAt indexPaths: [IndexPath] + ) { + let messageIDs = indexPaths.compactMap { indexPath in + orderedIDs.indices.contains(indexPath.item) ? orderedIDs[indexPath.item] : nil + } + cancelMarkdownPrefetches(for: Set(messageIDs)) + } + + private func finishMarkdownPrefetch( + messageID: String, + revision: MarkdownContentRevision + ) { + guard markdownPrefetches[messageID]?.revision == revision else { return } + markdownPrefetches.removeValue(forKey: messageID) + } + + private func cancelMarkdownPrefetches(for messageIDs: Set) { + for messageID in messageIDs { + markdownPrefetches.removeValue(forKey: messageID)?.task.cancel() + } + } + + private func cancelAllMarkdownPrefetches() { + markdownPrefetches.values.forEach { $0.task.cancel() } + markdownPrefetches.removeAll(keepingCapacity: true) + } + + private func isNearBottom(_ collectionView: UICollectionView) -> Bool { + let visibleBottom = collectionView.contentOffset.y + + collectionView.bounds.height + - collectionView.adjustedContentInset.bottom + return collectionView.contentSize.height - visibleBottom < 120 + } + + private func scrollToBottom( + _ collectionView: UICollectionView, + animated: Bool + ) { + guard let lastID = dataSource?.snapshot().itemIdentifiers.last, + let indexPath = dataSource?.indexPath(for: lastID) else { + return + } + collectionView.layoutIfNeeded() + collectionView.scrollToItem( + at: indexPath, + at: .bottom, + animated: animated + ) + (collectionView as? BottomAnchoredTranscriptCollectionView)?.maintainsBottomAnchor = true + } + + func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { + (scrollView as? BottomAnchoredTranscriptCollectionView)?.maintainsBottomAnchor = false + } + + func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { + guard !decelerate else { return } + updateBottomAnchor(for: scrollView) + } + + func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { + updateBottomAnchor(for: scrollView) + } + + private func updateBottomAnchor(for scrollView: UIScrollView) { + guard let collectionView = scrollView as? BottomAnchoredTranscriptCollectionView else { + return + } + collectionView.maintainsBottomAnchor = isNearBottom(collectionView) + } + } +} + +/// Self-sizing hosted Markdown can change the transcript height after a snapshot finishes. +/// Preserve the visual bottom only while the reader is already following the latest turn. +private final class BottomAnchoredTranscriptCollectionView: UICollectionView { + var maintainsBottomAnchor = false + + private var lastLaidOutContentHeight: CGFloat = 0 + private var isRestoringBottomAnchor = false + + override func layoutSubviews() { + super.layoutSubviews() + + let newHeight = contentSize.height + defer { lastLaidOutContentHeight = newHeight } + guard maintainsBottomAnchor, + !isDragging, + !isDecelerating, + !isRestoringBottomAnchor, + lastLaidOutContentHeight > 0, + abs(newHeight - lastLaidOutContentHeight) > 0.5 else { + return + } + + let minimumY = -adjustedContentInset.top + let bottomY = max( + minimumY, + newHeight - bounds.height + adjustedContentInset.bottom + ) + guard abs(contentOffset.y - bottomY) > 0.5 else { return } + + isRestoringBottomAnchor = true + contentOffset = CGPoint(x: contentOffset.x, y: bottomY) + isRestoringBottomAnchor = false + } +} + +private struct FeatureRemoteAttachmentThumbnail: View { + private struct Request: Hashable { + let url: URL + let maximumPixelSize: Int + } + + @SwiftUI.Environment(\.displayScale) private var displayScale + @State private var image: UIImage? + @State private var loadedRequest: Request? + @State private var failedRequest: Request? + + let url: URL + + var body: some View { + Group { + if loadedRequest == request, let image { + Image(uiImage: image) + .resizable() + .scaledToFit() + } else if failedRequest == request { + placeholder(systemImage: "exclamationmark.triangle") + } else { + placeholder(systemImage: "photo") + } + } + .accessibilityHidden(true) + .task(id: request) { + let activeRequest = request + do { + let image = try await FeatureAttachmentThumbnailLoader.image( + for: activeRequest.url, + maximumPixelSize: activeRequest.maximumPixelSize + ) + try Task.checkCancellation() + self.image = image + loadedRequest = activeRequest + failedRequest = nil + } catch is CancellationError { + return + } catch { + guard !Task.isCancelled else { return } + image = nil + loadedRequest = nil + failedRequest = activeRequest + } + } + } + + private var request: Request { + Request( + url: url, + maximumPixelSize: min(768, max(190, Int(ceil(190 * displayScale)))) + ) + } + + private func placeholder(systemImage: String) -> some View { + Image(systemName: systemImage) + .font(.system(size: 22, weight: .medium)) + .foregroundStyle(T3Colors.textSecondary) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } +} + +private enum FeatureAttachmentThumbnailLoader { + static func image(for url: URL, maximumPixelSize: Int) async throws -> UIImage { + let cacheKey = "\(url.absoluteString)#\(maximumPixelSize)" as NSString + if let cached = FeatureAttachmentThumbnailCache.shared.image(for: cacheKey) { + return cached + } + + let (data, response) = try await URLSession.shared.data(from: url) + try Task.checkCancellation() + if let response = response as? HTTPURLResponse, + !(200...299).contains(response.statusCode) { + throw FeatureAttachmentThumbnailError.invalidResponse + } + + let image = try await Task.detached(priority: .utility) { + try downsample(data: data, maximumPixelSize: maximumPixelSize) + }.value + try Task.checkCancellation() + FeatureAttachmentThumbnailCache.shared.insert(image, for: cacheKey) + return image + } + + private static func downsample(data: Data, maximumPixelSize: Int) throws -> UIImage { + let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary + guard let source = CGImageSourceCreateWithData(data as CFData, sourceOptions) else { + throw FeatureAttachmentThumbnailError.decodingFailed + } + + let thumbnailOptions = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: maximumPixelSize, + kCGImageSourceShouldCacheImmediately: true, + ] as CFDictionary + guard let thumbnail = CGImageSourceCreateThumbnailAtIndex( + source, + 0, + thumbnailOptions + ) else { + throw FeatureAttachmentThumbnailError.decodingFailed + } + return UIImage(cgImage: thumbnail) + } +} + +private final class FeatureAttachmentThumbnailCache: @unchecked Sendable { + static let shared = FeatureAttachmentThumbnailCache() + + private let images = NSCache() + + private init() { + images.countLimit = 96 + images.totalCostLimit = 32 * 1_024 * 1_024 + } + + func image(for key: NSString) -> UIImage? { + images.object(forKey: key) + } + + func insert(_ image: UIImage, for key: NSString) { + let cost = image.cgImage.map { $0.bytesPerRow * $0.height } ?? 0 + images.setObject(image, forKey: key, cost: cost) + } +} + +private enum FeatureAttachmentThumbnailError: Error { + case invalidResponse + case decodingFailed +} + struct FeatureMessageView: View { let message: FeatureMessage @@ -436,7 +963,10 @@ struct FeatureMessageView: View { VStack(alignment: .leading, spacing: 10) { FeatureMessageAttachmentsView(attachments: message.attachments) if !message.text.isEmpty { - MarkdownMessageView(message.text) + MarkdownMessageView( + message.text, + isStreaming: message.state == .streaming + ) } } .padding(.horizontal, 14) @@ -467,7 +997,10 @@ struct FeatureMessageView: View { } FeatureMessageAttachmentsView(attachments: message.attachments) if !message.text.isEmpty { - MarkdownMessageView(message.text) + MarkdownMessageView( + message.text, + isStreaming: message.state == .streaming + ) .frame(maxWidth: .infinity, alignment: .leading) } } @@ -527,22 +1060,7 @@ private struct FeatureMessageAttachmentsView: View { if attachment.mimeType.hasPrefix("image/") { Group { if let url = attachment.url { - AsyncImage(url: url) { phase in - switch phase { - case let .success(image): - image - .resizable() - .scaledToFit() - case .failure: - attachmentPlaceholder( - systemImage: "exclamationmark.triangle" - ) - case .empty: - attachmentPlaceholder(systemImage: "photo") - @unknown default: - attachmentPlaceholder(systemImage: "photo") - } - } + FeatureRemoteAttachmentThumbnail(url: url) } else { attachmentPlaceholder(systemImage: "photo") }