From c16593f6ee0f370b1f92e4d74151cb4fedc16325 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:06:18 -0800 Subject: [PATCH 1/9] Count a view's layout and image work in flight The layout engine and the image store now count their work in a PendingWork counter. A drain counts from when it is scheduled until it ends. A result counts until the view takes it from the mailbox. A picture load, a formula render and a code highlight count until they end, also when they return nothing. The relayout on main after a picture, a formula or code colors arrive counts too. The count reaches zero only when no work is left. A later commit uses it to tell when the view shows its final content. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Layout/ImageStore.swift | 16 ++ .../TranscriptKit/Layout/LayoutEngine.swift | 25 ++- .../TranscriptKit/Layout/PendingWork.swift | 36 +++++ .../iOS/TranscriptTextView.swift | 31 ++-- .../ContentSettledTests.swift | 148 ++++++++++++++++++ 5 files changed, 236 insertions(+), 20 deletions(-) create mode 100644 Sources/TranscriptKit/Layout/PendingWork.swift create mode 100644 Tests/TranscriptKitTests/ContentSettledTests.swift diff --git a/Sources/TranscriptKit/Layout/ImageStore.swift b/Sources/TranscriptKit/Layout/ImageStore.swift index 71a3e14..fa8c675 100644 --- a/Sources/TranscriptKit/Layout/ImageStore.swift +++ b/Sources/TranscriptKit/Layout/ImageStore.swift @@ -10,6 +10,8 @@ import Foundation final class TranscriptImageStore: @unchecked Sendable { typealias Loader = @Sendable (TranscriptImage) async -> CGImage? + /// Counts the loads, formulas and highlights in flight. + let work: PendingWork private let lock = NSLock() private var pictures: [String: CGImage] = [:] private var requested: Set = [] @@ -27,6 +29,10 @@ final class TranscriptImageStore: @unchecked Sendable { private var highlighting: Set = [] private var waitingCode: [String: (text: String, language: String?)] = [:] + init(work: PendingWork = PendingWork()) { + self.work = work + } + /// Goes up each time a picture arrives; layouts made at an older /// revision may show placeholders where pictures now are. var revision: Int { lock.withLock { _revision } } @@ -46,6 +52,7 @@ final class TranscriptImageStore: @unchecked Sendable { } /// Sets what to call (on any thread) when a picture or colors arrive. + /// Work that the call starts must begin on `work` before it returns. func setOnChange(_ onChange: (@Sendable () -> Void)?) { lock.withLock { self.onChange = onChange } } @@ -90,9 +97,12 @@ final class TranscriptImageStore: @unchecked Sendable { private func highlight(_ block: String, text: String, language: String?, with highlighter: @escaping TranscriptCodeHighlighter, generation: Int) { + let work = work + work.begin() Task.detached { [weak self] in let marks = await highlighter(text, language) self?.finishHighlight(block, text: text, language: language, marks: marks, generation: generation) + work.end() } } @@ -150,9 +160,12 @@ final class TranscriptImageStore: @unchecked Sendable { return (nil, mathRenderer, mathGeneration) } if let render { + let work = work + work.begin() Task.detached { [weak self] in let drawn = await render(math, CGFloat(key.size) / 2)?.withAlphaAsMask() self?.finishFormula(key, drawn, generation: generation) + work.end() } } return formula @@ -177,9 +190,12 @@ final class TranscriptImageStore: @unchecked Sendable { return (nil, loader, self.generation) } if let load { + let work = work + work.begin() Task.detached { [weak self] in let box = PictureBox(picture: await load(image)) self?.finish(image.source, box, generation: generation) + work.end() } } return picture diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index 4cf780d..644d75d 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -77,8 +77,16 @@ final class LayoutEngine: @unchecked Sendable { } let queue = DispatchQueue(label: "TranscriptKit.layout", qos: .userInitiated) + /// The work in flight: drains that are scheduled or running, a result + /// that the view has not taken yet, and the image store's loads. + let work: PendingWork /// Pictures for the documents' images, if the view was given a loader. - let images = TranscriptImageStore() + let images: TranscriptImageStore + + init() { + work = PendingWork() + images = TranscriptImageStore(work: work) + } // Guarded by `lock`. private let lock = NSLock() @@ -243,10 +251,11 @@ final class LayoutEngine: @unchecked Sendable { return max(lastDrain + frameInterval - CACurrentMediaTime(), 0) } if let delay { + work.begin() if delay > 0 { - queue.asyncAfter(deadline: .now() + delay) { self.drain() } + queue.asyncAfter(deadline: .now() + delay) { self.drain(); self.work.end() } } else { - queue.async { self.drain() } + queue.async { self.drain(); self.work.end() } } } return accepted @@ -398,7 +407,9 @@ final class LayoutEngine: @unchecked Sendable { /// update that adds no text, for when updates have stopped. The tail /// stays in use. Any thread; the result comes like any other. func settleFinishedFades() { + work.begin() queue.async { [self] in + defer { work.end() } guard let layout = base, width > 0, layout.width == width else { return } let (fading, band) = updateFades(layout: layout, appendedTo: layout, tagsStarted: false) guard let band else { return } @@ -458,6 +469,7 @@ final class LayoutEngine: @unchecked Sendable { } guard !wakeScheduled else { return nil } wakeScheduled = true + work.begin() return onOutput } handler?() @@ -465,13 +477,16 @@ final class LayoutEngine: @unchecked Sendable { /// The merged result waiting to be installed, if any. Main thread. func takeOutput() -> Output? { - lock.withLock { () -> Output? in + let (output, woke): (Output?, Bool) = lock.withLock { defer { mailbox = nil wakeScheduled = false } - return mailbox + return (mailbox, wakeScheduled) } + // The caller installs the output before main can see the work idle. + if woke { work.end() } + return output } // MARK: Synchronous layout (main thread) diff --git a/Sources/TranscriptKit/Layout/PendingWork.swift b/Sources/TranscriptKit/Layout/PendingWork.swift new file mode 100644 index 0000000..9526cd9 --- /dev/null +++ b/Sources/TranscriptKit/Layout/PendingWork.swift @@ -0,0 +1,36 @@ +import Foundation + +/// Counts one view's work in flight on other threads and queues: layouts +/// that are waiting or running, results that main has not installed yet, +/// and pictures, formulas and code colors that are loading. Any thread. +/// +/// Each piece of work calls `begin()` before it hands off and `end()` once +/// it is done, after it has begun whatever it leads to. The count therefore +/// reaches zero only when nothing is left to do. +final class PendingWork: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + private var onIdle: (@Sendable () -> Void)? + + /// Nothing is in flight. + var isIdle: Bool { lock.withLock { count == 0 } } + + /// Sets what to call, on the thread that ends the last piece of work, + /// when the count drops to zero. Nil to call nothing. + func setOnIdle(_ onIdle: (@Sendable () -> Void)?) { + lock.withLock { self.onIdle = onIdle } + } + + func begin() { + lock.withLock { count += 1 } + } + + func end() { + let handler: (@Sendable () -> Void)? = lock.withLock { + precondition(count > 0, "PendingWork.end() without a begin()") + count -= 1 + return count == 0 ? onIdle : nil + } + handler?() + } +} diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index fdb641f..328fcbe 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -149,11 +149,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// Fetch only from sources you trust. public var imageLoader: (@Sendable (TranscriptImage) async -> CGImage?)? { didSet { - engine.images.setLoader(imageLoader) { [weak self] in - DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } - } - } + engine.images.setLoader(imageLoader, onChange: imagesChanged) relayoutNow() } } @@ -165,11 +161,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// arrive. Not set by default. public var codeHighlighter: TranscriptCodeHighlighter? { didSet { - engine.images.setOnChange { [weak self] in - DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } - } - } + engine.images.setOnChange(imagesChanged) engine.images.setHighlighter(codeHighlighter) relayoutNow() } @@ -183,11 +175,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// default. public var mathRenderer: TranscriptMathRenderer? { didSet { - engine.images.setOnChange { [weak self] in - DispatchQueue.main.async { - MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } - } - } + engine.images.setOnChange(imagesChanged) engine.images.setMathRenderer(mathRenderer) relayoutNow() } @@ -195,6 +183,19 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD private let engine = LayoutEngine() + /// Lays out again on main when a picture, a formula or code colors + /// arrive. Any thread. + private var imagesChanged: @Sendable () -> Void { + let work = engine.work + return { [weak self] in + work.begin() + DispatchQueue.main.async { + MainActor.assumeIsolated { self?.relayoutNow(keepingFades: true) } + work.end() + } + } + } + /// Holds the tiles, and the tail layer above them, below the system's /// selection views. private let canvas = UIView() diff --git a/Tests/TranscriptKitTests/ContentSettledTests.swift b/Tests/TranscriptKitTests/ContentSettledTests.swift new file mode 100644 index 0000000..bb3af1b --- /dev/null +++ b/Tests/TranscriptKitTests/ContentSettledTests.swift @@ -0,0 +1,148 @@ +import CoreGraphics +import Foundation +import Testing +@testable import TranscriptKit + +/// Holds back async work until the test opens it. +private final class Gate: @unchecked Sendable { + private let lock = NSLock() + private var isOpen = false + private var waiting: [CheckedContinuation] = [] + + func wait() async { + await withCheckedContinuation { continuation in + let open = lock.withLock { + if !isOpen { waiting.append(continuation) } + return isOpen + } + if open { continuation.resume() } + } + } + + func open() { + let resumed = lock.withLock { + isOpen = true + defer { waiting = [] } + return waiting + } + resumed.forEach { $0.resume() } + } +} + +private final class Flag: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + func raise() { lock.withLock { count += 1 } } + var raised: Int { lock.withLock { count } } +} + +/// Waits until `condition` holds, for at most two seconds. +private func waitUntil(_ condition: () -> Bool) async { + for _ in 0..<200 where !condition() { + try? await Task.sleep(for: .milliseconds(10)) + } +} + +private let image = TranscriptImage(source: "https://x.y/c.png", alt: "a chart") + +@Test func pendingWorkCallsItsHandlerWhenTheLastPieceEnds() { + let work = PendingWork() + let idle = Flag() + work.setOnIdle { idle.raise() } + #expect(work.isIdle) + work.begin() + work.begin() + work.end() + #expect(!work.isIdle) + #expect(idle.raised == 0) + work.end() + #expect(work.isIdle) + #expect(idle.raised == 1) +} + +@Test func aLayoutIsPendingUntilTheViewTakesIt() async { + let engine = LayoutEngine() + let posted = Flag() + engine.setOutputHandler { posted.raise() } + _ = engine.relayout(width: 300, style: TranscriptStyle()) + #expect(engine.work.isIdle) + + engine.submit(.init(document: MarkdownStreamParser.document(from: "Some text"), source: 1, sequence: 1)) + #expect(!engine.work.isIdle) + await waitUntil { posted.raised > 0 } + try? await Task.sleep(for: .milliseconds(50)) + // Laid out, and waiting in the mailbox. + #expect(!engine.work.isIdle) + + #expect(engine.takeOutput() != nil) + await waitUntil { engine.work.isIdle } + #expect(engine.work.isIdle) +} + +@Test func aRequestThatLaysOutNothingEndsItsWork() async { + let engine = LayoutEngine() + // No width yet: the drain keeps the document and posts nothing. + engine.submit(.init(document: MarkdownStreamParser.document(from: "Some text"), source: 1, sequence: 1)) + await waitUntil { engine.work.isIdle } + #expect(engine.work.isIdle) + #expect(engine.takeOutput() == nil) +} + +@Test func aPictureThatDoesNotLoadStillEndsItsWork() async { + let store = TranscriptImageStore() + let gate = Gate() + let changes = Flag() + store.setLoader({ _ in + await gate.wait() + return nil + }, onChange: { changes.raise() }) + #expect(store.picture(for: image) == nil) + #expect(!store.work.isIdle) + gate.open() + await waitUntil { store.work.isIdle } + #expect(store.work.isIdle) + #expect(changes.raised == 0) +} + +@Test func workThatAChangeStartsKeepsTheStoreBusy() async { + let store = TranscriptImageStore() + let work = store.work + let changes = Flag() + store.setLoader({ _ in + CGContext(data: nil, width: 4, height: 4, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)?.makeImage() + }, onChange: { + // As the view does: the relayout on main is work too. + work.begin() + changes.raise() + }) + _ = store.picture(for: image) + await waitUntil { changes.raised > 0 } + try? await Task.sleep(for: .milliseconds(50)) + #expect(!work.isIdle) + work.end() + #expect(work.isIdle) +} + +@Test func formulasAndCodeColorsArePendingUntilTheyArrive() async { + let store = TranscriptImageStore() + let gate = Gate() + store.setMathRenderer { _, _ in + await gate.wait() + return nil + } + store.setHighlighter { code, _ in + await gate.wait() + return [TranscriptCodeHighlight(range: 0.. Date: Mon, 23 Nov 2026 17:07:04 -0800 Subject: [PATCH 2/9] Tell when a stream has no text left to parse TranscriptStream now has an internal isIdle and whenIdle. The stream is idle when no appended text waits for a frame and no parse runs. By then the attached views have every version. Text that the parser holds back makes no new version, so the views get no update for it. whenIdle lets a view know when such a parse ends. Co-Authored-By: Claude Opus 5.5 --- .../Stream/TranscriptStream.swift | 21 +++++++++++++++ Tests/TranscriptKitTests/StreamTests.swift | 27 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/Sources/TranscriptKit/Stream/TranscriptStream.swift b/Sources/TranscriptKit/Stream/TranscriptStream.swift index 4124486..7d9d1bd 100644 --- a/Sources/TranscriptKit/Stream/TranscriptStream.swift +++ b/Sources/TranscriptKit/Stream/TranscriptStream.swift @@ -48,6 +48,7 @@ public final class TranscriptStream { private var pending = "" private var finishPending = false private var jobInFlight = false + private var idleActions: [() -> Void] = [] /// - Parameters: /// - markdown: text that is already complete, such as earlier @@ -93,6 +94,7 @@ public final class TranscriptStream { return worker.latest } receive(latest) + runIdleActions() } private func receive(_ update: StreamUpdate) { @@ -115,6 +117,24 @@ public final class TranscriptStream { worker.detach(id) } + // MARK: Pending work + + /// No appended text waits to be parsed, and no parse is running. The + /// sinks have had every version by then. + var isIdle: Bool { !jobInFlight && pending.isEmpty && !finishPending } + + /// Calls `action` once, the next time the stream becomes idle. + func whenIdle(_ action: @escaping () -> Void) { + idleActions.append(action) + } + + private func runIdleActions() { + guard isIdle, !idleActions.isEmpty else { return } + let actions = idleActions + idleActions = [] + actions.forEach { $0() } + } + // MARK: Frame timing /// Starts parsing what has been appended, unless a parse is running. @@ -135,6 +155,7 @@ public final class TranscriptStream { self.jobInFlight = false if let update { self.receive(update) } if !self.pending.isEmpty || self.finishPending { self.scheduleFrame() } + self.runIdleActions() } } } diff --git a/Tests/TranscriptKitTests/StreamTests.swift b/Tests/TranscriptKitTests/StreamTests.swift index 0d8ae37..3dd3a0f 100644 --- a/Tests/TranscriptKitTests/StreamTests.swift +++ b/Tests/TranscriptKitTests/StreamTests.swift @@ -265,3 +265,30 @@ private final class Flag: @unchecked Sendable { #expect(changed.isRaised) #expect(stream.unplacedHeight.revision == before &+ 1) } + +@MainActor +@Test func aStreamIsIdleOnceItsTextIsParsed() async { + let stream = TranscriptStream() + #expect(stream.isIdle) + var idle = 0 + stream.whenIdle { idle += 1 } + stream.append("Some **text") + #expect(!stream.isIdle) + for _ in 0..<200 where idle == 0 { try? await Task.sleep(for: .milliseconds(10)) } + #expect(idle == 1) + #expect(stream.isIdle) + #expect(stream.document.block(at: 0).text.hasPrefix("Some")) + + // Held-back text changes nothing visible, and still ends. + stream.whenIdle { idle += 1 } + stream.append("\n\n#") + for _ in 0..<200 where idle == 1 { try? await Task.sleep(for: .milliseconds(10)) } + #expect(idle == 2) + + stream.whenIdle { idle += 1 } + stream.finish() + #expect(!stream.isIdle) + stream.flush() + #expect(stream.isIdle) + #expect(idle == 3) +} From 90690b87624b637dbf25c0a889d364071bc9ff1a Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:14:59 -0800 Subject: [PATCH 3/9] Add contentSettled() to wait for a view's final content A snapshot or a test needs to know when the view has nothing pending. Layouts of later updates, images, formulas and code colors come back on later turns of the main run loop, so a harness that does not wait for them misses them. TranscriptTextView.contentSettled() returns when no layout, stream parse, image load, formula or code colors are pending, the last layout is on screen and its tiles are drawn. The tiles take back the tail first, so that they hold all of the text. While a stream that has not finished goes on, it returns at the first moment when nothing is pending. A cancelled task returns at once. The bookkeeping is in ContentSettledWaiters, which has no UIKit code, so the macOS tests drive it with a layout engine and a stream. Co-Authored-By: Claude Opus 5.5 --- README.md | 19 ++ .../Layout/ContentSettledWaiters.swift | 93 ++++++++++ .../iOS/TranscriptTextView.swift | 33 ++++ .../ContentSettledTests.swift | 170 ++++++++++++++++++ 4 files changed, 315 insertions(+) create mode 100644 Sources/TranscriptKit/Layout/ContentSettledWaiters.swift diff --git a/README.md b/README.md index 15e4433..7a5a16e 100644 --- a/README.md +++ b/README.md @@ -346,6 +346,25 @@ selection ends, and its range is nil. The selection stays when the person opens In UIKit, use `onSelectionChange`, `selectedRange` and `selectsAllWhenShown` on `TranscriptTextView`. +### Waiting for the final content + +Plain text is laid out at once, but layouts of later updates, images, formulas and code colors come back on later +turns of the main run loop. A snapshot or a test that does not wait for them shows the text without them. +`contentSettled()` on `TranscriptTextView` returns when the view shows its final content. Then no layout, stream +parse, image load, formula or code colors are pending, the last layout is on screen, and its tiles are drawn: + +```swift +let view = TranscriptTextView(frame: CGRect(x: 0, y: 0, width: 320, height: 600)) +view.mathRenderer = myMathRenderer +view.document = document +await view.contentSettled() +let image = UIGraphicsImageRenderer(bounds: view.bounds).image { view.layer.render(in: $0.cgContext) } +``` + +While a stream that has not finished goes on, `contentSettled()` returns at the first moment when nothing is pending. +A cancelled task returns at once. An image or a formula that comes back as nil counts as done. Fades and tag +animations that play are not waited for, so turn off `textFadeInDuration` and `animatesTags` to compare pixels. + ## In this repository | Folder | Contents | diff --git a/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift b/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift new file mode 100644 index 0000000..24fa273 --- /dev/null +++ b/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift @@ -0,0 +1,93 @@ +import Foundation + +/// The tasks that wait for a view to show its final content (see +/// `TranscriptTextView.contentSettled()`), and when to let them go: when +/// nothing is in flight in `work`, the stream has no text left to parse, +/// and the view has laid out and drawn on main. +@MainActor +final class ContentSettledWaiters { + private let work: PendingWork + /// The stream that the view shows, if any. + var stream: () -> TranscriptStream? = { nil } + /// Lays out on main what cannot wait, such as a new width. It can start + /// work, such as image loads. + var layOut: () -> Void = {} + /// Draws what the last layout needs, once nothing is in flight. + var draw: () -> Void = {} + + private var waiters: [Int: CheckedContinuation] = [:] + private var nextID = 0 + private weak var watchedStream: TranscriptStream? + + init(work: PendingWork) { + self.work = work + } + + /// How many tasks wait. + var count: Int { waiters.count } + + /// Returns when the content has settled, or at once if the task is cancelled. + func wait() async { + guard !Task.isCancelled else { return } + let id = nextID + nextID += 1 + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + waiters[id] = continuation + if waiters.count == 1 { watchWork(true) } + check() + } + } onCancel: { [weak self] in + DispatchQueue.main.async { + MainActor.assumeIsolated { self?.resume(id) } + } + } + } + + /// Lets every waiting task go if the content has settled. + func check() { + guard !waiters.isEmpty, isSettled() else { return } + let resumed = waiters + waiters = [:] + watchWork(false) + resumed.values.forEach { $0.resume() } + } + + private func resume(_ id: Int) { + guard let continuation = waiters.removeValue(forKey: id) else { return } + if waiters.isEmpty { watchWork(false) } + continuation.resume() + } + + /// Checks again each time the work runs out, while a task waits. + private func watchWork(_ watches: Bool) { + guard watches else { + work.setOnIdle(nil) + return + } + work.setOnIdle { [weak self] in + DispatchQueue.main.async { + MainActor.assumeIsolated { self?.check() } + } + } + } + + private func isSettled() -> Bool { + guard work.isIdle else { return false } + if let stream = stream(), !stream.isIdle { + if watchedStream !== stream { + watchedStream = stream + stream.whenIdle { [weak self, weak stream] in + guard let self else { return } + if self.watchedStream === stream { self.watchedStream = nil } + self.check() + } + } + return false + } + layOut() + guard work.isIdle else { return false } + draw() + return true + } +} diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 328fcbe..9dc357a 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -181,7 +181,32 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } } + /// Waits until the view shows its final content: no layout, stream + /// parse, image load, formula or code colors are pending, the last + /// layout is on screen, and its tiles are drawn. Use it before a + /// snapshot, or in a test. + /// + /// Work that keeps arriving, such as a stream that has not finished, + /// does not hold it back: it returns at the first moment when nothing + /// is pending. A cancelled task returns at once. An image that the + /// loader returns nil for, and a formula that the renderer returns nil + /// for, count as done. Fades and tag animations that play are not + /// waited for: to compare pixels, turn off `textFadeInDuration` and + /// `animatesTags`. + public func contentSettled() async { + await settledWaiters.wait() + } + private let engine = LayoutEngine() + private lazy var settledWaiters = makeSettledWaiters() + + private func makeSettledWaiters() -> ContentSettledWaiters { + let waiters = ContentSettledWaiters(work: engine.work) + waiters.stream = { [weak self] in self?.stream } + waiters.layOut = { [weak self] in self?.layoutIfNeeded() } + waiters.draw = { [weak self] in self?.drawTilesNow() } + return waiters + } /// Lays out again on main when a picture, a formula or code colors /// arrive. Any thread. @@ -594,6 +619,14 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD trimSpareTiles() } + /// Draws now the tiles that wait for the next commit. They take back + /// the tail first, so that they hold all of the text. + private func drawTilesNow() { + handTailToTiles() + if canvasCheckScheduled { updateCanvas() } + for tile in tiles.values { tile.layer.displayIfNeeded() } + } + private func makeTile() -> CanvasView { let tile = CanvasView() tile.owner = self diff --git a/Tests/TranscriptKitTests/ContentSettledTests.swift b/Tests/TranscriptKitTests/ContentSettledTests.swift index bb3af1b..99112ad 100644 --- a/Tests/TranscriptKitTests/ContentSettledTests.swift +++ b/Tests/TranscriptKitTests/ContentSettledTests.swift @@ -146,3 +146,173 @@ private let image = TranscriptImage(source: "https://x.y/c.png", alt: "a chart") #expect(!store.highlights(for: "b", text: "let a", language: nil).isEmpty) #expect(store.work.isIdle) } + +// MARK: Waiting for the content to settle + +/// A layout engine wired as `TranscriptTextView` wires it, without UIKit: +/// results install on main, and a picture's arrival lays out again on main. +@MainActor +private final class Host { + let engine = LayoutEngine() + let waiters: ContentSettledWaiters + private(set) var stream: TranscriptStream? + private(set) var installed: DocumentLayout? + private(set) var draws = 0 + + init() { + waiters = ContentSettledWaiters(work: engine.work) + engine.setOutputHandler { [weak self] in + DispatchQueue.main.async { + MainActor.assumeIsolated { self?.install() } + } + } + waiters.stream = { [weak self] in self?.stream } + waiters.draw = { [weak self] in self?.draws += 1 } + relayout() + } + + var text: String { + guard let installed else { return "" } + return installed.document.text(in: 0.. CGImage?) { + let work = engine.work + engine.images.setLoader(loader) { [weak self] in + work.begin() + DispatchQueue.main.async { + MainActor.assumeIsolated { self?.relayout() } + work.end() + } + } + } + + func show(_ stream: TranscriptStream) { + self.stream = stream + let engine = engine + let attachment = stream.attachSink { update in + engine.submit(.init(document: update.document, source: 1, sequence: update.sequence, isFinished: update.isFinished)) + } + engine.submit(.init(document: attachment.latest.document, source: 1, sequence: attachment.latest.sequence, + isFinished: attachment.latest.isFinished)) + } +} + +/// Waits on main until `condition` holds, for at most two seconds. +@MainActor +private func waitOnMain(_ condition: () -> Bool) async { + for _ in 0..<200 where !condition() { + try? await Task.sleep(for: .milliseconds(10)) + } +} + +private func picture() -> CGImage? { + CGContext(data: nil, width: 40, height: 20, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)?.makeImage() +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func contentWithNothingPendingSettlesAtOnce() async { + let host = Host() + await host.waiters.wait() + #expect(host.draws == 1) + #expect(host.waiters.count == 0) +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func contentSettlesOnceTheStreamAndThePicturesAreIn() async throws { + let host = Host() + let gate = Gate() + host.setLoader { _ in + await gate.wait() + return picture() + } + let stream = TranscriptStream() + host.show(stream) + stream.append("see ![a chart](https://x.y/c.png) here") + stream.finish() + + var settled = false + let waiting = Task { @MainActor in + await host.waiters.wait() + settled = true + } + await waitOnMain { host.text.hasPrefix("see") } + try await Task.sleep(for: .milliseconds(100)) + #expect(!settled) + #expect(host.draws == 0) + #expect(try #require(host.installed).entry(at: 0).layout.attachments.first?.attachment.picture == nil) + + gate.open() + await waiting.value + #expect(settled) + #expect(host.draws == 1) + #expect(host.engine.work.isIdle) + #expect(stream.isIdle) + #expect(try #require(host.installed).entry(at: 0).layout.attachments.first?.attachment.picture != nil) +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func anUnfinishedStreamSettlesBetweenItsChunks() async { + let host = Host() + let stream = TranscriptStream() + host.show(stream) + stream.append("One two") + await host.waiters.wait() + #expect(host.text == "One two") + + stream.append(" three") + await host.waiters.wait() + #expect(host.text == "One two three") + + // Text that the parser holds back makes no new version, and still settles. + stream.append("\n\n#") + await host.waiters.wait() + #expect(stream.isIdle) + #expect(host.text == "One two three") +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func aCancelledWaitReturnsAtOnce() async { + let host = Host() + let gate = Gate() + host.setLoader { _ in + await gate.wait() + return nil + } + let stream = TranscriptStream() + host.show(stream) + stream.append("see ![a chart](https://x.y/c.png) here") + stream.flush() + await waitOnMain { host.text.hasPrefix("see") } + + let first = Task { @MainActor in await host.waiters.wait() } + let second = Task { @MainActor in await host.waiters.wait() } + await waitOnMain { host.waiters.count == 2 } + first.cancel() + await first.value + #expect(host.waiters.count == 1) + #expect(host.draws == 0) + + // Already cancelled: it does not wait at all. + let third = Task { @MainActor in + withUnsafeCurrentTask { $0?.cancel() } + await host.waiters.wait() + } + await third.value + #expect(host.waiters.count == 1) + + // The image loads nothing, and that counts as done. + gate.open() + await second.value + #expect(host.waiters.count == 0) + #expect(host.draws == 1) +} From 58322e0c4b6b10bef5c8a96b4aed4d99f1417966 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:34:31 -0800 Subject: [PATCH 4/9] Check again on a later turn of main when a stream becomes idle TranscriptStream.flush() runs its idle actions inline. The waiters therefore laid out and drew the view inside the caller's flush() call, which can be in the middle of a SwiftUI update or a layout pass. The stream's idle callback now hops to main before it checks again, as the work counter's callback does. PendingWork.end() without a begin() now stops only debug builds. A release build keeps the count at zero, so a counting mistake does not crash an app that never waits. New tests cover a flush while a task waits, work that the layout on main starts, the fade settling on the layout queue, and a stream that changes while a task waits. Two tests no longer sleep before they check a state that only the test can change. Co-Authored-By: Claude Opus 5.5 --- .../Layout/ContentSettledWaiters.swift | 6 +- .../TranscriptKit/Layout/PendingWork.swift | 5 +- .../ContentSettledTests.swift | 115 ++++++++++++++++-- 3 files changed, 116 insertions(+), 10 deletions(-) diff --git a/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift b/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift index 24fa273..288c322 100644 --- a/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift +++ b/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift @@ -77,10 +77,14 @@ final class ContentSettledWaiters { if let stream = stream(), !stream.isIdle { if watchedStream !== stream { watchedStream = stream + // `flush()` runs this inline, so the check must not lay out + // or draw inside the caller's call. stream.whenIdle { [weak self, weak stream] in guard let self else { return } if self.watchedStream === stream { self.watchedStream = nil } - self.check() + DispatchQueue.main.async { [weak self] in + MainActor.assumeIsolated { self?.check() } + } } } return false diff --git a/Sources/TranscriptKit/Layout/PendingWork.swift b/Sources/TranscriptKit/Layout/PendingWork.swift index 9526cd9..4c4cf15 100644 --- a/Sources/TranscriptKit/Layout/PendingWork.swift +++ b/Sources/TranscriptKit/Layout/PendingWork.swift @@ -27,7 +27,10 @@ final class PendingWork: @unchecked Sendable { func end() { let handler: (@Sendable () -> Void)? = lock.withLock { - precondition(count > 0, "PendingWork.end() without a begin()") + guard count > 0 else { + assertionFailure("PendingWork.end() without a begin()") + return nil + } count -= 1 return count == 0 ? onIdle : nil } diff --git a/Tests/TranscriptKitTests/ContentSettledTests.swift b/Tests/TranscriptKitTests/ContentSettledTests.swift index 99112ad..22eaf41 100644 --- a/Tests/TranscriptKitTests/ContentSettledTests.swift +++ b/Tests/TranscriptKitTests/ContentSettledTests.swift @@ -70,8 +70,7 @@ private let image = TranscriptImage(source: "https://x.y/c.png", alt: "a chart") engine.submit(.init(document: MarkdownStreamParser.document(from: "Some text"), source: 1, sequence: 1)) #expect(!engine.work.isIdle) await waitUntil { posted.raised > 0 } - try? await Task.sleep(for: .milliseconds(50)) - // Laid out, and waiting in the mailbox. + // Laid out, and waiting in the mailbox until the test takes it. #expect(!engine.work.isIdle) #expect(engine.takeOutput() != nil) @@ -118,12 +117,23 @@ private let image = TranscriptImage(source: "https://x.y/c.png", alt: "a chart") }) _ = store.picture(for: image) await waitUntil { changes.raised > 0 } - try? await Task.sleep(for: .milliseconds(50)) + // Busy until the test ends the work that the change began. #expect(!work.isIdle) work.end() #expect(work.isIdle) } +@Test func settlingFadesIsPendingWork() async { + let engine = LayoutEngine() + let release = DispatchSemaphore(value: 0) + engine.queue.async { release.wait() } + engine.settleFinishedFades() + #expect(!engine.work.isIdle) + release.signal() + await waitUntil { engine.work.isIdle } + #expect(engine.work.isIdle) +} + @Test func formulasAndCodeColorsArePendingUntilTheyArrive() async { let store = TranscriptImageStore() let gate = Gate() @@ -158,8 +168,11 @@ private final class Host { private(set) var stream: TranscriptStream? private(set) var installed: DocumentLayout? private(set) var draws = 0 + var width: CGFloat + private var source = 0 - init() { + init(width: CGFloat = 300) { + self.width = width waiters = ContentSettledWaiters(work: engine.work) engine.setOutputHandler { [weak self] in DispatchQueue.main.async { @@ -180,8 +193,8 @@ private final class Host { if let output = engine.takeOutput() { installed = output.layout } } - private func relayout() { - installed = engine.relayout(width: 300, style: TranscriptStyle())?.layout + func relayout() { + installed = engine.relayout(width: width, style: TranscriptStyle())?.layout } func setLoader(_ loader: @escaping @Sendable (TranscriptImage) async -> CGImage?) { @@ -197,11 +210,13 @@ private final class Host { func show(_ stream: TranscriptStream) { self.stream = stream + source += 1 + let source = source let engine = engine let attachment = stream.attachSink { update in - engine.submit(.init(document: update.document, source: 1, sequence: update.sequence, isFinished: update.isFinished)) + engine.submit(.init(document: update.document, source: source, sequence: update.sequence, isFinished: update.isFinished)) } - engine.submit(.init(document: attachment.latest.document, source: 1, sequence: attachment.latest.sequence, + engine.submit(.init(document: attachment.latest.document, source: source, sequence: attachment.latest.sequence, isFinished: attachment.latest.isFinished)) } } @@ -316,3 +331,87 @@ private func picture() -> CGImage? { #expect(host.waiters.count == 0) #expect(host.draws == 1) } + +@MainActor +@Test(.timeLimit(.minutes(1))) func aFlushDoesNotSettleInsideTheCall() async { + let host = Host() + let stream = TranscriptStream() + host.show(stream) + stream.append("One two") + await host.waiters.wait() + let draws = host.draws + + // Text that the parser holds back starts no layout work. + stream.append("\n\n#") + let waiting = Task { @MainActor in await host.waiters.wait() } + for _ in 0..<100 where host.waiters.count == 0 { + await Task.yield() + } + #expect(host.waiters.count == 1) + stream.flush() + #expect(host.draws == draws) + await waiting.value + #expect(host.draws == draws + 1) +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func workThatTheLayoutStartsHoldsTheWaitBack() async throws { + let host = Host(width: 0) + let gate = Gate() + host.setLoader { _ in + await gate.wait() + return picture() + } + host.engine.submit(.init(document: MarkdownStreamParser.document(from: "see ![a chart](https://x.y/c.png) here"), + source: 1, sequence: 1, isFinished: true)) + // No width yet: the drain keeps the document and lays out nothing. + await waitOnMain { host.engine.work.isIdle } + #expect(host.installed == nil) + + // As a view does when it gets its width: the layout asks for the picture. + host.waiters.layOut = { [weak host] in + guard let host, host.width == 0 else { return } + host.width = 300 + host.relayout() + } + var settled = false + let waiting = Task { @MainActor in + await host.waiters.wait() + settled = true + } + await waitOnMain { host.installed != nil } + try await Task.sleep(for: .milliseconds(100)) + #expect(!settled) + #expect(host.draws == 0) + #expect(try #require(host.installed).entry(at: 0).layout.attachments.first?.attachment.picture == nil) + + gate.open() + await waiting.value + #expect(host.draws == 1) + #expect(try #require(host.installed).entry(at: 0).layout.attachments.first?.attachment.picture != nil) +} + +@MainActor +@Test(.timeLimit(.minutes(1))) func aStreamThatChangesWhileATaskWaitsSettlesOnTheNewStream() async { + let host = Host() + let gate = Gate() + host.setLoader { _ in + await gate.wait() + return nil + } + let first = TranscriptStream() + host.show(first) + first.append("see ![a chart](https://x.y/c.png) here") + first.flush() + await waitOnMain { host.text.hasPrefix("see") } + + let waiting = Task { @MainActor in await host.waiters.wait() } + await waitOnMain { host.waiters.count == 1 } + let second = TranscriptStream() + host.show(second) + second.append("Other text") + gate.open() + await waiting.value + #expect(second.isIdle) + #expect(host.text == "Other text") +} From f66144b0014e01689337262f88015036bd665c3f Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:34:31 -0800 Subject: [PATCH 5/9] Tell what holds back contentSettled() and what it needs first A load, a formula or a highlight that never ends holds back contentSettled() until the task is cancelled. A view with no width lays out nothing, so it settles at once with no content. The doc comment and the README now say both. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 ++++-- Sources/TranscriptKit/iOS/TranscriptTextView.swift | 10 +++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7a5a16e..1e1aa96 100644 --- a/README.md +++ b/README.md @@ -362,8 +362,10 @@ let image = UIGraphicsImageRenderer(bounds: view.bounds).image { view.layer.rend ``` While a stream that has not finished goes on, `contentSettled()` returns at the first moment when nothing is pending. -A cancelled task returns at once. An image or a formula that comes back as nil counts as done. Fades and tag -animations that play are not waited for, so turn off `textFadeInDuration` and `animatesTags` to compare pixels. +A cancelled task returns at once. An image or a formula that comes back as nil counts as done. A load, a formula or +a highlight that never ends holds back `contentSettled()`, so use a timeout or cancel the task. Give the view its size +before the call: a view with no width lays out nothing and settles at once. Fades and tag animations that play are not +waited for, so turn off `textFadeInDuration` and `animatesTags` to compare pixels. ## In this repository diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 9dc357a..beff65c 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -190,9 +190,13 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// does not hold it back: it returns at the first moment when nothing /// is pending. A cancelled task returns at once. An image that the /// loader returns nil for, and a formula that the renderer returns nil - /// for, count as done. Fades and tag animations that play are not - /// waited for: to compare pixels, turn off `textFadeInDuration` and - /// `animatesTags`. + /// for, count as done. A load, a formula or a highlight that never ends + /// holds it back: use a timeout, or cancel the task. Fades and tag + /// animations that play are not waited for: to compare pixels, turn off + /// `textFadeInDuration` and `animatesTags`. + /// + /// Give the view its size before the call. A view with no width lays + /// out nothing, so it settles at once with no content. public func contentSettled() async { await settledWaiters.wait() } From 2cf2a16ededbbc36ab9aa57a9ae91c87a327c305 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:25:23 -0800 Subject: [PATCH 6/9] Make the flush test independent of the frame timer The test aFlushDoesNotSettleInsideTheCall failed in some full test runs. It started a second task for the wait and yielded until the wait registered. The wait registered at once. On a busy machine, the test task did not run again on main before the frame, 1/60 s after the append. The frame parsed the text that the parser holds back, so the wait settled before the test called flush(). The test task now calls wait() itself. The test puts a block in the main queue before the append. The block records the waiter count, calls flush(), and records the draw count. The append starts the frame timer after the block is in the queue, so the block always runs first. The test checks the same three facts: one wait is registered before the flush, the flush does not draw, and the wait resumes after the flush. Co-Authored-By: Claude Opus 5.5 --- .../ContentSettledTests.swift | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/Tests/TranscriptKitTests/ContentSettledTests.swift b/Tests/TranscriptKitTests/ContentSettledTests.swift index 22eaf41..f16e453 100644 --- a/Tests/TranscriptKitTests/ContentSettledTests.swift +++ b/Tests/TranscriptKitTests/ContentSettledTests.swift @@ -332,6 +332,12 @@ private func picture() -> CGImage? { #expect(host.draws == 1) } +@MainActor +private final class FlushRecord { + var waitersBefore = -1 + var drawsAfter = -1 +} + @MainActor @Test(.timeLimit(.minutes(1))) func aFlushDoesNotSettleInsideTheCall() async { let host = Host() @@ -341,16 +347,21 @@ private func picture() -> CGImage? { await host.waiters.wait() let draws = host.draws + let flush = FlushRecord() + // In the main queue before the append starts the frame timer, so the + // frame cannot parse the text before the flush. + DispatchQueue.main.async { + MainActor.assumeIsolated { + flush.waitersBefore = host.waiters.count + stream.flush() + flush.drawsAfter = host.draws + } + } // Text that the parser holds back starts no layout work. stream.append("\n\n#") - let waiting = Task { @MainActor in await host.waiters.wait() } - for _ in 0..<100 where host.waiters.count == 0 { - await Task.yield() - } - #expect(host.waiters.count == 1) - stream.flush() - #expect(host.draws == draws) - await waiting.value + await host.waiters.wait() + #expect(flush.waitersBefore == 1) + #expect(flush.drawsAfter == draws) #expect(host.draws == draws + 1) } From cbe983922692f7d587b1b80ef5a111dd7ce0802d Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:11:18 -0800 Subject: [PATCH 7/9] Check the stream again after the layout in contentSettled() A callback of the layout, such as onSelectionChange, can append to the stream. An append starts no work, so the check after the layout saw no work and let the waiting tasks go before the text was parsed. Now the check looks at the stream before and after the layout. Co-Authored-By: Claude Opus 5.5 --- .../Layout/ContentSettledWaiters.swift | 40 +++++++++++-------- .../ContentSettledTests.swift | 22 ++++++++++ 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift b/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift index 288c322..c3c0bd1 100644 --- a/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift +++ b/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift @@ -73,25 +73,31 @@ final class ContentSettledWaiters { } private func isSettled() -> Bool { - guard work.isIdle else { return false } - if let stream = stream(), !stream.isIdle { - if watchedStream !== stream { - watchedStream = stream - // `flush()` runs this inline, so the check must not lay out - // or draw inside the caller's call. - stream.whenIdle { [weak self, weak stream] in - guard let self else { return } - if self.watchedStream === stream { self.watchedStream = nil } - DispatchQueue.main.async { [weak self] in - MainActor.assumeIsolated { self?.check() } - } - } - } - return false - } + guard work.isIdle, streamIsIdle() else { return false } layOut() - guard work.isIdle else { return false } + // A callback of the layout, such as `onSelectionChange`, can append + // to the stream, and an append starts no work. + guard work.isIdle, streamIsIdle() else { return false } draw() return true } + + /// The stream has no text left to parse. If it has, checks again when + /// it becomes idle. + private func streamIsIdle() -> Bool { + guard let stream = stream(), !stream.isIdle else { return true } + if watchedStream !== stream { + watchedStream = stream + // `flush()` runs this inline, so the check must not lay out + // or draw inside the caller's call. + stream.whenIdle { [weak self, weak stream] in + guard let self else { return } + if self.watchedStream === stream { self.watchedStream = nil } + DispatchQueue.main.async { [weak self] in + MainActor.assumeIsolated { self?.check() } + } + } + } + return false + } } diff --git a/Tests/TranscriptKitTests/ContentSettledTests.swift b/Tests/TranscriptKitTests/ContentSettledTests.swift index f16e453..9318729 100644 --- a/Tests/TranscriptKitTests/ContentSettledTests.swift +++ b/Tests/TranscriptKitTests/ContentSettledTests.swift @@ -426,3 +426,25 @@ private final class FlushRecord { #expect(second.isIdle) #expect(host.text == "Other text") } + +@MainActor +@Test(.timeLimit(.minutes(1))) func textThatTheLayoutAppendsHoldsTheWaitBack() async { + let host = Host() + let stream = TranscriptStream() + host.show(stream) + stream.append("One two") + await host.waiters.wait() + + // As an app does that appends from a callback of the layout, such as + // `onSelectionChange`. + var appended = false + host.waiters.layOut = { + guard !appended else { return } + appended = true + stream.append(" three") + } + await host.waiters.wait() + #expect(appended) + #expect(stream.isIdle) + #expect(host.text == "One two three") +} From c0c212c1fe91ee40e775281d57ba6a1ddb11e7ba Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:15:12 -0800 Subject: [PATCH 8/9] Tell in the README when plain text shows on a later turn A style or a renderer that the app sets before the document, on a view that has a width, makes the view lay out the empty text first. The document then shows on a later turn of the main run loop. The README said that plain text is laid out at once, which is not true in that case, and the example of the section is that case. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1e1aa96..17c85d3 100644 --- a/README.md +++ b/README.md @@ -348,8 +348,11 @@ In UIKit, use `onSelectionChange`, `selectedRange` and `selectsAllWhenShown` on ### Waiting for the final content -Plain text is laid out at once, but layouts of later updates, images, formulas and code colors come back on later -turns of the main run loop. A snapshot or a test that does not wait for them shows the text without them. +The view lays out plain text at once only when it shows no layout yet. A style or a renderer that the app sets before +the document, on a view that has a width, makes the view lay out the empty text first. The text of the document then +shows on a later turn of the main run loop, as in the example below. Layouts of later updates, images, formulas and +code colors also come back on later turns. A snapshot or a test that does not wait for them can show no text, or the +text without them. `contentSettled()` on `TranscriptTextView` returns when the view shows its final content. Then no layout, stream parse, image load, formula or code colors are pending, the last layout is on screen, and its tiles are drawn: From 1a1f17b7fca6ec12c7365ff281754a4de4982191 Mon Sep 17 00:00:00 2001 From: Server Cimen <505984+servercimen@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:53:24 -0800 Subject: [PATCH 9/9] Capture the waiters strongly in the cancel handler Xcode 26.6 rejects the weak capture of self in the cancel handler of contentSettled(): it says that sending self risks data races. The waiters are main actor isolated and so Sendable, and the handler runs one time, so a strong capture is safe and builds with each Xcode. Co-Authored-By: Claude Opus 5.5 --- Sources/TranscriptKit/Layout/ContentSettledWaiters.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift b/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift index c3c0bd1..afa6470 100644 --- a/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift +++ b/Sources/TranscriptKit/Layout/ContentSettledWaiters.swift @@ -37,9 +37,9 @@ final class ContentSettledWaiters { if waiters.count == 1 { watchWork(true) } check() } - } onCancel: { [weak self] in + } onCancel: { [self] in DispatchQueue.main.async { - MainActor.assumeIsolated { self?.resume(id) } + MainActor.assumeIsolated { self.resume(id) } } } }