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

Refine history presentation and cache Stats summaries

altic-dev7e262b4b58cb
diff --git a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift
index 4b51d9b6..7d7ac3f4 100644
--- a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift
+++ b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift
@@ -2015,7 +2015,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
let modelName = (self.selectedModelByProvider[providerKey] ?? self.selectedModel)
.trimmingCharacters(in: .whitespacesAndNewlines)
guard !modelName.isEmpty else { return providerName }
- return "\(providerName) - \(modelName)"
+ return "\(providerName) - \(ModelDisplayName.forID(modelName))"
}
func selectPrivateAIPromptIfAvailable() {
diff --git a/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift b/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift
index 56c40b32..9202d4cc 100644
--- a/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift
+++ b/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift
@@ -1025,7 +1025,7 @@ extension AIEnhancementSettingsView {
}
private func privateAIModelDisplayName(_ modelID: String) -> String {
- PrivateAIModelRegistry.model(id: modelID)?.displayName ?? modelID
+ ModelDisplayName.forID(modelID)
}
private func isPrivateAIModelVerified(_ model: PrivateAIRegisteredModel) -> Bool {
@@ -1315,7 +1315,7 @@ extension AIEnhancementSettingsView {
.font(self.theme.typography.bodyStrong)
.foregroundStyle(Color.fluidGreen)
.frame(maxWidth: managementLayout ? .infinity : nil, alignment: .trailing)
- .help("Successfully tested \(self.viewModel.selectedModel(for: item.id)) with this endpoint and API key.")
+ .help("Successfully tested \(ModelDisplayName.forID(self.viewModel.selectedModel(for: item.id))) with this endpoint and API key.")
} else {
Button(action: {
Task { await self.viewModel.testAPIConnection() }
@@ -2399,7 +2399,7 @@ extension AIEnhancementSettingsView {
Image(systemName: "brain.head.profile")
.font(.system(size: 14))
.foregroundStyle(self.theme.palette.accent)
- Text("Reasoning for \(self.viewModel.selectedModel)")
+ Text("Reasoning for \(ModelDisplayName.forID(self.viewModel.selectedModel))")
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(self.theme.palette.primaryText)
Spacer()
diff --git a/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift b/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
index 46d4b0d0..fff0b211 100644
--- a/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
+++ b/Sources/Fluid/UI/AISettingsView+AdvancedSettings.swift
@@ -307,7 +307,7 @@ extension AIEnhancementSettingsView {
systemImage: "cpu",
text: modelPicker.selectedModel.isEmpty
? (modelPicker.providerName.isEmpty ? "No model" : modelPicker.summary)
- : modelPicker.selectedModel,
+ : ModelDisplayName.forID(modelPicker.selectedModel),
tone: tone
)
}
@@ -631,7 +631,7 @@ extension AIEnhancementSettingsView {
let providerName = self.viewModel.providerDisplayName(for: providerID)
let selectedModel = self.promptEditorModelDraft.trimmingCharacters(in: .whitespacesAndNewlines)
- let summary = selectedModel.isEmpty ? providerName : "\(providerName) - \(selectedModel)"
+ let summary = selectedModel.isEmpty ? providerName : "\(providerName) - \(ModelDisplayName.forID(selectedModel))"
return PromptCardModelPicker(
summary: summary,
@@ -889,7 +889,7 @@ extension AIEnhancementSettingsView {
) -> PromptCardModelPicker? {
if isPrivateAI {
return PromptCardModelPicker(
- summary: "fluid-1",
+ summary: ModelDisplayName.forID(PrivateAIIntegrationService.configuredModelID),
selectedModel: PrivateAIIntegrationService.configuredModelID,
models: PrivateAIModelRegistry.modelIDs(),
providerName: PrivateAIProviderFeature.displayName,
@@ -926,7 +926,7 @@ extension AIEnhancementSettingsView {
let providerName = self.viewModel.providerDisplayName(for: providerID)
let configuredModel = configuration.modelName.trimmingCharacters(in: .whitespacesAndNewlines)
let selectedModel = configuredModel.isEmpty ? self.viewModel.selectedModel(for: providerID) : configuredModel
- let summary = selectedModel.isEmpty ? providerName : "\(providerName) - \(selectedModel)"
+ let summary = selectedModel.isEmpty ? providerName : "\(providerName) - \(ModelDisplayName.forID(selectedModel))"
return PromptCardModelPicker(
summary: summary,
diff --git a/Sources/Fluid/UI/HistoryAppIcon.swift b/Sources/Fluid/UI/HistoryAppIcon.swift
new file mode 100644
index 00000000..f146d2ec
--- /dev/null
+++ b/Sources/Fluid/UI/HistoryAppIcon.swift
@@ -0,0 +1,61 @@
+import AppKit
+import SwiftUI
+
+/// Small presentation cache shared by history rows; no application lookup during rendering.
+@MainActor
+private final class HistoryAppIconCache {
+ static let shared = HistoryAppIconCache()
+
+ private final class Result {
+ let image: NSImage?
+ init(_ image: NSImage?) { self.image = image }
+ }
+
+ private let cache = NSCache<NSString, Result>()
+ private var pending: [String: Task<NSImage?, Never>] = [:]
+
+ private init() {
+ self.cache.countLimit = 48
+ }
+
+ func icon(for name: String) async -> NSImage? {
+ let name = name.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !name.isEmpty else { return nil }
+ if let result = self.cache.object(forKey: name as NSString) { return result.image }
+ if let task = self.pending[name] { return await task.value }
+ guard self.pending.count < 48 else { return nil }
+ let task = Task.detached(priority: .utility) { () -> NSImage? in
+ guard let path = NSWorkspace.shared.fullPath(forApplication: name) else { return nil }
+ return NSWorkspace.shared.icon(forFile: path)
+ }
+ self.pending[name] = task
+ let image = await task.value
+ self.cache.setObject(Result(image), forKey: name as NSString)
+ self.pending[name] = nil
+ return image
+ }
+}
+
+struct HistoryAppIcon: View {
+ let appName: String
+ @State private var image: NSImage?
+
+ var body: some View {
+ Group {
+ if let image {
+ Image(nsImage: image).resizable().scaledToFit()
+ } else {
+ Image(systemName: "app").resizable().scaledToFit().foregroundStyle(.secondary)
+ }
+ }
+ .frame(width: 22, height: 22)
+ .accessibilityLabel(self.appName.isEmpty ? "Unknown app" : self.appName)
+ .help(self.appName.isEmpty ? "Unknown app" : self.appName)
+ .task(id: self.appName) {
+ self.image = nil
+ let image = await HistoryAppIconCache.shared.icon(for: self.appName)
+ guard !Task.isCancelled else { return }
+ self.image = image
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/HistoryInlineAudioView.swift b/Sources/Fluid/UI/HistoryInlineAudioView.swift
new file mode 100644
index 00000000..9273f1b0
--- /dev/null
+++ b/Sources/Fluid/UI/HistoryInlineAudioView.swift
@@ -0,0 +1,124 @@
+import AVFoundation
+import SwiftUI
+
+/// Playback belongs only to this visible history entry, never to dictation capture.
+struct HistoryInlineAudioView: View {
+ @Environment(\.theme) private var theme
+ let entry: TranscriptionHistoryEntry
+ @State private var player: AVPlayer?
+ @State private var errorMessage: String?
+ @State private var elapsed: Double = 0
+ @State private var duration: Double = 0
+ @State private var isPlaying = false
+ @State private var isSeeking = false
+ @State private var timeObserver: Any?
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Recording").font(self.theme.typography.bodyStrong).foregroundStyle(.secondary)
+ if let errorMessage {
+ Label(errorMessage, systemImage: "exclamationmark.triangle")
+ .font(.callout).foregroundStyle(.secondary)
+ } else if let player {
+ HStack(spacing: 12) {
+ Button {
+ if self.isPlaying {
+ player.pause()
+ self.isPlaying = false
+ } else {
+ if self.elapsed >= self.duration - 0.1 {
+ player.seek(to: .zero)
+ self.elapsed = 0
+ }
+ player.play()
+ self.isPlaying = true
+ }
+ } label: {
+ Image(systemName: self.isPlaying ? "pause.fill" : "play.fill")
+ }
+ .fluidGlassAction(circular: true)
+ .accessibilityLabel(self.isPlaying ? "Pause recording" : "Play recording")
+ Text(Self.timeLabel(self.elapsed)).monospacedDigit().frame(width: 42)
+ Slider(value: self.$elapsed, in: 0...max(self.duration, 0.01)) { editing in
+ self.isSeeking = editing
+ if !editing {
+ player.seek(to: CMTime(seconds: self.elapsed, preferredTimescale: 600))
+ }
+ }
+ .tint(self.theme.palette.accent)
+ .accessibilityLabel("Recording position")
+ Text(Self.timeLabel(self.duration)).monospacedDigit().frame(width: 42)
+ }
+ .font(self.theme.typography.caption)
+ .foregroundStyle(.secondary)
+ .frame(minHeight: 40)
+ } else {
+ ProgressView("Loading recording…").controlSize(.small)
+ }
+ }
+ .task(id: self.entry.id) {
+ do {
+ let entry = self.entry
+ // Resolve the saved path off the main thread, only on an explicit Audio click.
+ let url = await Task.detached(priority: .userInitiated) {
+ DictationAudioHistoryStore.shared.audioFileURL(for: entry)
+ }.value
+ try Task.checkCancellation()
+ guard let url else { throw DictationAudioHistoryError.audioMissing }
+ let asset = AVURLAsset(url: url)
+ let deadline = Task {
+ do { try await Task.sleep(for: .seconds(15)) } catch { return }
+ asset.cancelLoading()
+ }
+ defer { deadline.cancel() }
+ let (playable, mediaDuration) = try await withTaskCancellationHandler {
+ try await asset.load(.isPlayable, .duration)
+ } onCancel: {
+ asset.cancelLoading()
+ }
+ guard playable else { throw DictationAudioHistoryError.audioMissing }
+ try Task.checkCancellation()
+ guard mediaDuration.seconds.isFinite, mediaDuration.seconds > 0 else { throw DictationAudioHistoryError.audioMissing }
+ self.duration = mediaDuration.seconds
+ let player = AVPlayer(playerItem: AVPlayerItem(asset: asset))
+ self.player = player
+ self.timeObserver = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 0.25, preferredTimescale: 600), queue: .main) { [weak player] time in
+ Task { @MainActor in
+ guard let player, self.player === player, !self.isSeeking, time.seconds.isFinite else { return }
+ self.elapsed = min(max(time.seconds, 0), self.duration)
+ }
+ }
+ player.play()
+ self.isPlaying = true
+ } catch {
+ // Disappearance is silent; a load cancelled by the deadline is a visible failure.
+ guard !Task.isCancelled else { return }
+ self.errorMessage = "This recording could not be played. It may have been removed."
+ }
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .AVPlayerItemDidPlayToEndTime)) { notification in
+ guard let item = notification.object as? AVPlayerItem, item === self.player?.currentItem else { return }
+ self.isPlaying = false
+ self.elapsed = self.duration
+ }
+ .onReceive(NotificationCenter.default.publisher(for: .AVPlayerItemFailedToPlayToEndTime)) { notification in
+ guard let item = notification.object as? AVPlayerItem, item === self.player?.currentItem else { return }
+ self.player?.pause()
+ self.isPlaying = false
+ self.errorMessage = "This recording could not be played."
+ }
+ .onDisappear {
+ self.player?.pause()
+ if let timeObserver { self.player?.removeTimeObserver(timeObserver) }
+ self.timeObserver = nil
+ self.player?.replaceCurrentItem(with: nil)
+ self.player = nil
+ self.isPlaying = false
+ }
+ }
+
+ private static func timeLabel(_ seconds: Double) -> String {
+ let value = Int(max(seconds, 0))
+ return String(format: "%d:%02d", value / 60, value % 60)
+ }
+}
diff --git a/Sources/Fluid/UI/HistoryTextComparisonView.swift b/Sources/Fluid/UI/HistoryTextComparisonView.swift
new file mode 100644
index 00000000..40785445
--- /dev/null
+++ b/Sources/Fluid/UI/HistoryTextComparisonView.swift
@@ -0,0 +1,94 @@
+import SwiftUI
+
+struct HistoryTextComparisonView: View {
+ @Environment(\.theme) private var theme
+ let entry: TranscriptionHistoryEntry
+ let copy: (String) -> Void
+ @State private var showChanges = true
+ @State private var comparison: HistoryTextDiff?
+ @State private var comparisonMessage: String?
+ @State private var hasCompared = false
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ if self.entry.wasAIProcessed {
+ HStack {
+ if self.showChanges, let message = self.comparisonMessage {
+ Text(message).foregroundStyle(.secondary)
+ .lineLimit(1).help(message)
+ }
+ Spacer()
+ Toggle("Show changes", isOn: self.$showChanges).toggleStyle(.switch).controlSize(.small)
+ .fixedSize()
+ }
+ .font(self.theme.typography.caption)
+ .frame(height: 24)
+ }
+ self.section(title: "Final text", content: self.entry.clipboardText ?? "", isOriginal: false)
+ if self.entry.wasAIProcessed {
+ self.section(title: "Original transcription", content: self.entry.rawText, isOriginal: true)
+ }
+ }
+ .task(id: self.showChanges) {
+ // Keep the result while toggling; only this selected entry is compared, once.
+ guard self.entry.wasAIProcessed, self.showChanges, !self.hasCompared else { return }
+ let original = self.entry.rawText
+ let final = self.entry.clipboardText ?? ""
+ let result = await Task.detached(priority: .utility) {
+ HistoryTextDiff.compare(original: original, final: final)
+ }.value
+ guard !Task.isCancelled else { return }
+ self.comparison = result
+ self.hasCompared = true
+ self.comparisonMessage = result == nil
+ ? "This entry is too long for inline comparison. Both texts remain available below."
+ : nil
+ }
+ }
+
+ private func section(title: String, content: String, isOriginal: Bool) -> some View {
+ VStack(alignment: .leading, spacing: 16) {
+ HStack(spacing: 8) {
+ Text(title).font(self.theme.typography.bodyStrong)
+ if !isOriginal, self.entry.wasAIProcessed {
+ Text("AI enhanced").font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.accent)
+ .padding(.horizontal, 8).padding(.vertical, 4)
+ .background(self.theme.palette.accent.opacity(0.1), in: Capsule())
+ }
+ Spacer()
+ Button { self.copy(content) } label: { Image(systemName: "doc.on.doc") }
+ .buttonStyle(.plain).foregroundStyle(.secondary)
+ .help(isOriginal ? "Copy raw text" : "Copy final text")
+ .accessibilityLabel(isOriginal ? "Copy raw text" : "Copy final text")
+ }
+ self.text(content, isOriginal: isOriginal)
+ .font(self.theme.typography.body).lineSpacing(5)
+ .foregroundStyle(isOriginal ? self.theme.palette.secondaryText : self.theme.palette.primaryText)
+ .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .padding(20)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: 16))
+ .overlay(RoundedRectangle(cornerRadius: 16).strokeBorder(self.theme.palette.cardBorder.opacity(0.5)))
+ }
+
+ private func text(_ content: String, isOriginal: Bool) -> Text {
+ guard self.showChanges, let comparison else { return Text(AttributedString(content)) }
+ let runs = isOriginal ? comparison.original : comparison.final
+ var text = AttributedString()
+ for run in runs {
+ var part = AttributedString(run.text)
+ if run.changed {
+ part.foregroundColor = isOriginal ? .red : .green
+ part.backgroundColor = (isOriginal ? Color.red : Color.green).opacity(0.1)
+ if isOriginal {
+ part.strikethroughStyle = .single
+ } else {
+ part.underlineStyle = .single
+ }
+ }
+ text.append(part)
+ }
+ return Text(text)
+ }
+}
diff --git a/Sources/Fluid/UI/HistoryTextDiff.swift b/Sources/Fluid/UI/HistoryTextDiff.swift
new file mode 100644
index 00000000..64272fbe
--- /dev/null
+++ b/Sources/Fluid/UI/HistoryTextDiff.swift
@@ -0,0 +1,49 @@
+import Foundation
+
+/// Bounded, presentation-only word/punctuation comparison. Whitespace is preserved verbatim.
+struct HistoryTextDiff: Sendable {
+ struct Run: Equatable, Sendable {
+ var text: String
+ let changed: Bool
+ }
+
+ let original: [Run]
+ let final: [Run]
+ var hasChanges: Bool { self.original.contains { $0.changed } || self.final.contains { $0.changed } }
+
+ static func compare(original: String, final: String) -> HistoryTextDiff? {
+ guard original.utf8.count + final.utf8.count <= 24_000 else { return nil }
+ let pattern = #"\s+|[\p{L}\p{N}_]+|[^\s\p{L}\p{N}_]"#
+ guard let expression = try? NSRegularExpression(pattern: pattern) else { return nil }
+ func tokens(_ text: String) -> [String] {
+ expression.matches(in: text, range: NSRange(text.startIndex..., in: text)).compactMap {
+ Range($0.range, in: text).map { String(text[$0]) }
+ }
+ }
+ let before = tokens(original)
+ let after = tokens(final)
+ guard before.count + after.count <= 2048 else { return nil }
+ let changes = after.difference(from: before)
+ var removed = Set<Int>()
+ var added = Set<Int>()
+ for change in changes {
+ switch change {
+ case let .remove(offset, _, _): removed.insert(offset)
+ case let .insert(offset, _, _): added.insert(offset)
+ }
+ }
+ func runs(_ tokens: [String], changed: Set<Int>) -> [Run] {
+ var result: [Run] = []
+ for (index, token) in tokens.enumerated() {
+ let isChanged = changed.contains(index)
+ if result.last?.changed == isChanged {
+ result[result.count - 1].text += token
+ } else {
+ result.append(Run(text: token, changed: isChanged))
+ }
+ }
+ return result
+ }
+ return HistoryTextDiff(original: runs(before, changed: removed), final: runs(after, changed: added))
+ }
+}
diff --git a/Sources/Fluid/UI/ModelDisplayName.swift b/Sources/Fluid/UI/ModelDisplayName.swift
new file mode 100644
index 00000000..e4050a83
--- /dev/null
+++ b/Sources/Fluid/UI/ModelDisplayName.swift
@@ -0,0 +1,11 @@
+import Foundation
+
+/// Presentation only. Picker tags, history records and API requests keep their original IDs.
+enum ModelDisplayName {
+ static func forID(_ modelID: String) -> String {
+ let id = modelID.trimmingCharacters(in: .whitespacesAndNewlines)
+ let canonical = PrivateAIModelRegistry.canonicalModelID(for: id) ?? id
+ guard let model = PrivateAIModelRegistry.model(id: canonical), !model.displayName.isEmpty else { return id }
+ return model.displayName.replacingOccurrences(of: "Fluid-1", with: "Fluid 1")
+ }
+}
diff --git a/Sources/Fluid/UI/SearchableModelPicker.swift b/Sources/Fluid/UI/SearchableModelPicker.swift
index f2c75aca..3169acbf 100644
--- a/Sources/Fluid/UI/SearchableModelPicker.swift
+++ b/Sources/Fluid/UI/SearchableModelPicker.swift
@@ -27,7 +27,7 @@ struct SearchableModelPicker: View {
isRefreshing: Bool = false,
refreshEnabled: Bool = true,
selectionEnabled: Bool = true,
- displayName: @escaping (String) -> String = { $0 },
+ displayName: @escaping (String) -> String = ModelDisplayName.forID,
controlWidth: CGFloat = 180,
controlHeight: CGFloat? = nil
) {
diff --git a/Sources/Fluid/UI/StatsSnapshot.swift b/Sources/Fluid/UI/StatsSnapshot.swift
new file mode 100644
index 00000000..cde26212
--- /dev/null
+++ b/Sources/Fluid/UI/StatsSnapshot.swift
@@ -0,0 +1,153 @@
+import Foundation
+
+/// A bounded, read-only summary. No transcription text is retained in the result.
+nonisolated struct StatsSnapshot: Sendable {
+ var totalWords = 0
+ var totalTranscriptions = 0
+ var aiProcessedCount = 0
+ var longestTranscriptionWords = 0
+ var mostWordsInDay = 0
+ var mostTranscriptionsInDay = 0
+ var currentStreak = 0
+ var bestStreak = 0
+ var weekdayCurrentStreak = 0
+ var weekdayBestStreak = 0
+ var peakHourFormatted = "N/A"
+ var topApps: [String] = []
+ var activity: [(date: Date, words: Int)] = []
+
+ var averageWordsPerTranscription: Int {
+ self.totalTranscriptions == 0 ? 0 : self.totalWords / self.totalTranscriptions
+ }
+
+ var aiEnhancementRate: Int {
+ self.totalTranscriptions == 0 ? 0 : self.aiProcessedCount * 100 / self.totalTranscriptions
+ }
+
+ func formattedTimeSaved(typingWPM: Int) -> String {
+ let minutes = typingWPM > 0 ? max(0, Double(self.totalWords) / Double(typingWPM) - Double(self.totalWords) / 150) : 0
+ if minutes < 1 { return "< 1m" }
+ if minutes < 60 { return "\(Int(minutes))m" }
+ let hours = Int(minutes) / 60
+ let remainder = Int(minutes) % 60
+ return remainder == 0 ? "\(hours)h" : "\(hours)h \(remainder)m"
+ }
+
+ func dailyWordCounts(days: Int) -> [(date: Date, words: Int)] {
+ Array(self.activity.suffix(max(0, days)))
+ }
+
+ func topAppsFormatted(limit: Int) -> [String] {
+ Array(self.topApps.prefix(max(0, limit)))
+ }
+
+ var wordMilestones: [(target: Int, achieved: Bool, label: String)] {
+ [(1000, "1K"), (10_000, "10K"), (50_000, "50K"), (100_000, "100K"), (500_000, "500K"), (1_000_000, "1M")]
+ .map { ($0.0, self.totalWords >= $0.0, $0.1) }
+ }
+
+ var transcriptionMilestones: [(target: Int, achieved: Bool, label: String)] {
+ [(50, "50"), (100, "100"), (500, "500"), (1000, "1K"), (5000, "5K"), (10_000, "10K")]
+ .map { ($0.0, self.totalTranscriptions >= $0.0, $0.1) }
+ }
+
+ var streakMilestones: [(target: Int, achieved: Bool, label: String)] {
+ [(7, "7 days"), (14, "14 days"), (30, "30 days"), (60, "60 days"), (100, "100 days"), (365, "1 year")]
+ .map { ($0.0, self.bestStreak >= $0.0, $0.1) }
+ }
+
+ var totalMilestonesAchieved: Int {
+ self.wordMilestones.filter(\.achieved).count + self.transcriptionMilestones.filter(\.achieved).count
+ + self.streakMilestones.filter(\.achieved).count
+ }
+
+ let totalMilestonesPossible = 18
+
+ func usingWeekdays(_ enabled: Bool) -> Self {
+ var result = self
+ if enabled {
+ result.currentStreak = self.weekdayCurrentStreak
+ result.bestStreak = self.weekdayBestStreak
+ }
+ return result
+ }
+
+ static func build(entries: [TranscriptionHistoryEntry], now: Date, calendar: Calendar) throws -> Self {
+ var result = Self()
+ var dayWords: [Date: Int] = [:]
+ var dayCounts: [Date: Int] = [:]
+ var appCounts: [String: Int] = [:]
+ var hours = Array(repeating: 0, count: 24)
+ result.totalTranscriptions = entries.count
+ for (index, entry) in entries.enumerated() {
+ if index.isMultiple(of: 128) { try Task.checkCancellation() }
+ let words = entry.processedText.components(separatedBy: .whitespacesAndNewlines).lazy.filter { !$0.isEmpty }.count
+ let day = calendar.startOfDay(for: entry.timestamp)
+ dayWords[day, default: 0] += words
+ dayCounts[day, default: 0] += 1
+ appCounts[entry.appName.isEmpty ? "Unknown" : entry.appName, default: 0] += 1
+ hours[calendar.component(.hour, from: entry.timestamp)] += 1
+ result.totalWords += words
+ result.longestTranscriptionWords = max(result.longestTranscriptionWords, words)
+ if entry.wasAIProcessed { result.aiProcessedCount += 1 }
+ }
+ try Task.checkCancellation()
+ result.mostWordsInDay = dayWords.values.max() ?? 0
+ result.mostTranscriptionsInDay = dayCounts.values.max() ?? 0
+ result.topApps = appCounts.sorted { $0.value == $1.value ? $0.key < $1.key : $0.value > $1.value }.prefix(5).map(\.key)
+ let today = calendar.startOfDay(for: now)
+ result.activity = (0..<30).reversed().compactMap { offset in
+ guard let date = calendar.date(byAdding: .day, value: -offset, to: today) else { return nil }
+ return (date, dayWords[date, default: 0])
+ }
+ let days = dayCounts.keys.sorted(by: >)
+ (result.currentStreak, result.bestStreak) = try Self.streaks(days: days, today: today, calendar: calendar, weekdays: false)
+ (result.weekdayCurrentStreak, result.weekdayBestStreak) = try Self.streaks(days: days, today: today, calendar: calendar, weekdays: true)
+ if !entries.isEmpty, let hour = hours.indices.max(by: { hours[$0] < hours[$1] }) {
+ let formatter = DateFormatter()
+ formatter.calendar = calendar
+ formatter.timeZone = calendar.timeZone
+ formatter.dateFormat = "h a"
+ if let start = calendar.date(from: DateComponents(hour: hour)),
+ let end = calendar.date(byAdding: .hour, value: 1, to: start)
+ {
+ result.peakHourFormatted = "\(formatter.string(from: start))-\(formatter.string(from: end))"
+ }
+ }
+ return result
+ }
+
+ private static func previousDay(_ day: Date, calendar: Calendar, weekdays: Bool) -> Date? {
+ var date = day
+ for _ in 0..<7 {
+ guard let previous = calendar.date(byAdding: .day, value: -1, to: date) else { return nil }
+ if !weekdays || !calendar.isDateInWeekend(previous) { return previous }
+ date = previous
+ }
+ return nil
+ }
+
+ private static func streaks(days: [Date], today: Date, calendar: Calendar, weekdays: Bool) throws -> (Int, Int) {
+ let days = weekdays ? days.filter { !calendar.isDateInWeekend($0) } : days
+ guard let first = days.first else { return (0, 0) }
+ let latest = weekdays && calendar.isDateInWeekend(today)
+ ? Self.previousDay(today, calendar: calendar, weekdays: true) : today
+ let recent = latest.map { first == $0 || first == Self.previousDay($0, calendar: calendar, weekdays: weekdays) } ?? false
+ var initialRun = 1
+ var run = 1
+ var best = 1
+ var initial = true
+ for index in 1..<days.count {
+ if index.isMultiple(of: 128) { try Task.checkCancellation() }
+ if days[index] == Self.previousDay(days[index - 1], calendar: calendar, weekdays: weekdays) {
+ run += 1
+ if initial { initialRun += 1 }
+ } else {
+ initial = false
+ run = 1
+ }
+ best = max(best, run)
+ }
+ return (recent ? initialRun : 0, best)
+ }
+}
diff --git a/Sources/Fluid/UI/StatsSnapshotStore.swift b/Sources/Fluid/UI/StatsSnapshotStore.swift
new file mode 100644
index 00000000..2b71f7a6
--- /dev/null
+++ b/Sources/Fluid/UI/StatsSnapshotStore.swift
@@ -0,0 +1,90 @@
+import AppKit
+import Combine
+
+/// Only aggregates while Stats is visible; keeps one small result for subsequent visits.
+@MainActor
+final class StatsSnapshotStore: ObservableObject {
+ static let shared = StatsSnapshotStore(history: .shared)
+
+ @Published private(set) var snapshot: StatsSnapshot?
+ @Published private(set) var isUpdating = false
+ private let history: TranscriptionHistoryStore
+ private var subscriptions = Set<AnyCancellable>()
+ private var owners = Set<UUID>()
+ private var revision: UInt64 = 0
+ private var completedRevision: UInt64?
+ private var completedDay: Date?
+ private var task: Task<Void, Never>?
+
+ init(history: TranscriptionHistoryStore) {
+ self.history = history
+ history.$entries.sink { [weak self] entries in
+ guard let self else { return }
+ self.revision &+= 1
+ self.task?.cancel()
+ self.task = nil
+ self.isUpdating = false
+ if entries.isEmpty { self.snapshot = nil }
+ if !self.owners.isEmpty { self.refresh(entries: entries) }
+ }.store(in: &self.subscriptions)
+
+ for name in [Notification.Name.NSCalendarDayChanged, .NSSystemTimeZoneDidChange, NSLocale.currentLocaleDidChangeNotification] {
+ NotificationCenter.default.publisher(for: name).receive(on: DispatchQueue.main).sink { [weak self] _ in
+ guard let self else { return }
+ self.revision &+= 1
+ if !self.owners.isEmpty { self.refresh(entries: self.history.entries) }
+ }.store(in: &self.subscriptions)
+ }
+ NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)
+ .receive(on: DispatchQueue.main).sink { [weak self] _ in
+ guard let self, !self.owners.isEmpty else { return }
+ self.refreshIfNeeded()
+ }.store(in: &self.subscriptions)
+ }
+
+ func activate(_ owner: UUID) {
+ self.owners.insert(owner)
+ self.refreshIfNeeded()
+ }
+
+ func deactivate(_ owner: UUID) {
+ self.owners.remove(owner)
+ if self.owners.isEmpty {
+ self.task?.cancel()
+ self.task = nil
+ self.isUpdating = false
+ }
+ }
+
+ private func refreshIfNeeded() {
+ guard self.completedRevision != self.revision || self.completedDay != Calendar.current.startOfDay(for: Date()) else { return }
+ self.refresh(entries: self.history.entries)
+ }
+
+ private func refresh(entries: [TranscriptionHistoryEntry]) {
+ self.task?.cancel()
+ let revision = self.revision
+ let calendar = Calendar.current
+ let now = Date()
+ self.isUpdating = true
+ self.task = Task { [weak self] in
+ let worker = Task.detached(priority: .utility) {
+ // Coalesce a burst of history mutations without delaying navigation.
+ try await Task.sleep(nanoseconds: 50_000_000)
+ return try StatsSnapshot.build(entries: entries, now: now, calendar: calendar)
+ }
+ let value = await withTaskCancellationHandler {
+ try? await worker.value
+ } onCancel: {
+ worker.cancel()
+ }
+ guard !Task.isCancelled, let self, self.revision == revision, !self.owners.isEmpty else { return }
+ self.isUpdating = false
+ self.task = nil
+ guard let value else { return }
+ self.snapshot = value
+ self.completedRevision = revision
+ self.completedDay = calendar.startOfDay(for: now)
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/StatsView.swift b/Sources/Fluid/UI/StatsView.swift
index 3519517a..26f012b4 100644
--- a/Sources/Fluid/UI/StatsView.swift
+++ b/Sources/Fluid/UI/StatsView.swift
@@ -2,6 +2,8 @@ import SwiftUI
struct StatsView: View {
@ObservedObject private var historyStore = TranscriptionHistoryStore.shared
+ @ObservedObject private var statsStore = StatsSnapshotStore.shared
+ @State private var statsOwner = UUID()
@ObservedObject private var settings = SettingsStore.shared
@Environment(\.theme) private var theme
@@ -17,43 +19,54 @@ struct StatsView: View {
return formatter
}()
+ private var stats: StatsSnapshot {
+ (self.statsStore.snapshot ?? StatsSnapshot()).usingWeekdays(self.settings.weekendsDontBreakStreak)
+ }
+
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
- VStack(spacing: 16) {
- self.todayHeaderCard
+ if self.statsStore.snapshot == nil {
+ ProgressView("Loading statistics…")
+ .frame(maxWidth: .infinity, minHeight: 240)
+ } else {
+ VStack(spacing: 16) {
+ self.todayHeaderCard
- Divider()
- .opacity(0.4)
+ Divider()
+ .opacity(0.4)
- // Header row: Time Saved + Total Words
- HStack(spacing: 16) {
- self.timeSavedCard
- self.totalWordsCard
- }
+ // Header row: Time Saved + Total Words
+ HStack(spacing: 16) {
+ self.timeSavedCard
+ self.totalWordsCard
+ }
- // Second row: Streak + Transcriptions
- HStack(spacing: 16) {
- self.streakCard
- self.transcriptionsCard
- }
+ // Second row: Streak + Transcriptions
+ HStack(spacing: 16) {
+ self.streakCard
+ self.transcriptionsCard
+ }
- // Activity Chart
- self.activityChartCard
+ // Activity Chart
+ self.activityChartCard
- // Milestones
- self.milestonesCard
+ // Milestones
+ self.milestonesCard
- // Insights
- self.insightsCard
+ // Insights
+ self.insightsCard
- // Personal Records
- self.recordsCard
+ // Personal Records
+ self.recordsCard
- // Reset Button
- self.resetSection
+ // Reset Button
+ self.resetSection
+ }
+ .padding(20)
}
- .padding(20)
}
+ .onAppear { self.statsStore.activate(self.statsOwner) }
+ .onDisappear { self.statsStore.deactivate(self.statsOwner) }
}
// MARK: - Today Header
@@ -63,7 +76,7 @@ struct StatsView: View {
let wordsToday = summary.words
let timeSavedToday = summary.formattedTimeSaved(typingWPM: self.settings.userTypingWPM)
let sessionsToday = summary.transcriptions
- let streak = self.historyStore.currentStreak
+ let streak = self.stats.currentStreak
return ThemedCard(style: .prominent, padding: 20, hoverEffect: false) {
VStack(alignment: .leading, spacing: 14) {
@@ -179,7 +192,7 @@ struct StatsView: View {
private var timeSavedCard: some View {
StatCard(title: "TIME SAVED", icon: "clock.fill") {
VStack(alignment: .leading, spacing: 8) {
- Text(self.historyStore.formattedTimeSaved(typingWPM: self.settings.userTypingWPM))
+ Text(self.stats.formattedTimeSaved(typingWPM: self.settings.userTypingWPM))
.font(.system(size: 32, weight: .bold, design: .rounded))
.foregroundStyle(.primary)
@@ -247,7 +260,7 @@ struct StatsView: View {
private var totalWordsCard: some View {
StatCard(title: "TOTAL WORDS", icon: "text.word.spacing") {
VStack(alignment: .leading, spacing: 8) {
- Text(self.formatNumber(self.historyStore.totalWords))
+ Text(self.formatNumber(self.stats.totalWords))
.font(.system(size: 32, weight: .bold, design: .rounded))
.foregroundStyle(.primary)
@@ -271,16 +284,16 @@ struct StatsView: View {
StatCard(title: "CURRENT STREAK", icon: "flame.fill") {
VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .firstTextBaseline, spacing: 4) {
- Text("\(self.historyStore.currentStreak)")
+ Text("\(self.stats.currentStreak)")
.font(.system(size: 32, weight: .bold, design: .rounded))
- .foregroundStyle(self.historyStore.currentStreak > 0 ? self.theme.palette.warning : .primary)
+ .foregroundStyle(self.stats.currentStreak > 0 ? self.theme.palette.warning : .primary)
- Text(self.historyStore.currentStreak == 1 ? "day" : "days")
+ Text(self.stats.currentStreak == 1 ? "day" : "days")
.font(.system(size: 14, weight: .medium))
.foregroundStyle(.secondary)
}
- Text("Best: \(self.historyStore.bestStreak) days")
+ Text("Best: \(self.stats.bestStreak) days")
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
@@ -296,7 +309,7 @@ struct StatsView: View {
.font(.system(size: 32, weight: .bold, design: .rounded))
.foregroundStyle(.primary)
- Text("Avg: \(self.historyStore.averageWordsPerTranscription) words each")
+ Text("Avg: \(self.stats.averageWordsPerTranscription) words each")
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
@@ -323,7 +336,7 @@ struct StatsView: View {
.frame(width: 140)
}
- let data = self.historyStore.dailyWordCounts(days: self.chartDays)
+ let data = self.stats.dailyWordCounts(days: self.chartDays)
let maxWords = data.map { $0.words }.max() ?? 0
if maxWords == 0 {
@@ -439,7 +452,7 @@ struct StatsView: View {
Spacer()
- Text("\(self.historyStore.totalMilestonesAchieved)/\(self.historyStore.totalMilestonesPossible)")
+ Text("\(self.stats.totalMilestonesAchieved)/\(self.stats.totalMilestonesPossible)")
.font(.system(size: 11, weight: .medium))
.foregroundStyle(self.theme.palette.accent)
}
@@ -448,19 +461,19 @@ struct StatsView: View {
// Word milestones
self.milestoneRow(
title: "Words",
- milestones: self.historyStore.wordMilestones
+ milestones: self.stats.wordMilestones
)
// Transcription milestones
self.milestoneRow(
title: "Transcriptions",
- milestones: self.historyStore.transcriptionMilestones
+ milestones: self.stats.transcriptionMilestones
)
// Streak milestones
self.milestoneRow(
title: "Streak",
- milestones: self.historyStore.streakMilestones
+ milestones: self.stats.streakMilestones
)
}
}
@@ -513,7 +526,7 @@ struct StatsView: View {
self.insightItem(
icon: "app.fill",
title: "Top Apps",
- value: self.historyStore.topAppsFormatted(limit: 3).joined(separator: ", "),
+ value: self.stats.topAppsFormatted(limit: 3).joined(separator: ", "),
fallback: "No data yet"
)
@@ -521,7 +534,7 @@ struct StatsView: View {
self.insightItem(
icon: "sparkles",
title: "AI Enhanced",
- value: "\(self.historyStore.aiEnhancementRate)%",
+ value: "\(self.stats.aiEnhancementRate)%",
fallback: "0%"
)
@@ -529,7 +542,7 @@ struct StatsView: View {
self.insightItem(
icon: "clock.fill",
title: "Peak Time",
- value: self.historyStore.peakHourFormatted,
+ value: self.stats.peakHourFormatted,
fallback: "N/A"
)
@@ -537,7 +550,7 @@ struct StatsView: View {
self.insightItem(
icon: "ruler.fill",
title: "Avg Length",
- value: "\(self.historyStore.averageWordsPerTranscription) words",
+ value: "\(self.stats.averageWordsPerTranscription) words",
fallback: "0 words"
)
}
@@ -582,17 +595,17 @@ struct StatsView: View {
HStack(spacing: 12) {
self.recordItem(
title: "Longest Transcription",
- value: "\(self.historyStore.longestTranscriptionWords) words"
+ value: "\(self.stats.longestTranscriptionWords) words"
)
self.recordItem(
title: "Most Words in a Day",
- value: "\(self.formatNumber(self.historyStore.mostWordsInDay)) words"
+ value: "\(self.formatNumber(self.stats.mostWordsInDay)) words"
)
self.recordItem(
title: "Most in a Day",
- value: "\(self.historyStore.mostTranscriptionsInDay) transcriptions"
+ value: "\(self.stats.mostTranscriptionsInDay) transcriptions"
)
}
}
@@ -654,15 +667,11 @@ struct StatsView: View {
// MARK: - Helpers
private func formatNumber(_ number: Int) -> String {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- return formatter.string(from: NSNumber(value: number)) ?? "\(number)"
+ number.formatted(.number)
}
private func dayLabel(_ date: Date) -> String {
- let formatter = DateFormatter()
- formatter.dateFormat = "EEE"
- return formatter.string(from: date)
+ date.formatted(.dateTime.weekday(.abbreviated))
}
}
diff --git a/Sources/Fluid/UI/TranscriptionHistoryView.swift b/Sources/Fluid/UI/TranscriptionHistoryView.swift
index 17b32cea..79e70ae0 100644
--- a/Sources/Fluid/UI/TranscriptionHistoryView.swift
+++ b/Sources/Fluid/UI/TranscriptionHistoryView.swift
@@ -12,6 +12,9 @@ struct TranscriptionHistoryView: View {
@State private var showReportConfirmation: Bool = false
@State private var selectedReportEntry: TranscriptionHistoryEntry?
@State private var selectedEntryID: UUID?
+ @State private var audioEntryID: UUID?
+ @State private var copiedEntryID: UUID?
+ @State private var copyFeedbackTask: Task<Void, Never>?
private var filteredEntries: [TranscriptionHistoryEntry] {
self.historyStore.search(query: self.searchQuery)
@@ -27,7 +30,14 @@ struct TranscriptionHistoryView: View {
// MARK: - Left Panel: Entry List
VStack(spacing: 0) {
- // Search Bar
+ HStack(spacing: 10) {
+ Image(systemName: "clock.arrow.circlepath").foregroundStyle(self.theme.palette.accent)
+ Text("History").font(self.theme.typography.sectionTitle)
+ Spacer()
+ }
+ .padding(.horizontal, 18)
+ .padding(.top, 20)
+ .padding(.bottom, 8)
self.searchBar
.padding(12)
@@ -59,7 +69,7 @@ struct TranscriptionHistoryView: View {
self.footerView
.disabled(self.historyStore.isLoading)
}
- .frame(minWidth: 280, idealWidth: 320, maxWidth: 400)
+ .frame(minWidth: 280, idealWidth: 340, maxWidth: 400)
.background(self.theme.palette.contentBackground)
// MARK: - Right Panel: Entry Detail
@@ -72,6 +82,14 @@ struct TranscriptionHistoryView: View {
.frame(minWidth: 400)
}
}
+ .onChange(of: self.selectedEntry?.id) { _, _ in
+ self.audioEntryID = nil
+ }
+ .onDisappear {
+ self.audioEntryID = nil
+ self.copyFeedbackTask?.cancel()
+ self.copiedEntryID = nil
+ }
.onAppear {
if self.selectedEntryID == nil {
self.selectedEntryID = self.filteredEntries.first?.id
@@ -137,7 +155,7 @@ struct TranscriptionHistoryView: View {
private var entryListView: some View {
ScrollView {
- LazyVStack(spacing: 2) {
+ LazyVStack(spacing: 6) {
ForEach(self.filteredEntries) { entry in
self.entryRow(entry)
}
@@ -149,150 +167,133 @@ struct TranscriptionHistoryView: View {
private func entryRow(_ entry: TranscriptionHistoryEntry) -> some View {
let isSelected = self.selectedEntryID == entry.id
-
- return Button {
- withAnimation(.easeInOut(duration: 0.15)) {
+ return HStack(alignment: .top, spacing: 8) {
+ Button {
self.selectedEntryID = entry.id
- }
- } label: {
- VStack(alignment: .leading, spacing: 4) {
- // Top row: App name and time
- HStack(spacing: 6) {
- Text(entry.appName.isEmpty ? "Unknown App" : entry.appName)
- .font(.system(size: 11, weight: .semibold))
- .foregroundStyle(isSelected ? .white : .secondary)
- .lineLimit(1)
-
- if self.settings.showHistoryPerformanceMetrics,
- let duration = entry.transcriptionDurationMilliseconds
- {
- self.processingBadge(
- text: "ASR \(TranscriptionHistoryEntry.formattedDuration(milliseconds: duration))",
- isSelected: isSelected,
- isAccent: false
- )
- }
-
- if self.settings.showHistoryPerformanceMetrics,
- entry.wasAIProcessed || entry.aiProcessingError != nil
- {
- self.processingBadge(
- text: entry.aiProcessingDurationMilliseconds.map {
- "AI \(TranscriptionHistoryEntry.formattedDuration(milliseconds: $0))"
- } ?? "AI",
- isSelected: isSelected,
- isAccent: true
- )
- } else if entry.wasAIProcessed {
- self.processingBadge(text: "AI", isSelected: isSelected, isAccent: true)
- }
-
- if self.settings.showHistoryPerformanceMetrics,
- let tokensPerSecond = entry.aiTokensPerSecond
- {
- self.processingBadge(
- text: TranscriptionHistoryEntry.formattedTokensPerSecond(tokensPerSecond, compact: true),
- isSelected: isSelected,
- isAccent: true
- )
- }
-
- if self.hasAudio(entry) {
- Image(systemName: "waveform")
- .font(.system(size: 10, weight: .semibold))
- .foregroundStyle(isSelected ? .white.opacity(0.8) : self.theme.palette.accent)
- .help("Saved local dictation audio")
+ } label: {
+ VStack(alignment: .leading, spacing: 7) {
+ HStack(spacing: 8) {
+ HistoryAppIcon(appName: entry.appName)
+ Spacer(minLength: 4)
+ Text(entry.relativeTimeString)
+ .font(self.theme.typography.caption).foregroundStyle(.secondary)
}
-
- if entry.aiProcessingError != nil {
- Image(systemName: "exclamationmark.triangle.fill")
- .font(.system(size: 10, weight: .bold))
- .foregroundStyle(isSelected ? .white : Color.orange)
- .help(entry.aiProcessingError ?? "")
+ Text(entry.previewText)
+ .font(self.theme.typography.body)
+ .lineLimit(2).multilineTextAlignment(.leading)
+ HStack(spacing: 10) {
+ if let model = self.recordedModel(entry) {
+ Label(model, systemImage: "sparkles")
+ .lineLimit(1).truncationMode(.middle)
+ .help("Recorded AI model: \(model)")
+ } else if entry.wasAIProcessed {
+ Label("AI enhanced", systemImage: "sparkles")
+ }
+ if self.hasAudio(entry) {
+ Image(systemName: "waveform").accessibilityLabel("Saved audio")
+ }
+ if entry.aiProcessingError != nil {
+ Image(systemName: "exclamationmark.triangle")
+ .foregroundStyle(.orange).help(entry.aiProcessingError ?? "")
+ }
+ Spacer(minLength: 0)
+ if self.settings.showHistoryPerformanceMetrics, let speed = entry.aiTokensPerSecond {
+ Text(TranscriptionHistoryEntry.formattedTokensPerSecond(speed, compact: true))
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.theme.palette.accent)
+ .monospacedDigit()
+ .fixedSize()
+ .help("AI generation speed, in tokens per second—not total processing time")
+ }
}
-
- Spacer()
-
- Text(entry.relativeTimeString)
- .font(.system(size: 10, weight: .medium))
- .foregroundStyle(isSelected ? .white.opacity(0.7) : Color.secondary.opacity(0.6))
+ .font(self.theme.typography.caption).foregroundStyle(.secondary)
}
-
- // Preview text
- Text(entry.previewText)
- .font(.system(size: 12))
- .foregroundStyle(isSelected ? .white.opacity(0.9) : .primary)
- .lineLimit(2)
- .multilineTextAlignment(.leading)
- }
- .padding(.horizontal, 10)
- .padding(.vertical, 8)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(
- RoundedRectangle(cornerRadius: 8)
- .fill(isSelected ? self.theme.palette.accent : Color.clear)
- )
- .contentShape(Rectangle())
- }
- .buttonStyle(.plain)
- .contextMenu {
- Button {
- self.copyToClipboard(entry.processedText)
- } label: {
- Label(entry.wasAIProcessed ? "Copy AI Text" : "Copy Text", systemImage: "doc.on.doc")
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .contentShape(Rectangle())
}
-
- if entry.wasAIProcessed {
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(isSelected ? .isSelected : [])
+ VStack(spacing: 10) {
Button {
- self.copyToClipboard(entry.rawText)
+ self.copyFinalText(entry)
} label: {
- Label("Copy Raw Text", systemImage: "doc.on.doc.fill")
+ Image(systemName: self.copiedEntryID == entry.id ? "checkmark" : "doc.on.doc")
}
-
- Button {
- self.copyToClipboard(self.combinedText(for: entry))
- } label: {
- Label("Copy Both", systemImage: "doc.on.doc")
+ .buttonStyle(.plain)
+ .help("Copy final text")
+ .accessibilityLabel(self.copiedEntryID == entry.id ? "Copied" : "Copy final text")
+ Menu { self.entryActions(entry) } label: {
+ Image(systemName: "ellipsis")
}
+ .menuStyle(.borderlessButton).menuIndicator(.hidden)
+ .fixedSize().accessibilityLabel("Dictation actions")
}
+ .foregroundStyle(.secondary)
+ }
+ .padding(12)
+ .background(self.theme.palette.accent.opacity(isSelected ? 0.12 : 0), in: RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14)
+ .strokeBorder(isSelected ? self.theme.palette.accent.opacity(0.6) : self.theme.palette.cardBorder.opacity(0.25)))
+ .contextMenu { self.entryActions(entry) }
+ }
- if self.hasAudio(entry) {
- Divider()
+ @ViewBuilder
+ private func entryActions(_ entry: TranscriptionHistoryEntry) -> some View {
+ Button {
+ self.copyFinalText(entry)
+ } label: {
+ Label(entry.wasAIProcessed ? "Copy AI Text" : "Copy Text", systemImage: "doc.on.doc")
+ }
- Button {
- self.exportPair(entry)
- } label: {
- Label("Export Pair...", systemImage: "square.and.arrow.up")
- }
+ if entry.wasAIProcessed {
+ Button {
+ self.copyToClipboard(entry.rawText)
+ } label: {
+ Label("Copy Raw Text", systemImage: "doc.on.doc.fill")
+ }
- Button {
- self.revealAudio(entry)
- } label: {
- Label("Reveal Audio", systemImage: "waveform")
- }
+ Button {
+ self.copyToClipboard(self.combinedText(for: entry))
+ } label: {
+ Label("Copy Both", systemImage: "doc.on.doc")
}
+ }
+ if self.hasAudio(entry) {
Divider()
Button {
- self.openFeedbackReport(for: entry)
+ self.exportPair(entry)
} label: {
- Label("Report Bad Result...", systemImage: "hand.thumbsup.slash")
+ Label("Export Pair...", systemImage: "square.and.arrow.up")
}
- Divider()
-
- Button(role: .destructive) {
- withAnimation(.easeInOut(duration: 0.2)) {
- self.historyStore.deleteEntry(id: entry.id)
- if self.selectedEntryID == entry.id {
- self.selectedEntryID = self.filteredEntries.first(where: { $0.id != entry.id })?.id
- }
- }
+ Button {
+ self.revealAudio(entry)
} label: {
- Label("Delete", systemImage: "trash")
+ Label("Reveal Audio", systemImage: "waveform")
}
}
+
+ Divider()
+
+ Button {
+ self.openFeedbackReport(for: entry)
+ } label: {
+ Label("Report Bad Result...", systemImage: "hand.thumbsup.slash")
+ }
+
+ Divider()
+
+ Button(role: .destructive) {
+ if self.audioEntryID == entry.id { self.audioEntryID = nil }
+ self.historyStore.deleteEntry(id: entry.id)
+ if self.selectedEntryID == entry.id {
+ self.selectedEntryID = self.filteredEntries.first(where: { $0.id != entry.id })?.id
+ }
+ } label: {
+ Label("Delete", systemImage: "trash")
+ }
}
// MARK: - Empty State
@@ -362,288 +363,178 @@ struct TranscriptionHistoryView: View {
private func entryDetailView(_ entry: TranscriptionHistoryEntry) -> some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
- // Header
- VStack(alignment: .leading, spacing: 8) {
- HStack(spacing: 8) {
- Text("Transcription Details")
- .font(.system(size: 18, weight: .semibold))
-
- Spacer()
-
- Button {
- self.copyToClipboard(entry.processedText)
- } label: {
- Label(entry.wasAIProcessed ? "Copy AI" : "Copy", systemImage: "doc.on.doc")
- .font(.system(size: 12, weight: .medium))
+ ViewThatFits(in: .horizontal) {
+ HStack(spacing: 16) {
+ self.detailHeading(entry)
+ Spacer(minLength: 12)
+ self.detailActions(entry)
+ }
+ VStack(alignment: .leading, spacing: 16) {
+ self.detailHeading(entry)
+ self.detailActions(entry)
+ }
+ }
+ if self.audioEntryID == entry.id {
+ HistoryInlineAudioView(entry: entry)
+ .id(entry.id)
+ }
+ if let error = entry.aiProcessingError {
+ Label {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("AI enhancement failed—raw transcription was used").font(self.theme.typography.bodyStrong)
+ Text(error).font(self.theme.typography.caption).textSelection(.enabled)
}
- .buttonStyle(.bordered)
- .controlSize(.small)
-
- if self.hasAudio(entry) {
- Button {
- self.exportPair(entry)
- } label: {
- Label("Export Pair", systemImage: "square.and.arrow.up")
- .font(.system(size: 12, weight: .medium))
- }
- .buttonStyle(.bordered)
- .controlSize(.small)
-
- Button {
- self.revealAudio(entry)
- } label: {
- Label("Audio", systemImage: "waveform")
- .font(.system(size: 12, weight: .medium))
+ } icon: {
+ Image(systemName: "exclamationmark.triangle").foregroundStyle(.orange)
+ }
+ .padding(16)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(Color.orange.opacity(0.08), in: RoundedRectangle(cornerRadius: 16))
+ }
+ HistoryTextComparisonView(entry: entry, copy: self.copyToClipboard)
+ .id(entry.id)
+ if self.settings.showHistoryPerformanceMetrics {
+ FluidManagementGroup(title: "Processing") {
+ LazyVGrid(columns: self.detailColumns, alignment: .leading, spacing: 16) {
+ if let duration = entry.transcriptionDurationMilliseconds {
+ self.metadataItem(
+ icon: "waveform",
+ label: "Transcription",
+ value: TranscriptionHistoryEntry.formattedDuration(milliseconds: duration)
+ )
}
- .buttonStyle(.bordered)
- .controlSize(.small)
- }
-
- Button {
- self.openFeedbackReport(for: entry)
- } label: {
- Label("Report", systemImage: "hand.thumbsup.slash")
- .font(.system(size: 12, weight: .medium))
- }
- .buttonStyle(.bordered)
- .controlSize(.small)
- .help("Review and send this example to FluidVoice")
-
- if entry.wasAIProcessed {
- Button {
- self.copyToClipboard(entry.rawText)
- } label: {
- Label("Raw", systemImage: "doc.on.doc.fill")
- .font(.system(size: 12, weight: .medium))
+ if let duration = entry.aiProcessingDurationMilliseconds {
+ self.metadataItem(
+ icon: "sparkles",
+ label: "AI cleanup",
+ value: TranscriptionHistoryEntry.formattedDuration(milliseconds: duration)
+ )
}
- .buttonStyle(.bordered)
- .controlSize(.small)
-
- Button {
- self.copyToClipboard(self.combinedText(for: entry))
- } label: {
- Label("Both", systemImage: "doc.on.doc")
- .font(.system(size: 12, weight: .medium))
+ if let speed = entry.aiTokensPerSecond {
+ self.metadataItem(
+ icon: "speedometer",
+ label: "AI speed",
+ value: TranscriptionHistoryEntry.formattedTokensPerSecond(speed, compact: true)
+ )
}
- .buttonStyle(.bordered)
- .controlSize(.small)
}
}
-
- Text(entry.fullDateString)
- .font(.system(size: 13))
- .foregroundStyle(.secondary)
}
-
- Divider()
- .opacity(0.3)
-
- if let aiError = entry.aiProcessingError {
- HStack(alignment: .top, spacing: 8) {
- Image(systemName: "exclamationmark.triangle.fill")
- .foregroundStyle(Color.orange)
- VStack(alignment: .leading, spacing: 2) {
- Text("AI Enhancement failed - raw transcription was typed instead")
- .font(.system(size: 12, weight: .semibold))
- Text(aiError)
- .font(.system(size: 11))
- .foregroundStyle(.secondary)
- .textSelection(.enabled)
- }
+ FluidManagementGroup(title: "Details") {
+ LazyVGrid(columns: self.detailColumns, alignment: .leading, spacing: 16) {
+ self.metadataItem(icon: "app", label: "Application", value: entry.appName.isEmpty ? "Unknown" : entry.appName)
+ self.metadataItem(icon: "character.cursor.ibeam", label: "Characters", value: "\(entry.characterCount)")
+ self.metadataItem(icon: "waveform", label: "Recording", value: self.audioMetadataText(for: entry))
}
- .padding(10)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .fill(Color.orange.opacity(0.08))
- .overlay(
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .stroke(Color.orange.opacity(0.3), lineWidth: 1)
- )
- )
- }
-
- // Final Text Section
- self.detailSection(
- title: "Final Text",
- content: entry.processedText,
- badge: entry.wasAIProcessed ? "AI Enhanced" : nil
- )
-
- // Raw Text Section (only if different)
- if entry.wasAIProcessed {
- self.detailSection(
- title: "Original Transcription",
- content: entry.rawText,
- badge: nil,
- isSecondary: true
+ Divider().opacity(0.4)
+ self.metadataItem(
+ icon: "sparkles",
+ label: entry.aiProcessingError == nil ? "AI model" : "AI model (failed)",
+ value: self.recordedModel(entry) ?? (entry.wasAIProcessed ? "Not recorded" : "No AI cleanup")
)
}
-
- Divider()
- .opacity(0.3)
-
- // Metadata Grid
- self.metadataGrid(entry)
-
- Spacer(minLength: 20)
-
- // Delete Button
- HStack {
- Spacer()
- Button(role: .destructive) {
- withAnimation(.easeInOut(duration: 0.2)) {
- let nextEntry = self.filteredEntries.first(where: { $0.id != entry.id })
- self.historyStore.deleteEntry(id: entry.id)
- self.selectedEntryID = nextEntry?.id
- }
- } label: {
- Label("Delete Entry", systemImage: "trash")
- .font(.system(size: 12, weight: .medium))
+ ViewThatFits(in: .horizontal) {
+ HStack {
+ self.secondaryActions(entry)
+ Spacer()
+ }
+ VStack(alignment: .leading, spacing: 12) {
+ self.secondaryActions(entry)
}
- .buttonStyle(.bordered)
- .tint(.red)
- .controlSize(.small)
}
}
.padding(24)
+ .frame(maxWidth: 1080, alignment: .leading)
+ .frame(maxWidth: .infinity)
}
.background(self.theme.palette.contentBackground)
}
- private func detailSection(
- title: String,
- content: String,
- badge: String?,
- isSecondary: Bool = false
- ) -> some View {
- VStack(alignment: .leading, spacing: 8) {
- HStack(spacing: 8) {
- Text(title)
- .font(.system(size: 12, weight: .semibold))
- .foregroundStyle(.secondary)
- .textCase(.uppercase)
- .tracking(0.5)
-
- if let badge = badge {
- Text(badge)
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(self.theme.palette.accent)
- .padding(.horizontal, 6)
- .padding(.vertical, 2)
- .background(
- RoundedRectangle(cornerRadius: 4)
- .fill(self.theme.palette.accent.opacity(0.15))
- )
- }
+ private func detailHeading(_ entry: TranscriptionHistoryEntry) -> some View {
+ HStack(spacing: 14) {
+ Image(systemName: "clock.arrow.circlepath")
+ .font(.system(size: 24, weight: .medium))
+ .foregroundStyle(self.theme.palette.accent)
+ .frame(width: 52, height: 52)
+ .background(self.theme.palette.accent.opacity(0.1), in: RoundedRectangle(cornerRadius: 16))
+ VStack(alignment: .leading, spacing: 5) {
+ Text("Dictation details").font(self.theme.typography.title)
+ Text(entry.fullDateString).font(self.theme.typography.caption).foregroundStyle(.secondary)
}
-
- Text(content)
- .font(.system(size: 14, design: .default))
- .foregroundStyle(isSecondary ? .secondary : .primary)
- .textSelection(.enabled)
- .padding(14)
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(RoundedRectangle(cornerRadius: 10)
- .fill(self.theme.palette.cardBackground)
- .overlay(RoundedRectangle(cornerRadius: 10)
- .stroke(self.theme.palette.cardBorder.opacity(isSecondary ? 0.35 : 0.5), lineWidth: 1)))
}
}
- private func metadataGrid(_ entry: TranscriptionHistoryEntry) -> some View {
- VStack(alignment: .leading, spacing: 12) {
- Text("Details")
- .font(.system(size: 12, weight: .semibold))
- .foregroundStyle(.secondary)
- .textCase(.uppercase)
- .tracking(0.5)
-
- LazyVGrid(columns: [
- GridItem(.flexible(), spacing: 16),
- GridItem(.flexible(), spacing: 16),
- ], spacing: 12) {
- self.metadataItem(icon: "app.fill", label: "Application", value: entry.appName.isEmpty ? "Unknown" : entry.appName)
- self.metadataItem(icon: "macwindow", label: "Window", value: entry.windowTitle.isEmpty ? "Unknown" : entry.windowTitle)
- self.metadataItem(icon: "character.cursor.ibeam", label: "Characters", value: "\(entry.characterCount)")
- self.metadataItem(icon: "sparkles", label: "AI Processed", value: entry.wasAIProcessed ? "Yes" : "No")
- if self.settings.showHistoryPerformanceMetrics,
- let duration = entry.transcriptionDurationMilliseconds
- {
- self.metadataItem(
- icon: "waveform",
- label: "Transcription Time",
- value: TranscriptionHistoryEntry.formattedDuration(milliseconds: duration)
- )
- }
- if self.settings.showHistoryPerformanceMetrics,
- let duration = entry.aiProcessingDurationMilliseconds
- {
- self.metadataItem(
- icon: "sparkles",
- label: "Cleanup Time",
- value: TranscriptionHistoryEntry.formattedDuration(milliseconds: duration)
+ private var detailColumns: [GridItem] {
+ Array(repeating: GridItem(.flexible(minimum: 0), spacing: 16, alignment: .leading), count: 3)
+ }
+
+ private func recordedModel(_ entry: TranscriptionHistoryEntry) -> String? {
+ guard let model = entry.processingModel?.trimmingCharacters(in: .whitespacesAndNewlines), !model.isEmpty else { return nil }
+ return ModelDisplayName.forID(model)
+ }
+
+ private func detailActions(_ entry: TranscriptionHistoryEntry) -> some View {
+ FluidGlassControlGroup {
+ HStack(spacing: 8) {
+ Button { self.copyFinalText(entry) } label: {
+ Label(
+ self.copiedEntryID == entry.id ? "Copied" : "Copy text",
+ systemImage: self.copiedEntryID == entry.id ? "checkmark" : "doc.on.doc"
)
}
- if self.settings.showHistoryPerformanceMetrics,
- let tokensPerSecond = entry.aiTokensPerSecond
- {
- self.metadataItem(
- icon: "speedometer",
- label: "AI Speed",
- value: TranscriptionHistoryEntry.formattedTokensPerSecond(tokensPerSecond)
- )
+ .fluidGlassAction(prominent: true)
+ .disabled(entry.clipboardText == nil)
+ if self.hasAudio(entry) {
+ Button {
+ self.audioEntryID = self.audioEntryID == entry.id ? nil : entry.id
+ } label: {
+ Label(self.audioEntryID == entry.id ? "Close audio" : "Audio", systemImage: "waveform")
+ }
+ .fluidGlassAction()
}
- self.metadataItem(icon: "waveform", label: "Audio", value: self.audioMetadataText(for: entry))
+ Menu { self.entryActions(entry) } label: { Image(systemName: "ellipsis") }
+ .menuIndicator(.hidden)
+ .fluidGlassAction(circular: true)
+ .accessibilityLabel("Dictation actions")
}
}
}
- private func metadataItem(icon: String, label: String, value: String) -> some View {
- HStack(spacing: 10) {
- Image(systemName: icon)
- .font(.system(size: 12, weight: .medium))
- .foregroundStyle(.tertiary)
- .frame(width: 20)
-
- VStack(alignment: .leading, spacing: 2) {
- Text(label)
- .font(.system(size: 10, weight: .medium))
- .foregroundStyle(.tertiary)
-
- Text(value)
- .font(.system(size: 12, weight: .medium))
- .foregroundStyle(.primary)
- .lineLimit(1)
+ @ViewBuilder
+ private func secondaryActions(_ entry: TranscriptionHistoryEntry) -> some View {
+ if self.hasAudio(entry) {
+ Button { self.exportPair(entry) } label: {
+ Label("Export pair", systemImage: "square.and.arrow.up")
}
+ .fluidGlassAction()
+ }
+ Button { self.openFeedbackReport(for: entry) } label: {
+ Label("Report issue", systemImage: "hand.thumbsup.slash")
+ }
+ .fluidGlassAction()
+ }
- Spacer()
+ private func metadataItem(icon: String, label: String, value: String) -> some View {
+ HStack(spacing: 12) {
+ Image(systemName: icon).font(.system(size: 18)).foregroundStyle(self.theme.palette.accent)
+ .frame(width: 24)
+ VStack(alignment: .leading, spacing: 5) {
+ Text(label).font(self.theme.typography.caption).foregroundStyle(.secondary)
+ Text(value).font(self.theme.typography.bodyStrong).monospacedDigit()
+ }
+ Spacer(minLength: 0)
}
- .padding(10)
- .background(RoundedRectangle(cornerRadius: 8)
- .fill(self.theme.palette.cardBackground.opacity(0.9)))
}
- private func processingBadge(
- text: String,
- isSelected: Bool,
- isAccent: Bool
- ) -> some View {
- Text(text)
- .font(.system(size: 9, weight: .bold))
- .foregroundStyle(
- isSelected ? .white.opacity(0.8) : (isAccent ? self.theme.palette.accent : Color.secondary)
- )
- .padding(.horizontal, 4)
- .padding(.vertical, 1)
- .background(
- RoundedRectangle(cornerRadius: 3)
- .fill(
- isSelected
- ? .white.opacity(0.2)
- : (isAccent ? self.theme.palette.accent.opacity(0.15) : Color.secondary.opacity(0.12))
- )
- )
+ private func copyFinalText(_ entry: TranscriptionHistoryEntry) {
+ guard let text = entry.clipboardText else { return }
+ self.copyToClipboard(text)
+ self.copyFeedbackTask?.cancel()
+ self.copiedEntryID = entry.id
+ self.copyFeedbackTask = Task { @MainActor in
+ do { try await Task.sleep(for: .seconds(1.5)) } catch { return }
+ self.copiedEntryID = nil
+ }
}
private func copyToClipboard(_ text: String) {
@@ -660,7 +551,7 @@ struct TranscriptionHistoryView: View {
}
private func hasAudio(_ entry: TranscriptionHistoryEntry) -> Bool {
- DictationAudioHistoryStore.shared.audioFileExists(for: entry)
+ entry.audio != nil
}
private func audioMetadataText(for entry: TranscriptionHistoryEntry) -> String {
diff --git a/Tests/HistoryPresentationTests.swift b/Tests/HistoryPresentationTests.swift
new file mode 100644
index 00000000..866771c8
--- /dev/null
+++ b/Tests/HistoryPresentationTests.swift
@@ -0,0 +1,70 @@
+import Foundation
+
+// Display-only fixture; the test executable does not load the private provider or settings.
+enum PrivateAIModelRegistry {
+ struct Model { let displayName: String }
+ static func canonicalModelID(for value: String) -> String? {
+ value == "legacy-mini" ? "mini-internal" : nil
+ }
+
+ static func model(id: String) -> Model? {
+ id == "mini-internal" ? Model(displayName: "Fluid-1 Mini") : nil
+ }
+}
+
+@main
+struct HistoryPresentationTests {
+ static func main() throws {
+ let audio = DictationAudioMetadata(fileName: "saved.wav", durationMilliseconds: 10300,
+ byteCount: 331000, sampleRate: 16000, channels: 1, model: nil)
+ let enhanced = TranscriptionHistoryEntry(rawText: " raw words ", processedText: " final words ",
+ appName: "Notes", windowTitle: "", wasAIProcessed: true, processingModel: "historical-model",
+ transcriptionDurationMilliseconds: 57,
+ aiProcessingDurationMilliseconds: 104, aiTokensPerSecond: 746,
+ audio: audio)
+ let before = enhanced
+ precondition(enhanced.clipboardText == "final words")
+ precondition(enhanced == before, "Reading copy text must not mutate an entry")
+ let raw = TranscriptionHistoryEntry(rawText: " raw words ", processedText: " ",
+ appName: "Notes", windowTitle: "", wasAIProcessed: false)
+ precondition(raw.clipboardText == "raw words")
+ let empty = TranscriptionHistoryEntry(rawText: " ", processedText: " ",
+ appName: "Notes", windowTitle: "", wasAIProcessed: false)
+ precondition(empty.clipboardText == nil)
+ let decoded = try JSONDecoder().decode(TranscriptionHistoryEntry.self, from: JSONEncoder().encode(enhanced))
+ precondition(decoded == enhanced, "Presentation must preserve persisted fields")
+ precondition(decoded.processingModel == "historical-model")
+ precondition(TranscriptionHistoryEntry.formattedTokensPerSecond(746, compact: true) == "746 tok/s")
+ precondition(TranscriptionHistoryEntry.formattedDuration(milliseconds: 104) == "104 ms")
+ let cases = [
+ ("Hello world", "Hello world"),
+ ("Hello world", "Hello, world!"),
+ ("red blue", "green blue"),
+ ("", "new words"),
+ ("old words", ""),
+ ("one two\nthree", "One two\n\nthree."),
+ ("hello hello world", "hello world"),
+ ("வணக்கம் 👋🏽 café", "வணக்கம் 👋🏽 Café!"),
+ ]
+ for (original, final) in cases {
+ let diff = HistoryTextDiff.compare(original: original, final: final)!
+ precondition(diff.original.map(\.text).joined() == original)
+ precondition(diff.final.map(\.text).joined() == final)
+ precondition(diff.hasChanges == (original != final))
+ }
+ let replacement = HistoryTextDiff.compare(original: "red blue", final: "green blue")!
+ precondition(replacement.original.filter(\.changed).map(\.text).joined() == "red")
+ precondition(replacement.final.filter(\.changed).map(\.text).joined() == "green")
+ precondition(HistoryTextDiff.compare(original: String(repeating: "a ", count: 2000), final: "") == nil)
+ precondition(HistoryTextDiff.compare(original: String(repeating: "x", count: 24001), final: "") == nil)
+ precondition(ModelDisplayName.forID("mini-internal") == "Fluid 1 Mini")
+ precondition(ModelDisplayName.forID("legacy-mini") == "Fluid 1 Mini")
+ precondition(ModelDisplayName.forID(" mini-internal ") == "Fluid 1 Mini")
+ precondition(ModelDisplayName.forID("external/model-v2") == "external/model-v2")
+ precondition(ModelDisplayName.forID("") == "")
+ precondition(decoded.processingModel == "historical-model", "Display lookup cannot rewrite stored model IDs")
+ print("PASS: final/raw/empty copy, immutable entry, audio and timing round-trip, metric labels")
+ print("PASS: unchanged/replaced/added/deleted text, punctuation, whitespace, Unicode, repeated words and bounded diff")
+ print("PASS: display names, aliases, unknown-provider fallback and original stored model ID")
+ }
+}
diff --git a/Tests/StatsSnapshotStoreFixtures.swift b/Tests/StatsSnapshotStoreFixtures.swift
new file mode 100644
index 00000000..b2b983fa
--- /dev/null
+++ b/Tests/StatsSnapshotStoreFixtures.swift
@@ -0,0 +1,8 @@
+import Combine
+
+/// In-memory publisher only: tests never open the production history or settings.
+@MainActor
+final class TranscriptionHistoryStore {
+ static let shared = TranscriptionHistoryStore()
+ @Published var entries: [TranscriptionHistoryEntry] = []
+}
diff --git a/Tests/StatsSnapshotTests.swift b/Tests/StatsSnapshotTests.swift
new file mode 100644
index 00000000..299a15f3
--- /dev/null
+++ b/Tests/StatsSnapshotTests.swift
@@ -0,0 +1,104 @@
+import Foundation
+
+@main
+struct StatsSnapshotTests {
+ static func main() async throws {
+ var calendar = Calendar(identifier: .gregorian)
+ calendar.timeZone = TimeZone(identifier: "America/Los_Angeles")!
+ func date(_ day: Int, month: Int = 9) -> Date {
+ calendar.date(from: DateComponents(year: 2026, month: month, day: day, hour: 12))!
+ }
+ func entry(_ day: Int, text: String, app: String = "Notes", ai: Bool = false, month: Int = 9) -> TranscriptionHistoryEntry {
+ TranscriptionHistoryEntry(timestamp: date(day, month: month), rawText: "raw must not count", processedText: text,
+ appName: app, windowTitle: "", wasAIProcessed: ai)
+ }
+ let entries = [entry(7, text: "one two\nthree", ai: true), entry(7, text: "four", app: ""),
+ entry(6, text: "five six"), entry(4, text: "seven"), entry(3, text: "eight")]
+ let original = entries
+ let snapshot = try StatsSnapshot.build(entries: entries, now: date(7), calendar: calendar)
+ precondition(entries == original, "Summary must not mutate history")
+ precondition(snapshot.totalWords == 8 && snapshot.totalTranscriptions == 5)
+ precondition(snapshot.averageWordsPerTranscription == 1 && snapshot.aiEnhancementRate == 20)
+ precondition(snapshot.currentStreak == 2 && snapshot.bestStreak == 2)
+ precondition(snapshot.usingWeekdays(true).currentStreak == 3 && snapshot.usingWeekdays(true).bestStreak == 3)
+ precondition(snapshot.currentStreak == 2, "Settings projection must not alter cached summary")
+ precondition(snapshot.longestTranscriptionWords == 3 && snapshot.mostWordsInDay == 4 && snapshot.mostTranscriptionsInDay == 2)
+ precondition(snapshot.dailyWordCounts(days: 7).count == 7 && snapshot.activity.count == 30)
+ precondition(snapshot.activity.last!.words == 4 && snapshot.activity.reduce(0) { $0 + $1.words } == 8)
+ precondition(snapshot.topAppsFormatted(limit: 3) == ["Notes", "Unknown"])
+ precondition(snapshot.formattedTimeSaved(typingWPM: 0) == "< 1m")
+ precondition(snapshot.formattedTimeSaved(typingWPM: 200) == "< 1m")
+ let empty = try StatsSnapshot.build(entries: [], now: date(7), calendar: calendar)
+ precondition(empty.totalWords == 0 && empty.currentStreak == 0 && empty.bestStreak == 0 && empty.peakHourFormatted == "N/A")
+ precondition(empty.totalMilestonesAchieved == 0 && empty.totalMilestonesPossible == 18)
+ let stale = try StatsSnapshot.build(entries: entries, now: date(10), calendar: calendar)
+ precondition(stale.currentStreak == 0 && stale.weekdayCurrentStreak == 0 && stale.bestStreak == 2)
+ let weekend = try StatsSnapshot.build(entries: [entry(3, text: "x"), entry(4, text: "x"), entry(6, text: "x")], now: date(6), calendar: calendar)
+ precondition(weekend.weekdayCurrentStreak == 2 && weekend.weekdayBestStreak == 2)
+ let dst = try StatsSnapshot.build(entries: [entry(7, text: "a", month: 3), entry(8, text: "b", month: 3), entry(9, text: "c", month: 3)], now: date(9, month: 3), calendar: calendar)
+ precondition(dst.currentStreak == 3 && dst.bestStreak == 3, "Streaks must use calendar days across DST")
+ let large = Array(repeating: entry(7, text: String(repeating: "word ", count: 100)), count: 9000)
+ let start = Date()
+ let big = try StatsSnapshot.build(entries: large, now: date(7), calendar: calendar)
+ precondition(big.totalWords == 900000 && big.longestTranscriptionWords == 100 && big.activity.count == 30)
+ print("9,000-entry / 900,000-word summary: \(Int(Date().timeIntervalSince(start) * 1000)) ms off-main workload")
+ let cancelled = Task.detached {
+ try await Task.sleep(nanoseconds: 50_000_000)
+ return try StatsSnapshot.build(entries: large, now: Date(), calendar: Calendar.current)
+ }
+ cancelled.cancel()
+ do { _ = try await cancelled.value; preconditionFailure("Cancelled worker must not return a snapshot") } catch is CancellationError {}
+ try await self.testStore(entries: entries)
+ print("PASS: totals, records, chart bounds, immutable input, settings projection, empty, stale, weekends, DST, large history and cancellation")
+ }
+
+ @MainActor
+ static func testStore(entries: [TranscriptionHistoryEntry]) async throws {
+ let history = TranscriptionHistoryStore()
+ let store = StatsSnapshotStore(history: history)
+ let first = UUID()
+ let second = UUID()
+ history.entries = entries
+ try await Task.sleep(nanoseconds: 100_000_000)
+ precondition(store.snapshot == nil && !store.isUpdating, "Hidden Stats must not aggregate")
+ store.activate(first)
+ for _ in 0..<100 {
+ if !store.isUpdating { break }
+ try await Task.sleep(nanoseconds: 10_000_000)
+ }
+ precondition(store.snapshot?.totalWords == 8 && !store.isUpdating)
+ store.deactivate(first)
+ store.activate(first)
+ precondition(!store.isUpdating, "Reopening unchanged Stats must use the cache")
+ history.entries = Array(repeating: entries[0], count: 1000)
+ history.entries = [entries[1]]
+ for _ in 0..<100 {
+ if !store.isUpdating { break }
+ try await Task.sleep(nanoseconds: 10_000_000)
+ }
+ precondition(store.snapshot?.totalWords == 1, "Only newest publisher value may win")
+ store.activate(second)
+ store.deactivate(first)
+ history.entries = entries
+ for _ in 0..<100 {
+ if !store.isUpdating { break }
+ try await Task.sleep(nanoseconds: 10_000_000)
+ }
+ precondition(store.snapshot?.totalWords == 8, "One window closing must not cancel another")
+ history.entries = Array(repeating: entries[0], count: 1000)
+ store.deactivate(second)
+ try await Task.sleep(nanoseconds: 100_000_000)
+ precondition(!store.isUpdating && store.snapshot?.totalWords == 8, "Hidden cancelled work cannot publish")
+ history.entries = []
+ precondition(store.snapshot == nil, "Reset must discard old totals immediately")
+ store.activate(first)
+ for _ in 0..<100 {
+ if !store.isUpdating { break }
+ try await Task.sleep(nanoseconds: 10_000_000)
+ }
+ precondition(store.snapshot?.totalWords == 0 && store.snapshot?.totalTranscriptions == 0)
+ precondition(history.entries.isEmpty, "Stats must never write to history")
+ store.deactivate(first)
+ print("PASS: hidden inactivity, cache reuse, rapid replacement, multiple windows, cancellation, reset and no history writes")
+ }
+}
diff --git a/scripts/test_history_presentation.sh b/scripts/test_history_presentation.sh
new file mode 100644
index 00000000..3222c526
--- /dev/null
+++ b/scripts/test_history_presentation.sh
@@ -0,0 +1,12 @@
+#!/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-history-presentation.XXXXXX)
+# Compile the real value types without starting the app or accessing user history.
+sed '/^\/\/ MARK: - Transcription History Store/,$d' Sources/Fluid/Persistence/TranscriptionHistoryStore.swift > "$task_test_dir/Entry.swift"
+sed '/^final nonisolated class DictationAudioHistoryStore/,$d' Sources/Fluid/Persistence/DictationAudioHistoryStore.swift > "$task_test_dir/Audio.swift"
+xcrun swiftc -parse-as-library "$task_test_dir/Entry.swift" "$task_test_dir/Audio.swift" Sources/Fluid/UI/HistoryTextDiff.swift Sources/Fluid/UI/ModelDisplayName.swift Tests/HistoryPresentationTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/scripts/test_stats_snapshot.sh b/scripts/test_stats_snapshot.sh
new file mode 100644
index 00000000..aabc87fe
--- /dev/null
+++ b/scripts/test_stats_snapshot.sh
@@ -0,0 +1,11 @@
+#!/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-stats-snapshot.XXXXXX)
+sed '/^\/\/ MARK: - Transcription History Store/,$d' Sources/Fluid/Persistence/TranscriptionHistoryStore.swift > "$task_test_dir/Entry.swift"
+sed '/^final nonisolated class DictationAudioHistoryStore/,$d' Sources/Fluid/Persistence/DictationAudioHistoryStore.swift > "$task_test_dir/Audio.swift"
+xcrun swiftc -parse-as-library "$task_test_dir/Entry.swift" "$task_test_dir/Audio.swift" Sources/Fluid/UI/StatsSnapshot.swift Sources/Fluid/UI/StatsSnapshotStore.swift Tests/StatsSnapshotStoreFixtures.swift Tests/StatsSnapshotTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"