fix(swift-ios): show active work and image previews

This commit is contained in:
Theo Browne committed 2026-08-09 20:52:52 -07:00
1 parent 14d1a9ed6b
commit b01cc94775
5 files changed
+125 -31

No files matched your search

+24 -1
View File
@@ -2394,6 +2394,12 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
renderCacheIsSource: true,
delta: delta
)
self.scheduleAttachmentHydration(
in: detail,
threadID: route.uiID,
client: route.client,
environmentID: route.environmentID
)
}
}
@@ -4042,7 +4048,16 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
client: T3Client,
environmentID: String
) {
attachmentHydrationTasks[threadID]?.task.cancel()
guard detail.messages.contains(where: { message in
message.attachments.contains {
$0.mimeType.hasPrefix("image/") && $0.url == nil
}
}) else {
return
}
// Streaming activity can publish many detail revisions per second. Let the
// current asset resolution finish instead of continuously restarting it.
guard attachmentHydrationTasks[threadID] == nil else { return }
let generation = environmentGeneration
let workID = UUID()
let task = Task { [weak self] in
@@ -4061,6 +4076,14 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging,
self.latestDetails[threadID] == detail,
hydrated != detail else {
self.finishAttachmentHydration(threadID: threadID, workID: workID)
if let latest = self.latestDetails[threadID], latest != detail {
self.scheduleAttachmentHydration(
in: latest,
threadID: threadID,
client: client,
environmentID: environmentID
)
}
return
}
self.publish(
@@ -131,25 +131,23 @@ struct FeatureImageAttachmentPicker: View {
// A confirmation dialog remains the active presenter during its action. Dispatch
// independently of the dialog's view task so dismissal cannot cancel presentation.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) {
FeaturePhotoLibraryPresenter.present(maximumCount: max(1, remainingCount)) { images in
loadPhotoSelection(images)
FeaturePhotoLibraryPresenter.present(maximumCount: max(1, remainingCount)) { image in
loadPhotoSelection(image)
}
}
}
private func loadPhotoSelection(_ images: [Data]) {
guard !images.isEmpty else { return }
let operation = preparationState.begin(itemCount: images.count)
private func loadPhotoSelection(_ image: Data) {
guard remainingCount > 0 else { return }
let ordinal = attachments.count + preparationState.pendingItemCount + 1
let operation = preparationState.begin(itemCount: 1)
Task {
defer { preparationState.finish(operation) }
for data in images.prefix(remainingCount) {
do {
try await appendImage(data)
} catch {
errorMessage = error.localizedDescription
break
}
do {
try await appendImage(image, ordinal: ordinal)
} catch {
errorMessage = error.localizedDescription
}
}
}
@@ -204,8 +202,8 @@ struct FeatureImageAttachmentPicker: View {
}
}
private func appendImage(_ data: Data) async throws {
let ordinal = attachments.count + 1
private func appendImage(_ data: Data, ordinal: Int? = nil) async throws {
let ordinal = ordinal ?? attachments.count + 1
let attachment = try await Task.detached(priority: .userInitiated) {
try FeatureImageProcessor.attachment(from: data, ordinal: ordinal)
}.value
@@ -217,7 +215,7 @@ struct FeatureImageAttachmentPicker: View {
private enum FeaturePhotoLibraryPresenter {
private static var delegates: [ObjectIdentifier: Delegate] = [:]
static func present(maximumCount: Int, onSelect: @escaping ([Data]) -> Void) {
static func present(maximumCount: Int, onSelect: @escaping (Data) -> Void) {
var configuration = PHPickerConfiguration(photoLibrary: .shared())
configuration.filter = .images
configuration.selectionLimit = maximumCount
@@ -246,9 +244,13 @@ private enum FeaturePhotoLibraryPresenter {
}
final class Delegate: NSObject, PHPickerViewControllerDelegate {
private let onSelect: ([Data]) -> Void
private struct Provider: @unchecked Sendable {
let value: NSItemProvider
}
init(onSelect: @escaping ([Data]) -> Void) {
private let onSelect: (Data) -> Void
init(onSelect: @escaping (Data) -> Void) {
self.onSelect = onSelect
}
@@ -256,13 +258,19 @@ private enum FeaturePhotoLibraryPresenter {
picker.dismiss(animated: true)
guard !results.isEmpty else { return FeaturePhotoLibraryPresenter.finish(picker) }
let providers = results.map { Provider(value: $0.itemProvider) }
Task { @MainActor in
var images: [Data] = []
for result in results {
guard let data = try? await result.itemProvider.imageData() else { continue }
images.append(data)
await withTaskGroup(of: Data?.self) { group in
for provider in providers {
group.addTask {
try? await provider.value.imageData()
}
}
for await data in group {
guard let data else { continue }
onSelect(data)
}
}
onSelect(images)
FeaturePhotoLibraryPresenter.finish(picker)
}
}
@@ -289,8 +289,9 @@ public struct ThreadDetailView: View {
}
private func timeline(_ detail: FeatureThreadDetail) -> some View {
Group {
if detail.messages.isEmpty {
let isWorking = detail.thread.state == .working || detail.thread.state == .queued
return Group {
if detail.messages.isEmpty, !isWorking {
ContentUnavailableView(
"Ready for a task",
systemImage: "sparkles",
@@ -303,6 +304,7 @@ public struct ThreadDetailView: View {
messages: detail.messages,
renderUpdate: model.detailRenderUpdates[thread.id],
dynamicTypeSize: dynamicTypeSize,
isWorking: isWorking,
onDismissKeyboard: dismissKeyboard
)
}
@@ -572,6 +574,8 @@ enum FeatureComposerDraftRestoration {
/// 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 static let workingIndicatorID = "__t3-working-indicator__"
private enum Section: Hashable {
case transcript
}
@@ -580,6 +584,7 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
let messages: [FeatureMessage]
let renderUpdate: FeatureDetailRenderUpdate?
let dynamicTypeSize: DynamicTypeSize
let isWorking: Bool
let onDismissKeyboard: () -> Void
func makeCoordinator() -> Coordinator {
@@ -608,6 +613,7 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
messages: messages,
renderUpdate: renderUpdate,
dynamicTypeSize: dynamicTypeSize,
isWorking: isWorking,
onDismissKeyboard: onDismissKeyboard,
in: collectionView
)
@@ -651,6 +657,7 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
private var currentThreadID: String?
private var currentDetailRevision: UInt64?
private var currentDynamicTypeSize: DynamicTypeSize?
private var currentIsWorking = false
private var markdownPrefetches: [String: MarkdownPrefetch] = [:]
private var onDismissKeyboard: (() -> Void)?
@@ -661,6 +668,15 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
func connect(to collectionView: UICollectionView) {
let registration = UICollectionView.CellRegistration<UICollectionViewCell, String> {
[weak self] cell, _, messageID in
if messageID == FeatureTranscriptCollectionView.workingIndicatorID {
cell.contentConfiguration = UIHostingConfiguration {
FeatureThreadWorkingIndicator()
}
.margins(.all, 0)
cell.backgroundConfiguration = UIBackgroundConfiguration.clear()
cell.accessibilityIdentifier = "thread-working-indicator"
return
}
guard let message = self?.messagesByID[messageID] else {
cell.contentConfiguration = nil
return
@@ -693,6 +709,7 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
messages: [FeatureMessage],
renderUpdate: FeatureDetailRenderUpdate?,
dynamicTypeSize: DynamicTypeSize,
isWorking: Bool,
onDismissKeyboard: @escaping () -> Void,
in collectionView: UICollectionView
) {
@@ -702,7 +719,8 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
let threadChanged = currentThreadID != threadID
let typeSizeChanged = currentDynamicTypeSize != dynamicTypeSize
let revisionChanged = currentDetailRevision != renderUpdate?.revision
guard threadChanged || typeSizeChanged || revisionChanged else { return }
let workingChanged = currentIsWorking != isWorking
guard threadChanged || typeSizeChanged || revisionChanged || workingChanged else { return }
let incremental = !threadChanged
? incrementalState(messages: messages, renderUpdate: renderUpdate)
@@ -716,7 +734,8 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
currentDetailRevision = renderUpdate?.revision
currentDynamicTypeSize = dynamicTypeSize
guard threadChanged || idsChanged || !changedIDs.isEmpty else { return }
currentIsWorking = isWorking
guard threadChanged || idsChanged || !changedIDs.isEmpty || workingChanged else { return }
if threadChanged {
cancelAllMarkdownPrefetches()
@@ -729,7 +748,7 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
}
let wasNearBottom = isNearBottom(collectionView)
let lastIDChanged = orderedIDs.last != newIDs.last
let lastIDChanged = orderedIDs.last != newIDs.last || workingChanged
let isInitialLoad = currentThreadID == nil || threadChanged
let previousIDs = orderedIDs
@@ -755,6 +774,15 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
snapshot.appendSections([.transcript])
snapshot.appendItems(newIDs, toSection: .transcript)
}
if snapshot.indexOfItem(FeatureTranscriptCollectionView.workingIndicatorID) != nil {
snapshot.deleteItems([FeatureTranscriptCollectionView.workingIndicatorID])
}
if isWorking {
snapshot.appendItems(
[FeatureTranscriptCollectionView.workingIndicatorID],
toSection: .transcript
)
}
let appendedIDSet = Set(state.appendedIDs)
snapshot.reconfigureItems(changedIDs.filter { !appendedIDSet.contains($0) })
@@ -954,6 +982,30 @@ private struct FeatureTranscriptCollectionView: UIViewRepresentable {
}
}
private struct FeatureThreadWorkingIndicator: View {
var body: some View {
HStack(alignment: .top, spacing: 10) {
Image(systemName: "circle.dotted")
.font(.system(size: 17, weight: .semibold))
.foregroundStyle(T3Colors.statusRunning)
.frame(width: 22, height: 22)
VStack(alignment: .leading, spacing: 2) {
Text("Agent is working")
.font(T3Typography.supportingStrong)
.foregroundStyle(T3Colors.statusRunning)
Text("New output will appear here")
.font(T3Typography.supporting)
.foregroundStyle(T3Colors.textTertiary)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.vertical, 4)
.accessibilityElement(children: .combine)
.accessibilityLabel("Agent is working. New output will appear here.")
}
}
struct TranscriptViewportGeometry: Equatable {
let contentHeight: CGFloat
let viewportHeight: CGFloat
@@ -1257,7 +1309,12 @@ private struct FeatureMessageAttachmentsView: View {
VStack(alignment: .leading, spacing: 6) {
if attachment.mimeType.hasPrefix("image/") {
Group {
if let url = attachment.url {
if let previewData = attachment.previewData,
let image = UIImage(data: previewData) {
Image(uiImage: image)
.resizable()
.scaledToFit()
} else if let url = attachment.url {
FeatureRemoteAttachmentThumbnail(url: url)
} else {
attachmentPlaceholder(systemImage: "photo")
@@ -390,7 +390,8 @@ public final class FeatureRootModel {
id: $0.id.uuidString,
name: $0.filename,
mimeType: $0.mimeType,
sizeBytes: $0.byteCount
sizeBytes: $0.byteCount,
previewData: $0.thumbnailData
)
}
)
@@ -231,19 +231,24 @@ public struct FeatureMessageAttachment: Identifiable, Sendable, Equatable, Hasha
public var mimeType: String
public var sizeBytes: Int
public var url: URL?
/// Small local preview retained only while an optimistic message is replaced
/// by its server-backed attachment URL.
public var previewData: Data?
public init(
id: String,
name: String,
mimeType: String,
sizeBytes: Int,
url: URL? = nil
url: URL? = nil,
previewData: Data? = nil
) {
self.id = id
self.name = name
self.mimeType = mimeType
self.sizeBytes = sizeBytes
self.url = url
self.previewData = previewData
}
}