From 041df3c44ddd5f949b54e88d732470fcddce1e98 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 6 Aug 2026 03:19:36 -0700 Subject: [PATCH] fix(swift-ios): address review findings on streaming and caps - Move streaming markdown rendering out of .task(id:) into a renderer that survives revision changes; the per-revision task cancelled any in-flight parse, so messages that parse slower than the publish cadence never rendered. One render runs at a time, latest revision wins, 150ms throttle. Keep showing the previous streamed document between renders instead of flashing back to plain text. - Cap the terminal buffer in UTF-8 bytes (the unit the limit is defined in) instead of Character count, snapping to a character boundary. - Start the home list timer after items are populated so an initially working thread gets the 1Hz interval; re-evaluate on every update. - Sort activities by memoized parsed dates (stable, wire-order ties); raw ISO strings sort wrong across mixed fractional representations. Co-Authored-By: Claude Fable 5 --- apps/swift-ios/App/NativeFeatureClient.swift | 33 +++++-- .../Features/Chat/MarkdownMessageView.swift | 99 +++++++++++++------ .../Workspace/HomeThreadCollectionView.swift | 4 +- 3 files changed, 99 insertions(+), 37 deletions(-) diff --git a/apps/swift-ios/App/NativeFeatureClient.swift b/apps/swift-ios/App/NativeFeatureClient.swift index d7ff6630fb..458d5d08bd 100644 --- a/apps/swift-ios/App/NativeFeatureClient.swift +++ b/apps/swift-ios/App/NativeFeatureClient.swift @@ -1877,8 +1877,22 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, private static let terminalBufferLimit = 256 * 1024 private static func cappedTerminalBuffer(_ buffer: String) -> String { - guard buffer.utf8.count > terminalBufferLimit else { return buffer } - let tail = buffer.suffix(terminalBufferLimit) + let utf8 = buffer.utf8 + guard utf8.count > terminalBufferLimit else { return buffer } + // Slice in UTF-8 bytes (the unit the limit is defined in), then snap + // forward to a character boundary so multibyte output cannot blow + // past the cap or tear a scalar. + let byteStart = utf8.index(utf8.endIndex, offsetBy: -terminalBufferLimit) + var start = byteStart.samePosition(in: buffer) + if start == nil { + var probe = byteStart + while probe < utf8.endIndex, start == nil { + probe = utf8.index(after: probe) + start = probe.samePosition(in: buffer) + } + } + guard let start else { return buffer } + let tail = buffer[start...] // Trim to the next line boundary so the top of the view isn't a torn line. if let newline = tail.firstIndex(of: "\n") { return String(tail[tail.index(after: newline)...]) @@ -3423,13 +3437,20 @@ final class NativeFeatureClient: FeatureClient, FeatureDeviceManaging, upsertMergedMessage(message, cache: cache) } - /// Wire timestamps are fixed-width ISO8601 UTC, so lexicographic order is - /// chronological order. Comparing raw strings avoids running the date - /// formatter O(n log n) times over a long activity log. + /// Decorate-sort so each timestamp is parsed once (via the memoized date + /// cache) instead of inside an O(n log n) comparator. Raw string order is + /// not safe here: the wire can mix fractional and non-fractional ISO8601 + /// representations, which sort lexicographically wrong. Ties keep wire + /// order so a request and its resolution never swap. private func sortedByCreation( _ activities: [OrchestrationActivity] ) -> [OrchestrationActivity] { - activities.sorted { $0.createdAt < $1.createdAt } + activities.enumerated() + .map { (index: $0.offset, date: parseDate($0.element.createdAt), activity: $0.element) } + .sorted { lhs, rhs in + lhs.date != rhs.date ? lhs.date < rhs.date : lhs.index < rhs.index + } + .map(\.activity) } private func seedWorkLogs( diff --git a/apps/swift-ios/Features/Chat/MarkdownMessageView.swift b/apps/swift-ios/Features/Chat/MarkdownMessageView.swift index a9a218bf43..eb1fdb4f77 100644 --- a/apps/swift-ios/Features/Chat/MarkdownMessageView.swift +++ b/apps/swift-ios/Features/Chat/MarkdownMessageView.swift @@ -12,7 +12,7 @@ struct MarkdownMessageView: View { private let revision: MarkdownContentRevision private let isStreaming: Bool @State private var renderedDocument: MarkdownRenderedDocument? - @State private var lastStreamRenderAt: Date? + @State private var streamingRenderer = StreamingMarkdownRenderer() @State private var isSelectingText = false init(_ source: String, isStreaming: Bool = false) { @@ -79,34 +79,15 @@ struct MarkdownMessageView: View { return } - // Streamed revisions arrive faster than a trailing debounce could - // ever fire, so throttle instead: render right away when the last - // render is old enough, otherwise wait out the remainder. The - // message stays live markdown while streaming instead of falling - // back to plain text for the whole turn. - let throttle: Duration = .milliseconds(150) - if let lastStreamRenderAt { - let elapsed = Duration.seconds(-lastStreamRenderAt.timeIntervalSinceNow) - if elapsed < throttle { - do { - try await Task.sleep(for: throttle - elapsed) - } catch { - return - } - } - } - guard !Task.isCancelled else { return } - - guard let rendered = await MarkdownRenderCache.shared.document( - for: revision, - isIntermediate: true - ), - !Task.isCancelled, - rendered.revision == revision else { - return - } - lastStreamRenderAt = .now - renderedDocument = rendered + // Hand the revision to a renderer that outlives this task. The + // task modifier cancels on every revision, so rendering inside it + // starves as soon as parsing is slower than the publish cadence; + // the renderer instead keeps one render running and always picks + // up the newest revision when it finishes (latest wins). + streamingRenderer.submit(revision) { renderedDocument = $0 } + } + .onDisappear { + streamingRenderer.cancel() } } @@ -114,11 +95,69 @@ struct MarkdownMessageView: View { if let renderedDocument, renderedDocument.revision == revision { return renderedDocument } - guard !isStreaming else { return nil } + // While streaming, a slightly stale document is better than flashing + // back to plain text between renders; streamed content only appends. + if isStreaming { return renderedDocument } return MarkdownRenderCache.shared.documentImmediately(for: revision) } } +/// Renders streaming revisions outside SwiftUI's task lifecycle so a render +/// in progress is never cancelled by the next revision arriving. One render +/// runs at a time; newer revisions replace the pending slot (latest wins) and +/// a 150ms throttle bounds the render cadence. +@MainActor +private final class StreamingMarkdownRenderer { + private let throttle: Duration = .milliseconds(150) + private var pending: MarkdownContentRevision? + private var deliver: ((MarkdownRenderedDocument) -> Void)? + private var renderTask: Task? + private var lastRenderAt: Date? + + func submit( + _ revision: MarkdownContentRevision, + deliver: @escaping (MarkdownRenderedDocument) -> Void + ) { + pending = revision + self.deliver = deliver + guard renderTask == nil else { return } + renderTask = Task { [weak self] in + await self?.drain() + } + } + + func cancel() { + renderTask?.cancel() + renderTask = nil + pending = nil + deliver = nil + } + + private func drain() async { + defer { renderTask = nil } + while let revision = pending { + pending = nil + if let lastRenderAt { + let elapsed = Duration.seconds(-lastRenderAt.timeIntervalSinceNow) + if elapsed < throttle { + try? await Task.sleep(for: throttle - elapsed) + } + } + guard !Task.isCancelled else { return } + // Render the newest revision available after the throttle wait. + let target = pending ?? revision + pending = nil + guard let document = await MarkdownRenderCache.shared.document( + for: target, + isIntermediate: true + ) else { continue } + guard !Task.isCancelled else { return } + lastRenderAt = .now + deliver?(document) + } + } +} + private struct MarkdownTextSelectionModifier: ViewModifier { let isEnabled: Bool diff --git a/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift b/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift index 365b5ec2e5..0e7d1e8698 100644 --- a/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift +++ b/apps/swift-ios/Features/Workspace/HomeThreadCollectionView.swift @@ -102,7 +102,6 @@ struct HomeThreadCollectionView: UIViewRepresentable { ) } - startTimer() update(parent: parent, collectionView: collectionView) } @@ -117,6 +116,9 @@ struct HomeThreadCollectionView: UIViewRepresentable { seenIdentifiers.insert(item.id).inserted } itemsByID = Dictionary(uniqueKeysWithValues: items.map { ($0.id, $0) }) + // After items land: picks 1 Hz when a working thread is present, + // 60s otherwise, and is a no-op when the interval is unchanged. + startTimer() guard let dataSource else { return } let currentIdentifiers = dataSource.snapshot().itemIdentifiers