perf(swift-ios): lighten streaming UI and close lifecycle gaps

- Move table column-width estimation into the background render pass
  and store it on MarkdownRenderedTable; the view measured every cell's
  AttributedString per body evaluation on the main thread
- Make rendered markdown blocks Equatable (inline runs compare by
  reference thanks to the streaming run cache) and wrap block views in
  .equatable(), so only the changed tail of a streaming message
  re-renders instead of every block
- Gate the thread header's per-second TimelineView on working status;
  idle threads render a static status
- Decode local attachment previews off-main through the shared
  thumbnail cache; UIImage(data:) ran in body per reconfigure
- Memoize composer trigger parsing (was parsed 4x per keystroke)
- Drop markdown caches on memory warnings
- Stop the QR capture session on viewDidDisappear/backgrounding and
  resume on reappear; dismantle was the only stop path
- Retry pending workspace navigation requests when snapshot data lands
  so cold-start deep links are not silently dropped
- Scope approval/user-input resolution to details that contain the
  request instead of deep-comparing every cached transcript
- Binary-search diff hydration anchors (was O(n^2) on large files)

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Fable 5 committed 2026-08-09 20:53:11 -07:00
1 parent 99f78a7d1f
commit 106d7b866d
8 files changed
+188 -41

No files matched your search

@@ -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] {
@@ -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 {
@@ -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<NSString, MarkdownRenderedDocument>()
private let inlineRuns = NSCache<NSString, MarkdownRenderedInlineBox>()
@@ -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
)
)
}
@@ -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 {
@@ -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
@@ -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: []))
@@ -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] = []
@@ -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 {