Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

Keep overlay captions smooth as new words arrive (#1232)

ALTIC74c0a2d55540
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 1e7b1769..3e84dc64 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -108,12 +108,29 @@ jobs:
- name: Build and test (excluding flaky Tiny Whisper E2E)
run: |
set -o pipefail
+ mkdir -p build/test-results
xcodebuild test \
-project Fluid.xcodeproj \
-scheme Fluid \
-destination 'platform=macOS,arch=arm64' \
+ -resultBundlePath build/test-results/Fluid.xcresult \
-skip-testing:FluidDictationIntegrationTests/DictationE2ETests/testDictationEndToEnd_whisperTiny_transcribesFixture \
CODE_SIGN_IDENTITY="" \
CODE_SIGNING_REQUIRED=NO \
CODE_SIGNING_ALLOWED=NO \
- | xcpretty
+ 2>&1 | tee build/test-results/xcodebuild.log | xcpretty
+
+ - name: Collect crash reports
+ if: always()
+ run: |
+ mkdir -p build/test-results/crashes
+ find "$HOME/Library/Logs/DiagnosticReports" -maxdepth 1 -type f -name 'FluidVoice*' -exec cp {} build/test-results/crashes/ \; 2>/dev/null || true
+
+ - name: Save test diagnostics
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: macos-test-results
+ path: build/test-results
+ if-no-files-found: ignore
+ retention-days: 7
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index af833e0c..c4816754 100644
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@ -7,6 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
+ AD1130000000000000000004 /* OverlayCaptionPresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD1130000000000000000003 /* OverlayCaptionPresentationTests.swift */; };
AD1030000000000000000004 /* HoldToMutePresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD1030000000000000000003 /* HoldToMutePresentationTests.swift */; };
AD1030000000000000000002 /* HoldToMuteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD1030000000000000000001 /* HoldToMuteTests.swift */; };
D63B0F8456B440F1A123B987 /* PronunciationModelRevisionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFA73C8D5E7647C4AB125DEE /* PronunciationModelRevisionTests.swift */; };
@@ -201,6 +202,7 @@
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
+ AD1130000000000000000003 /* OverlayCaptionPresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OverlayCaptionPresentationTests.swift; sourceTree = "<group>"; };
AD1030000000000000000003 /* HoldToMutePresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HoldToMutePresentationTests.swift; sourceTree = "<group>"; };
AD1030000000000000000001 /* HoldToMuteTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HoldToMuteTests.swift; sourceTree = "<group>"; };
AFA73C8D5E7647C4AB125DEE /* PronunciationModelRevisionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PronunciationModelRevisionTests.swift; sourceTree = "<group>"; };
@@ -474,6 +476,7 @@
7CDB0A292F3C4D5600FB7CAD /* DictationE2ETests.swift */,
CD1C7A0000000000000000B1 /* CustomDictionaryManualEntryTests.swift */,
7C91B0022F42AA0100C0DEF0 /* HotkeyShortcutTests.swift */,
+ AD1130000000000000000003 /* OverlayCaptionPresentationTests.swift */,
AD1030000000000000000003 /* HoldToMutePresentationTests.swift */,
AD1030000000000000000001 /* HoldToMuteTests.swift */,
DAB600000000000000000002 /* DashboardLayoutTests.swift */,
@@ -879,6 +882,7 @@
B52000000000000000000002 /* PrivateAIDictationTokenBudgetTests.swift in Sources */,
CD1C7A0000000000000000B2 /* CustomDictionaryManualEntryTests.swift in Sources */,
7C91B0012F42AA0100C0DEF0 /* HotkeyShortcutTests.swift in Sources */,
+ AD1130000000000000000004 /* OverlayCaptionPresentationTests.swift in Sources */,
AD1030000000000000000004 /* HoldToMutePresentationTests.swift in Sources */,
AD1030000000000000000002 /* HoldToMuteTests.swift in Sources */,
DAB600000000000000000001 /* DashboardLayoutTests.swift in Sources */,
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 13a28fde..96837b80 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -1150,7 +1150,7 @@ struct ContentView: View {
switch old {
case .commandMode:
// Close expanded command output notch if visible
- if NotchOverlayManager.shared.isCommandOutputExpanded {
+ if NotchOverlayManager.shared.hasCommandOutputToDismiss {
DebugLogger.shared.debug("Closing expanded command notch on mode transition", source: "ContentView")
NotchOverlayManager.shared.hideExpandedCommandOutput()
}
@@ -5165,7 +5165,7 @@ struct ContentView: View {
DictionaryCorrectionOverlayController.shared.dismiss()
return .dismissedOverlay
}
- if NotchOverlayManager.shared.isCommandOutputExpanded {
+ if NotchOverlayManager.shared.hasCommandOutputToDismiss {
NotchOverlayManager.shared.hideExpandedCommandOutput()
NotchOverlayManager.shared.onCommandOutputDismiss?()
handled = true
diff --git a/Sources/Fluid/Services/ActiveAppMonitor.swift b/Sources/Fluid/Services/ActiveAppMonitor.swift
index c4226547..1b0e9d64 100644
--- a/Sources/Fluid/Services/ActiveAppMonitor.swift
+++ b/Sources/Fluid/Services/ActiveAppMonitor.swift
@@ -44,7 +44,8 @@ final class ActiveAppMonitor: ObservableObject {
queue: .main
) { [weak self] _ in
Task { @MainActor [weak self] in
- self?.updateActiveApp()
+ guard let self, self.isMonitoring else { return }
+ self.updateActiveApp()
}
}
}
diff --git a/Sources/Fluid/Services/NotchOverlayManager.swift b/Sources/Fluid/Services/NotchOverlayManager.swift
index ade6374b..ccd3f058 100644
--- a/Sources/Fluid/Services/NotchOverlayManager.swift
+++ b/Sources/Fluid/Services/NotchOverlayManager.swift
@@ -68,6 +68,7 @@ final class NotchOverlayManager {
/// Track if expanded command output is showing
private(set) var isCommandOutputExpanded: Bool = false
+ var hasCommandOutputToDismiss: Bool { self.isCommandOutputExpanded || self.commandOutputPresentationTask != nil }
/// Track if bottom overlay is visible
private(set) var isBottomOverlayVisible: Bool = false
@@ -92,6 +93,7 @@ final class NotchOverlayManager {
private var hideWaiters: [CheckedContinuation<RecordingOverlayHideOutcome, Never>] = []
private var notchAnimationTask: Task<Void, Never>?
private var notchPresentationTask: Task<Void, Never>?
+ private var commandOutputPresentationTask: Task<Void, Never>?
// Cancel shortcut monitors for dismissing notch / overlay
private var globalEscapeMonitor: Any?
@@ -149,6 +151,9 @@ final class NotchOverlayManager {
}
func show(audioLevelPublisher: AnyPublisher<CGFloat, Never>, mode: OverlayMode) {
+ // A new recording supersedes output that has not appeared yet.
+ self.commandOutputPresentationTask?.cancel()
+ self.commandOutputPresentationTask = nil
self.refreshNotchPresentationPolicy()
Self.overlayBench("show_called mode=\(mode.rawValue) state=\(self.state) commandExpanded=\(self.isCommandOutputExpanded)")
self.cancelInFlightHideForNewPresentation()
@@ -578,19 +583,26 @@ final class NotchOverlayManager {
func showExpandedCommandOutput() {
guard self.canShowExpandedCommandOutput else { return }
+ self.commandOutputPresentationTask?.cancel()
+
// Hide regular notch first if visible
if self.notch != nil {
self.hide()
}
// Wait a bit for cleanup
- Task { [weak self] in
- try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
- await self?.showExpandedCommandOutputInternal()
+ self.commandOutputPresentationTask = Task { [weak self] in
+ do {
+ try await Task.sleep(nanoseconds: 100_000_000) // 100ms
+ } catch { return }
+ guard let self, !Task.isCancelled else { return }
+ self.commandOutputPresentationTask = nil
+ await self.showExpandedCommandOutputInternal()
}
}
private func showExpandedCommandOutputInternal() async {
+ guard !Task.isCancelled else { return }
guard self.canShowExpandedCommandOutput else { return }
guard self.commandOutputState == .idle else { return }
@@ -687,6 +699,8 @@ final class NotchOverlayManager {
/// Hide expanded command output notch - force close regardless of hover state
func hideExpandedCommandOutput() {
+ self.commandOutputPresentationTask?.cancel()
+ self.commandOutputPresentationTask = nil
self.commandOutputGeneration &+= 1
let currentGeneration = self.commandOutputGeneration
@@ -717,7 +731,7 @@ final class NotchOverlayManager {
/// Toggle expanded command output (for hotkey handling)
func toggleExpandedCommandOutput() {
- if self.isCommandOutputExpanded {
+ if self.hasCommandOutputToDismiss {
self.hideExpandedCommandOutput()
} else if self.canShowExpandedCommandOutput,
NotchContentState.shared.commandConversationHistory.isEmpty == false
diff --git a/Sources/Fluid/UI/OverlayCaptionView.swift b/Sources/Fluid/UI/OverlayCaptionView.swift
new file mode 100644
index 00000000..cfee6750
--- /dev/null
+++ b/Sources/Fluid/UI/OverlayCaptionView.swift
@@ -0,0 +1,494 @@
+import AppKit
+import QuartzCore
+import SwiftUI
+
+/// The bounded preview and its position in the recognizer's complete transcript.
+/// Keeping that position lets the renderer retain a wrapped line as the preview limit advances.
+struct OverlayCaptionText: Equatable {
+ let text: String
+ let sourceOffset: Int
+
+ static let empty = Self(text: "", sourceOffset: 0)
+
+ static func tail(_ text: String, limit: Int, sourceOffset: Int = 0) -> Self {
+ guard limit > 0, !text.isEmpty else { return .empty }
+ let start = text.index(text.endIndex, offsetBy: -limit, limitedBy: text.startIndex) ?? text.startIndex
+ let suffix = String(text[start...])
+ return Self(text: suffix, sourceOffset: sourceOffset + text.utf16.count - suffix.utf16.count)
+ }
+}
+
+/// Paces only the preview. Keep one bounded target, not a queue of recognizer results.
+struct OverlayCaptionReveal {
+ static let interval: CFTimeInterval = 0.07
+ static let maximumDelay: CFTimeInterval = 0.42
+ private(set) var target = OverlayCaptionText.empty
+ private(set) var displayed = OverlayCaptionText.empty
+ private var boundaries: [Int] = []
+ private var deadline: CFTimeInterval = 0
+
+ var hasPendingWords: Bool { self.displayed != self.target }
+
+ mutating func update(_ target: OverlayCaptionText, now: CFTimeInterval) {
+ guard target != self.target else { return }
+ let wasPending = self.hasPendingWords
+ let visibleEnd = self.displayed.sourceOffset + self.displayed.text.utf16.count
+ let wasEmpty = self.displayed.text.isEmpty
+ self.target = target
+ var boundaries: [Int] = []
+ target.text.enumerateSubstrings(in: target.text.startIndex..<target.text.endIndex, options: [.byWords, .substringNotRequired]) { _, range, _, _ in
+ let start = range.lowerBound.utf16Offset(in: target.text)
+ if start > 0 { boundaries.append(start) }
+ }
+ if !target.text.isEmpty { boundaries.append(target.text.utf16.count) }
+ self.boundaries = boundaries
+ // Revisions replace already visible words without replaying the whole caption.
+ // Round forward to a word boundary so a correction never leaves half a word.
+ let retained = wasEmpty ? 0 : max(0, visibleEnd - target.sourceOffset)
+ let end = retained == 0 ? 0 : self.boundaries.first(where: { $0 >= retained }) ?? target.text.utf16.count
+ self.show(through: end)
+ if !wasPending { self.deadline = now + Self.maximumDelay }
+ }
+
+ mutating func advance(now: CFTimeInterval) {
+ let remaining = self.boundaries.filter { $0 > self.displayed.text.utf16.count }
+ guard !remaining.isEmpty else { return }
+ let steps = max(1, Int(ceil((self.deadline - now) / Self.interval)))
+ let count = max(1, Int(ceil(Double(remaining.count) / Double(steps))))
+ self.show(through: remaining[min(count, remaining.count) - 1])
+ }
+
+ mutating func finish() { self.displayed = self.target }
+
+ private mutating func show(through end: Int) {
+ guard let range = Range(NSRange(location: 0, length: end), in: self.target.text) else { return }
+ self.displayed = OverlayCaptionText(text: String(self.target.text[range]), sourceOffset: self.target.sourceOffset)
+ }
+}
+
+struct OverlayCaptionBuffer {
+ private(set) var text = ""
+ private(set) var sourceOffset = 0
+ private(set) var preview = OverlayCaptionText.empty
+
+ /// Retain enough recent context to fill the viewport, never an entire recording.
+ /// Returns false for a reset, replacement, or a gap in the incoming transcript.
+ mutating func update(_ preview: OverlayCaptionText, context: OverlayCaptionText? = nil) -> Bool {
+ let previousText = self.text
+ let relativeOffset = preview.sourceOffset - self.sourceOffset
+ let prefixRange = NSRange(location: 0, length: max(0, relativeOffset))
+ // A hidden view may receive many updates before its next layout pass.
+ let prefix = relativeOffset >= 0 && relativeOffset <= 4096 ? Range(prefixRange, in: previousText) : nil
+ let overlap = prefix.map { String(previousText[$0.upperBound...]) } ?? ""
+ let commonPrefix = zip(overlap, preview.text).prefix { $0 == $1 }.count
+ var continuous = !overlap.isEmpty && commonPrefix >= min(12, overlap.count)
+
+ if !preview.text.isEmpty, let context,
+ context.sourceOffset <= preview.sourceOffset,
+ context.sourceOffset + context.text.utf16.count == preview.sourceOffset + preview.text.utf16.count,
+ context.text.hasSuffix(preview.text)
+ {
+ // Context also corrects retained visible lines before an unchanged short tail.
+ // Prefer its current words over the prefix saved from the previous update.
+ let retainedStart = self.sourceOffset - context.sourceOffset
+ let retainedRange = NSRange(location: max(0, retainedStart), length: max(0, context.text.utf16.count - retainedStart))
+ if continuous, retainedStart < 0,
+ let prefix = Range(NSRange(location: 0, length: -retainedStart), in: previousText)
+ {
+ // A caller may supply only the short preview. Keep visible text
+ // preceding its context, and replace everything it does cover.
+ self.text = String(previousText[prefix]) + context.text
+ } else if retainedStart >= 0, !previousText.isEmpty,
+ let range = Range(retainedRange, in: context.text),
+ continuous || context.text[range].hasPrefix(previousText.prefix(12))
+ {
+ self.text = String(context.text[range])
+ continuous = true
+ } else {
+ self.text = context.text
+ self.sourceOffset = context.sourceOffset
+ continuous = false
+ }
+ } else if continuous, let prefix {
+ self.text = String(previousText[prefix]) + preview.text
+ } else {
+ self.text = preview.text
+ self.sourceOffset = preview.sourceOffset
+ }
+ self.preview = preview
+ return continuous
+ }
+
+ mutating func removeHiddenPrefix(utf16Count: Int) {
+ guard utf16Count > 0,
+ utf16Count <= self.preview.sourceOffset - self.sourceOffset,
+ let range = Range(NSRange(location: 0, length: utf16Count), in: self.text)
+ else { return }
+ self.text.removeSubrange(range)
+ self.sourceOffset += utf16Count
+ }
+}
+
+/// TextKit supplies both line breaks and drawing, so measurement and the displayed glyphs agree.
+final class OverlayCaptionLayout {
+ struct Line {
+ let characters: NSRange
+ let rect: CGRect
+ }
+
+ let storage: NSTextStorage
+ let manager = NSLayoutManager()
+ let container: NSTextContainer
+ private(set) var lines: [Line] = []
+ let lineHeight: CGFloat
+ // All production caption sizes, measured once; waveform refreshes need no text layout.
+ private static let lineHeights: [CGFloat: CGFloat] = {
+ let manager = NSLayoutManager()
+ return Dictionary(uniqueKeysWithValues: [9.0, 10, 11, 13, 15].map { size in
+ let font = NSFont.fluidSystemFont(ofSize: size, weight: .medium)
+ return (size, ceil(manager.defaultLineHeight(for: font)) + 2)
+ })
+ }()
+
+ init(text: String, width: CGFloat, fontSize: CGFloat, opacity: CGFloat) {
+ let font = NSFont.fluidSystemFont(ofSize: fontSize, weight: .medium)
+ self.lineHeight = ceil(self.manager.defaultLineHeight(for: font)) + 2
+ let paragraph = NSMutableParagraphStyle()
+ paragraph.lineBreakMode = .byWordWrapping
+ paragraph.minimumLineHeight = self.lineHeight
+ paragraph.maximumLineHeight = self.lineHeight
+ self.storage = NSTextStorage(string: text, attributes: [
+ .font: font,
+ .foregroundColor: NSColor.white.withAlphaComponent(opacity),
+ .paragraphStyle: paragraph,
+ ])
+ self.container = NSTextContainer(size: CGSize(width: max(1, width), height: .greatestFiniteMagnitude))
+ self.container.lineFragmentPadding = 0
+ self.storage.addLayoutManager(self.manager)
+ self.manager.addTextContainer(self.container)
+ self.manager.ensureLayout(for: self.container)
+ self.manager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: self.manager.numberOfGlyphs)) { rect, _, _, glyphs, _ in
+ self.lines.append(Line(characters: self.manager.characterRange(forGlyphRange: glyphs, actualGlyphRange: nil), rect: rect))
+ }
+ }
+
+ var height: CGFloat { ceil(self.lines.last?.rect.maxY ?? self.lineHeight) }
+
+ func viewportHeight(maxHeight: CGFloat, maxLines: Int?) -> CGFloat {
+ Self.viewportHeight(lineHeight: self.lineHeight, maxHeight: maxHeight, maxLines: maxLines)
+ }
+
+ static func viewportHeight(fontSize: CGFloat, maxHeight: CGFloat, maxLines: Int? = nil) -> CGFloat {
+ let lineHeight = Self.lineHeights[fontSize] ?? ceil(NSLayoutManager().defaultLineHeight(
+ for: NSFont.fluidSystemFont(ofSize: fontSize, weight: .medium)
+ )) + 2
+ return Self.viewportHeight(lineHeight: lineHeight, maxHeight: maxHeight, maxLines: maxLines)
+ }
+
+ private static func viewportHeight(lineHeight: CGFloat, maxHeight: CGFloat, maxLines: Int?) -> CGFloat {
+ let capacity = max(1, Int((maxHeight / lineHeight).rounded(.down)))
+ return min(maxHeight, CGFloat(min(capacity, maxLines ?? capacity)) * lineHeight)
+ }
+}
+
+/// Shared by the top notch, expanded command recording, and every bottom preview size.
+struct OverlayCaptionView: NSViewRepresentable {
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+
+ let caption: OverlayCaptionText
+ var context: OverlayCaptionText?
+ let fontSize: CGFloat
+ let maxHeight: CGFloat
+ var opacity: CGFloat = 0.96
+ var maxLines: Int?
+ var isActive = true
+
+ func makeNSView(context: Context) -> OverlayCaptionNSView {
+ OverlayCaptionNSView()
+ }
+
+ func updateNSView(_ nsView: OverlayCaptionNSView, context: Context) {
+ nsView.update(caption: self.caption, context: self.context, fontSize: self.fontSize, opacity: self.opacity, reduceMotion: self.reduceMotion, isActive: self.isActive)
+ }
+
+ func sizeThatFits(_ proposal: ProposedViewSize, nsView: OverlayCaptionNSView, context: Context) -> CGSize? {
+ guard let width = proposal.width, width.isFinite, width > 0 else { return nil }
+ // Reserve complete line slots from the first word. Text updates must not resize
+ // the window or move the controls underneath the preview.
+ return CGSize(width: width, height: nsView.fittingHeight(width: width, maxHeight: self.maxHeight, maxLines: self.maxLines))
+ }
+
+ static func dismantleNSView(_ nsView: OverlayCaptionNSView, coordinator: ()) {
+ nsView.stopScrolling()
+ }
+}
+
+final class OverlayCaptionNSView: NSView {
+ private let drawingLayer = OverlayCaptionDrawingLayer()
+ private let revealLayer = OverlayCaptionDrawingLayer()
+ private var buffer = OverlayCaptionBuffer()
+ private var reveal = OverlayCaptionReveal()
+ private var revealFromOffset: Int?
+ private var fontSize: CGFloat = 13
+ private var opacity: CGFloat = 0.96
+ private var reduceMotion = false
+ private var cachedLayout: OverlayCaptionLayout?
+ private var cachedWidth: CGFloat = 0
+ private var renderedWidth: CGFloat = 0
+ private var renderedHeight: CGFloat = 0
+ private var targetY: CGFloat = 0
+ private var contentOriginY: CGFloat = 0
+ private var canAnimate = false
+ private var hasRendered = false
+ private var pendingUpdate = true
+ private struct Update: Equatable {
+ let caption: OverlayCaptionText
+ let context: OverlayCaptionText?
+ }
+
+ private var latestUpdate: Update?
+ private var scheduledUpdate: DispatchWorkItem?
+ static let scrollDuration: CFTimeInterval = 0.18
+ static let revealDuration: CFTimeInterval = 0.125
+ private static let scrollAnimationKey = "captionScroll"
+
+ override var isFlipped: Bool { true }
+ override var intrinsicContentSize: NSSize { NSSize(width: NSView.noIntrinsicMetric, height: NSView.noIntrinsicMetric) }
+
+ override init(frame frameRect: NSRect) {
+ super.init(frame: frameRect)
+ self.wantsLayer = true
+ self.layer?.masksToBounds = true
+ self.drawingLayer.actions = ["contents": NSNull(), "bounds": NSNull(), "position": NSNull()]
+ self.revealLayer.actions = self.drawingLayer.actions
+ self.layer?.addSublayer(self.drawingLayer)
+ self.layer?.addSublayer(self.revealLayer)
+ self.setAccessibilityElement(true)
+ self.setAccessibilityRole(.staticText)
+ self.setAccessibilityLabel("Live transcription")
+ }
+
+ @available(*, unavailable)
+ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
+
+ override func viewDidMoveToWindow() {
+ super.viewDidMoveToWindow()
+ if self.window == nil { self.stopScrolling() }
+ self.updateBackingScale()
+ }
+
+ override func viewDidHide() {
+ super.viewDidHide()
+ self.stopScrolling()
+ }
+
+ override func viewDidChangeBackingProperties() {
+ super.viewDidChangeBackingProperties()
+ self.updateBackingScale()
+ }
+
+ private func updateBackingScale() {
+ self.drawingLayer.contentsScale = self.window?.backingScaleFactor ?? 1
+ self.revealLayer.contentsScale = self.drawingLayer.contentsScale
+ self.drawingLayer.setNeedsDisplay()
+ self.revealLayer.setNeedsDisplay()
+ }
+
+ // The caption must never take clicks or focus away from overlay controls or the target app.
+ override func hitTest(_ point: NSPoint) -> NSView? { nil }
+
+ func update(caption: OverlayCaptionText, context: OverlayCaptionText? = nil, fontSize: CGFloat, opacity: CGFloat, reduceMotion: Bool, isActive: Bool = true) {
+ guard isActive, !self.isHiddenOrHasHiddenAncestor else {
+ if self.latestUpdate != nil { self.stopScrolling() }
+ return
+ }
+ let update = Update(caption: caption, context: context)
+ let styleChanged = self.fontSize != fontSize || self.opacity != opacity
+ let motionChanged = self.reduceMotion != reduceMotion
+ guard update != self.latestUpdate || styleChanged || motionChanged else { return }
+ self.latestUpdate = update
+ self.fontSize = fontSize
+ self.opacity = opacity
+ self.reduceMotion = reduceMotion
+
+ let source: OverlayCaptionText
+ if !caption.text.isEmpty, let context, context.sourceOffset <= caption.sourceOffset,
+ context.sourceOffset + context.text.utf16.count == caption.sourceOffset + caption.text.utf16.count,
+ context.text.hasSuffix(caption.text)
+ { source = context } else { source = caption }
+ self.reveal.update(source, now: CACurrentMediaTime())
+ if caption.text.isEmpty || reduceMotion {
+ self.cancelPendingCaption()
+ self.reveal.finish()
+ } else if self.scheduledUpdate == nil {
+ self.reveal.advance(now: CACurrentMediaTime())
+ }
+ self.presentRevealedCaption(resetLayout: styleChanged, resetMotion: motionChanged)
+ self.scheduleNextWord()
+ }
+
+ /// Also used by layout tests to inspect the final, fully revealed snapshot.
+ func flushPendingCaption() {
+ self.cancelPendingCaption()
+ self.reveal.finish()
+ self.presentRevealedCaption()
+ }
+
+ private func scheduleNextWord() {
+ guard self.reveal.hasPendingWords, self.scheduledUpdate == nil else { return }
+ let work = DispatchWorkItem { [weak self] in
+ guard let self else { return }
+ self.scheduledUpdate = nil
+ self.reveal.advance(now: CACurrentMediaTime())
+ self.presentRevealedCaption()
+ self.scheduleNextWord()
+ }
+ self.scheduledUpdate = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + OverlayCaptionReveal.interval, execute: work)
+ }
+
+ private func cancelPendingCaption() {
+ self.scheduledUpdate?.cancel()
+ self.scheduledUpdate = nil
+ }
+
+ private func presentRevealedCaption(resetLayout: Bool = false, resetMotion: Bool = false) {
+ guard let latestUpdate else { return }
+ let context = self.reveal.displayed
+ let caption = OverlayCaptionText.tail(context.text, limit: latestUpdate.caption.text.count, sourceOffset: context.sourceOffset)
+ let previousBuffer = self.buffer
+ let previousEnd = previousBuffer.sourceOffset + previousBuffer.text.utf16.count
+ let continuous = self.buffer.update(caption, context: context)
+ if caption != previousBuffer.preview || self.buffer.text != previousBuffer.text || self.buffer.sourceOffset != previousBuffer.sourceOffset {
+ if !continuous { self.contentOriginY = 0 }
+ self.canAnimate = (self.pendingUpdate ? self.canAnimate : true) && continuous
+ self.revealFromOffset = self.reduceMotion ? nil : continuous ? previousEnd : self.buffer.sourceOffset
+ if caption != previousBuffer.preview { self.setAccessibilityValue(caption.text) }
+ } else if !resetLayout, !resetMotion {
+ return
+ }
+ if resetLayout { self.contentOriginY = 0 }
+ if resetLayout || resetMotion { self.canAnimate = false }
+ self.cachedLayout = nil
+ self.pendingUpdate = true
+ self.invalidateIntrinsicContentSize()
+ self.needsLayout = true
+ }
+
+ func fittingHeight(width: CGFloat, maxHeight: CGFloat, maxLines: Int?) -> CGFloat {
+ self.textLayout(width: width).viewportHeight(maxHeight: maxHeight, maxLines: maxLines)
+ }
+
+ private func textLayout(width: CGFloat) -> OverlayCaptionLayout {
+ if let cachedLayout, self.cachedWidth == width { return cachedLayout }
+ let layout = OverlayCaptionLayout(text: self.buffer.text, width: width, fontSize: self.fontSize, opacity: self.opacity)
+ self.cachedWidth = width
+ self.cachedLayout = layout
+ return layout
+ }
+
+ override func layout() {
+ super.layout()
+ guard self.bounds.width > 0, self.bounds.height > 0, let layer else { return }
+ let resized = self.renderedWidth != self.bounds.width || self.renderedHeight != self.bounds.height
+ guard self.pendingUpdate || resized else { return }
+ if self.renderedWidth != self.bounds.width { self.contentOriginY = 0 }
+
+ var layout = self.textLayout(width: self.bounds.width)
+ let currentY = layer.presentation()?.sublayerTransform.m42 ?? self.targetY
+ let visibleOffset = self.buffer.preview.sourceOffset - self.buffer.sourceOffset
+ let currentTop = max(0, -currentY - self.contentOriginY)
+ let nextTop = max(0, layout.height - self.bounds.height)
+ let retainFromY = min(currentTop, nextTop) - layout.lineHeight
+ // The character limit must never erase a line the user is still reading. Keep
+ // the full viewport plus an entering line, and discard only complete hidden lines.
+ if let first = layout.lines.first(where: {
+ $0.characters.upperBound > visibleOffset || $0.rect.maxY > retainFromY
+ }), first.characters.location > 0 {
+ self.contentOriginY += first.rect.minY
+ self.buffer.removeHiddenPrefix(utf16Count: first.characters.location)
+ self.cachedLayout = nil
+ layout = self.textLayout(width: self.bounds.width)
+ }
+
+ let nextY = self.buffer.preview.text.isEmpty ? 0 : -max(0, self.contentOriginY + layout.height - self.bounds.height)
+ let shouldAnimate = self.hasRendered && self.canAnimate && !resized && !self.reduceMotion && !self.buffer.preview.text.isEmpty
+ CATransaction.begin()
+ CATransaction.setDisableActions(true)
+ self.drawingLayer.captionLayout = layout
+ let textLength = self.buffer.text.utf16.count
+ let revealStart = self.revealFromOffset.map { max(0, min(textLength, $0 - self.buffer.sourceOffset)) } ?? textLength
+ let fadeWords = self.pendingUpdate && !self.reduceMotion && (!resized || !self.hasRendered) && revealStart < textLength
+ self.drawingLayer.visibleRange = NSRange(location: 0, length: fadeWords ? revealStart : textLength)
+ // Keep absolute line positions when freeing old text. Rebasing the scroll
+ // transform here would restart its easing on each trim and make it crawl.
+ self.drawingLayer.frame = CGRect(x: 0, y: self.contentOriginY, width: self.bounds.width, height: layout.height)
+ self.drawingLayer.setNeedsDisplay()
+ self.revealLayer.removeAnimation(forKey: "captionReveal")
+ self.revealLayer.captionLayout = layout
+ self.revealLayer.visibleRange = NSRange(location: revealStart, length: fadeWords ? textLength - revealStart : 0)
+ if fadeWords {
+ let glyphs = layout.manager.glyphRange(forCharacterRange: self.revealLayer.visibleRange, actualCharacterRange: nil)
+ let rect = layout.manager.boundingRect(forGlyphRange: glyphs, in: layout.container).insetBy(dx: -1, dy: -1).integral
+ self.revealLayer.drawingOrigin = CGPoint(x: -rect.minX, y: -rect.minY)
+ self.revealLayer.frame = rect.offsetBy(dx: 0, dy: self.contentOriginY)
+ let animation = CABasicAnimation(keyPath: "opacity")
+ animation.fromValue = 0
+ animation.toValue = 1
+ animation.duration = Self.revealDuration
+ animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.23, 1, 0.32, 1)
+ self.revealLayer.add(animation, forKey: "captionReveal")
+ }
+ self.revealLayer.setNeedsDisplay()
+ layer.sublayerTransform = CATransform3DMakeTranslation(0, nextY, 0)
+ // New words on the same line must not restart an in-flight scroll.
+ if !shouldAnimate || abs(nextY - self.targetY) > 0.5 {
+ layer.removeAnimation(forKey: Self.scrollAnimationKey)
+ if shouldAnimate, abs(nextY - currentY) > 0.5 {
+ let animation = CABasicAnimation(keyPath: "sublayerTransform.translation.y")
+ animation.fromValue = currentY
+ animation.toValue = nextY
+ animation.duration = Self.scrollDuration
+ animation.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil)
+ animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.23, 1, 0.32, 1)
+ layer.add(animation, forKey: Self.scrollAnimationKey)
+ }
+ }
+ CATransaction.commit()
+ self.targetY = nextY
+ self.renderedWidth = self.bounds.width
+ self.renderedHeight = self.bounds.height
+ self.hasRendered = true
+ self.pendingUpdate = false
+ self.canAnimate = true
+ }
+
+ func stopScrolling() {
+ self.cancelPendingCaption()
+ self.latestUpdate = nil
+ self.reveal = OverlayCaptionReveal()
+ self.canAnimate = false
+ self.revealFromOffset = nil
+ self.layer?.removeAnimation(forKey: Self.scrollAnimationKey)
+ self.revealLayer.removeAllAnimations()
+ }
+}
+
+/// An owned layer renders the complete bounded text, including lines outside the viewport.
+/// An NSView subview would cull that offscreen drawing before the compositor scrolls it in.
+private final class OverlayCaptionDrawingLayer: CALayer {
+ var captionLayout: OverlayCaptionLayout?
+ var visibleRange = NSRange(location: 0, length: 0)
+ var drawingOrigin = CGPoint.zero
+
+ override func draw(in context: CGContext) {
+ guard let captionLayout, self.visibleRange.length > 0 else { return }
+ context.saveGState()
+ NSGraphicsContext.saveGraphicsState()
+ NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: true)
+ let glyphs = captionLayout.manager.glyphRange(forCharacterRange: self.visibleRange, actualCharacterRange: nil)
+ captionLayout.manager.drawGlyphs(forGlyphRange: glyphs, at: self.drawingOrigin)
+ NSGraphicsContext.restoreGraphicsState()
+ context.restoreGState()
+ }
+}
diff --git a/Sources/Fluid/Views/BottomOverlayView.swift b/Sources/Fluid/Views/BottomOverlayView.swift
index 2cd059c8..c06045e0 100644
--- a/Sources/Fluid/Views/BottomOverlayView.swift
+++ b/Sources/Fluid/Views/BottomOverlayView.swift
@@ -27,6 +27,7 @@ final class BottomOverlayWindowController {
static let shared = BottomOverlayWindowController()
private var window: NSPanel?
+ private var hostingView: BottomOverlayHostingView?
private var audioSubscription: AnyCancellable?
private var pendingResizeWorkItem: DispatchWorkItem?
private var pendingReleaseTransitionResetWorkItem: DispatchWorkItem?
@@ -55,6 +56,7 @@ final class BottomOverlayWindowController {
self.audioSubscription = nil
self.window?.orderOut(nil)
self.window = nil
+ self.hostingView = nil
}
var isParkedOffscreenForTests: Bool {
@@ -66,6 +68,8 @@ final class BottomOverlayWindowController {
self.window?.frame.size
}
+ var contentViewForTests: NSView? { self.hostingView }
+
private init() {
NotificationCenter.default.addObserver(forName: NSNotification.Name("OverlayOffsetChanged"), object: nil, queue: .main) { [weak self] _ in
Task { @MainActor [weak self] in
@@ -333,6 +337,7 @@ final class BottomOverlayWindowController {
self.pendingIgnoreMouseWorkItem?.cancel()
let workItem = DispatchWorkItem { [weak self] in
guard let self, self.window?.alphaValue == 0 else { return }
+ self.pendingIgnoreMouseWorkItem = nil
let startedAt = ProcessInfo.processInfo.systemUptime
self.window?.ignoresMouseEvents = true
DebugLogger.shared.debug(
@@ -484,6 +489,7 @@ final class BottomOverlayWindowController {
self.pendingResizeWorkItem?.cancel()
self.pendingResizeWorkItem = nil
self.pendingReleaseTransitionResetWorkItem?.cancel()
+ self.pendingReleaseTransitionResetWorkItem = nil
self.targetScreen = nil
self.removeMouseDownMonitors()
trace.mark("cancelWorkAndMonitors")
@@ -516,6 +522,7 @@ final class BottomOverlayWindowController {
}
func beginReleaseTransition(duration: TimeInterval = 0.28) {
+ guard NotchContentState.shared.isBottomOverlayPresented, self.window?.alphaValue != 0 else { return }
let now = Date()
let deadline = now.addingTimeInterval(max(duration, 0.12))
if let existingDeadline = self.releaseTransitionActiveUntil, existingDeadline > deadline {
@@ -563,6 +570,7 @@ final class BottomOverlayWindowController {
}
private func scheduleSizeAndPositionUpdate(after delay: TimeInterval = 0.08) {
+ guard NotchContentState.shared.isBottomOverlayPresented, self.window?.alphaValue != 0 else { return }
if self.isReleaseTransitionActive {
self.deferredResizePending = true
return
@@ -577,6 +585,7 @@ final class BottomOverlayWindowController {
Self.overlayBench("bottom_resize_drop reason=stale_generation")
return
}
+ self.pendingResizeWorkItem = nil
self.updateSizeAndPosition()
}
self.pendingResizeWorkItem = resizeWorkItem
@@ -587,9 +596,7 @@ final class BottomOverlayWindowController {
/// session geometry before the warm panel moves onscreen. Otherwise the
/// panel can reveal its previous multiline frame until resize debounce.
private func prepareFirstFrameForNewPresentation(trace: inout OverlayCloseTrace) {
- guard let window,
- let hostingView = window.contentView as? NSHostingView<BottomOverlayView>
- else { return }
+ guard let window, let hostingView else { return }
hostingView.rootView = BottomOverlayView()
hostingView.invalidateIntrinsicContentSize()
@@ -597,8 +604,8 @@ final class BottomOverlayWindowController {
trace.mark("layout1")
let firstFrameSize = hostingView.fittingSize
trace.mark("fittingSize")
- hostingView.frame = NSRect(origin: .zero, size: firstFrameSize)
window.setFrame(NSRect(origin: window.frame.origin, size: firstFrameSize), display: false)
+ hostingView.frame = NSRect(origin: .zero, size: firstFrameSize)
trace.mark("setFrame")
self.positionWindow()
trace.mark("position")
@@ -609,6 +616,7 @@ final class BottomOverlayWindowController {
/// Update window size based on current SwiftUI content and re-position
private func updateSizeAndPosition() {
+ guard NotchContentState.shared.isBottomOverlayPresented, self.window?.alphaValue != 0 else { return }
var trace = OverlayCloseTrace("bottom.layout")
defer { trace.finish() }
if self.isReleaseTransitionActive {
@@ -616,7 +624,7 @@ final class BottomOverlayWindowController {
return
}
- guard let window = window, let hostingView = window.contentView as? NSHostingView<BottomOverlayView> else { return }
+ guard let window, let hostingView else { return }
// Re-calculate fitting size for the new layout constants
let newSize = hostingView.fittingSize
@@ -667,6 +675,7 @@ final class BottomOverlayWindowController {
let contentView = BottomOverlayView()
let hostingView = BottomOverlayHostingView(rootView: contentView)
+ hostingView.sizingOptions = .intrinsicContentSize
// Let SwiftUI determine the size
let fittingSize = hostingView.fittingSize
@@ -676,12 +685,20 @@ final class BottomOverlayWindowController {
hostingView.wantsLayer = true
hostingView.layer?.backgroundColor = .clear
+ // A hosting view used directly as window content can resize that window
+ // during SwiftUI updates even with sizingOptions disabled. Keep window
+ // sizing in this controller, including while its warm panel is hidden.
+ let container = BottomOverlayContainerView(frame: hostingView.frame)
+ container.wantsLayer = true
+ container.addSubview(hostingView)
+ hostingView.autoresizingMask = [.width, .height]
panel.setContentSize(fittingSize)
- panel.contentView = hostingView
+ panel.contentView = container
hostingView.layoutSubtreeIfNeeded()
hostingView.display()
self.window = panel
+ self.hostingView = hostingView
}
private var isReleaseTransitionActive: Bool {
@@ -930,7 +947,10 @@ final class BottomOverlayPromptMenuController {
}
private func showMenuIfPossible() {
- guard self.selectorFrameInScreen.width > 0, self.selectorFrameInScreen.height > 0 else { return }
+ guard NotchContentState.shared.isBottomOverlayPresented,
+ let parentWindow = self.parentWindow, parentWindow.isVisible, parentWindow.alphaValue > 0,
+ self.selectorFrameInScreen.width > 0, self.selectorFrameInScreen.height > 0
+ else { return }
self.createWindowIfNeeded()
self.updateMenuContent()
@@ -1207,7 +1227,10 @@ final class BottomOverlayModeMenuController {
}
private func showMenuIfPossible() {
- guard self.selectorFrameInScreen.width > 0, self.selectorFrameInScreen.height > 0 else { return }
+ guard NotchContentState.shared.isBottomOverlayPresented,
+ let parentWindow = self.parentWindow, parentWindow.isVisible, parentWindow.alphaValue > 0,
+ self.selectorFrameInScreen.width > 0, self.selectorFrameInScreen.height > 0
+ else { return }
self.createWindowIfNeeded()
self.updateMenuContent()
@@ -1471,7 +1494,10 @@ final class BottomOverlayActionsMenuController {
}
private func showMenuIfPossible() {
- guard self.selectorFrameInScreen.width > 0, self.selectorFrameInScreen.height > 0 else { return }
+ guard NotchContentState.shared.isBottomOverlayPresented,
+ let parentWindow = self.parentWindow, parentWindow.isVisible, parentWindow.alphaValue > 0,
+ self.selectorFrameInScreen.width > 0, self.selectorFrameInScreen.height > 0
+ else { return }
self.createWindowIfNeeded()
self.updateMenuContent()
@@ -2244,7 +2270,7 @@ private struct PromptSelectorAnchorReader: NSViewRepresentable {
func updateNSView(_ nsView: AnchorReportingView, context: Context) {
nsView.onFrameChange = self.onFrameChange
- nsView.reportFrame(force: true)
+ DispatchQueue.main.async { [weak nsView] in nsView?.reportFrame(force: true) }
}
final class AnchorReportingView: NSView {
@@ -2340,6 +2366,13 @@ private enum PillShadowMetrics {
static var visibleWidth: CGFloat = 100
}
+private final class BottomOverlayContainerView: NSView {
+ override func hitTest(_ point: NSPoint) -> NSView? {
+ let hit = super.hitTest(point)
+ return hit === self ? nil : hit
+ }
+}
+
private final class BottomOverlayHostingView: NSHostingView<BottomOverlayView> {
override func hitTest(_ point: NSPoint) -> NSView? {
if SettingsStore.shared.overlaySize == .pill {
@@ -2389,7 +2422,6 @@ struct BottomOverlayView: View {
@State private var actionsSelectorWindow: NSWindow?
@State private var dynamicPreviewMeasuredHeight: CGFloat = 0
@State private var frozenDynamicPreviewHeight: CGFloat?
- @State private var dynamicPreviewResizeBucket: Int = 0
@State private var processingStatusVisible = false
@State private var processingStatusCycleID = 0
@State private var lastResolvedAppIcon: NSImage?
@@ -2471,7 +2503,7 @@ struct BottomOverlayView: View {
case .medium:
return LayoutConstants(
hPadding: 18,
- vPadding: 12,
+ vPadding: 8,
waveformWidth: 130,
waveformHeight: 32,
iconSize: 20,
@@ -2771,7 +2803,12 @@ struct BottomOverlayView: View {
let verticalPadding = self.settings.overlaySize == .small
? max(2, self.transcriptionVerticalPadding - 1)
: self.transcriptionVerticalPadding
- return self.estimatedPreviewLineHeight + verticalPadding * 2
+ let height = OverlayCaptionLayout.viewportHeight(
+ fontSize: self.layout.transFontSize,
+ maxHeight: self.previewMaxHeight,
+ maxLines: self.settings.overlaySize == .small ? 1 : nil
+ )
+ return height + verticalPadding * 2
}
private var effectiveDynamicPreviewLockedHeight: CGFloat? {
@@ -2784,18 +2821,6 @@ struct BottomOverlayView: View {
self.effectiveDynamicPreviewLockedHeight ?? self.dynamicPreviewBaseMinHeight
}
- private var estimatedPreviewLineHeight: CGFloat {
- max(self.layout.transFontSize * 1.25, self.layout.transFontSize + 2)
- }
-
- private var currentPreviewSizingText: String {
- guard self.shouldReservePreviewArea else { return "" }
- if self.shouldShowProcessingPreview {
- return self.processingPreviewText
- }
- return self.shouldShowProcessingStatus ? self.processingStatusText : self.transcriptionPreviewText
- }
-
private var shouldShowProcessingStatus: Bool {
self.shouldReservePreviewArea && self.contentState.isProcessing && self.processingStatusVisible
}
@@ -2815,33 +2840,6 @@ struct BottomOverlayView: View {
return self.contentState.isBottomOverlayReleaseTransitioning || self.contentState.isBottomOverlayDismissing
}
- private func previewResizeBucket(for previewText: String) -> Int {
- guard self.shouldReservePreviewArea else { return 0 }
- if self.shouldShowAIProcessingFailure || self.shouldShowTextDeliveryFailure { return 1 }
- let trimmed = previewText.trimmingCharacters(in: .whitespacesAndNewlines)
- guard !trimmed.isEmpty else { return self.shouldShowProcessingStatus ? 1 : 0 }
-
- if self.settings.overlaySize == .small {
- return 1
- }
-
- let newlineCount = trimmed.filter { $0 == "\n" }.count
- let estimatedCharacterWidth = max(self.layout.transFontSize * 0.56, 1)
- let characterCapacity = max(Int((self.previewMaxWidth / estimatedCharacterWidth).rounded(.down)), 12)
- let estimatedWrappedLines = max(1, (trimmed.count + characterCapacity - 1) / characterCapacity)
- let maxVisibleLines = max(Int((self.previewMaxHeight / max(self.estimatedPreviewLineHeight, 1)).rounded(.down)), 1)
- return min(max(estimatedWrappedLines + newlineCount, 1), maxVisibleLines)
- }
-
- private func refreshDynamicPreviewSizeIfNeeded(for previewText: String) {
- guard self.shouldReservePreviewArea else { return }
- guard !self.layout.usesFixedCanvas else { return }
- let nextBucket = self.previewResizeBucket(for: previewText)
- guard nextBucket != self.dynamicPreviewResizeBucket else { return }
- self.dynamicPreviewResizeBucket = nextBucket
- BottomOverlayWindowController.shared.refreshSizeForContent()
- }
-
private var transcriptionVerticalPadding: CGFloat {
max(4, self.layout.vPadding / 2)
}
@@ -2864,11 +2862,6 @@ struct BottomOverlayView: View {
!self.processingPreviewText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
- private func richPreviewText(_ previewText: String) -> Text {
- Text(previewText)
- .foregroundColor(.white.opacity(0.96))
- }
-
private var overlayAnimatedOffsetY: CGFloat {
if self.contentState.isBottomOverlayDismissing {
return self.contentState.bottomOverlayDismissOffsetY
@@ -2926,11 +2919,14 @@ struct BottomOverlayView: View {
/// Expands after a short dwell so a passing pointer never moves the pill, and
/// collapses late so the trip from pill to menu does not close it.
private func handlePillHover(_ hovering: Bool) {
- guard self.isPillSize else { return }
+ guard self.isPillSize, self.contentState.isBottomOverlayPresented, !self.contentState.isBottomOverlayDismissing else { return }
self.pillHoverWorkItem?.cancel()
+ self.pillHoverWorkItem = nil
let shouldExpand = hovering && self.isPromptSelectableMode && !self.contentState.isProcessing
guard shouldExpand != self.isPillExpanded else { return }
let work = DispatchWorkItem {
+ self.pillHoverWorkItem = nil
+ guard self.contentState.isBottomOverlayPresented, !self.contentState.isBottomOverlayDismissing else { return }
if !shouldExpand, BottomOverlayPromptMenuController.shared.isMenuVisible {
self.handlePillHover(false)
return
@@ -3333,7 +3329,7 @@ struct BottomOverlayView: View {
private var targetAppIconView: some View {
let appIcon = self.displayedAppIcon
- let showModelLoading = self.layout.showsModeLabel && !self.appServices.asr.isAsrReady &&
+ let showModelLoading = self.contentState.isBottomOverlayPresented && self.layout.showsModeLabel && !self.appServices.asr.isAsrReady &&
(self.appServices.asr.isLoadingModel || self.appServices.asr.isDownloadingModel)
return VStack(spacing: 2) {
if showModelLoading {
@@ -3393,47 +3389,33 @@ struct BottomOverlayView: View {
.id(failureID)
}
- private func scrollablePreviewText(_ previewText: String) -> some View {
- ScrollViewReader { proxy in
- ScrollView(.vertical, showsIndicators: false) {
- self.richPreviewText(previewText)
- .font(.fluidSystem(size: self.layout.transFontSize, weight: .medium))
- .multilineTextAlignment(.leading)
- .lineLimit(nil)
- .fixedSize(horizontal: false, vertical: true)
- .frame(maxWidth: .infinity, alignment: .leading)
- Color.clear.frame(height: 1).id("bottom")
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
- .clipped()
- .onChange(of: previewText) { _, _ in
- DispatchQueue.main.async {
- proxy.scrollTo("bottom", anchor: .bottom)
- }
- }
- }
+ private var scrollingCaption: some View {
+ OverlayCaptionView(
+ caption: self.contentState.captionPreview,
+ context: self.contentState.captionContext,
+ fontSize: self.layout.transFontSize,
+ maxHeight: max(1, self.previewMaxHeight - self.transcriptionVerticalPadding * 2),
+ isActive: self.contentState.isBottomOverlayPresented
+ )
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
- @ViewBuilder
- private func dynamicPreviewText(_ previewText: String) -> some View {
- if self.settings.overlaySize == .small {
- self.richPreviewText(previewText)
- .font(.fluidSystem(size: self.layout.transFontSize, weight: .medium))
- .multilineTextAlignment(.leading)
- .lineLimit(1)
- .truncationMode(.head)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(.vertical, max(2, self.transcriptionVerticalPadding - 1))
- } else {
- self.richPreviewText(previewText)
- .font(.fluidSystem(size: self.layout.transFontSize, weight: .medium))
- .multilineTextAlignment(.leading)
- .lineLimit(Int(self.previewMaxHeight / max(self.estimatedPreviewLineHeight, 1)))
- .truncationMode(.head)
- .fixedSize(horizontal: false, vertical: true)
- .frame(width: self.previewMaxWidth, alignment: .leading)
- .padding(.vertical, self.transcriptionVerticalPadding)
- }
+ private var dynamicCaption: some View {
+ OverlayCaptionView(
+ caption: self.contentState.captionPreview,
+ context: self.contentState.captionContext,
+ fontSize: self.layout.transFontSize,
+ maxHeight: self.previewMaxHeight,
+ maxLines: self.settings.overlaySize == .small ? 1 : nil,
+ isActive: self.contentState.isBottomOverlayPresented
+ )
+ .frame(width: self.previewMaxWidth, alignment: .leading)
+ .padding(
+ .vertical,
+ self.settings.overlaySize == .small
+ ? max(2, self.transcriptionVerticalPadding - 1)
+ : self.transcriptionVerticalPadding
+ )
}
var body: some View {
@@ -3458,7 +3440,7 @@ struct BottomOverlayView: View {
} else if self.shouldShowAIProcessingFailure {
self.aiProcessingFailureView
} else if self.shouldShowProcessingPreview {
- self.scrollablePreviewText(self.processingPreviewText)
+ self.scrollingCaption
} else if self.shouldShowProcessingStatus {
// Temporarily hidden; the waveform sweep carries processing state.
// ShimmerText(
@@ -3474,30 +3456,7 @@ struct BottomOverlayView: View {
} else if self.hasTranscription {
let previewText = self.transcriptionPreviewText
if !previewText.isEmpty {
- ScrollViewReader { proxy in
- ScrollView(.vertical, showsIndicators: false) {
- Text(previewText)
- .font(.fluidSystem(size: self.layout.transFontSize, weight: .medium))
- .foregroundStyle(.white.opacity(0.96))
- .multilineTextAlignment(.leading)
- .lineLimit(nil)
- .fixedSize(horizontal: false, vertical: true)
- .frame(maxWidth: .infinity, alignment: .leading)
- Color.clear.frame(height: 1).id("bottom")
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
- .clipped()
- .onAppear {
- DispatchQueue.main.async {
- proxy.scrollTo("bottom", anchor: .bottom)
- }
- }
- .onChange(of: previewText) { _, _ in
- DispatchQueue.main.async {
- proxy.scrollTo("bottom", anchor: .bottom)
- }
- }
- }
+ self.scrollingCaption
}
} else {
Color.clear
@@ -3511,7 +3470,7 @@ struct BottomOverlayView: View {
alignment: .topLeading
)
} else {
- // Original dynamic preview behavior for small/medium
+ // Reserve the line slots before the first result so controls stay still.
Group {
if self.shouldSuppressPreviewDuringRelease {
Color.clear
@@ -3520,30 +3479,11 @@ struct BottomOverlayView: View {
} else if self.shouldShowAIProcessingFailure {
self.aiProcessingFailureView
} else if self.shouldShowProcessingPreview {
- self.dynamicPreviewText(self.processingPreviewText)
+ self.dynamicCaption
} else if self.hasTranscription && !self.contentState.isProcessing {
let previewText = self.transcriptionPreviewText
if !previewText.isEmpty {
- if self.settings.overlaySize == .small {
- Text(previewText)
- .font(.fluidSystem(size: self.layout.transFontSize, weight: .medium))
- .foregroundStyle(.white.opacity(0.96))
- .multilineTextAlignment(.leading)
- .lineLimit(1)
- .truncationMode(.head)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(.vertical, max(2, self.transcriptionVerticalPadding - 1))
- } else {
- Text(previewText)
- .font(.fluidSystem(size: self.layout.transFontSize, weight: .medium))
- .foregroundStyle(.white.opacity(0.96))
- .multilineTextAlignment(.leading)
- .lineLimit(Int(self.previewMaxHeight / max(self.estimatedPreviewLineHeight, 1)))
- .truncationMode(.head)
- .fixedSize(horizontal: false, vertical: true)
- .frame(width: self.previewMaxWidth, alignment: .leading)
- .padding(.vertical, self.transcriptionVerticalPadding)
- }
+ self.dynamicCaption
}
} else if self.shouldShowProcessingStatus {
// Temporarily hidden; the waveform sweep carries processing state.
@@ -3571,10 +3511,6 @@ struct BottomOverlayView: View {
minHeight: self.effectiveDynamicPreviewMinHeight,
maxHeight: self.effectiveDynamicPreviewLockedHeight
)
- .animation(
- self.reduceMotion ? nil : BottomOverlayWindowController.growthAnimation,
- value: self.dynamicPreviewResizeBucket
- )
}
}
@@ -3738,13 +3674,9 @@ struct BottomOverlayView: View {
if processing { self.handlePillHover(false) }
}
.onChange(of: self.settings.enableStreamingPreview) { _, _ in
- self.dynamicPreviewResizeBucket = self.previewResizeBucket(for: self.currentPreviewSizingText)
self.frozenDynamicPreviewHeight = nil
BottomOverlayWindowController.shared.refreshSizeForContent()
}
- .onChange(of: self.contentState.cachedPreviewText) { _, _ in
- self.refreshDynamicPreviewSizeIfNeeded(for: self.currentPreviewSizingText)
- }
.onChange(of: self.contentState.mode) { _, _ in
if !self.isPromptSelectableMode || self.contentState.isProcessing {
self.closePromptMenu()
@@ -3761,7 +3693,6 @@ struct BottomOverlayView: View {
case .command: break
}
if !self.layout.usesFixedCanvas {
- self.dynamicPreviewResizeBucket = self.previewResizeBucket(for: self.currentPreviewSizingText)
BottomOverlayWindowController.shared.refreshSizeForContent()
}
}
@@ -3778,20 +3709,20 @@ struct BottomOverlayView: View {
self.isHoveringActionsChip = false
self.isHoveringSettingsChip = false
if !self.layout.usesFixedCanvas {
- self.refreshDynamicPreviewSizeIfNeeded(for: self.currentPreviewSizingText)
+ BottomOverlayWindowController.shared.refreshSizeForContent()
}
}
.onChange(of: self.contentState.isAIProcessingFailureVisible) { _, _ in
guard !self.layout.usesFixedCanvas else { return }
- self.refreshDynamicPreviewSizeIfNeeded(for: self.currentPreviewSizingText)
+ BottomOverlayWindowController.shared.refreshSizeForContent()
}
.onChange(of: self.contentState.isTextDeliveryFailureVisible) { _, _ in
guard !self.layout.usesFixedCanvas else { return }
- self.refreshDynamicPreviewSizeIfNeeded(for: self.currentPreviewSizingText)
+ BottomOverlayWindowController.shared.refreshSizeForContent()
}
.onChange(of: self.processingStatusVisible) { _, _ in
guard !self.layout.usesFixedCanvas else { return }
- self.refreshDynamicPreviewSizeIfNeeded(for: self.currentPreviewSizingText)
+ BottomOverlayWindowController.shared.refreshSizeForContent()
}
.onChange(of: self.contentState.isBottomOverlayReleaseTransitioning) { _, transitioning in
guard self.shouldReservePreviewArea else {
@@ -3812,16 +3743,20 @@ struct BottomOverlayView: View {
.onPreferenceChange(DynamicPreviewHeightPreferenceKey.self) { measuredHeight in
guard !self.layout.usesFixedCanvas else { return }
guard measuredHeight > 0 else { return }
+ guard abs(self.dynamicPreviewMeasuredHeight - measuredHeight) > 0.5 else { return }
self.dynamicPreviewMeasuredHeight = measuredHeight
+ if self.contentState.isBottomOverlayPresented {
+ BottomOverlayWindowController.shared.refreshSizeForContent()
+ }
}
.onAppear {
self.rememberAppIcon(self.contentState.targetAppIcon ?? self.activeAppMonitor.activeAppIcon)
- self.dynamicPreviewResizeBucket = self.previewResizeBucket(for: self.currentPreviewSizingText)
}
.onReceive(self.contentState.$targetAppIcon) { icon in
self.rememberAppIcon(icon)
}
.onDisappear {
+ self.collapsePillImmediately()
self.closePromptMenu()
self.closeModeMenu()
self.closeActionsMenu()
@@ -3830,6 +3765,12 @@ struct BottomOverlayView: View {
self.isHoveringActionsChip = false
self.isHoveringSettingsChip = false
}
+ .transaction { transaction in
+ if !self.contentState.isBottomOverlayPresented {
+ transaction.animation = nil
+ transaction.disablesAnimations = true
+ }
+ }
// TODO: Add tap-to-expand for command mode history (future enhancement)
// .contentShape(Rectangle())
// .onTapGesture {
diff --git a/Sources/Fluid/Views/BottomWaveformView.swift b/Sources/Fluid/Views/BottomWaveformView.swift
index 434db75d..d6b44c67 100644
--- a/Sources/Fluid/Views/BottomWaveformView.swift
+++ b/Sources/Fluid/Views/BottomWaveformView.swift
@@ -78,7 +78,7 @@ struct BottomWaveformView: View {
.foregroundStyle(self.barFillColor)
if self.isProcessingVisualActive {
- CompositorShimmerSweep(duration: 1.05, peakOpacity: 0.9)
+ CompositorShimmerSweep(duration: 1.05, peakOpacity: 0.9, isActive: self.contentState.isBottomOverlayPresented)
.mask {
self.barsView
}
diff --git a/Sources/Fluid/Views/NotchContentViews.swift b/Sources/Fluid/Views/NotchContentViews.swift
index 04499bb7..95e07fae 100644
--- a/Sources/Fluid/Views/NotchContentViews.swift
+++ b/Sources/Fluid/Views/NotchContentViews.swift
@@ -129,8 +129,15 @@ class NotchContentState: ObservableObject {
@Published var recordingTargetPID: pid_t? = nil
var recordingTargetContext: TypingService.RecordingTargetContext?
- /// Cached transcription preview text to avoid recomputing on every render
- @Published private(set) var cachedPreviewText: String = ""
+ /// The preview keeps its source position so trimming cannot move wrapped caption lines.
+ @Published private(set) var captionPreview: OverlayCaptionText = .empty
+ var cachedPreviewText: String { self.captionPreview.text }
+ private var transcriptionSourceOffset = 0
+
+ /// Bounded recovery context for a revision or a chunk that skips past the short preview.
+ var captionContext: OverlayCaptionText {
+ OverlayCaptionText(text: self.transcriptionText, sourceOffset: self.transcriptionSourceOffset)
+ }
// MARK: - Expanded Command Output State
@@ -235,35 +242,23 @@ class NotchContentState: ObservableObject {
/// Update transcription and recompute cached lines
func updateTranscription(_ text: String) {
- let boundedText = Self.tailCharacters(in: text, maxCharacters: Self.maxStoredTranscriptionCharacters)
- guard boundedText != self.transcriptionText else { return }
+ let bounded = OverlayCaptionText.tail(text, limit: Self.maxStoredTranscriptionCharacters)
+ guard bounded.text != self.transcriptionText || bounded.sourceOffset != self.transcriptionSourceOffset else { return }
- self.transcriptionText = boundedText
+ self.transcriptionSourceOffset = bounded.sourceOffset
+ self.transcriptionText = bounded.text
self.recomputeTranscriptionLines()
}
/// Recompute cached transcription lines (called only when text changes)
private func recomputeTranscriptionLines() {
- let text = self.transcriptionText
-
- guard !text.isEmpty else {
- if !self.cachedPreviewText.isEmpty {
- self.cachedPreviewText = ""
- }
- return
- }
-
- let maxChars = SettingsStore.shared.transcriptionPreviewCharLimit
- let previewText = Self.tailCharacters(in: text, maxCharacters: maxChars)
- guard previewText != self.cachedPreviewText else { return }
- self.cachedPreviewText = previewText
- }
-
- private static func tailCharacters(in text: String, maxCharacters: Int) -> String {
- guard maxCharacters > 0, !text.isEmpty else { return "" }
-
- let start = text.index(text.endIndex, offsetBy: -maxCharacters, limitedBy: text.startIndex) ?? text.startIndex
- return String(text[start..<text.endIndex])
+ let preview = OverlayCaptionText.tail(
+ self.transcriptionText,
+ limit: SettingsStore.shared.transcriptionPreviewCharLimit,
+ sourceOffset: self.transcriptionSourceOffset
+ )
+ guard preview != self.captionPreview else { return }
+ self.captionPreview = preview
}
// MARK: - Recording State for Expanded View
@@ -427,17 +422,23 @@ struct ShimmerText: View {
}
struct CompositorShimmerSweep: NSViewRepresentable {
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
var duration: CFTimeInterval = 1.0
var peakOpacity: CGFloat = 0.88
+ var isActive = true
func makeNSView(context: Context) -> CompositorShimmerSweepView {
let view = CompositorShimmerSweepView()
- view.configure(duration: self.duration, peakOpacity: self.peakOpacity)
+ view.configure(duration: self.duration, peakOpacity: self.peakOpacity, isActive: self.isActive && !self.reduceMotion)
return view
}
func updateNSView(_ nsView: CompositorShimmerSweepView, context: Context) {
- nsView.configure(duration: self.duration, peakOpacity: self.peakOpacity)
+ nsView.configure(duration: self.duration, peakOpacity: self.peakOpacity, isActive: self.isActive && !self.reduceMotion)
+ }
+
+ static func dismantleNSView(_ nsView: CompositorShimmerSweepView, coordinator: ()) {
+ nsView.configure(duration: 1, peakOpacity: 0, isActive: false)
}
}
@@ -445,6 +446,8 @@ final class CompositorShimmerSweepView: NSView {
private let gradientLayer = CAGradientLayer()
private var animationDuration: CFTimeInterval = 1.0
private var peakOpacity: CGFloat = 0.88
+ private var isActive = true
+ private var visibilitySubscriptions = Set<AnyCancellable>()
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
@@ -476,14 +479,35 @@ final class CompositorShimmerSweepView: NSView {
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
- if self.window == nil {
- self.gradientLayer.removeAnimation(forKey: "fluid.shimmer.locations")
- } else {
- self.startAnimationIfNeeded()
+ self.visibilitySubscriptions.removeAll()
+ if let window {
+ NotificationCenter.default.publisher(for: NSWindow.didChangeOcclusionStateNotification)
+ .filter { [weak window] in $0.object as? NSWindow === window }
+ .sink { [weak self] _ in self?.updateAnimation() }
+ .store(in: &self.visibilitySubscriptions)
+ // Alpha-zero panels remain ordered in. Stop on that property change
+ // immediately; occlusion notifications arrive later from WindowServer.
+ window.publisher(for: \.alphaValue, options: [.new])
+ .sink { [weak self] _ in self?.updateAnimation() }
+ .store(in: &self.visibilitySubscriptions)
+ window.publisher(for: \.isVisible, options: [.new])
+ .sink { [weak self] _ in self?.updateAnimation() }
+ .store(in: &self.visibilitySubscriptions)
}
+ self.updateAnimation()
}
- func configure(duration: CFTimeInterval, peakOpacity: CGFloat) {
+ override func viewDidHide() {
+ super.viewDidHide()
+ self.updateAnimation()
+ }
+
+ override func viewDidUnhide() {
+ super.viewDidUnhide()
+ self.updateAnimation()
+ }
+
+ func configure(duration: CFTimeInterval, peakOpacity: CGFloat, isActive: Bool = true) {
let clampedDuration = max(duration, 0.2)
let clampedOpacity = min(max(peakOpacity, 0.0), 1.0)
let shouldRestart = abs(self.animationDuration - clampedDuration) > 0.01
@@ -491,12 +515,14 @@ final class CompositorShimmerSweepView: NSView {
self.animationDuration = clampedDuration
self.peakOpacity = clampedOpacity
+ self.isActive = isActive
if shouldUpdateColors {
self.updateColors()
}
if shouldRestart {
- self.startAnimationIfNeeded()
+ self.gradientLayer.removeAnimation(forKey: "fluid.shimmer.locations")
}
+ self.updateAnimation()
}
private func updateColors() {
@@ -507,9 +533,15 @@ final class CompositorShimmerSweepView: NSView {
]
}
- private func startAnimationIfNeeded() {
- guard self.window != nil else { return }
- self.gradientLayer.removeAnimation(forKey: "fluid.shimmer.locations")
+ private func updateAnimation() {
+ guard self.isActive, !self.isHiddenOrHasHiddenAncestor,
+ let window = self.window, window.isVisible, window.alphaValue > 0,
+ window.occlusionState.contains(.visible)
+ else {
+ self.gradientLayer.removeAnimation(forKey: "fluid.shimmer.locations")
+ return
+ }
+ guard self.gradientLayer.animation(forKey: "fluid.shimmer.locations") == nil else { return }
let animation = CABasicAnimation(keyPath: "locations")
animation.fromValue = [-0.45, -0.15, 0.15]
@@ -1133,31 +1165,14 @@ struct NotchExpandedView: View {
} else if self.presentationPolicy.showsStreamingPreview && self.hasTranscription && !self.contentState.isProcessing {
let previewText = self.visiblePreviewText
if !previewText.isEmpty {
- ScrollViewReader { proxy in
- ScrollView(.vertical, showsIndicators: false) {
- Text(previewText)
- .font(.fluidSystem(size: 10, weight: .medium))
- .foregroundStyle(.white.opacity(0.75))
- .multilineTextAlignment(.leading)
- .lineLimit(nil)
- .fixedSize(horizontal: false, vertical: true)
- .frame(maxWidth: .infinity, alignment: .leading)
- Color.clear.frame(height: 1).id("bottom")
- }
- .frame(width: self.previewMaxWidth, alignment: .leading)
- .frame(maxHeight: self.previewMaxHeight, alignment: .leading)
- .clipped()
- .onAppear {
- DispatchQueue.main.async {
- proxy.scrollTo("bottom", anchor: .bottom)
- }
- }
- .onChange(of: previewText) { _, _ in
- DispatchQueue.main.async {
- proxy.scrollTo("bottom", anchor: .bottom)
- }
- }
- }
+ OverlayCaptionView(
+ caption: self.contentState.captionPreview,
+ context: self.contentState.captionContext,
+ fontSize: 10,
+ maxHeight: self.previewMaxHeight,
+ opacity: 0.75
+ )
+ .frame(width: self.previewMaxWidth, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .center)
.transition(.opacity.combined(with: .scale(scale: 0.95)))
}
@@ -1401,13 +1416,17 @@ struct NotchCompactBottomView: View {
var body: some View {
ZStack(alignment: .leading) {
- Text(self.compactPreviewText)
- .font(.fluidSystem(size: 9, weight: .medium))
- .foregroundStyle(.white.opacity(0.82))
- .lineLimit(1)
- .truncationMode(.head)
- .offset(y: self.shouldShowPreview ? 0 : -4)
- .opacity(self.shouldShowPreview ? 1 : 0)
+ OverlayCaptionView(
+ caption: self.contentState.captionPreview,
+ context: self.contentState.captionContext,
+ fontSize: 9,
+ maxHeight: self.previewHeight,
+ opacity: 0.82,
+ maxLines: 1,
+ isActive: self.shouldShowPreview
+ )
+ .offset(y: self.shouldShowPreview ? 0 : -4)
+ .opacity(self.shouldShowPreview ? 1 : 0)
}
.frame(width: self.previewWidth, height: SettingsStore.shared.enableStreamingPreview ? self.previewHeight : 0, alignment: .leading)
.padding(.horizontal, SettingsStore.shared.enableStreamingPreview ? 10 : 0)
@@ -1432,6 +1451,7 @@ struct NotchCommandOutputExpandedView: View {
@State private var inputText: String = ""
@FocusState private var isInputFocused: Bool
@State private var scrollProxy: ScrollViewProxy?
+ @State private var pendingScrollWorkItem: DispatchWorkItem?
@State private var isHoveringNewChat = false
@State private var isHoveringRecent = false
@State private var isHoveringClear = false
@@ -1447,8 +1467,12 @@ struct NotchCommandOutputExpandedView: View {
private var dynamicHeight: CGFloat {
let baseHeight: CGFloat = 120 // Minimum height
let contentHeight = self.estimateContentHeight()
+ // Reserve the caption's full height while recording so its wrapped lines
+ // cannot squeeze the header and follow-up input out of the window.
+ let captionHeight = self.contentState.isRecordingInExpandedMode && !self.contentState.cachedPreviewText.isEmpty
+ ? self.previewMaxHeight + 12 : 0
let maxHeight = (NSScreen.main?.frame.height ?? 800) * 0.45 // 45% of screen
- return min(max(baseHeight, contentHeight), maxHeight)
+ return min(max(baseHeight, contentHeight) + captionHeight, maxHeight)
}
private func estimateContentHeight() -> CGFloat {
@@ -1652,30 +1676,14 @@ struct NotchCommandOutputExpandedView: View {
if self.contentState.isRecordingInExpandedMode && !self.contentState.transcriptionText.isEmpty {
let previewText = self.contentState.cachedPreviewText
if !previewText.isEmpty {
- ScrollViewReader { proxy in
- ScrollView(.vertical, showsIndicators: false) {
- Text(previewText)
- .font(.fluidSystem(size: 11, weight: .medium))
- .foregroundStyle(.white.opacity(0.75))
- .multilineTextAlignment(.leading)
- .lineLimit(nil)
- .fixedSize(horizontal: false, vertical: true)
- .frame(maxWidth: .infinity, alignment: .leading)
- Color.clear.frame(height: 1).id("bottom")
- }
- .frame(maxWidth: .infinity, maxHeight: self.previewMaxHeight)
- .clipped()
- .onAppear {
- DispatchQueue.main.async {
- proxy.scrollTo("bottom", anchor: .bottom)
- }
- }
- .onChange(of: previewText) { _, _ in
- DispatchQueue.main.async {
- proxy.scrollTo("bottom", anchor: .bottom)
- }
- }
- }
+ OverlayCaptionView(
+ caption: self.contentState.captionPreview,
+ context: self.contentState.captionContext,
+ fontSize: 11,
+ maxHeight: self.previewMaxHeight,
+ opacity: 0.75
+ )
+ .frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 12)
.padding(.vertical, 6)
.background(self.commandRed.opacity(0.1))
@@ -1684,7 +1692,6 @@ struct NotchCommandOutputExpandedView: View {
}
}
.animation(.easeInOut(duration: 0.2), value: self.contentState.isRecordingInExpandedMode)
- .animation(.easeInOut(duration: 0.15), value: self.contentState.transcriptionText)
}
// MARK: - Conversation Area
@@ -1720,6 +1727,11 @@ struct NotchCommandOutputExpandedView: View {
// Always scroll to bottom when view appears
self.scrollToBottom(proxy, animated: false)
}
+ .onDisappear {
+ self.pendingScrollWorkItem?.cancel()
+ self.pendingScrollWorkItem = nil
+ self.scrollProxy = nil
+ }
.onChange(of: self.contentState.commandConversationHistory.count) { _, _ in
self.scrollToBottom(proxy, animated: true)
}
@@ -1735,7 +1747,10 @@ struct NotchCommandOutputExpandedView: View {
}
private func scrollToBottom(_ proxy: ScrollViewProxy, animated: Bool = true) {
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) {
+ guard self.pendingScrollWorkItem == nil else { return }
+ let work = DispatchWorkItem {
+ self.pendingScrollWorkItem = nil
+ guard self.scrollProxy != nil else { return }
if animated {
withAnimation(.easeOut(duration: 0.15)) {
proxy.scrollTo("bottom", anchor: .bottom)
@@ -1744,6 +1759,8 @@ struct NotchCommandOutputExpandedView: View {
proxy.scrollTo("bottom", anchor: .bottom)
}
}
+ self.pendingScrollWorkItem = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.05, execute: work)
}
// MARK: - Message Views
diff --git a/Tests/FluidDictationIntegrationTests/HoldToMutePresentationTests.swift b/Tests/FluidDictationIntegrationTests/HoldToMutePresentationTests.swift
index c8b1f943..2941c372 100644
--- a/Tests/FluidDictationIntegrationTests/HoldToMutePresentationTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HoldToMutePresentationTests.swift
@@ -13,16 +13,19 @@ final class HoldToMutePresentationTests: XCTestCase {
let priorText = state.transcriptionText
let priorProcessing = state.isProcessing
let priorMode = state.mode
+ let priorPresented = state.isBottomOverlayPresented
defer {
settings.overlaySize = priorSize
state.isDictationMuted = priorMuted
state.updateTranscription(priorText)
state.isProcessing = priorProcessing
state.mode = priorMode
+ state.setBottomOverlayPresented(priorPresented)
}
state.mode = .dictation
state.isProcessing = false
state.isDictationMuted = true
+ state.setBottomOverlayPresented(true)
state.updateTranscription("This is the thought I want to keep.")
for size in SettingsStore.OverlaySize.allCases {
diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
index cff3d7ae..41950f7b 100644
--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift
@@ -2674,6 +2674,9 @@ final class HotkeyShortcutTests: XCTestCase {
controller.show(audioPublisher: audioPublisher, mode: .dictation)
let emptySize = try XCTUnwrap(controller.windowSizeForTests)
+ // Captions now reserve their line slots. Use the large preset to leave a
+ // genuinely different old frame for the reopen path to discard.
+ SettingsStore.shared.overlaySize = .large
NotchContentState.shared.updateTranscription(String(repeating: "multiline preview text ", count: 30))
controller.refreshSizeForContent()
// SwiftUI layout can finish after 120 ms on a busy host; await the actual resize.
@@ -2684,6 +2687,7 @@ final class HotkeyShortcutTests: XCTestCase {
let expandedSize = try XCTUnwrap(controller.windowSizeForTests)
XCTAssertGreaterThan(expandedSize.height, emptySize.height)
+ SettingsStore.shared.overlaySize = .medium
_ = await controller.hideAndWait()
try await Task.sleep(nanoseconds: 100_000_000)
controller.show(audioPublisher: audioPublisher, mode: .dictation)
diff --git a/Tests/FluidDictationIntegrationTests/OverlayCaptionPresentationTests.swift b/Tests/FluidDictationIntegrationTests/OverlayCaptionPresentationTests.swift
new file mode 100644
index 00000000..0b5b56ef
--- /dev/null
+++ b/Tests/FluidDictationIntegrationTests/OverlayCaptionPresentationTests.swift
@@ -0,0 +1,608 @@
+import AppKit
+import Combine
+@testable import FluidVoice_Debug
+import SwiftUI
+import XCTest
+
+@MainActor
+final class OverlayCaptionPresentationTests: XCTestCase {
+ private func animationState(_ layer: CALayer?) -> String {
+ guard let layer else { return "no layer" }
+ return (layer.animationKeys() ?? []).map { key in
+ guard let animation = layer.animation(forKey: key) else { return key }
+ return "\(key): begin=\(animation.beginTime), duration=\(animation.duration), localNow=\(layer.convertTime(CACurrentMediaTime(), from: nil)), speed=\(layer.speed), removed=\(animation.isRemovedOnCompletion)"
+ }.joined(separator: "; ")
+ }
+
+ private func waitForAnimationRemoval(_ layer: CALayer?, key: String) async throws {
+ let layer = try XCTUnwrap(layer)
+ let deadline = CACurrentMediaTime() + 1
+ // The presentation can finish before Core Animation retires its client-side
+ // animation record. Check the visual deadline separately, then drain commits.
+ while layer.animation(forKey: key) != nil, CACurrentMediaTime() < deadline {
+ CATransaction.flush()
+ try await Task.sleep(for: .milliseconds(20))
+ }
+ XCTAssertNil(layer.animation(forKey: key), self.animationState(layer))
+ }
+
+ private func visibilityState(_ view: NSView) -> String {
+ "hidden=\(view.isHiddenOrHasHiddenAncestor), frame=\(view.frame), visible=\(view.window?.isVisible ?? false), alpha=\(view.window?.alphaValue ?? 0), " +
+ "occlusion=\(view.window?.occlusionState.rawValue ?? 0), reduceMotion=\(NSWorkspace.shared.accessibilityDisplayShouldReduceMotion)"
+ }
+
+ func testQueuedAppActivationDoesNotRestoreTheDismissedTarget() async {
+ let monitor = ActiveAppMonitor.shared
+ let state = NotchContentState.shared
+ let previousIcon = state.targetAppIcon
+ defer { monitor.stopMonitoring(); state.targetAppIcon = previousIcon }
+ monitor.startMonitoring()
+ NSWorkspace.shared.notificationCenter.post(name: NSWorkspace.didActivateApplicationNotification, object: nil)
+ monitor.stopMonitoring()
+ state.targetAppIcon = nil
+ await Task.yield()
+ await Task.yield()
+ XCTAssertNil(monitor.activeApp)
+ XCTAssertNil(monitor.activeAppIcon)
+ XCTAssertNil(state.targetAppIcon, "An already queued activation must not repopulate a dismissed overlay")
+ }
+
+ func testDismissCancelsACommandPanelThatHasNotOpenedYet() async throws {
+ let settings = SettingsStore.shared
+ let previousPosition = settings.overlayPosition
+ let previousMode = settings.notchPresentationMode
+ let manager = NotchOverlayManager.shared
+ defer {
+ manager.hideExpandedCommandOutput()
+ settings.overlayPosition = previousPosition
+ settings.notchPresentationMode = previousMode
+ }
+ settings.overlayPosition = .top
+ settings.notchPresentationMode = .standard
+ XCTAssertTrue(manager.canShowExpandedCommandOutput)
+ for _ in 0..<3 {
+ manager.showExpandedCommandOutput()
+ XCTAssertTrue(manager.hasCommandOutputToDismiss, "Escape and mode changes must recognize the pending panel")
+ manager.hideExpandedCommandOutput()
+ XCTAssertFalse(manager.hasCommandOutputToDismiss)
+ }
+ try await Task.sleep(for: .milliseconds(350))
+ XCTAssertFalse(manager.isCommandOutputExpanded, "A canceled delayed presentation must not reopen the command panel")
+ XCTAssertFalse(NotchContentState.shared.isExpandedForCommandOutput)
+ manager.showExpandedCommandOutput()
+ try await Task.sleep(for: .milliseconds(350))
+ XCTAssertTrue(manager.isCommandOutputExpanded, "Cancellation must not block a fresh presentation")
+ manager.hideExpandedCommandOutput()
+ try await Task.sleep(for: .milliseconds(350))
+ XCTAssertFalse(manager.isCommandOutputExpanded)
+ }
+
+ func testNewRecordingSupersedesPendingCommandOutput() async throws {
+ let settings = SettingsStore.shared
+ let previousPosition = settings.overlayPosition
+ let previousMode = settings.notchPresentationMode
+ let manager = NotchOverlayManager.shared
+ defer {
+ manager.hideImmediately()
+ manager.hideExpandedCommandOutput()
+ settings.overlayPosition = previousPosition
+ settings.notchPresentationMode = previousMode
+ }
+ settings.overlayPosition = .bottom
+ settings.notchPresentationMode = .standard
+ manager.showExpandedCommandOutput()
+ manager.show(audioLevelPublisher: Just(CGFloat.zero).eraseToAnyPublisher(), mode: .dictation)
+ manager.updateTranscriptionText("The new dictation owns the preview")
+ try await Task.sleep(for: .milliseconds(350))
+ XCTAssertFalse(manager.isCommandOutputExpanded)
+ XCTAssertFalse(manager.hasCommandOutputToDismiss)
+ XCTAssertTrue(manager.isBottomOverlayVisible)
+ XCTAssertEqual(NotchContentState.shared.mode, .dictation)
+ XCTAssertEqual(NotchContentState.shared.transcriptionText, "The new dictation owns the preview")
+ manager.hideImmediately()
+ try await Task.sleep(for: .milliseconds(150))
+ }
+
+ func testManagerHideStopsHiddenUpdatesAndDoesNotResizeTheParkedPanel() async throws {
+ let settings = SettingsStore.shared
+ let state = NotchContentState.shared
+ let previousPosition = settings.overlayPosition
+ let previousSize = settings.overlaySize
+ let previousPreview = settings.enableStreamingPreview
+ let manager = NotchOverlayManager.shared
+ let controller = BottomOverlayWindowController.shared
+ let levels = PassthroughSubject<CGFloat, Never>()
+ defer {
+ manager.hideImmediately()
+ settings.overlayPosition = previousPosition
+ settings.overlaySize = previousSize
+ settings.enableStreamingPreview = previousPreview
+ }
+ settings.overlayPosition = .bottom
+ settings.overlaySize = .medium
+ settings.enableStreamingPreview = true
+ manager.show(audioLevelPublisher: levels.eraseToAnyPublisher(), mode: .dictation)
+ manager.updateTranscriptionText("These pending words must stop when the whole dictation overlay has finished its work.")
+ manager.setProcessing(true)
+ try await Task.sleep(for: .milliseconds(40))
+ manager.hideImmediately()
+ XCTAssertTrue(controller.isVisuallyHiddenForTests)
+ try await Task.sleep(for: .milliseconds(300))
+ XCTAssertFalse(state.isBottomOverlayPresented, "The manager must preserve bottom-panel cleanup")
+ XCTAssertFalse(state.isProcessing)
+ XCTAssertFalse(state.isBottomOverlayDismissing)
+ XCTAssertFalse(state.isBottomOverlayReleaseTransitioning)
+ let panel = try XCTUnwrap(controller.contentViewForTests?.window)
+ let anchor = CGRect(x: panel.frame.minX + 10, y: panel.frame.minY + 10, width: 80, height: 24)
+ let visibleWindows = Set(NSApp.windows.filter { $0.isVisible && $0.alphaValue > 0 }.map(\.windowNumber))
+ BottomOverlayPromptMenuController.shared.updateAnchor(selectorFrameInScreen: anchor, parentWindow: panel, maxWidth: 220, menuGap: 6)
+ BottomOverlayModeMenuController.shared.updateAnchor(selectorFrameInScreen: anchor, parentWindow: panel, maxWidth: 220, menuGap: 6)
+ BottomOverlayActionsMenuController.shared.updateAnchor(selectorFrameInScreen: anchor, parentWindow: panel, maxWidth: 220, menuGap: 6)
+ BottomOverlayPromptMenuController.shared.toggleFromTap()
+ BottomOverlayModeMenuController.shared.toggleFromTap()
+ BottomOverlayActionsMenuController.shared.toggleFromTap()
+ XCTAssertEqual(Set(NSApp.windows.filter { $0.isVisible && $0.alphaValue > 0 }.map(\.windowNumber)), visibleWindows, "A late menu action must not reopen controls from a hidden overlay")
+ let parkedSize = controller.windowSizeForTests
+ levels.send(0.9)
+ settings.overlaySize = .large
+ controller.refreshSizeForContent()
+ try await Task.sleep(for: .milliseconds(300))
+ XCTAssertEqual(OverlayAudioLevelState.shared.level, 0, "Hidden panels must unsubscribe from audio levels")
+ XCTAssertEqual(controller.windowSizeForTests, parkedSize, "Settings and stale resize requests must not lay out a hidden panel")
+ manager.show(audioLevelPublisher: levels.eraseToAnyPublisher(), mode: .dictation)
+ manager.hideImmediately()
+ manager.show(audioLevelPublisher: levels.eraseToAnyPublisher(), mode: .dictation)
+ manager.updateTranscriptionText("Only the new recording may remain visible")
+ try await Task.sleep(for: .milliseconds(500))
+ XCTAssertTrue(state.isBottomOverlayPresented)
+ XCTAssertFalse(controller.isVisuallyHiddenForTests)
+ XCTAssertEqual(state.transcriptionText, "Only the new recording may remain visible")
+ manager.hideImmediately()
+ try await Task.sleep(for: .milliseconds(200))
+ }
+
+ func testProcessingShimmerStopsAcrossEveryBottomSize() async throws {
+ let settings = SettingsStore.shared
+ let state = NotchContentState.shared
+ let previousPosition = settings.overlayPosition
+ let previousSize = settings.overlaySize
+ let previousProcessing = state.isProcessing
+ let controller = BottomOverlayWindowController.shared
+ let manager = NotchOverlayManager.shared
+ defer {
+ manager.hideImmediately()
+ settings.overlayPosition = previousPosition
+ settings.overlaySize = previousSize
+ state.isProcessing = previousProcessing
+ }
+ settings.overlayPosition = .bottom
+ func shimmers(in view: NSView) -> [CompositorShimmerSweepView] {
+ (view as? CompositorShimmerSweepView).map { [$0] } ?? view.subviews.flatMap { shimmers(in: $0) }
+ }
+ for size in [SettingsStore.OverlaySize.pill, .small, .medium, .large] {
+ settings.overlaySize = size
+ // Use the recording entry point so a previous manager hide cannot
+ // clear this presentation after its transaction finishes.
+ manager.show(audioLevelPublisher: Just(CGFloat.zero).eraseToAnyPublisher(), mode: .dictation)
+ controller.setProcessing(true)
+ try await Task.sleep(for: .milliseconds(180))
+ let host = try XCTUnwrap(controller.contentViewForTests)
+ XCTAssertEqual(host.frame.size, host.superview?.bounds.size, "Hosting content must fit its window after every preset change")
+ if size == .pill {
+ let container = try XCTUnwrap(host.window?.contentView)
+ XCTAssertNil(container.hitTest(NSPoint(x: 1, y: 1)), "Transparent padding must not intercept clicks")
+ XCTAssertNotNil(container.hitTest(NSPoint(x: container.bounds.midX, y: container.bounds.midY)), "Visible pill controls must remain clickable")
+ }
+ let waitingViews = shimmers(in: host)
+ XCTAssertFalse(waitingViews.isEmpty, "Exercise the real waiting view for \(size): \(self.visibilityState(host)), processing=\(state.isProcessing), muted=\(state.isDictationMuted)")
+ let visibility = waitingViews.map { self.visibilityState($0) }.joined(separator: "; ")
+ let hasAnimation = waitingViews.contains { $0.layer?.sublayers?.first?.animation(forKey: "fluid.shimmer.locations") != nil }
+ XCTAssertEqual(hasAnimation, !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion, "Processing must respect Reduce Motion for \(size): \(visibility)")
+ XCTAssertTrue(state.isProcessing, "A previous presentation must not clear this processing state")
+ if let output = ProcessInfo.processInfo.environment["CAPTION_TEST_OUTPUT"] {
+ let bitmap = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds))
+ host.cacheDisplay(in: host.bounds, to: bitmap)
+ let png = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
+ try png.write(to: URL(fileURLWithPath: output).appendingPathComponent("processing-\(size.rawValue).png"))
+ }
+ manager.hideImmediately()
+ try await Task.sleep(for: .milliseconds(300))
+ XCTAssertFalse(state.isBottomOverlayPresented)
+ XCTAssertTrue(waitingViews.allSatisfy { $0.layer?.sublayers?.first?.animationKeys()?.isEmpty != false }, "No waiting shimmer may survive dismissal for \(size)")
+ }
+ }
+
+ func testWaitingShimmerStopsWhenItsViewOrWindowIsHidden() async throws {
+ let view = CompositorShimmerSweepView(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
+ let window = NSWindow(contentRect: view.frame, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.animationBehavior = .none
+ window.contentView = view
+ window.orderFrontRegardless()
+ defer { window.orderOut(nil); window.contentView = nil; window.close() }
+ try await Task.sleep(for: .milliseconds(50))
+ let gradient = try XCTUnwrap(view.layer?.sublayers?.first)
+ XCTAssertNotNil(gradient.animation(forKey: "fluid.shimmer.locations"))
+ window.alphaValue = 0
+ XCTAssertNil(gradient.animation(forKey: "fluid.shimmer.locations"), "A cached alpha-zero panel must stop immediately")
+ window.alphaValue = 1
+ XCTAssertNotNil(gradient.animation(forKey: "fluid.shimmer.locations"))
+ view.isHidden = true
+ XCTAssertNil(gradient.animation(forKey: "fluid.shimmer.locations"), "A retained hidden view must stop its infinite shimmer")
+ view.isHidden = false
+ XCTAssertNotNil(gradient.animation(forKey: "fluid.shimmer.locations"))
+ window.orderOut(nil)
+ XCTAssertNil(gradient.animation(forKey: "fluid.shimmer.locations"), "Ordering out a retained window must stop the shimmer")
+ window.orderFrontRegardless()
+ try await Task.sleep(for: .milliseconds(100))
+ XCTAssertNotNil(gradient.animation(forKey: "fluid.shimmer.locations"))
+ view.configure(duration: 1, peakOpacity: 0.88, isActive: false)
+ XCTAssertNil(gradient.animation(forKey: "fluid.shimmer.locations"), "Inactive and Reduce Motion presentations must remain static")
+ view.configure(duration: 1, peakOpacity: 0.88, isActive: true)
+ XCTAssertNotNil(gradient.animation(forKey: "fluid.shimmer.locations"))
+ window.contentView = nil
+ XCTAssertNil(gradient.animation(forKey: "fluid.shimmer.locations"))
+ }
+
+ func testRetainedVisibleLineUpdatesWhenTheShortPreviewIsUnchanged() async throws {
+ let view = OverlayCaptionNSView(frame: CGRect(x: 0, y: 0, width: 304, height: 54))
+ let window = NSWindow(contentRect: view.frame, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = view
+ window.orderFront(nil)
+ defer { view.stopScrolling(); window.orderOut(nil); window.contentView = nil; window.close() }
+ func drawnLines(_ text: String) async throws -> [Data] {
+ view.update(caption: .tail(text, limit: 50), context: .tail(text, limit: 800), fontSize: 13, opacity: 1, reduceMotion: true)
+ view.layoutSubtreeIfNeeded()
+ try await Task.sleep(for: .milliseconds(50))
+ let bitmap = try XCTUnwrap(NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: 304,
+ pixelsHigh: 54,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ ))
+ let graphics = try XCTUnwrap(NSGraphicsContext(bitmapImageRep: bitmap))
+ try XCTUnwrap(view.layer?.presentation()).render(in: graphics.cgContext)
+ let pixels = try XCTUnwrap(bitmap.bitmapData)
+ return (0..<3).map { line in
+ Data(bytes: pixels.advanced(by: line * 18 * bitmap.bytesPerRow), count: 18 * bitmap.bytesPerRow)
+ }
+ }
+ let original = "The old word sits on line one.\nThe second line is unchanged.\nThe last line is unchanged."
+ let corrected = original.replacingOccurrences(of: "old", with: "new")
+ XCTAssertEqual(OverlayCaptionText.tail(original, limit: 50), .tail(corrected, limit: 50))
+ let before = try await drawnLines(original)
+ let after = try await drawnLines(corrected)
+ XCTAssertEqual(zip(before, after).filter { $0 != $1 }.count, 1, "Redraw the corrected visible line while preserving both unchanged lines")
+ XCTAssertEqual(view.accessibilityValue() as? String, OverlayCaptionText.tail(corrected, limit: 50).text)
+ XCTAssertEqual(view.layer?.sublayerTransform.m42, 0)
+ XCTAssertTrue(view.layer?.animationKeys()?.isEmpty ?? true, self.animationState(view.layer))
+ }
+
+ func testWordsAppearInStepsWithACompositorFade() async throws {
+ let view = OverlayCaptionNSView(frame: CGRect(x: 0, y: 0, width: 304, height: 54))
+ let window = NSWindow(contentRect: view.frame, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = view
+ window.orderFront(nil)
+ defer { view.stopScrolling(); window.orderOut(nil); window.contentView = nil; window.close() }
+ let phrase = "Words gently flow into place instead of arriving as a whole pasted chunk."
+ view.update(caption: .tail(phrase, limit: 100), fontSize: 13, opacity: 1, reduceMotion: false)
+ view.layoutSubtreeIfNeeded()
+ let initial = try XCTUnwrap(view.accessibilityValue() as? String)
+ XCTAssertFalse(initial.isEmpty)
+ XCTAssertTrue(phrase.hasPrefix(initial))
+ XCTAssertNotEqual(initial, phrase)
+ let fade = try XCTUnwrap(view.layer?.sublayers?.last)
+ XCTAssertEqual(try XCTUnwrap(fade.animation(forKey: "captionReveal")).duration, OverlayCaptionNSView.revealDuration)
+ try await Task.sleep(for: .milliseconds(35))
+ let opacity = try XCTUnwrap(fade.presentation()).opacity
+ XCTAssertGreaterThan(opacity, 0)
+ XCTAssertLessThan(opacity, 1, "New words must actually fade, not just change the text snapshot")
+ try await Task.sleep(for: .milliseconds(75))
+ let intermediate = try XCTUnwrap(view.accessibilityValue() as? String)
+ XCTAssertGreaterThan(intermediate.count, initial.count)
+ XCTAssertLessThan(intermediate.count, phrase.count)
+ try await Task.sleep(for: .milliseconds(480))
+ XCTAssertEqual(view.accessibilityValue() as? String, phrase)
+ XCTAssertEqual(try XCTUnwrap(fade.presentation()).opacity, 1, accuracy: 0.01)
+ try await self.waitForAnimationRemoval(fade, key: "captionReveal")
+ let bitmap = try XCTUnwrap(NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: 304,
+ pixelsHigh: 54,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ ))
+ let graphics = try XCTUnwrap(NSGraphicsContext(bitmapImageRep: bitmap))
+ try XCTUnwrap(view.layer?.presentation()).render(in: graphics.cgContext)
+ let ink = (0..<54).reduce(0) { count, y in
+ count + (0..<304).filter { (bitmap.colorAt(x: $0, y: y)?.alphaComponent ?? 0) > 0.1 }.count
+ }
+ XCTAssertGreaterThan(ink, 400, "Both the settled prefix and the final faded word must remain drawn")
+ if let output = ProcessInfo.processInfo.environment["CAPTION_TEST_OUTPUT"] {
+ let png = try XCTUnwrap(bitmap.representation(using: .png, properties: [:]))
+ try png.write(to: URL(fileURLWithPath: output).appendingPathComponent("word-reveal-settled.png"))
+ }
+ }
+
+ func testBufferedRevisionKeepsThreeDrawnLinesAndCancelsOnClear() async throws {
+ let view = OverlayCaptionNSView(frame: CGRect(x: 0, y: 0, width: 304, height: 54))
+ let window = NSWindow(contentRect: view.frame, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = view
+ window.orderFront(nil)
+ defer { view.stopScrolling(); window.orderOut(nil); window.contentView = nil; window.close() }
+ func update(_ text: String) {
+ view.update(caption: .tail(text, limit: 50), context: .tail(text, limit: 800), fontSize: 13, opacity: 1, reduceMotion: false)
+ }
+ let original = "Earlier complete lines stay readable. The latest words may be corrected as the recognizer hears more speech."
+ update(original)
+ view.flushPendingCaption()
+ view.layoutSubtreeIfNeeded()
+ let revision = original + " A much larger chunk arrives together with enough new words to replace the entire short preview."
+ update(revision + " provisional")
+ update(revision)
+ XCTAssertNotEqual(view.accessibilityValue() as? String, OverlayCaptionText.tail(revision, limit: 50).text)
+ try await Task.sleep(for: .milliseconds(500))
+ XCTAssertEqual(view.accessibilityValue() as? String, OverlayCaptionText.tail(revision, limit: 50).text)
+ view.layoutSubtreeIfNeeded()
+ try await Task.sleep(for: .milliseconds(220))
+ let bitmap = try XCTUnwrap(NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: 304,
+ pixelsHigh: 54,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ ))
+ let graphics = try XCTUnwrap(NSGraphicsContext(bitmapImageRep: bitmap))
+ try XCTUnwrap(view.layer?.presentation()).render(in: graphics.cgContext)
+ for line in 0..<3 {
+ let ink = (line * 18..<(line + 1) * 18).reduce(0) { count, y in
+ count + (0..<304).filter { (bitmap.colorAt(x: $0, y: y)?.alphaComponent ?? 0) > 0.1 }.count
+ }
+ XCTAssertGreaterThan(ink, 40, "A large revision must preserve all three drawn lines")
+ }
+ update(revision + " first")
+ update(revision + " stale pending result")
+ update("")
+ update("New recording")
+ try await Task.sleep(for: .milliseconds(140))
+ XCTAssertEqual(view.accessibilityValue() as? String, "New recording")
+ XCTAssertEqual(view.layer?.sublayerTransform.m42, 0)
+ }
+
+ func testVisibleLinesSurviveTrimmingAndScrollingFinishesOnTime() async throws {
+ let view = OverlayCaptionNSView(frame: CGRect(x: 0, y: 0, width: 304, height: 54))
+ let window = NSWindow(contentRect: view.frame, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = view
+ window.orderFront(nil)
+ defer { window.orderOut(nil); window.contentView = nil; window.close() }
+ func update(_ text: String, reduceMotion: Bool = false) {
+ view.update(caption: .tail(text, limit: 50), fontSize: 13, opacity: 1, reduceMotion: reduceMotion)
+ view.flushPendingCaption()
+ view.layoutSubtreeIfNeeded()
+ }
+ var text = ""
+ for word in String(repeating: "Every visible line stays readable as the preview limit advances through the sentence. ", count: 5).split(separator: " ") {
+ text += "\(word) "
+ update(text, reduceMotion: true)
+ }
+ try await Task.sleep(for: .milliseconds(50))
+ let bitmap = try XCTUnwrap(NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: 304,
+ pixelsHigh: 54,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ ))
+ let context = try XCTUnwrap(NSGraphicsContext(bitmapImageRep: bitmap))
+ try XCTUnwrap(view.layer?.presentation()).render(in: context.cgContext)
+ for line in 0..<3 {
+ let ink = (line * 18..<(line + 1) * 18).reduce(0) { count, y in
+ count + (0..<304).filter { (bitmap.colorAt(x: $0, y: y)?.alphaComponent ?? 0) > 0.1 }.count
+ }
+ XCTAssertGreaterThan(ink, 40, "Trimming must keep all three visible lines drawn")
+ }
+ update("")
+ let prefix = "First sentence.\nSecond sentence.\nThird sentence."
+ update(prefix)
+ try await Task.sleep(for: .milliseconds(50))
+ update(prefix + "\nNext")
+ let begin = try XCTUnwrap(view.layer?.animation(forKey: "captionScroll")).beginTime
+ try await Task.sleep(for: .milliseconds(60))
+ update(prefix + "\nNext word at a time")
+ XCTAssertEqual(try XCTUnwrap(view.layer?.animation(forKey: "captionScroll")).beginTime, begin)
+ try await Task.sleep(for: .milliseconds(160))
+ XCTAssertEqual(
+ try XCTUnwrap(view.layer?.presentation()).sublayerTransform.m42,
+ try XCTUnwrap(view.layer).sublayerTransform.m42,
+ accuracy: 0.5
+ )
+ try await self.waitForAnimationRemoval(view.layer, key: "captionScroll")
+ }
+
+ func testScrollInterpolatesThenStopsAndHonorsReduceMotion() async throws {
+ let view = OverlayCaptionNSView(frame: CGRect(x: 0, y: 0, width: 180, height: 32))
+ let window = NSWindow(contentRect: view.frame, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = view
+ window.orderFront(nil)
+ defer { window.orderOut(nil); window.contentView = nil; window.close() }
+ func update(_ text: String, reduceMotion: Bool = false) {
+ view.update(caption: .tail(text, limit: 100), fontSize: 13, opacity: 1, reduceMotion: reduceMotion)
+ view.flushPendingCaption()
+ view.layoutSubtreeIfNeeded()
+ }
+ update("First line\nSecond line")
+ try await Task.sleep(for: .milliseconds(50))
+ let start = try XCTUnwrap(view.layer).sublayerTransform.m42
+ update("First line\nSecond line\nThird")
+ let target = try XCTUnwrap(view.layer).sublayerTransform.m42
+ try await Task.sleep(for: .milliseconds(60))
+ let intermediate = try XCTUnwrap(view.layer?.presentation()).sublayerTransform.m42
+ XCTAssertLessThan(intermediate, start)
+ XCTAssertGreaterThan(intermediate, target)
+ update("First line\nSecond line\nThird word")
+ XCTAssertEqual(view.layer?.sublayerTransform.m42, target)
+ try await Task.sleep(for: .milliseconds(300))
+ XCTAssertEqual(try XCTUnwrap(view.layer?.presentation()).sublayerTransform.m42, target, accuracy: 0.5)
+ try await self.waitForAnimationRemoval(view.layer, key: "captionScroll")
+ update("First line\nSecond line\nThird word\nFourth", reduceMotion: true)
+ XCTAssertTrue(view.layer?.animationKeys()?.isEmpty ?? true, self.animationState(view.layer))
+ view.frame.size.height = 16
+ update("First line\nSecond line\nThird word\nFourth\nFifth\nLatest caption", reduceMotion: true)
+ try await Task.sleep(for: .milliseconds(50))
+ let bitmap = try XCTUnwrap(NSBitmapImageRep(
+ bitmapDataPlanes: nil,
+ pixelsWide: 180,
+ pixelsHigh: 16,
+ bitsPerSample: 8,
+ samplesPerPixel: 4,
+ hasAlpha: true,
+ isPlanar: false,
+ colorSpaceName: .deviceRGB,
+ bytesPerRow: 0,
+ bitsPerPixel: 0
+ ))
+ let context = try XCTUnwrap(NSGraphicsContext(bitmapImageRep: bitmap))
+ // Read the compositor's already-rendered contents; forcing NSView.draw here would
+ // hide the regression where AppKit culled the offscreen lines before scrolling.
+ try XCTUnwrap(view.layer?.presentation()).render(in: context.cgContext)
+ let inkPixels = (0..<16).reduce(0) { count, y in
+ count + (0..<180).filter { (bitmap.colorAt(x: $0, y: y)?.alphaComponent ?? 0) > 0.1 }.count
+ }
+ XCTAssertGreaterThan(inkPixels, 40, "The latest line must remain drawn after older lines scroll out")
+ update("")
+ XCTAssertEqual(view.layer?.sublayerTransform.m42, 0)
+ }
+
+ func testWindowAndControlsStayStillThroughWrappingAndCorrections() async throws {
+ let settings = SettingsStore.shared
+ let state = NotchContentState.shared
+ let previousSize = settings.overlaySize
+ let previousPreview = settings.enableStreamingPreview
+ let previousText = state.transcriptionText
+ let controller = BottomOverlayWindowController.shared
+ defer {
+ controller.hideImmediately()
+ settings.overlaySize = previousSize
+ settings.enableStreamingPreview = previousPreview
+ state.updateTranscription(previousText)
+ }
+ settings.overlaySize = .medium
+ settings.enableStreamingPreview = true
+ state.updateTranscription("")
+ controller.show(audioPublisher: Just(CGFloat.zero).eraseToAnyPublisher(), mode: .dictation)
+ try await Task.sleep(for: .milliseconds(350))
+ let initial = try XCTUnwrap(controller.windowSizeForTests)
+ XCTAssertEqual(initial.height, 114, accuracy: 1, "Keep all three caption lines while removing excess outer padding")
+ for text in ["Short", String(repeating: "W", count: 34), String(repeating: "A full caption with three visible lines. ", count: 6), "A short correction", ""] {
+ state.updateTranscription(text)
+ try await Task.sleep(for: .milliseconds(200))
+ XCTAssertEqual(try XCTUnwrap(controller.windowSizeForTests), initial, "Text updates must not resize the overlay")
+ }
+ }
+
+ func testHiddenBottomOverlayStopsPendingWordsWithoutClearingTheTranscript() async throws {
+ let settings = SettingsStore.shared
+ let state = NotchContentState.shared
+ let previousSize = settings.overlaySize
+ let previousPreview = settings.enableStreamingPreview
+ let previousText = state.transcriptionText
+ let previousProcessing = state.isProcessing
+ let controller = BottomOverlayWindowController.shared
+ defer {
+ controller.hideImmediately()
+ settings.overlaySize = previousSize
+ settings.enableStreamingPreview = previousPreview
+ state.updateTranscription(previousText)
+ state.isProcessing = previousProcessing
+ }
+ func caption(in view: NSView) -> OverlayCaptionNSView? {
+ if let caption = view as? OverlayCaptionNSView { return caption }
+ return view.subviews.lazy.compactMap { caption(in: $0) }.first
+ }
+ settings.overlaySize = .medium
+ settings.enableStreamingPreview = true
+ state.isProcessing = false
+ controller.show(audioPublisher: Just(CGFloat.zero).eraseToAnyPublisher(), mode: .dictation)
+ let text = "The hidden preview must stop revealing this long sentence while preserving the transcript for the next action."
+ state.updateTranscription(text)
+ try await Task.sleep(for: .milliseconds(35))
+ let host = try XCTUnwrap(controller.contentViewForTests)
+ let view = try XCTUnwrap(caption(in: host))
+ if NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {
+ XCTAssertEqual(view.accessibilityValue() as? String, state.cachedPreviewText, "Reduce Motion presents all words immediately")
+ } else {
+ XCTAssertNotEqual(view.accessibilityValue() as? String, state.cachedPreviewText, self.visibilityState(view))
+ }
+ controller.hideImmediately()
+ for _ in 0..<30 where state.isBottomOverlayPresented {
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ XCTAssertFalse(state.isBottomOverlayPresented)
+ host.layoutSubtreeIfNeeded()
+ let hiddenValue = view.accessibilityValue() as? String
+ try await Task.sleep(for: .milliseconds(500))
+ XCTAssertEqual(view.accessibilityValue() as? String, hiddenValue)
+ XCTAssertEqual(state.transcriptionText, text)
+ XCTAssertTrue(view.layer?.sublayers?.allSatisfy { $0.animationKeys()?.isEmpty != false } == true)
+ controller.show(audioPublisher: Just(CGFloat.zero).eraseToAnyPublisher(), mode: .dictation)
+ state.updateTranscription("Fresh words after reopening")
+ try await Task.sleep(for: .milliseconds(500))
+ XCTAssertEqual(try XCTUnwrap(caption(in: host)).accessibilityValue() as? String, "Fresh words after reopening")
+ }
+
+ func testPreviewTracksItsPositionWithoutChangingRecordingState() {
+ let state = NotchContentState.shared
+ let settings = SettingsStore.shared
+ let previousLimit = settings.transcriptionPreviewCharLimit
+ let previousText = state.transcriptionText
+ let mode = state.mode
+ let processing = state.isProcessing
+ let muted = state.isDictationMuted
+ let target = state.recordingTargetPID
+ let commandOutput = state.commandOutput
+ defer {
+ settings.transcriptionPreviewCharLimit = previousLimit
+ state.updateTranscription(previousText)
+ }
+ settings.transcriptionPreviewCharLimit = 100
+ let source = String(repeating: "Captions stay readable while the user keeps speaking. 👩🏽‍💻 ", count: 100)
+ state.updateTranscription(source)
+ XCTAssertEqual(state.captionPreview, OverlayCaptionText.tail(source, limit: 100))
+ XCTAssertEqual(state.transcriptionText.count, 800)
+ state.updateTranscription(source + "New words")
+ XCTAssertEqual(state.captionPreview, OverlayCaptionText.tail(source + "New words", limit: 100))
+ state.updateTranscription("")
+ XCTAssertEqual(state.captionPreview, .empty)
+ XCTAssertEqual(state.mode, mode)
+ XCTAssertEqual(state.isProcessing, processing)
+ XCTAssertEqual(state.isDictationMuted, muted)
+ XCTAssertEqual(state.recordingTargetPID, target)
+ XCTAssertEqual(state.commandOutput, commandOutput)
+ }
+}
diff --git a/Tests/OverlayCaptionTests.swift b/Tests/OverlayCaptionTests.swift
new file mode 100644
index 00000000..51f0b492
--- /dev/null
+++ b/Tests/OverlayCaptionTests.swift
@@ -0,0 +1,364 @@
+import AppKit
+import QuartzCore
+import SwiftUI
+
+@main
+struct OverlayCaptionTests {
+ @MainActor
+ static func main() async throws {
+ _ = NSApplication.shared
+ self.testBoundedUnicodePreview()
+ self.testStableWrapping()
+ self.testCorrectionsAndReset()
+ self.testHiddenBufferIsBounded()
+ self.testRecoveryAfterRevisionsAndLargeChunks()
+ self.testRetainedContextCorrectionWithUnchangedPreview()
+ self.testWordRevealDeadlinesAndUnicode()
+ try await self.testDisplayBufferDeadlinesAndCancellation()
+ try await self.testStoppedCaptionCannotRestartFromLayoutOrDetachment()
+ try await self.testReopenedCaptionStartsAnewWithoutAnIntermediateEmptyUpdate()
+ self.testScrollingAndReducedMotion()
+ self.testPreviewLimitKeepsAFullViewport()
+ self.testTrimmingDoesNotRestartTheSameLineScroll()
+ try self.testSizingAndRendering()
+ print("PASS: paced word reveal, deadlines, revisions, Unicode, cancellation, fixed viewport, bounded context, wrapping, scrolling and Reduce Motion")
+ }
+
+ static func testBoundedUnicodePreview() {
+ let source = String(repeating: "字幕 👩🏽‍💻 cafe\u{301} ", count: 100)
+ let preview = OverlayCaptionText.tail(source, limit: 50)
+ precondition(preview.text.count == 50)
+ precondition(preview.sourceOffset + preview.text.utf16.count == source.utf16.count)
+ let stored = OverlayCaptionText.tail(source, limit: 800)
+ precondition(OverlayCaptionText.tail(stored.text, limit: 50, sourceOffset: stored.sourceOffset) == preview)
+ precondition(OverlayCaptionText.tail(source, limit: 0) == .empty)
+ }
+
+ static func testStableWrapping() {
+ var buffer = OverlayCaptionBuffer()
+ var text = ""
+ let words = "These captions keep their wrapped lines still while more words arrive at the end of the sentence. "
+ for character in String(repeating: words, count: 8) {
+ text.append(character)
+ _ = buffer.update(.tail(text, limit: 100))
+ let layout = OverlayCaptionLayout(text: buffer.text, width: 180, fontSize: 13, opacity: 1)
+ let full = OverlayCaptionLayout(text: text, width: 180, fontSize: 13, opacity: 1)
+ let actual = layout.lines.map { $0.characters.location + buffer.sourceOffset }
+ let expected = full.lines.map(\.characters.location).filter { $0 >= buffer.sourceOffset }
+ precondition(actual == expected, "Trimming the character limit changed the wrapped line starts")
+ let visibleOffset = buffer.preview.sourceOffset - buffer.sourceOffset
+ if let line = layout.lines.first(where: { $0.characters.upperBound > visibleOffset }) {
+ buffer.removeHiddenPrefix(utf16Count: line.characters.location)
+ }
+ precondition(buffer.text.count <= 150)
+ }
+ }
+
+ static func testCorrectionsAndReset() {
+ var buffer = OverlayCaptionBuffer()
+ _ = buffer.update(.tail("Keep the beginning and correct the last world", limit: 100))
+ precondition(buffer.update(.tail("Keep the beginning and correct the last word", limit: 100)))
+ precondition(buffer.text.hasSuffix("last word"))
+ precondition(!buffer.update(.tail("A completely different result", limit: 100)))
+ precondition(buffer.text == "A completely different result")
+ precondition(!buffer.update(.empty))
+ precondition(buffer.text.isEmpty && buffer.sourceOffset == 0)
+ _ = buffer.update(.tail("New recording", limit: 100))
+ precondition(buffer.text == "New recording")
+ }
+
+ static func testHiddenBufferIsBounded() {
+ var buffer = OverlayCaptionBuffer()
+ for count in stride(from: 100, through: 20_000, by: 20) {
+ _ = buffer.update(.tail(String(repeating: "a", count: count), limit: 100))
+ precondition(buffer.text.utf16.count <= 4196)
+ }
+ }
+
+ static func testRecoveryAfterRevisionsAndLargeChunks() {
+ var buffer = OverlayCaptionBuffer()
+ let first = "The first complete sentence stays in place. We can still correct the latest word."
+ let next = first + " A large result arrives all at once and contains more than fifty new characters."
+ _ = buffer.update(.tail(first, limit: 50), context: .tail(first, limit: 800))
+ precondition(buffer.update(.tail(next, limit: 50), context: .tail(next, limit: 800)))
+ precondition(buffer.text == next, "A large chunk must keep earlier visible lines")
+ let revision = next.replacingOccurrences(of: "result arrives", with: "revision arrived")
+ precondition(buffer.update(.tail(revision, limit: 50), context: .tail(revision, limit: 800)))
+ precondition(buffer.text == revision, "Revisions need the source context, not a freshly wrapped short tail")
+ precondition(OverlayCaptionLayout(text: buffer.text, width: 304, fontSize: 13, opacity: 1).lines.count >= 3)
+ let unrelated = String(repeating: "An entirely different revised sentence with enough context to fill the preview. ", count: 20)
+ precondition(!buffer.update(.tail(unrelated, limit: 50), context: .tail(unrelated, limit: 800)))
+ precondition(buffer.text.count <= 800)
+ _ = buffer.update(.empty, context: .empty)
+ precondition(buffer.text.isEmpty && buffer.sourceOffset == 0)
+ }
+
+ static func testRetainedContextCorrectionWithUnchangedPreview() {
+ var buffer = OverlayCaptionBuffer()
+ let hidden = String(repeating: "Earlier hidden context. ", count: 40)
+ let visible = "The old word sits on line one.\nThe second line is unchanged.\nThe last line is unchanged."
+ let original = hidden + visible
+ let corrected = hidden + visible.replacingOccurrences(of: "old", with: "new")
+ let preview = OverlayCaptionText.tail(original, limit: 50)
+ precondition(preview == .tail(corrected, limit: 50))
+ _ = buffer.update(preview, context: .tail(original, limit: 800))
+ buffer.removeHiddenPrefix(utf16Count: hidden.utf16.count - buffer.sourceOffset)
+ let retainedOffset = buffer.sourceOffset
+ precondition(buffer.update(preview, context: .tail(corrected, limit: 800)))
+ precondition(buffer.text == visible.replacingOccurrences(of: "old", with: "new"), "A correction before an unchanged preview must update retained visible lines")
+ precondition(buffer.sourceOffset == retainedOffset && buffer.preview == preview)
+ let hiddenCorrection = corrected.replacingOccurrences(of: "Earlier", with: "Another")
+ precondition(buffer.update(preview, context: .tail(hiddenCorrection, limit: 800)))
+ precondition(buffer.text == visible.replacingOccurrences(of: "old", with: "new"))
+ precondition(buffer.sourceOffset == retainedOffset && buffer.preview == preview)
+ }
+
+ static func testWordRevealDeadlinesAndUnicode() {
+ var reveal = OverlayCaptionReveal()
+ let text = "These words arrive gradually instead of appearing together as one pasted chunk."
+ reveal.update(.tail(text, limit: 800), now: 0)
+ reveal.advance(now: 0)
+ precondition(!reveal.displayed.text.isEmpty && reveal.displayed.text != text)
+ var previous = reveal.displayed.text
+ for tick in 1...6 {
+ reveal.advance(now: Double(tick) * OverlayCaptionReveal.interval)
+ precondition(reveal.displayed.text.hasPrefix(previous))
+ previous = reveal.displayed.text
+ }
+ precondition(reveal.displayed.text == text && !reveal.hasPendingWords)
+ for source in ["字幕会慢慢出现。接下来是更多文字。", "👩🏽‍💻 café e\u{301} مرحبا more words", String(repeating: "word ", count: 150)] {
+ reveal = OverlayCaptionReveal()
+ reveal.update(.tail(source, limit: 800), now: 0)
+ for tick in 0...6 {
+ reveal.advance(now: Double(tick) * OverlayCaptionReveal.interval)
+ precondition(source.hasPrefix(reveal.displayed.text), "Never split a Unicode grapheme")
+ }
+ precondition(reveal.displayed.text == source)
+ }
+ // Replacing the target must not push an existing deadline into the future.
+ reveal = OverlayCaptionReveal()
+ for tick in 0...6 {
+ let latest = text + String(repeating: " latest", count: tick)
+ reveal.update(.tail(latest, limit: 800), now: Double(tick) * 0.06)
+ reveal.advance(now: Double(tick) * 0.06)
+ }
+ reveal.advance(now: 0.42)
+ precondition(!reveal.hasPendingWords)
+ reveal.update(.empty, now: 0.43)
+ precondition(reveal.displayed == .empty && !reveal.hasPendingWords)
+ }
+
+ @MainActor
+ static func testDisplayBufferDeadlinesAndCancellation() async throws {
+ let view = OverlayCaptionNSView(frame: CGRect(x: 0, y: 0, width: 304, height: 54))
+ func update(_ text: String, reduceMotion: Bool = false, isActive: Bool = true) {
+ view.update(caption: .tail(text, limit: 100), context: .tail(text, limit: 800), fontSize: 13, opacity: 1, reduceMotion: reduceMotion, isActive: isActive)
+ view.layoutSubtreeIfNeeded()
+ }
+ let first = "Words should flow into the preview instead of being pasted in a whole chunk."
+ update(first)
+ let initial = view.accessibilityValue() as? String ?? ""
+ precondition(!initial.isEmpty && first.hasPrefix(initial) && initial != first)
+ try await Task.sleep(for: .milliseconds(85))
+ let next = view.accessibilityValue() as? String ?? ""
+ precondition(next.count > initial.count && next != first, "Words must appear in intermediate steps")
+ for index in 0..<100 {
+ update(first + " latest revision \(index)")
+ }
+ update(first + " final corrected words")
+ try await Task.sleep(for: .milliseconds(500))
+ precondition(view.accessibilityValue() as? String == first + " final corrected words", "Finish the latest revision within the display deadline")
+ update(first + " stale pending words must never survive a new recording")
+ update("")
+ update("New recording")
+ try await Task.sleep(for: .milliseconds(500))
+ precondition(view.accessibilityValue() as? String == "New recording")
+ update("Before teardown with many pending words that should not appear later")
+ let beforeTeardown = view.accessibilityValue() as? String
+ view.stopScrolling()
+ try await Task.sleep(for: .milliseconds(500))
+ precondition(view.accessibilityValue() as? String == beforeTeardown)
+ let hiddenText = "A retained hidden view must stop revealing words until it is presented again."
+ update(hiddenText)
+ let beforeHide = view.accessibilityValue() as? String
+ update(hiddenText, isActive: false)
+ update(hiddenText + " An update while hidden must not restart it.", isActive: false)
+ try await Task.sleep(for: .milliseconds(500))
+ precondition(view.accessibilityValue() as? String == beforeHide)
+ update(hiddenText)
+ try await Task.sleep(for: .milliseconds(500))
+ precondition(view.accessibilityValue() as? String == hiddenText)
+ update("Reduce Motion presents the complete result immediately", reduceMotion: true)
+ precondition(view.accessibilityValue() as? String == "Reduce Motion presents the complete result immediately")
+ precondition(view.layer?.sublayers?.allSatisfy { $0.animationKeys()?.isEmpty != false } == true)
+ }
+
+ @MainActor
+ static func testStoppedCaptionCannotRestartFromLayoutOrDetachment() async throws {
+ let view = OverlayCaptionNSView(frame: CGRect(x: 0, y: 0, width: 304, height: 54))
+ let window = NSWindow(contentRect: view.frame, styleMask: [.borderless], backing: .buffered, defer: false)
+ window.isReleasedWhenClosed = false
+ window.contentView = view
+ defer { window.contentView = nil; window.close() }
+ func update() {
+ view.update(caption: .tail("Words still waiting to appear must not animate after the preview has been removed.", limit: 100), fontSize: 13, opacity: 1, reduceMotion: false)
+ }
+ update()
+ view.stopScrolling()
+ view.layoutSubtreeIfNeeded()
+ precondition(view.layer?.sublayers?.allSatisfy { $0.animationKeys()?.isEmpty != false } == true, "A pending layout must not restart a stopped fade")
+ update()
+ window.contentView = nil
+ let removedValue = view.accessibilityValue() as? String
+ view.layoutSubtreeIfNeeded()
+ try await Task.sleep(for: .milliseconds(500))
+ precondition(view.accessibilityValue() as? String == removedValue, "Detached captions must cancel their pending word queue")
+ precondition(view.layer?.sublayers?.allSatisfy { $0.animationKeys()?.isEmpty != false } == true)
+ }
+
+ @MainActor
+ static func testReopenedCaptionStartsAnewWithoutAnIntermediateEmptyUpdate() async throws {
+ let view = OverlayCaptionNSView(frame: CGRect(x: 0, y: 0, width: 304, height: 54))
+ func update(_ text: String, active: Bool = true) {
+ view.update(caption: .tail(text, limit: 100), context: .tail(text, limit: 800), fontSize: 13, opacity: 1, reduceMotion: false, isActive: active)
+ }
+ update(String(repeating: "Older words fill this preview. ", count: 10))
+ view.flushPendingCaption()
+ view.stopScrolling()
+ let hiddenValue = view.accessibilityValue() as? String
+ update("", active: false)
+ precondition(view.accessibilityValue() as? String == hiddenValue, "A hidden reset must not repaint the parked caption")
+ let next = "New recording words should begin gradually instead of appearing together in one block."
+ update(next)
+ let initial = view.accessibilityValue() as? String ?? ""
+ precondition(!initial.isEmpty && next.hasPrefix(initial) && initial != next, "A previous recording must not skip the new recording's word reveal")
+ try await Task.sleep(for: .milliseconds(500))
+ precondition(view.accessibilityValue() as? String == next)
+ view.stopScrolling()
+ }
+
+ @MainActor
+ static func testScrollingAndReducedMotion() {
+ let view = OverlayCaptionNSView(frame: CGRect(x: 0, y: 0, width: 180, height: 32))
+ func update(_ text: String, reduceMotion: Bool = false) {
+ view.update(caption: .tail(text, limit: 800), fontSize: 13, opacity: 1, reduceMotion: reduceMotion)
+ view.flushPendingCaption()
+ view.layoutSubtreeIfNeeded()
+ }
+ update("First line\nSecond line")
+ precondition(view.layer?.animationKeys()?.isEmpty != false, "First presentation must not scroll from the start")
+ update("First line\nSecond line\nThird")
+ let scroll = view.layer?.animation(forKey: "captionScroll") as? CABasicAnimation
+ precondition(scroll != nil && scroll?.duration == OverlayCaptionNSView.scrollDuration)
+ let target = view.layer?.sublayerTransform.m42
+ update("First line\nSecond line\nThird word")
+ precondition(view.layer?.sublayerTransform.m42 == target, "Words on the same line must not move the viewport")
+ precondition(view.layer?.animation(forKey: "captionScroll") != nil)
+ update("First line\nSecond line\nThird word\nFourth", reduceMotion: true)
+ precondition(view.layer?.animationKeys()?.isEmpty != false)
+ update("")
+ precondition(view.layer?.sublayerTransform.m42 == 0)
+ precondition(view.layer?.animationKeys()?.isEmpty != false, "Clearing must cancel stale scrolling")
+ update("New recording")
+ precondition(view.layer?.sublayerTransform.m42 == 0)
+ precondition(view.hitTest(.zero) == nil)
+ precondition(view.accessibilityValue() as? String == "New recording")
+ update("A long caption that fills more than one line while the user keeps speaking and thinking out loud.")
+ let expandedHeight = view.fittingHeight(width: 180, maxHeight: 60, maxLines: nil)
+ update("A shorter correction")
+ precondition(view.fittingHeight(width: 180, maxHeight: 60, maxLines: nil) == expandedHeight)
+ update("")
+ precondition(view.fittingHeight(width: 180, maxHeight: 60, maxLines: nil) == expandedHeight, "Clearing text must keep the reserved line slots")
+ }
+
+ @MainActor
+ static func testPreviewLimitKeepsAFullViewport() {
+ // A 50-character preview is shorter than three visible lines. Once the
+ // window fills, its older lines must survive until they actually scroll out.
+ let view = OverlayCaptionNSView()
+ precondition(view.fittingHeight(width: 304, maxHeight: 54.6, maxLines: 3) == 54)
+ var text = ""
+ var filled = false
+ var sourceHasThreeLines = false
+ var previousTarget: CGFloat = 0
+ let words = String(repeating: "These captions stay readable while more words arrive at the end of the sentence. ", count: 30)
+ for word in words.split(separator: " ") {
+ text += "\(word) "
+ view.update(caption: .tail(text, limit: 50), fontSize: 13, opacity: 1, reduceMotion: true)
+ view.flushPendingCaption()
+ let height = view.fittingHeight(width: 304, maxHeight: 54.6, maxLines: 3)
+ view.frame = CGRect(x: 0, y: 0, width: 304, height: height)
+ view.layoutSubtreeIfNeeded()
+ guard let layer = view.layer, let drawing = layer.sublayers?.first else {
+ preconditionFailure("Caption layers must exist")
+ }
+ sourceHasThreeLines = sourceHasThreeLines || OverlayCaptionLayout(text: text, width: 304, fontSize: 13, opacity: 1).lines.count >= 3
+ filled = filled || sourceHasThreeLines
+ if filled {
+ precondition(height == 54, "A full caption window must not lose a visible line")
+ precondition(
+ abs(drawing.frame.maxY + layer.sublayerTransform.m42 - height) < 0.5,
+ "Trimming must not leave an empty line at the bottom"
+ )
+ precondition(
+ layer.sublayerTransform.m42 <= previousTarget,
+ "Appending words must not pull previous lines back down"
+ )
+ }
+ previousTarget = layer.sublayerTransform.m42
+ precondition(drawing.frame.height <= 180, "Retained context must remain bounded")
+ }
+ precondition(filled, "The preview limit must not prevent the window from filling")
+ }
+
+ @MainActor
+ static func testTrimmingDoesNotRestartTheSameLineScroll() {
+ let view = OverlayCaptionNSView(frame: CGRect(x: 0, y: 0, width: 180, height: 36))
+ func update(_ text: String) {
+ view.update(caption: .tail(text, limit: 50), fontSize: 13, opacity: 1, reduceMotion: false)
+ view.flushPendingCaption()
+ view.layoutSubtreeIfNeeded()
+ }
+ let prefix = "First sentence.\nSecond sentence.\nThird sentence."
+ update(prefix)
+ update(prefix + "\nNext")
+ guard let layer = view.layer, let before = layer.animation(forKey: "captionScroll") else {
+ preconditionFailure("A new line must start scrolling")
+ }
+ let target = layer.sublayerTransform.m42
+ update(prefix + "\nNext word at a time")
+ guard let after = layer.animation(forKey: "captionScroll") else {
+ preconditionFailure("The original scroll must continue")
+ }
+ precondition(layer.sublayerTransform.m42 == target)
+ precondition(before.beginTime == after.beginTime, "Trimming must not restart an unfinished scroll")
+ update("")
+ precondition(layer.sublayers?.first?.frame.minY == 0, "A new recording must reset the retained line origin")
+ }
+
+ @MainActor
+ static func testSizingAndRendering() throws {
+ for (width, fontSize, maximumHeight, maximumLines) in [(180.0, 10.0, 60.0, 5), (198.0, 11.0, 46.2, 1), (304.0, 13.0, 54.6, 3), (396.0, 15.0, 80.0, 4)] {
+ let view = OverlayCaptionNSView()
+ for text in ["Short caption", String(repeating: "A stable caption with readable words. ", count: 30), "字幕 مرحبا 👩🏽‍💻 café", String(repeating: "x", count: 800)] {
+ view.update(caption: .tail(text, limit: 100), fontSize: fontSize, opacity: 1, reduceMotion: true)
+ view.flushPendingCaption()
+ let height = view.fittingHeight(width: width, maxHeight: maximumHeight, maxLines: maximumLines)
+ precondition(height > 0 && height <= maximumHeight)
+ view.frame = CGRect(x: 0, y: 0, width: width, height: height)
+ view.layoutSubtreeIfNeeded()
+ precondition(view.frame.height == height)
+ if let output = ProcessInfo.processInfo.environment["CAPTION_TEST_OUTPUT"], text.hasPrefix("A stable") {
+ guard let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) else {
+ preconditionFailure("Caption must produce a bitmap")
+ }
+ view.cacheDisplay(in: view.bounds, to: bitmap)
+ guard let png = bitmap.representation(using: .png, properties: [:]) else {
+ preconditionFailure("Caption must produce a PNG")
+ }
+ try png.write(to: URL(fileURLWithPath: output).appendingPathComponent("caption-\(Int(fontSize)).png"))
+ }
+ }
+ }
+ }
+}
diff --git a/Tests/run_overlay_captions.sh b/Tests/run_overlay_captions.sh
new file mode 100755
index 00000000..0fed139f
--- /dev/null
+++ b/Tests/run_overlay_captions.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+test -d "$task_developer_dir/Platforms/MacOSX.platform"
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-overlay-captions.XXXXXX)
+trap 'rm -rf "$task_test_dir"' EXIT
+xcrun swiftc -parse-as-library Sources/Fluid/Theme/FluidTypography.swift Sources/Fluid/UI/OverlayCaptionView.swift Tests/OverlayCaptionTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"