diff --git a/apps/swift-ios/Features/Chat/FeatureComposerView.swift b/apps/swift-ios/Features/Chat/FeatureComposerView.swift index c21bd93fe9..369e2427f2 100644 --- a/apps/swift-ios/Features/Chat/FeatureComposerView.swift +++ b/apps/swift-ios/Features/Chat/FeatureComposerView.swift @@ -315,8 +315,22 @@ struct FeatureComposerView: View { DailyUXModelOptions.supportsImages(selection: selection, providers: providers) } + /// Trigger detection walks the whole draft with character indices and is + /// read from several computed properties per body evaluation, so one parse + /// per keystroke is memoized instead of four. + private final class TriggerMemo { + var text: String? + var trigger: FeatureComposerTrigger? + } + + @State private var triggerMemo = TriggerMemo() + private var composerTrigger: FeatureComposerTrigger? { - FeatureComposerTriggerParser.detect(in: text) + if triggerMemo.text == text { return triggerMemo.trigger } + let trigger = FeatureComposerTriggerParser.detect(in: text) + triggerMemo.text = text + triggerMemo.trigger = trigger + return trigger } private var commandMenuItems: [FeatureComposerMenuItem] { diff --git a/apps/swift-ios/Features/Chat/MarkdownMessageView.swift b/apps/swift-ios/Features/Chat/MarkdownMessageView.swift index 29584d2333..a9a218bf43 100644 --- a/apps/swift-ios/Features/Chat/MarkdownMessageView.swift +++ b/apps/swift-ios/Features/Chat/MarkdownMessageView.swift @@ -139,13 +139,17 @@ private struct MarkdownBlocksView: View { var body: some View { VStack(alignment: .leading, spacing: spacing) { ForEach(blocks.indices, id: \.self) { index in + // Unchanged blocks share inline runs by reference across + // streaming revisions, so equatable comparison skips their + // body and layout entirely; only the changed tail re-renders. MarkdownBlockView(block: blocks[index]) + .equatable() } } } } -private struct MarkdownBlockView: View { +private struct MarkdownBlockView: View, Equatable { let block: MarkdownRenderedBlock @ViewBuilder @@ -193,12 +197,8 @@ private struct MarkdownBlockView: View { private struct MarkdownTableView: View { let table: MarkdownRenderedTable - private let columnWidths: [CGFloat] - init(table: MarkdownRenderedTable) { - self.table = table - columnWidths = Self.measureColumnWidths(table) - } + private var columnWidths: [CGFloat] { table.columnWidths } var body: some View { ScrollView(.horizontal) { @@ -266,24 +266,6 @@ private struct MarkdownTableView: View { } } - private static func measureColumnWidths(_ table: MarkdownRenderedTable) -> [CGFloat] { - let cells = [table.header] + table.rows - return table.header.indices.map { columnIndex in - let longestLine = cells - .compactMap { row -> Int? in - guard row.indices.contains(columnIndex) else { return nil } - return String(row[columnIndex].attributedText.characters) - .split(separator: "\n", omittingEmptySubsequences: false) - .map(\.count) - .max() - } - .max() ?? 0 - - // This is deliberately an estimate rather than text measurement. Exact widths - // would require laying every cell out twice, which is expensive in long threads. - return min(300, max(140, CGFloat(longestLine) * 8.25)) - } - } } private struct MarkdownListView: View { diff --git a/apps/swift-ios/Features/Chat/MarkdownRenderCache.swift b/apps/swift-ios/Features/Chat/MarkdownRenderCache.swift index 583a680ba2..62dff05350 100644 --- a/apps/swift-ios/Features/Chat/MarkdownRenderCache.swift +++ b/apps/swift-ios/Features/Chat/MarkdownRenderCache.swift @@ -1,5 +1,6 @@ import Foundation import SwiftUI +import UIKit /// An exact content revision with a cheap, deterministic hash for SwiftUI task identity. /// Source equality remains the final check, so a fingerprint collision cannot return stale text. @@ -74,18 +75,52 @@ final class MarkdownRenderedInline: @unchecked Sendable { } } -struct MarkdownRenderedListItem: @unchecked Sendable { +extension MarkdownRenderedInline: Equatable { + /// Streaming revisions share unchanged runs by reference (see the inline + /// cache), so identity comparison is both cheap and effective: unchanged + /// paragraphs compare equal without touching their attributed text. + static func == (lhs: MarkdownRenderedInline, rhs: MarkdownRenderedInline) -> Bool { + lhs === rhs + } +} + +struct MarkdownRenderedListItem: Equatable, @unchecked Sendable { let task: MarkdownTaskState? let blocks: [MarkdownRenderedBlock] } -struct MarkdownRenderedTable: @unchecked Sendable { +struct MarkdownRenderedTable: Equatable, @unchecked Sendable { let header: [MarkdownRenderedInline] let alignments: [MarkdownTableAlignment] let rows: [[MarkdownRenderedInline]] + /// Estimated per-column widths, computed once on the render task so the + /// table view never measures cell text on the main thread. + let columnWidths: [CGFloat] + + static func estimatedColumnWidths( + header: [MarkdownRenderedInline], + rows: [[MarkdownRenderedInline]] + ) -> [CGFloat] { + let cells = [header] + rows + return header.indices.map { columnIndex in + let longestLine = cells + .compactMap { row -> Int? in + guard row.indices.contains(columnIndex) else { return nil } + return String(row[columnIndex].attributedText.characters) + .split(separator: "\n", omittingEmptySubsequences: false) + .map(\.count) + .max() + } + .max() ?? 0 + + // Deliberately an estimate rather than text measurement. Exact + // widths would require laying every cell out twice. + return min(300, max(140, CGFloat(longestLine) * 8.25)) + } + } } -indirect enum MarkdownRenderedBlock: @unchecked Sendable { +indirect enum MarkdownRenderedBlock: Equatable, @unchecked Sendable { case paragraph(MarkdownRenderedInline) case heading(level: Int, inline: MarkdownRenderedInline) case unorderedList([MarkdownRenderedListItem]) @@ -119,7 +154,19 @@ private final class MarkdownRenderedInlineBox: NSObject { /// unchanged messages. Cache misses are rendered by a detached task and duplicate requests /// for the same revision share one in-flight render. final class MarkdownRenderCache: @unchecked Sendable { - static let shared = MarkdownRenderCache() + static let shared: MarkdownRenderCache = { + let cache = MarkdownRenderCache() + // NSCache only sheds objects; in-flight renders and their waiters are + // ours to drop when the system is under pressure. + NotificationCenter.default.addObserver( + forName: UIApplication.didReceiveMemoryWarningNotification, + object: nil, + queue: nil + ) { _ in + cache.removeAll() + } + return cache + }() private let documents = NSCache() private let inlineRuns = NSCache() @@ -348,7 +395,11 @@ final class MarkdownRenderCache: @unchecked Sendable { return MarkdownRenderedTable( header: header, alignments: table.alignments, - rows: rows + rows: rows, + columnWidths: MarkdownRenderedTable.estimatedColumnWidths( + header: header, + rows: rows + ) ) } diff --git a/apps/swift-ios/Features/Chat/ThreadDetailView.swift b/apps/swift-ios/Features/Chat/ThreadDetailView.swift index d4a2305e04..98ec9c2f21 100644 --- a/apps/swift-ios/Features/Chat/ThreadDetailView.swift +++ b/apps/swift-ios/Features/Chat/ThreadDetailView.swift @@ -178,8 +178,17 @@ public struct ThreadDetailView: View { Spacer(minLength: 6) - TimelineView(.periodic(from: .now, by: 1)) { context in - headerStatus(at: context.date) + // The per-second timeline only exists for the live working + // duration; idle threads render a static status instead of + // waking every second forever. + Group { + if currentThread.homeStatus == .working { + TimelineView(.periodic(from: .now, by: 1)) { context in + headerStatus(at: context.date) + } + } else { + headerStatus(at: .now) + } } .fixedSize(horizontal: true, vertical: false) } @@ -1147,6 +1156,55 @@ private struct FeatureRemoteAttachmentThumbnail: View { } } +/// Local preview bytes routed through the shared thumbnail cache so streaming +/// reconfigures of a message with attachments never re-allocate UIImages in +/// body. Decode happens once, off the main thread. +private struct FeatureLocalAttachmentThumbnail: View { + let attachmentID: String + let previewData: Data + + @State private var image: UIImage? + @State private var failed = false + + private var cacheKey: NSString { "local:\(attachmentID)" as NSString } + + var body: some View { + Group { + if let image = image ?? FeatureAttachmentThumbnailCache.shared.image(for: cacheKey) { + Image(uiImage: image) + .resizable() + .scaledToFit() + } else if failed { + placeholder(systemImage: "exclamationmark.triangle") + } else { + placeholder(systemImage: "photo") + } + } + .accessibilityHidden(true) + .task(id: attachmentID) { + guard FeatureAttachmentThumbnailCache.shared.image(for: cacheKey) == nil else { return } + let data = previewData + let decoded = await Task.detached(priority: .utility) { + UIImage(data: data) + }.value + guard !Task.isCancelled else { return } + if let decoded { + FeatureAttachmentThumbnailCache.shared.insert(decoded, for: cacheKey) + image = decoded + } else { + failed = true + } + } + } + + 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 @@ -1324,11 +1382,11 @@ private struct FeatureMessageAttachmentsView: View { VStack(alignment: .leading, spacing: 6) { if attachment.mimeType.hasPrefix("image/") { Group { - if let previewData = attachment.previewData, - let image = UIImage(data: previewData) { - Image(uiImage: image) - .resizable() - .scaledToFit() + if let previewData = attachment.previewData { + FeatureLocalAttachmentThumbnail( + attachmentID: attachment.id, + previewData: previewData + ) } else if let url = attachment.url { FeatureRemoteAttachmentThumbnail(url: url) } else { diff --git a/apps/swift-ios/Features/Connection/QRCodeScannerView.swift b/apps/swift-ios/Features/Connection/QRCodeScannerView.swift index e0dc3f292f..9ff3b77a71 100644 --- a/apps/swift-ios/Features/Connection/QRCodeScannerView.swift +++ b/apps/swift-ios/Features/Connection/QRCodeScannerView.swift @@ -213,6 +213,25 @@ private final class QRScannerViewController: UIViewController { view.backgroundColor = .black } + // SwiftUI does not reliably dismantle a representable the moment its + // fullScreenCover dismisses, and backgrounding never dismantles it, so + // stop the camera on disappear and resume it when the view returns. + override func viewDidDisappear(_ animated: Bool) { + super.viewDidDisappear(animated) + stop() + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + guard previewLayer != nil else { return } + let session = captureSession + sessionQueue.async { + if !session.isRunning { + session.startRunning() + } + } + } + override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() previewLayer?.frame = view.bounds diff --git a/apps/swift-ios/Features/Root/FeatureRootModel.swift b/apps/swift-ios/Features/Root/FeatureRootModel.swift index e1ccd519f9..cbd1e5ae7f 100644 --- a/apps/swift-ios/Features/Root/FeatureRootModel.swift +++ b/apps/swift-ios/Features/Root/FeatureRootModel.swift @@ -471,7 +471,10 @@ public final class FeatureRootModel { await perform { try await client.resolveApproval(id: id, decision: decision) guard currentEnvironmentIdentity == environment else { return } - for key in Array(details.keys) { + // Only touch details that actually hold the request; mutateDetail + // deep-compares each mutated detail and the cache never shrinks. + for key in Array(details.keys) + where details[key]?.approvals.contains(where: { $0.id == id }) == true { mutateDetail( id: key, change: .delta(FeatureDetailDelta(changedMessages: [])) @@ -487,7 +490,8 @@ public final class FeatureRootModel { await perform { try await client.resolveUserInput(id: id, answers: answers) guard currentEnvironmentIdentity == environment else { return } - for key in Array(details.keys) { + for key in Array(details.keys) + where details[key]?.userInputs.contains(where: { $0.id == id }) == true { mutateDetail( id: key, change: .delta(FeatureDetailDelta(changedMessages: [])) diff --git a/apps/swift-ios/Features/Shared/FeatureToolModels.swift b/apps/swift-ios/Features/Shared/FeatureToolModels.swift index 9cae0a0b79..78ecf40b12 100644 --- a/apps/swift-ios/Features/Shared/FeatureToolModels.swift +++ b/apps/swift-ios/Features/Shared/FeatureToolModels.swift @@ -658,9 +658,22 @@ enum FeatureFullDiffHydrator { guard let oldLine = line.oldLine, let newLine = line.newLine else { return nil } return (newLine, oldLine - newLine) } + // Anchors ascend by new-line number; binary search keeps hydration + // linear instead of scanning every anchor per emitted context line. func oldLine(for newLine: Int) -> Int? { - let anchor = anchors.last(where: { $0.new <= newLine }) ?? anchors.first - return anchor.map { newLine + $0.offset } + guard !anchors.isEmpty else { return nil } + var low = 0 + var high = anchors.count + while low < high { + let mid = (low + high) / 2 + if anchors[mid].new <= newLine { + low = mid + 1 + } else { + high = mid + } + } + let anchor = low > 0 ? anchors[low - 1] : anchors[0] + return newLine + anchor.offset } var output: [FeatureDiffLine] = [] diff --git a/apps/swift-ios/Features/Workspace/WorkspaceView.swift b/apps/swift-ios/Features/Workspace/WorkspaceView.swift index 96f33ba8ba..737c451d1e 100644 --- a/apps/swift-ios/Features/Workspace/WorkspaceView.swift +++ b/apps/swift-ios/Features/Workspace/WorkspaceView.swift @@ -170,6 +170,12 @@ public struct WorkspaceView: View { .onChange(of: navigationRequest?.id, initial: true) { _, _ in consumeNavigationRequest() } + // A request that arrives before its thread or project exists in the + // snapshot stays pending; retry it as data lands so cold-start deep + // links are not silently stranded. + .onChange(of: model.homePresentationRevision) { _, _ in + if navigationRequest != nil { consumeNavigationRequest() } + } .task(id: nextSidebarBoundary) { guard let boundary = nextSidebarBoundary else { return } do {