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 AI provider setup and model verification

altic-dev26ad5a41898a
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxproj
index 8bf0e82f..ac45b54b 100644
--- a/Fluid.xcodeproj/project.pbxproj
+++ b/Fluid.xcodeproj/project.pbxproj
@@ -501,7 +501,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 1;
+ CURRENT_PROJECT_VERSION = 22;
DEVELOPMENT_TEAM = V4J43B279J;
ENABLE_APP_SANDBOX = NO;
ENABLE_CODE_COVERAGE = NO;
@@ -529,7 +529,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
- MARKETING_VERSION = 1.5.1;
+ MARKETING_VERSION = "1.6.10-beta.1";
PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app.debug;
PRODUCT_NAME = "FluidVoice Debug";
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -556,7 +556,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
- CURRENT_PROJECT_VERSION = 1;
+ CURRENT_PROJECT_VERSION = 22;
DEVELOPMENT_TEAM = V4J43B279J;
ENABLE_APP_SANDBOX = NO;
ENABLE_CODE_COVERAGE = NO;
@@ -584,7 +584,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
- MARKETING_VERSION = 1.5.1;
+ MARKETING_VERSION = "1.6.10-beta.1";
PRODUCT_BUNDLE_IDENTIFIER = com.FluidApp.app;
PRODUCT_NAME = FluidVoice;
PROVISIONING_PROFILE_SPECIFIER = "";
diff --git a/Info.plist b/Info.plist
index 95e77175..3dcd596e 100644
--- a/Info.plist
+++ b/Info.plist
@@ -15,7 +15,7 @@
<key>CFBundleVersion</key>
<string>22</string>
<key>CFBundleShortVersionString</key>
- <string>1.6.10</string>
+ <string>1.6.10-beta.1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>LSApplicationCategoryType</key>
diff --git a/Sources/Fluid/Services/PreservedPasteboardSnapshot.swift b/Sources/Fluid/Services/PreservedPasteboardSnapshot.swift
new file mode 100644
index 00000000..7928b507
--- /dev/null
+++ b/Sources/Fluid/Services/PreservedPasteboardSnapshot.swift
@@ -0,0 +1,35 @@
+import AppKit
+
+/// Preserves every readable representation, not just the plain text used for pasting.
+struct PreservedPasteboardSnapshot {
+ let items: [[NSPasteboard.PasteboardType: Data]]
+
+ init(_ pasteboard: NSPasteboard) {
+ self.items = pasteboard.pasteboardItems?.map { item in
+ var dataByType: [NSPasteboard.PasteboardType: Data] = [:]
+ for type in item.types {
+ if let data = item.data(forType: type) {
+ dataByType[type] = data
+ }
+ }
+ return dataByType
+ } ?? []
+ }
+
+ @discardableResult
+ func restore(to pasteboard: NSPasteboard, ifUnchangedSince changeCount: Int) -> Bool {
+ // Equal text is not ownership: a user may have copied that same text with
+ // different formats since our write. Their newer clipboard always wins.
+ guard pasteboard.changeCount == changeCount else { return false }
+ pasteboard.clearContents()
+ guard !self.items.isEmpty else { return true }
+ let restoredItems = self.items.map { snapshot -> NSPasteboardItem in
+ let item = NSPasteboardItem()
+ for (type, data) in snapshot {
+ item.setData(data, forType: type)
+ }
+ return item
+ }
+ return pasteboard.writeObjects(restoredItems)
+ }
+}
diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swift
index a3849cfc..28478c7e 100644
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@ -93,14 +93,6 @@ final class TypingService {
let element: AXUIElement?
}
- private struct PasteboardItemSnapshot {
- let dataByType: [NSPasteboard.PasteboardType: Data]
- }
-
- private struct PasteboardSnapshot {
- let items: [PasteboardItemSnapshot]
- }
-
private struct FocusedTextSnapshot {
let pid: pid_t
let bundleIdentifier: String?
@@ -110,15 +102,6 @@ final class TypingService {
let appScriptSelectedRange: CFRange?
}
- private enum PasteVerificationResult: String {
- case appScriptContainsText = "appscript_contains_text"
- case appScriptCaretMovedExpectedDistance = "appscript_caret_moved_expected_distance"
- case fieldContainsText = "field_contains_text"
- case caretMovedExpectedDistance = "caret_moved_expected_distance"
- case timeout
- case unavailable
- }
-
private static let focusSnapshotQueue = DispatchQueue(label: "TypingService.FocusSnapshot")
private static let pasteboardSessionSemaphore = DispatchSemaphore(value: 1)
private static let pasteboardRestoreQueue = DispatchQueue(label: "TypingService.PasteboardRestore", qos: .utility)
@@ -791,33 +774,6 @@ final class TypingService {
return ["AXTextField", "AXTextArea", "AXSearchField", "AXComboBox", "AXWebArea", "AXGroup"].contains(currentRole)
}
- private func capturePasteboardSnapshot(_ pasteboard: NSPasteboard) -> PasteboardSnapshot {
- let items: [PasteboardItemSnapshot] = pasteboard.pasteboardItems?.map { item in
- var dataByType: [NSPasteboard.PasteboardType: Data] = [:]
- for type in item.types {
- if let data = item.data(forType: type) {
- dataByType[type] = data
- }
- }
- return PasteboardItemSnapshot(dataByType: dataByType)
- } ?? []
- return PasteboardSnapshot(items: items)
- }
-
- private func restorePasteboardSnapshot(_ snapshot: PasteboardSnapshot, to pasteboard: NSPasteboard) {
- pasteboard.clearContents()
- guard !snapshot.items.isEmpty else { return }
-
- let restoredItems = snapshot.items.map { snap -> NSPasteboardItem in
- let item = NSPasteboardItem()
- for (type, data) in snap.dataByType {
- item.setData(data, forType: type)
- }
- return item
- }
- _ = pasteboard.writeObjects(restoredItems)
- }
-
/// Builds the pasteboard item for a temporary paste write, tagged with the nspasteboard.org
/// Transient and AutoGenerated marker types so clipboard managers exclude it from history.
/// `ConcealedType` is deliberately not used: it signals sensitive/password content, which
@@ -832,7 +788,6 @@ final class TypingService {
private func withTemporaryPasteboardString(
_ text: String,
- restoreDelayMicros: useconds_t,
action: () -> Bool
) -> Bool {
let pasteboardWaitStartedAt = ProcessInfo.processInfo.systemUptime
@@ -847,47 +802,38 @@ final class TypingService {
let pasteboard = NSPasteboard.general
let snapshotStartedAt = ProcessInfo.processInfo.systemUptime
- let snapshot = self.capturePasteboardSnapshot(pasteboard)
+ let snapshot = PreservedPasteboardSnapshot(pasteboard)
self.bench("pasteboard_snapshot_done elapsedMs=\(Self.elapsedMs(since: snapshotStartedAt)) items=\(snapshot.items.count)")
let writeStartedAt = ProcessInfo.processInfo.systemUptime
- pasteboard.clearContents()
+ let clearedChangeCount = pasteboard.clearContents()
guard pasteboard.writeObjects([Self.makeTransientPasteboardItem(text)]) else {
self.log("[TypingService] ERROR: Failed to set temporary clipboard string")
- self.restorePasteboardSnapshot(snapshot, to: pasteboard)
+ snapshot.restore(to: pasteboard, ifUnchangedSince: clearedChangeCount)
return false
}
let temporaryChangeCount = pasteboard.changeCount
self.bench("pasteboard_write_done elapsedMs=\(Self.elapsedMs(since: writeStartedAt))")
- let focusSnapshotStartedAt = ProcessInfo.processInfo.systemUptime
- let focusedTextSnapshot = self.captureFocusedTextSnapshot()
- self.bench("paste_focus_snapshot_done elapsedMs=\(Self.elapsedMs(since: focusSnapshotStartedAt))")
let actionStartedAt = ProcessInfo.processInfo.systemUptime
let actionResult = action()
self.bench("paste_dispatch_done elapsedMs=\(Self.elapsedMs(since: actionStartedAt)) success=\(actionResult)")
guard actionResult else {
- self.restorePasteboardSnapshot(snapshot, to: pasteboard)
- self.log("[TypingService] Restored previous clipboard snapshot after paste dispatch failure")
+ let restored = snapshot.restore(to: pasteboard, ifUnchangedSince: temporaryChangeCount)
+ self.bench("paste_dispatch_failure_restore restored=\(restored)")
return false
}
releasesPasteboardSessionOnReturn = false
Self.pasteboardRestoreQueue.async {
defer { Self.pasteboardSessionSemaphore.signal() }
- _ = self.waitForFocusedTextVerification(
- from: focusedTextSnapshot,
- expectedText: text,
- timeoutMicros: restoreDelayMicros
- )
+ // Give Cmd+V time to consume the temporary text without holding the
+ // next dictation behind the old five-second verification window.
+ Thread.sleep(forTimeInterval: 0.5)
let pasteboard = NSPasteboard.general
// Avoid clobbering user clipboard changes that happened after our insertion.
- if pasteboard.changeCount == temporaryChangeCount || pasteboard.string(forType: .string) == text {
- self.restorePasteboardSnapshot(snapshot, to: pasteboard)
- self.log("[TypingService] Restored previous clipboard snapshot")
- } else {
- self.log("[TypingService] Skipped clipboard restore because clipboard changed externally")
- }
+ let restored = snapshot.restore(to: pasteboard, ifUnchangedSince: temporaryChangeCount)
+ self.bench("paste_clipboard_restore restored=\(restored)")
}
return true
@@ -910,7 +856,7 @@ final class TypingService {
}
self.bench("paste_target_prepared elapsedMs=\(Self.elapsedMs(since: targetStartedAt))")
- return self.withTemporaryPasteboardString(text, restoreDelayMicros: 5_000_000) {
+ return self.withTemporaryPasteboardString(text) {
let dispatchStartedAt = ProcessInfo.processInfo.systemUptime
let vKey = Self.pasteVirtualKeyCode
let keyResolvedAt = ProcessInfo.processInfo.systemUptime
@@ -1035,7 +981,7 @@ final class TypingService {
/// More reliable but slightly slower - copies text to clipboard then pastes
private func insertTextViaClipboard(_ text: String) -> Bool {
self.log("[TypingService] Starting clipboard-based insertion")
- return self.withTemporaryPasteboardString(text, restoreDelayMicros: 5_000_000) {
+ return self.withTemporaryPasteboardString(text) {
let dispatchStartedAt = ProcessInfo.processInfo.systemUptime
let vKey = Self.pasteVirtualKeyCode
let keyResolvedAt = ProcessInfo.processInfo.systemUptime
@@ -1075,7 +1021,7 @@ final class TypingService {
return false
}
- return self.withTemporaryPasteboardString(text, restoreDelayMicros: 5_000_000) {
+ return self.withTemporaryPasteboardString(text) {
let escapedAppName = appName.replacingOccurrences(of: "\"", with: "\\\"")
let script = """
tell application "System Events"
@@ -1335,71 +1281,6 @@ final class TypingService {
let selectedRange: CFRange?
}
- private func waitForFocusedTextVerification(
- from snapshot: FocusedTextSnapshot?,
- expectedText: String,
- timeoutMicros: useconds_t
- ) -> PasteVerificationResult {
- guard let snapshot else {
- usleep(timeoutMicros)
- return .unavailable
- }
-
- let pollMicros: useconds_t = 50_000
- let expectedLength = max(1, (expectedText as NSString).length)
- let tolerance = max(2, expectedLength / 5)
- var waited: useconds_t = 0
-
- while waited < timeoutMicros {
- usleep(pollMicros)
- waited += pollMicros
-
- guard let current = self.captureFocusedTextSnapshot(),
- current.pid == snapshot.pid
- else {
- continue
- }
-
- if let currentValue = current.appScriptValue,
- currentValue.contains(expectedText),
- currentValue != snapshot.appScriptValue
- {
- return .appScriptContainsText
- }
-
- if let before = snapshot.appScriptSelectedRange,
- let after = current.appScriptSelectedRange,
- after.length == 0
- {
- let expectedCaretLocation = before.location + expectedLength
- let caretDelta = abs(after.location - expectedCaretLocation)
- if caretDelta <= tolerance {
- return .appScriptCaretMovedExpectedDistance
- }
- }
-
- if let currentValue = current.value,
- currentValue.contains(expectedText),
- currentValue != snapshot.value
- {
- return .fieldContainsText
- }
-
- if let before = snapshot.selectedRange,
- let after = current.selectedRange,
- after.length == 0
- {
- let expectedCaretLocation = before.location + expectedLength
- let caretDelta = abs(after.location - expectedCaretLocation)
- if caretDelta <= tolerance {
- return .caretMovedExpectedDistance
- }
- }
- }
-
- return .timeout
- }
-
private func captureAppScriptTextSnapshot(forBundleIdentifier bundleIdentifier: String?) -> AppScriptTextSnapshot? {
switch bundleIdentifier {
case "com.apple.dt.Xcode":
diff --git a/Sources/Fluid/Theme/AppTheme.swift b/Sources/Fluid/Theme/AppTheme.swift
index 3c8d48a6..efca4cfc 100644
--- a/Sources/Fluid/Theme/AppTheme.swift
+++ b/Sources/Fluid/Theme/AppTheme.swift
@@ -1,5 +1,10 @@
import SwiftUI
+/// Shared product accents. Onboarding and feature surfaces use the same source of truth.
+enum FluidBrandColors {
+ static let blue = Color(red: 0.10, green: 0.46, blue: 1.0)
+}
+
/// Central theme definition for the Fluid app. All colors, spacings and materials
/// should be defined here to keep styling consistent and easy to evolve.
struct AppTheme {
diff --git a/Sources/Fluid/Theme/Components/FluidGlassControls.swift b/Sources/Fluid/Theme/Components/FluidGlassControls.swift
new file mode 100644
index 00000000..3abe3afd
--- /dev/null
+++ b/Sources/Fluid/Theme/Components/FluidGlassControls.swift
@@ -0,0 +1,74 @@
+import SwiftUI
+
+struct ProviderDefaultButton: View {
+ let isCurrent: Bool
+ let isEnabled: Bool
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: self.action) {
+ HStack(spacing: 6) {
+ if self.isCurrent { Image(systemName: "checkmark.circle.fill") }
+ Text(self.isCurrent ? "Current default" : "Set as default")
+ }
+ }
+ .fluidGlassAction()
+ .disabled(self.isCurrent || !self.isEnabled)
+ .help(self.isCurrent ? "Used by your main dictation shortcut. App-specific cleanup styles can override it."
+ : "Use this provider for your main dictation shortcut. Choose a model and complete setup first; verification is optional.")
+ }
+}
+
+/// Opt-in native controls. Existing app-wide button styles are deliberately unchanged.
+struct FluidGlassControlGroup<Content: View>: View {
+ @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
+ @ViewBuilder let content: () -> Content
+
+ var body: some View {
+ if #available(macOS 26, *), !self.reduceTransparency {
+ GlassEffectContainer(spacing: 8) { self.content() }
+ } else {
+ self.content()
+ }
+ }
+}
+
+private struct FluidGlassActionModifier: ViewModifier {
+ @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
+ let prominent: Bool
+ let circular: Bool
+
+ @ViewBuilder func body(content: Content) -> some View {
+ if #available(macOS 26, *), !self.reduceTransparency {
+ if self.prominent {
+ content.buttonStyle(.glassProminent).tint(FluidBrandColors.blue)
+ .controlSize(.large).buttonBorderShape(.capsule)
+ } else {
+ content.buttonStyle(.glass).controlSize(.large).buttonBorderShape(self.circular ? .circle : .capsule)
+ }
+ } else {
+ content.fluidButton(self.prominent ? .accent : .secondary, size: .large)
+ }
+ }
+}
+
+extension View {
+ func fluidGlassAction(prominent: Bool = false, circular: Bool = false) -> some View {
+ self.modifier(FluidGlassActionModifier(prominent: prominent, circular: circular))
+ .fixedSize(horizontal: true, vertical: false)
+ }
+}
+
+extension AppTheme.Metrics {
+ /// Shared showcase geometry, separate from compact form rows.
+ enum Showcase {
+ static let pageMaxWidth: CGFloat = 1080
+ static let sideCardMaxWidth: CGFloat = 240
+ static let cardHeight: CGFloat = 320
+ static let cardMaxWidth: CGFloat = 320
+ static let cardRadius: CGFloat = 24
+ static let stageHeight: CGFloat = 350
+ static let metricWidth: CGFloat = 128
+ static let compactMetricWidth: CGFloat = 112
+ }
+}
diff --git a/Sources/Fluid/Theme/Components/FluidManagementSheet.swift b/Sources/Fluid/Theme/Components/FluidManagementSheet.swift
new file mode 100644
index 00000000..c4c023a7
--- /dev/null
+++ b/Sources/Fluid/Theme/Components/FluidManagementSheet.swift
@@ -0,0 +1,83 @@
+import SwiftUI
+
+/// Shared presentation only: callers retain dismissal guards and all settings ownership.
+struct FluidManagementSheet<Content: View>: View {
+ @Environment(\.theme) private var theme
+ let title: String
+ let subtitle: String
+ let symbol: String
+ var dismissDisabled = false
+ var height: CGFloat = 650
+ let close: () -> Void
+ @ViewBuilder let content: () -> Content
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: 16) {
+ Image(systemName: self.symbol)
+ .font(.system(size: 24, weight: .medium))
+ .foregroundStyle(FluidBrandColors.blue)
+ .frame(width: 52, height: 52)
+ .background(FluidBrandColors.blue.opacity(0.10), in: RoundedRectangle(cornerRadius: 16))
+ VStack(alignment: .leading, spacing: 5) {
+ Text(self.title).font(self.theme.typography.title)
+ Text(self.subtitle).font(self.theme.typography.body).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ Button("Done", action: self.close)
+ .fluidGlassAction()
+ .keyboardShortcut(.cancelAction)
+ .disabled(self.dismissDisabled)
+ }
+ .padding(28)
+ Divider()
+ ScrollView {
+ VStack(alignment: .leading, spacing: 20, content: self.content)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(28)
+ }
+ }
+ .frame(width: 720, height: self.height)
+ .background(self.theme.palette.windowBackground)
+ .tint(FluidBrandColors.blue)
+ .appTheme(self.theme)
+ }
+}
+
+/// Opaque content surfaces keep form text legible; glass is reserved for actions.
+struct FluidManagementGroup<Content: View>: View {
+ @Environment(\.theme) private var theme
+ let title: String
+ @ViewBuilder let content: () -> Content
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ Text(self.title).font(self.theme.typography.bodyStrong).foregroundStyle(self.theme.palette.secondaryText)
+ VStack(alignment: .leading, spacing: 16, content: self.content)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(20)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: 16))
+ }
+ }
+}
+
+struct FluidManagementRow<Control: View>: View {
+ @Environment(\.theme) private var theme
+ let title: String
+ var detail: String = ""
+ @ViewBuilder let control: () -> Control
+
+ var body: some View {
+ HStack(spacing: 24) {
+ VStack(alignment: .leading, spacing: 5) {
+ Text(self.title).font(self.theme.typography.bodyStrong)
+ if !self.detail.isEmpty {
+ Text(self.detail).font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ Spacer(minLength: 0)
+ self.control()
+ }
+ }
+}
diff --git a/Sources/Fluid/Theme/Components/FluidModelUpdateButton.swift b/Sources/Fluid/Theme/Components/FluidModelUpdateButton.swift
new file mode 100644
index 00000000..04ee67cf
--- /dev/null
+++ b/Sources/Fluid/Theme/Components/FluidModelUpdateButton.swift
@@ -0,0 +1,29 @@
+import SwiftUI
+
+/// Reserved space prevents the neighbouring menu moving during the hover transition.
+struct FluidModelUpdateButton: View {
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var hovered = false
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: self.action) {
+ ZStack {
+ Image(systemName: "arrow.down")
+ .font(.system(size: 12, weight: .semibold))
+ .opacity(self.hovered ? 0 : 1)
+ Text("Update").font(.system(size: 12, weight: .semibold))
+ .opacity(self.hovered ? 1 : 0)
+ }
+ .foregroundStyle(.black)
+ .frame(width: self.hovered ? 76 : 34, height: 34)
+ .background(Color(red: 0.84, green: 0.50, blue: 0.24), in: Capsule())
+ .contentShape(Capsule())
+ }
+ .buttonStyle(.plain)
+ .onHover { self.hovered = $0 }
+ .animation(self.reduceMotion ? nil : .timingCurve(0.77, 0, 0.175, 1, duration: 0.16), value: self.hovered)
+ .frame(width: 76, alignment: .trailing)
+ .accessibilityLabel("Update model")
+ }
+}
diff --git a/Sources/Fluid/Theme/Components/OnboardingComponents.swift b/Sources/Fluid/Theme/Components/OnboardingComponents.swift
index 52c71d66..9a1d879c 100644
--- a/Sources/Fluid/Theme/Components/OnboardingComponents.swift
+++ b/Sources/Fluid/Theme/Components/OnboardingComponents.swift
@@ -430,7 +430,7 @@ private struct FluidOnboardingPortalGlow: View {
}
enum FluidOnboardingLandingColors {
- static let blue = Color(red: 0.10, green: 0.46, blue: 1.0)
+ static let blue = FluidBrandColors.blue
}
private struct OnboardingSelectableSurfaceModifier: ViewModifier {
diff --git a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsView.swift b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsView.swift
index 28b06f43..a03a4b1a 100644
--- a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsView.swift
+++ b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsView.swift
@@ -27,52 +27,9 @@ extension SidebarItem {
}
}
-enum PrivateAIModelLoadState: Equatable {
- case idle
- case downloading(modelID: String, progress: PrivateAIModelDownloadProgress?)
- case loading(modelID: String)
- case loaded(modelID: String, latencyMilliseconds: Int?)
- case failed(modelID: String, message: String)
-
- func isLoading(_ modelID: String) -> Bool {
- if case .loading(modelID) = self { return true }
- return false
- }
-
- func isDownloading(_ modelID: String) -> Bool {
- if case .downloading(modelID, _) = self { return true }
- return false
- }
-
- func isLoaded(_ modelID: String) -> Bool {
- if case .loaded(modelID, _) = self { return true }
- return false
- }
-
- func latencyMilliseconds(for modelID: String) -> Int? {
- if case let .loaded(loadedModelID, latencyMilliseconds) = self, loadedModelID == modelID {
- return latencyMilliseconds
- }
- return nil
- }
-
- func failureMessage(for modelID: String) -> String? {
- if case let .failed(failedModelID, message) = self, failedModelID == modelID {
- return message
- }
- return nil
- }
-
- func downloadProgress(for modelID: String) -> PrivateAIModelDownloadProgress? {
- if case let .downloading(downloadingModelID, progress) = self, downloadingModelID == modelID {
- return progress
- }
- return nil
- }
-}
-
struct AIEnhancementSettingsView: View {
@ObservedObject var viewModel: AIEnhancementSettingsViewModel
+ @ObservedObject var privateAIController: PrivateAISettingsController
@ObservedObject var settings: SettingsStore
@ObservedObject var promptTest: DictationPromptTestCoordinator
let theme: AppTheme
@@ -80,10 +37,9 @@ struct AIEnhancementSettingsView: View {
@Binding var activeShortcutRecordingTarget: ShortcutRecordingTarget?
@Binding var shortcutRecordingMessage: String?
@State var expandedProviderID: String? = nil
+ @State var showingAddProviderSheet = false
+ @State var managedExternalProviderID: String?
@State var providerSearchText: String = ""
- @State var privateAISelectedModelID: String = PrivateAIIntegrationService.configuredModelID
- @State var privateAILoadState: PrivateAIModelLoadState = .idle
- @State var privateAIModelUpdateStatusByID: [String: PrivateAIModelUpdateStatus] = [:]
@State var hoveredPromptCardKey: String? = nil
@State var selectedPromptMode: SettingsStore.PromptMode = .dictate
@State var hoveredPromptModeKey: String? = nil
@@ -99,9 +55,9 @@ struct AIEnhancementSettingsView: View {
self.aiConfigurationCard
.onAppear {
self.viewModel.onAppear()
- self.privateAISelectedModelID = PrivateAIIntegrationService.configuredModelID
- self.refreshPrivateAILoadState()
- self.refreshPrivateAIModelUpdateStatus(self.selectedPrivateAIModel)
+ self.privateAIController.synchronizeSelection()
+ self.privateAIController.refreshPrivateAILoadState()
+ self.privateAIController.refreshPrivateAIModelUpdateStatus(self.privateAIController.selectedPrivateAIModel)
}
.onChange(of: self.viewModel.connectionStatus) { oldValue, newValue in
if oldValue == .success && newValue != .success {
diff --git a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel+ProviderSetup.swift b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel+ProviderSetup.swift
new file mode 100644
index 00000000..2bdc39e0
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel+ProviderSetup.swift
@@ -0,0 +1,50 @@
+import Foundation
+
+extension AIEnhancementSettingsViewModel {
+ static let addedProviderIDsKey = "AISettingsAddedProviderIDs"
+
+ /// Keep legacy connections discoverable even when their verification or credentials expire.
+ func addedProviderItems(from items: [ProviderItemData]) -> [ProviderItemData] {
+ let explicit = Set(UserDefaults.standard.stringArray(forKey: Self.addedProviderIDsKey) ?? [])
+ let referenced = Set(self.settings.dictationPromptConfigurations.values.map(\.providerID))
+ return items.filter { item in
+ guard item.id != PrivateAIProviderFeature.shared.providerID else { return false }
+ let key = self.providerKey(for: item.id)
+ return !item.isBuiltIn || explicit.contains(item.id) || referenced.contains(item.id)
+ || self.settings.selectedProviderID == item.id
+ || !self.providerAPIKey(for: item.id).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ || self.settings.verifiedProviderFingerprints[key] != nil
+ }.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
+ }
+
+ /// Saves credentials first. Failure keeps the form open and creates no provider/model record.
+ /// Does not select a provider, change shortcuts, fetch models, or start a network request.
+ func addProvider(_ draft: ProviderSetupDraft) -> Bool {
+ guard draft.isValid, !self.isTestingConnection, !self.isFetchingModels else { return false }
+ let builtIn = !draft.providerID.isEmpty && ModelRepository.shared.isBuiltIn(draft.providerID)
+ guard draft.providerID.isEmpty || builtIn else { return false }
+ guard !builtIn || !self.cachedAddedProviderItems.contains(where: { $0.id == draft.providerID }) else { return false }
+ let models = draft.trimmedModel.isEmpty ? (builtIn ? ModelRepository.shared.defaultModels(for: draft.providerID) : []) : [draft.trimmedModel]
+ let provider = SettingsStore.SavedProvider(name: draft.trimmedName, baseURL: draft.trimmedBaseURL, models: models)
+ let id = builtIn ? draft.providerID : provider.id
+ let key = self.providerKey(for: id)
+ let previousKeys = self.providerAPIKeys
+ let apiKey = draft.apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !apiKey.isEmpty {
+ self.updateProviderAPIKey(apiKey, for: id)
+ guard self.saveProviderAPIKeys(invalidating: id) else {
+ self.providerAPIKeys = previousKeys
+ self.refreshProviderItems()
+ return false
+ }
+ }
+ if !builtIn { self.savedProviders.append(provider) }
+ self.availableModelsByProvider[key] = models
+ self.selectedModelByProvider[key] = models.first ?? ""
+ var added = Set(UserDefaults.standard.stringArray(forKey: Self.addedProviderIDsKey) ?? [])
+ added.insert(id)
+ UserDefaults.standard.set(added.sorted(), forKey: Self.addedProviderIDsKey)
+ self.saveSavedProviders()
+ return true
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift
index ebd67642..4b51d9b6 100644
--- a/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift
+++ b/Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel.swift
@@ -7,6 +7,7 @@ import UniformTypeIdentifiers
@MainActor
final class AIEnhancementSettingsViewModel: ObservableObject {
+ private let modelVerifications = ProviderModelVerificationStore()
let settings: SettingsStore
let menuBarManager: MenuBarManager
let promptTest: DictationPromptTestCoordinator
@@ -104,6 +105,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
}
@Published var cachedProviderItems: [ProviderItemData] = []
+ @Published var cachedAddedProviderItems: [ProviderItemData] = []
@Published var cachedVerifiedProviderItems: [ProviderItemData] = []
@Published var cachedUnverifiedProviderItems: [ProviderItemData] = []
@@ -333,6 +335,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
}
self.cachedProviderItems = items
+ self.cachedAddedProviderItems = self.addedProviderItems(from: items)
self.cachedVerifiedProviderItems = items.filter { self.connectionStatus(for: $0.id) == .success }
self.cachedUnverifiedProviderItems = items.filter { self.connectionStatus(for: $0.id) != .success }
}
@@ -368,6 +371,15 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
let key = self.providerKey(for: providerID)
guard !self.isTestingConnection else { return false }
let currentModel = PrivateAIModelRegistry.model(id: model.id) ?? model
+ let configuredModelID = PrivateAIIntegrationService.configuredModelID
+ let fingerprint = self.privateAIFingerprint(for: currentModel.id)
+
+ // Navigation may expose another settings owner while verification is awaiting the runtime.
+ // Do not publish an old verification into a newly selected model/backend configuration.
+ func configurationIsCurrent() -> Bool {
+ PrivateAIIntegrationService.configuredModelID == configuredModelID
+ && self.privateAIFingerprint(for: currentModel.id) == fingerprint
+ }
self.isTestingConnection = true
self.updateConnectionStatus(.testing, for: providerID)
@@ -384,9 +396,12 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
do {
let status = try await PrivateAIIntegrationService.shared.verifyModel(currentModel)
+ guard configurationIsCurrent() else {
+ self.updateConnectionStatus(.unknown, for: providerID)
+ return false
+ }
switch status.state {
case .ready:
- let fingerprint = self.privateAIFingerprint(for: currentModel.id)
var fingerprints = self.settings.verifiedProviderFingerprints
fingerprints[key] = fingerprint
self.settings.verifiedProviderFingerprints = fingerprints
@@ -407,6 +422,10 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
return false
}
} catch {
+ guard configurationIsCurrent() else {
+ self.updateConnectionStatus(.unknown, for: providerID)
+ return false
+ }
self.updateConnectionStatus(.failed, for: providerID)
self.setConnectionError(self.privateAIErrorMessage(for: error), for: providerID)
DebugLogger.shared.error(
@@ -795,10 +814,13 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
}
let usesResponsesAPI = self.shouldVerifyWithResponsesAPI(baseURL: baseURL, model: trimmedModel)
- await MainActor.run {
- self.isTestingConnection = true
- self.updateConnectionStatus(.testing, for: providerID)
- }
+ let verificationIdentity = ProviderModelVerificationStore.identity(
+ providerID: providerID, baseURL: baseURL, apiKey: apiKey, model: trimmedModel
+ )
+ self.isTestingConnection = true
+ self.updateConnectionStatus(.testing, for: providerID)
+ // Every validation/network exit must stop the spinner.
+ defer { self.isTestingConnection = false }
// Build the endpoint URL
let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -921,12 +943,19 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
// Make the request
do {
let (data, response) = try await URLSession.shared.data(for: request)
+ // A late result must never label a different model or changed credentials.
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
if let httpResponse = response as? HTTPURLResponse {
let statusCode = httpResponse.statusCode
+ let payload = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
+ let apiError = payload?["error"]
+ let hasAPIError = apiError != nil && !(apiError is NSNull)
- if statusCode >= 200, statusCode < 300 {
+ if statusCode >= 200, statusCode < 300, !hasAPIError {
await MainActor.run {
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
+ self.modelVerifications.recordSuccess(verificationIdentity)
self.updateConnectionStatus(.success, for: providerID)
self.setEditingAPIKey(false, for: providerID)
self.storeVerificationFingerprint(for: providerID, baseURL: baseURL, apiKey: apiKey)
@@ -942,31 +971,53 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
source: "AISettingsView"
)
await MainActor.run {
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
+ self.modelVerifications.remove(verificationIdentity)
self.updateConnectionStatus(.failed, for: providerID)
self.setConnectionError(errorMessage, for: providerID)
}
}
} else {
await MainActor.run {
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
+ self.modelVerifications.remove(verificationIdentity)
self.updateConnectionStatus(.failed, for: providerID)
self.setConnectionError("Unexpected response type from server", for: providerID)
}
}
} catch {
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
+ self.modelVerifications.remove(verificationIdentity)
let errorMessage = self.interpretNetworkError(error, providerID: providerID)
DebugLogger.shared.error(
"testAPIConnection network error for \(providerID): \(error.localizedDescription)",
source: "AISettingsView"
)
await MainActor.run {
+ guard verificationIdentity == self.modelVerificationIdentity(for: providerID) else { return }
self.updateConnectionStatus(.failed, for: providerID)
self.setConnectionError(errorMessage, for: providerID)
}
}
+ }
- await MainActor.run {
- self.isTestingConnection = false
- }
+ private func modelVerificationIdentity(for providerID: String) -> String {
+ ProviderModelVerificationStore.identity(
+ providerID: providerID,
+ baseURL: self.providerBaseURL(for: providerID),
+ apiKey: self.providerAPIKey(for: providerID),
+ model: self.selectedModel(for: providerID)
+ )
+ }
+
+ func isModelVerified(for providerID: String) -> Bool {
+ self.modelVerifications.contains(self.modelVerificationIdentity(for: providerID))
+ }
+
+ func canUseProviderWithoutVerification(_ providerID: String) -> Bool {
+ let baseURL = self.providerBaseURL(for: providerID).trimmingCharacters(in: .whitespacesAndNewlines)
+ return !baseURL.isEmpty && !self.selectedModel(for: providerID).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ && (self.isLocalEndpoint(baseURL) || !self.providerAPIKey(for: providerID).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
/// Returns the provider's HTTP error body unchanged so setup errors match the real API response.
@@ -1100,6 +1151,8 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
func deleteCurrentProvider() {
let deletedProviderID = self.selectedProviderID
let deletedDefaultProvider = self.settings.selectedProviderID == deletedProviderID
+ let remainingAddedIDs = (UserDefaults.standard.stringArray(forKey: Self.addedProviderIDsKey) ?? []).filter { $0 != deletedProviderID }
+ UserDefaults.standard.set(remainingAddedIDs, forKey: Self.addedProviderIDsKey)
self.savedProviders.removeAll { $0.id == deletedProviderID }
self.saveSavedProviders()
let key = self.providerKey(for: deletedProviderID)
@@ -1171,6 +1224,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
}
func fetchModelsForCurrentProvider() async {
+ guard !self.isFetchingModels, !self.isTestingConnection else { return }
self.refreshingProviderID = self.selectedProviderID
self.isFetchingModels = true
self.fetchModelsError = nil
@@ -1262,6 +1316,7 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
guard !trimmedModel.isEmpty else { return }
let key = self.providerKey(for: providerID)
+ let changed = self.selectedModelByProvider[key] != trimmedModel
self.selectedModelByProvider[key] = trimmedModel
self.settings.selectedModelByProvider = self.selectedModelByProvider
@@ -1270,6 +1325,9 @@ final class AIEnhancementSettingsViewModel: ObservableObject {
self.selectedModel = trimmedModel
self.syncPromptSelectionForSelectedProvider()
}
+ if changed {
+ self.updateConnectionStatus(self.isModelVerified(for: providerID) ? .success : .unknown, for: providerID)
+ }
}
func fetchModels(for providerID: String) async {
diff --git a/Sources/Fluid/UI/AISettings/AIProvidersDesignPreview.swift b/Sources/Fluid/UI/AISettings/AIProvidersDesignPreview.swift
new file mode 100644
index 00000000..9f0bcea1
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/AIProvidersDesignPreview.swift
@@ -0,0 +1,411 @@
+import SwiftUI
+
+private enum AIProvidersPreviewPanel { case manage, add, compare, external }
+
+/// Milestone 3: isolated sample data. This view intentionally has no settings/service/controller reference.
+struct AIProvidersDesignPreview: View {
+ @Environment(\.dismiss) private var dismiss
+ @State private var isLight = false
+ @State private var isCompact = false
+ @State private var showsExamples = true
+ @State private var activePanel: AIProvidersPreviewPanel?
+
+ private var theme: AppTheme { AppTheme.adaptive(accent: .blue, colorScheme: self.isLight ? .light : .dark) }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ HStack(spacing: 12) {
+ Text("Design preview · sample data")
+ .font(self.theme.typography.captionStrong)
+ Spacer()
+ Toggle("Light", isOn: self.$isLight)
+ Toggle("Compact", isOn: self.$isCompact)
+ Toggle("Example providers", isOn: self.$showsExamples)
+ Button("Done") { self.dismiss() }
+ .keyboardShortcut(self.activePanel == nil ? .cancelAction : nil)
+ .fluidButton(.secondary, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ }
+ .toggleStyle(.checkbox)
+ .font(self.theme.typography.caption)
+ .padding(self.theme.metrics.spacing.lg)
+ Divider()
+ AIProvidersPresentation(panel: self.$activePanel, showsExamples: self.showsExamples)
+ .frame(width: self.isCompact ? 580 : 820)
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ .frame(width: 860, height: 650)
+ .background(self.theme.palette.windowBackground)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .appTheme(self.theme)
+ .environment(\.colorScheme, self.isLight ? .light : .dark)
+ }
+}
+
+private struct AIProvidersPresentation: View {
+ @Environment(\.theme) private var theme
+ @Environment(\.colorScheme) private var colorScheme
+ @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State private var preview = Model.mini
+ @State private var selected = Model.mini
+ @Binding var panel: AIProvidersPreviewPanel?
+ @FocusState private var panelCloseFocused: Bool
+ let showsExamples: Bool
+
+ private enum Model: String, CaseIterable, Identifiable {
+ case pico = "Pico", mini = "Fluid-1 Mini", full = "Fluid-1"
+ var id: String { self.rawValue }
+ var detail: String {
+ switch self {
+ case .pico: "Fast and lightweight.\nGreat for everyday use."
+ case .mini: "Better understanding.\nHandles more context."
+ case .full: "Most capable.\nFor complex tasks."
+ }
+ }
+
+ var tags: [String] {
+ switch self {
+ case .pico: ["Fast", "Lightweight"]
+ case .mini: ["Balanced", "Smart cleanup"]
+ case .full: ["Quality", "Long context"]
+ }
+ }
+ }
+
+ private var spacing: AppTheme.Metrics.Spacing { self.theme.metrics.spacing }
+ private var isDark: Bool { self.colorScheme == .dark }
+ private var supportingText: Color { self.isDark ? self.theme.palette.secondaryText : self.theme.palette.primaryText.opacity(0.75) }
+
+ var body: some View {
+ ZStack(alignment: .trailing) {
+ ScrollView {
+ VStack(alignment: .leading, spacing: self.spacing.xl) {
+ self.intelligence
+ self.externalProviders
+ }
+ .padding(self.spacing.xl)
+ }
+ .disabled(self.panel != nil)
+ .accessibilityHidden(self.panel != nil)
+
+ if let panel = self.panel {
+ Button { self.panel = nil } label: {
+ Color.black.opacity(0.25)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Close panel")
+ self.inspector(panel)
+ }
+ }
+ }
+
+ private var intelligence: some View {
+ VStack(alignment: .leading, spacing: self.spacing.lg) {
+ HStack(spacing: self.spacing.lg) {
+ Image("Provider_Fluid1")
+ .resizable()
+ .scaledToFit()
+ .frame(width: 42, height: 48)
+ .clipShape(RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: self.spacing.xs) {
+ Text("Fluid Intelligence")
+ .font(self.theme.typography.title)
+ Text("Private, on-device intelligence.")
+ .font(self.theme.typography.body)
+ .foregroundStyle(self.supportingText)
+ }
+ Spacer(minLength: 0)
+ Image(systemName: "lock.shield")
+ .font(self.theme.typography.titleIcon)
+ .foregroundStyle(Color.blue)
+ .help("Your words stay on your Mac")
+ }
+
+ Divider().overlay(Color.blue.opacity(0.12))
+
+ HStack {
+ Text("Choose your model")
+ .font(self.theme.typography.sectionTitle)
+ Spacer()
+ Text("On your Mac")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.supportingText)
+ }
+
+ self.carousel
+
+ HStack(spacing: self.spacing.md) {
+ Button("Compare models", systemImage: "square.split.2x1") { self.panel = .compare }
+ .fluidButton(.inline, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ Spacer(minLength: 0)
+ if self.selected != self.preview {
+ Button("Use \(self.preview.rawValue)") { self.selected = self.preview }
+ .fluidButton(.accent, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ .help("Changes sample selection only")
+ }
+ Button("Manage", systemImage: "slider.horizontal.3") { self.panel = .manage }
+ .fluidButton(.secondary, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ }
+ }
+ .padding(self.spacing.xl)
+ .background {
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg)
+ .fill(self.theme.palette.cardBackground)
+ .overlay {
+ if !self.reduceTransparency {
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg)
+ .fill(LinearGradient(
+ colors: [Color.blue.opacity(self.isDark ? 0.20 : 0.09), Color.blue.opacity(0.015)],
+ startPoint: .topTrailing,
+ endPoint: .bottomLeading
+ ))
+ }
+ }
+ .overlay {
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg)
+ .strokeBorder(Color.blue.opacity(self.isDark ? 0.36 : 0.25), lineWidth: 1)
+ }
+ }
+ }
+
+ private var carousel: some View {
+ VStack(spacing: self.spacing.sm) {
+ GeometryReader { geometry in
+ let cardWidth = min(300, geometry.size.width * 0.44)
+ let sideWidth = (geometry.size.width - cardWidth - self.spacing.md * 2 - 80) / 2
+ let stride = cardWidth / 2 + sideWidth / 2 + self.spacing.md
+ ZStack {
+ ForEach(Model.allCases) { model in
+ let position = self.carouselPosition(model)
+ self.modelCard(model, compactSide: position != 0 && geometry.size.width < 640)
+ .frame(width: position == 0 ? cardWidth : sideWidth, height: 190)
+ .scaleEffect(position == 0 ? 1 : 0.86)
+ .opacity(position == 0 ? 1 : 0.85)
+ .offset(x: CGFloat(position) * stride)
+ .zIndex(position == 0 ? 1 : 0)
+ }
+ }
+ .frame(width: geometry.size.width, height: geometry.size.height)
+ .clipped()
+ .overlay(alignment: .leading) { self.carouselArrow(forward: false) }
+ .overlay(alignment: .trailing) { self.carouselArrow(forward: true) }
+ .simultaneousGesture(DragGesture(minimumDistance: 24).onEnded { value in
+ guard abs(value.translation.width) > abs(value.translation.height) else { return }
+ self.advanceCarousel(forward: value.translation.width < 0)
+ })
+ }
+ .frame(height: 214)
+
+ HStack(spacing: self.spacing.xs) {
+ ForEach(Model.allCases) { model in
+ Button { self.browse(model) } label: {
+ Circle()
+ .fill(self.preview == model ? Color.cyan : Color.blue.opacity(0.4))
+ .frame(width: self.preview == model ? 10 : 7, height: self.preview == model ? 10 : 7)
+ .frame(width: 24, height: 24)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Show \(model.rawValue)")
+ .accessibilityValue(self.preview == model ? "Current page" : "")
+ }
+ }
+ }
+ }
+
+ private func carouselPosition(_ model: Model) -> Int {
+ let models = Model.allCases
+ let index = models.firstIndex(of: model) ?? 0
+ let current = models.firstIndex(of: self.preview) ?? 0
+ let distance = (index - current + models.count) % models.count
+ return distance > models.count / 2 ? distance - models.count : distance
+ }
+
+ private func browse(_ model: Model) {
+ withAnimation(self.reduceMotion ? nil : .easeInOut(duration: 0.22)) {
+ self.preview = model
+ }
+ }
+
+ private func advanceCarousel(forward: Bool) {
+ let models = Model.allCases
+ let index = models.firstIndex(of: self.preview) ?? 0
+ self.browse(models[(index + (forward ? 1 : models.count - 1)) % models.count])
+ }
+
+ private func carouselArrow(forward: Bool) -> some View {
+ Button { self.advanceCarousel(forward: forward) } label: {
+ Image(systemName: forward ? "chevron.right" : "chevron.left")
+ .font(self.theme.typography.sectionTitle)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .frame(width: 34, height: 34)
+ .background(self.theme.palette.contentBackground, in: Circle())
+ .overlay { Circle().strokeBorder(Color.blue.opacity(0.65), lineWidth: 1) }
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(forward ? "Next model" : "Previous model")
+ }
+
+ private func modelCard(_ model: Model, compactSide: Bool) -> some View {
+ let isPreview = self.preview == model
+ return Button { self.browse(model) } label: {
+ VStack(alignment: .leading, spacing: self.spacing.md) {
+ HStack {
+ Spacer()
+ if self.selected == model {
+ Text("Selected")
+ .font(self.theme.typography.badge)
+ .foregroundStyle(self.supportingText)
+ }
+ }
+ Text(model.rawValue)
+ .font(compactSide ? self.theme.typography.sectionTitle : self.theme.typography.title)
+ if !compactSide {
+ Text(model.detail)
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.supportingText)
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(minHeight: 36, alignment: .topLeading)
+ HStack(spacing: self.spacing.sm) {
+ ForEach(isPreview ? model.tags : Array(model.tags.prefix(1)), id: \.self) { tag in
+ Text(tag)
+ .font(self.theme.typography.badge)
+ .padding(.horizontal, self.spacing.sm)
+ .padding(.vertical, self.spacing.xs)
+ .background(Color.blue.opacity(0.12), in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))
+ }
+ }
+ }
+ }
+ .padding(self.spacing.lg)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ .background {
+ self.theme.palette.contentBackground
+ if isPreview && !self.reduceTransparency {
+ Color.blue.opacity(self.isDark ? 0.16 : 0.06)
+ }
+ }
+ .clipShape(RoundedRectangle(cornerRadius: self.theme.metrics.corners.md))
+ .overlay {
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md)
+ .strokeBorder(isPreview ? Color.cyan : Color.blue.opacity(0.3), lineWidth: isPreview ? 2 : 1)
+ }
+ .shadow(color: isPreview && !self.reduceTransparency ? Color.blue.opacity(0.24) : .clear, radius: 8)
+ .contentShape(RoundedRectangle(cornerRadius: self.theme.metrics.corners.md))
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Preview \(model.rawValue)")
+ .accessibilityValue(isPreview ? "Previewed" : "")
+ .accessibilityHint("Browse without changing the selected model")
+ }
+
+ private var externalProviders: some View {
+ VStack(alignment: .leading, spacing: self.spacing.md) {
+ HStack {
+ Text("Other providers")
+ .font(self.theme.typography.sectionTitle)
+ Spacer()
+ Button("Add Provider", systemImage: "plus") { self.panel = .add }
+ .fluidButton(.secondary, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ }
+ VStack(spacing: 0) {
+ if self.showsExamples {
+ self.providerRow("OpenAI", subtitle: "Cloud provider", image: "Provider_OpenAI")
+ Divider().padding(.leading, 60)
+ self.providerRow("Ollama", subtitle: "Local provider", image: "Provider_Ollama")
+ } else {
+ HStack(spacing: self.spacing.md) {
+ Image(systemName: "square.stack.3d.up")
+ .foregroundStyle(self.supportingText)
+ Text("No other providers added")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.supportingText)
+ Spacer()
+ }
+ .padding(self.spacing.xl)
+ }
+ }
+ .background(self.theme.palette.cardBackground)
+ .clipShape(RoundedRectangle(cornerRadius: self.theme.metrics.corners.md))
+ }
+ }
+
+ private func providerRow(_ name: String, subtitle: String, image: String) -> some View {
+ HStack(spacing: self.spacing.md) {
+ Image(image).resizable().scaledToFit().frame(width: 26, height: 26)
+ .padding(5)
+ .background(Color.white, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))
+ .accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: self.spacing.xs) {
+ Text(name).font(self.theme.typography.bodySmallStrong)
+ Text(subtitle).font(self.theme.typography.caption).foregroundStyle(self.supportingText)
+ }
+ Spacer()
+ Button("Manage") { self.panel = .external }
+ .fluidButton(.secondary, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ .accessibilityLabel("Manage \(name)")
+ }
+ .padding(self.spacing.lg)
+ }
+
+ private func inspector(_ panel: AIProvidersPreviewPanel) -> some View {
+ VStack(alignment: .leading, spacing: self.spacing.xl) {
+ HStack {
+ Text(panel == .add ? "Add Provider" : panel == .compare ? "Compare models" : "Manage")
+ .font(self.theme.typography.sectionTitle)
+ Spacer()
+ Button { self.panel = nil } label: { Image(systemName: "xmark") }
+ .fluidButton(.secondary, size: .small)
+ .fixedSize(horizontal: true, vertical: false)
+ .accessibilityLabel("Close panel")
+ .focused(self.$panelCloseFocused)
+ .keyboardShortcut(.cancelAction)
+ }
+ Divider()
+ if panel == .add {
+ ForEach(["OpenAI", "Anthropic", "Ollama", "Custom provider"], id: \.self) { provider in
+ Label(provider, systemImage: "plus.circle")
+ .font(self.theme.typography.body)
+ }
+ } else if panel == .compare {
+ ForEach(Model.allCases) { model in
+ VStack(alignment: .leading, spacing: self.spacing.sm) {
+ Text(model.rawValue).font(self.theme.typography.sectionTitle)
+ Text(model.detail).font(self.theme.typography.bodySmall)
+ }
+ }
+ } else {
+ Text(panel == .manage ? "Fluid Intelligence" : "Provider settings")
+ .font(self.theme.typography.title)
+ Text(panel == .manage ? "\(self.selected.rawValue) · On-device" : "Connection · Models · Preferences")
+ .font(self.theme.typography.bodySmall)
+ .foregroundStyle(self.supportingText)
+ Divider()
+ ForEach(panel == .manage ? ["Model downloads", "Backend & context", "Startup preferences", "Storage & maintenance"] : ["Connection details", "Model selection", "Verification"], id: \.self) { label in
+ Text(label).font(self.theme.typography.body)
+ }
+ }
+ Spacer()
+ Text("Panel layout preview. Settings and connections are not wired yet.")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.supportingText)
+ }
+ .padding(self.spacing.xl)
+ .frame(width: 290)
+ .frame(maxHeight: .infinity)
+ .background(self.theme.palette.elevatedCardBackground)
+ .overlay(alignment: .leading) {
+ Rectangle().fill(self.theme.palette.separator).frame(width: 1)
+ }
+ .onAppear { self.panelCloseFocused = true }
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/AISettingsScreens.swift b/Sources/Fluid/UI/AISettings/AISettingsScreens.swift
index 565cc8b2..3480c6f4 100644
--- a/Sources/Fluid/UI/AISettings/AISettingsScreens.swift
+++ b/Sources/Fluid/UI/AISettings/AISettingsScreens.swift
@@ -34,6 +34,7 @@ struct AIEnhancementSettingsScreen: View {
@Binding var shortcutRecordingMessage: String?
@StateObject private var viewModel: AIEnhancementSettingsViewModel
+ @StateObject private var privateAIController: PrivateAISettingsController
init(
menuBarManager: MenuBarManager,
@@ -47,11 +48,13 @@ struct AIEnhancementSettingsScreen: View {
_selectedConfigurationSection = selectedConfigurationSection
_activeShortcutRecordingTarget = activeShortcutRecordingTarget
_shortcutRecordingMessage = shortcutRecordingMessage
- _viewModel = StateObject(wrappedValue: AIEnhancementSettingsViewModel(
+ let enhancementModel = AIEnhancementSettingsViewModel(
settings: SettingsStore.shared,
menuBarManager: menuBarManager,
promptTest: DictationPromptTestCoordinator.shared
- ))
+ )
+ _viewModel = StateObject(wrappedValue: enhancementModel)
+ _privateAIController = StateObject(wrappedValue: PrivateAISettingsController(viewModel: enhancementModel))
}
var body: some View {
@@ -59,6 +62,7 @@ struct AIEnhancementSettingsScreen: View {
VStack(alignment: .leading, spacing: 14) {
AIEnhancementSettingsView(
viewModel: self.viewModel,
+ privateAIController: self.privateAIController,
settings: self.viewModel.settings,
promptTest: self.viewModel.promptTest,
theme: self.theme,
diff --git a/Sources/Fluid/UI/AISettings/AddProviderSheet.swift b/Sources/Fluid/UI/AISettings/AddProviderSheet.swift
new file mode 100644
index 00000000..5432abb7
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/AddProviderSheet.swift
@@ -0,0 +1,164 @@
+import SwiftUI
+
+struct AddProviderSheet<Logo: View>: View {
+ @Environment(\.dismiss) private var dismiss
+ @Environment(\.theme) private var theme
+ @ObservedObject var viewModel: AIEnhancementSettingsViewModel
+ @ViewBuilder let logo: (String, String) -> Logo
+ @State private var draft = ProviderSetupDraft()
+ @State private var isEditing = false
+ @State private var saveFailed = false
+
+ private var providers: [AIEnhancementSettingsViewModel.ProviderItemData] {
+ let added = Set(self.viewModel.cachedAddedProviderItems.map(\.id))
+ return self.viewModel.cachedProviderItems.filter {
+ $0.isBuiltIn && $0.id != PrivateAIProviderFeature.shared.providerID && !added.contains($0.id)
+ }
+ }
+
+ var body: some View {
+ FluidGlassControlGroup {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ HStack {
+ if self.isEditing && !self.draft.providerID.isEmpty {
+ self.logo(self.draft.providerID, self.draft.name)
+ } else {
+ Image(systemName: "square.stack.3d.up")
+ .font(.system(size: 26)).foregroundStyle(FluidBrandColors.blue)
+ .frame(width: 48, height: 48)
+ }
+ VStack(alignment: .leading, spacing: 6) {
+ Text(self.isEditing ? self.draft.name : "Add a provider").font(self.theme.typography.title)
+ Text(self.isEditing ? "Add connection details to get started." : "Your preferred models. Connected to FluidVoice.")
+ .font(self.theme.typography.body).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ Button("Cancel") { self.dismiss() }
+ .keyboardShortcut(.cancelAction)
+ .fluidGlassAction()
+ }
+ Divider()
+ if self.isEditing {
+ self.form
+ } else {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 20) {
+ Text("Choose a provider").font(self.theme.typography.bodyStrong)
+ LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 12) {
+ ForEach(self.providers) { provider in
+ Button {
+ self.draft = ProviderSetupDraft(
+ providerID: provider.id,
+ name: provider.name,
+ baseURL: ModelRepository.shared.defaultBaseURL(for: provider.id)
+ )
+ self.isEditing = true
+ } label: {
+ HStack(spacing: 14) {
+ self.logo(provider.id, provider.name).accessibilityHidden(true)
+ VStack(alignment: .leading, spacing: 5) {
+ Text(provider.name).font(self.theme.typography.bodyStrong)
+ Text(["ollama", "lmstudio"].contains(provider.id) ? "Local connection" : "Connect with an API key")
+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ Image(systemName: "chevron.right").accessibilityHidden(true)
+ }
+ .padding(16).frame(maxWidth: .infinity, minHeight: 76, alignment: .leading)
+ .contentShape(RoundedRectangle(cornerRadius: 16))
+ }
+ .buttonStyle(ProviderChoiceStyle())
+ }
+ Button {
+ self.draft = ProviderSetupDraft(name: "Custom Provider")
+ self.isEditing = true
+ } label: {
+ HStack(spacing: 14) {
+ Image(systemName: "server.rack").font(.system(size: 24))
+ .foregroundStyle(FluidBrandColors.blue).frame(width: 38, height: 38)
+ VStack(alignment: .leading, spacing: 5) {
+ Text("Custom Provider").font(self.theme.typography.bodyStrong)
+ Text("Your service or server")
+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ Image(systemName: "plus").foregroundStyle(FluidBrandColors.blue)
+ }.padding(16).contentShape(RoundedRectangle(cornerRadius: 16))
+ }
+ .buttonStyle(ProviderChoiceStyle())
+ }
+ }
+ }
+ Label("Adding a provider won’t change your current dictation setup.", systemImage: "info.circle")
+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ }
+ }
+ .padding(28)
+ .frame(width: 720, height: 650)
+ .background(self.theme.palette.windowBackground)
+ }
+
+ private var form: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 20) {
+ FluidManagementGroup(title: "Connection details") {
+ if self.draft.providerID.isEmpty {
+ self.field("Name") { TextField("Custom Provider", text: self.$draft.name) }
+ self.field("Server URL") { TextField("https://your-server.com/v1", text: self.$draft.baseURL) }
+ }
+ self.field(self.draft.requiresAPIKey ? "API key" : "API key · Optional") {
+ SecureField("Enter API key", text: self.$draft.apiKey)
+ }
+ if let website = ModelRepository.shared.providerWebsiteURL(for: self.draft.providerID), let url = URL(string: website.url) {
+ Link(destination: url) { Label(website.label, systemImage: "arrow.up.right").font(self.theme.typography.caption) }
+ }
+ }
+ FluidManagementGroup(title: "Model") {
+ self.field("Model name · Optional") { TextField("Enter a model ID", text: self.$draft.model) }
+ Text(self.draft.providerID.isEmpty ? "Add a model now, or fetch models from Manage later." : "Leave blank to start with the provider’s default models.")
+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Label("Your current dictation setup stays unchanged.", systemImage: "info.circle")
+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ }
+ .textFieldStyle(.roundedBorder)
+ if self.saveFailed {
+ Text("Couldn’t save this provider. Check Keychain access and try again.")
+ .font(self.theme.typography.caption).foregroundStyle(.red)
+ }
+ Spacer()
+ HStack {
+ Button("Back") { self.isEditing = false; self.saveFailed = false }
+ .fluidGlassAction()
+ Spacer()
+ Button("Add Provider") {
+ if self.viewModel.addProvider(self.draft) { self.dismiss() } else { self.saveFailed = true }
+ }
+ .keyboardShortcut(.defaultAction)
+ .fluidGlassAction(prominent: true)
+ .disabled(!self.draft.isValid || self.viewModel.isTestingConnection || self.viewModel.isFetchingModels)
+ }
+ }
+ }
+
+ private func field<Control: View>(_ title: String, @ViewBuilder control: () -> Control) -> some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(title).font(self.theme.typography.bodyStrong)
+ control().textFieldStyle(.roundedBorder).controlSize(.large).accessibilityLabel(title)
+ }
+ }
+}
+
+private struct ProviderChoiceStyle: ButtonStyle {
+ @Environment(\.theme) private var theme
+ func makeBody(configuration: Configuration) -> some View {
+ configuration.label.foregroundStyle(self.theme.palette.primaryText)
+ .background(
+ configuration.isPressed ? FluidBrandColors.blue.opacity(0.12) : self.theme.palette.cardBackground,
+ in: RoundedRectangle(cornerRadius: 16, style: .continuous)
+ )
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/DictationDefaultProvider.swift b/Sources/Fluid/UI/AISettings/DictationDefaultProvider.swift
new file mode 100644
index 00000000..8db6c32f
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/DictationDefaultProvider.swift
@@ -0,0 +1,29 @@
+import Foundation
+
+/// Identifies the main shortcut's provider without reading credentials or app-specific overrides.
+enum DictationDefaultProvider {
+ static func setupIssue(requiresAPIKey: Bool, hasAPIKey: Bool, hasModel: Bool, isVerified: Bool, verificationFailed: Bool) -> String? {
+ if requiresAPIKey, !hasAPIKey { return "API key missing" }
+ if !hasModel { return "Choose a model" }
+ if verificationFailed { return "Verification failed" }
+ // A test is optional; only missing setup prevents use.
+ return nil
+ }
+
+ static func providerID(
+ selection: SettingsStore.DictationPromptSelection,
+ configuration: SettingsStore.DictationPromptConfiguration,
+ selectedProviderID: String,
+ privateProviderID: String
+ ) -> String {
+ if selection == .off { return "" }
+ if selection == .privateAI { return privateProviderID }
+ let providerID = configuration.providerID.trimmingCharacters(in: .whitespacesAndNewlines)
+ let model = configuration.modelName.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !providerID.isEmpty, !model.isEmpty { return providerID }
+ if selection == .default, selectedProviderID == privateProviderID,
+ providerID.isEmpty, model.isEmpty { return privateProviderID }
+ let fallback = selectedProviderID.trimmingCharacters(in: .whitespacesAndNewlines)
+ return fallback == privateProviderID ? "" : fallback
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift b/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift
new file mode 100644
index 00000000..9c9d80ce
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift
@@ -0,0 +1,192 @@
+import SwiftUI
+
+/// Retains controller ownership; card inspection never selects or loads a model.
+struct FluidIntelligenceLiveSection<Management: View>: View {
+ @Environment(\.theme) private var theme
+ @ObservedObject var controller: PrivateAISettingsController
+ let backendID: String
+ let isPrimary: Bool
+ let isVerified: Bool
+ let makePrimary: () -> Void
+ @ViewBuilder let management: () -> Management
+ @State private var showsManagement = false
+ @State private var pendingDeletion: PrivateAIRegisteredModel?
+ @State private var showsDeleteConfirmation = false
+ @State private var showsVerificationResult = false
+ @State private var verificationError: String?
+ @State private var verifiedModelName = ""
+ @State private var snapshots: [String: ModelFiles] = [:]
+ @State private var recommendedModelID: String?
+
+ private struct ModelFiles: Sendable {
+ let installed: Bool
+ let removable: Bool
+ }
+
+ private struct ReadIdentity: Equatable {
+ let selectedID: String
+ let backendID: String
+ let busy: Bool
+ }
+
+ private var models: [PrivateAIRegisteredModel] {
+ PrivateAIModelRegistry.modelIDs().compactMap { PrivateAIModelRegistry.model(id: $0) }
+ }
+
+ private var readIdentity: ReadIdentity {
+ ReadIdentity(selectedID: self.controller.privateAISelectedModelID, backendID: self.backendID, busy: self.controller.isBusy)
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 20) {
+ HStack {
+ VStack(alignment: .leading, spacing: 4) {
+ Text("Fluid Intelligence").font(self.theme.typography.title).fontWeight(.semibold)
+ Text("Polish your words. Privately, on your Mac.")
+ .font(self.theme.typography.body).foregroundStyle(self.theme.palette.secondaryText)
+ }
+ Spacer()
+ ProviderDefaultButton(isCurrent: self.isPrimary, isEnabled: self.isVerified && !self.controller.isBusy, action: self.makePrimary)
+ Button("Manage", systemImage: "slider.horizontal.3") { self.showsManagement = true }
+ .fluidGlassAction()
+ }
+ FluidIntelligenceModelCarousel(
+ models: self.models,
+ previewID: self.controller.previewModelID,
+ selectedID: self.controller.privateAISelectedModelID,
+ recommendedModelID: self.recommendedModelID,
+ onBrowse: self.controller.previewModel
+ ) { model in
+ self.cardControls(model)
+ }
+ }
+ .padding(20)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: AppTheme.Metrics.Showcase.cardRadius))
+ .task {
+ let recommendation = await Task.detached(priority: .utility) {
+ PrivateAIModelRecommendation.currentModelID
+ }.value
+ guard !Task.isCancelled else { return }
+ self.recommendedModelID = recommendation
+ }
+ .task(id: self.readIdentity) {
+ self.snapshots = [:]
+ guard !self.controller.isBusy else { return }
+ let identity = self.readIdentity
+ let models = self.models
+ let files = await Task.detached(priority: .utility) {
+ Dictionary(uniqueKeysWithValues: models.map { model in
+ (model.id, ModelFiles(
+ installed: PrivateAIIntegrationService.isModelInstalled(model),
+ removable: PrivateAIIntegrationService.canRemoveInstalledModel(model)
+ ))
+ })
+ }.value
+ guard !Task.isCancelled, identity == self.readIdentity else { return }
+ self.snapshots = files
+ for model in models {
+ self.controller.refreshPrivateAIModelUpdateStatus(model)
+ }
+ }
+ .alert("Delete downloaded model?", isPresented: self.$showsDeleteConfirmation, presenting: self.pendingDeletion) { model in
+ Button("Cancel", role: .cancel) { self.pendingDeletion = nil }
+ Button("Delete model", role: .destructive) {
+ self.controller.deletePrivateAIModel(model)
+ self.pendingDeletion = nil
+ }
+ } message: { model in
+ Text("This removes \(model.displayName) from your Mac. You’ll need to download it again to use it. Your dictation history and shortcut settings won’t change.")
+ }
+ .alert(self.verificationError == nil ? "Model verified" : "Verification failed", isPresented: self.$showsVerificationResult) {
+ Button("OK", role: .cancel) {}
+ } message: {
+ Text(self.verificationError ?? "\(self.verifiedModelName) is ready to use on your Mac.")
+ }
+ .sheet(isPresented: self.$showsManagement) {
+ FluidManagementSheet(title: "Manage Fluid Intelligence", subtitle: "These settings apply to all Fluid Intelligence models.", symbol: "slider.horizontal.3", close: { self.showsManagement = false }) {
+ self.management()
+ FluidManagementGroup(title: "Storage") {
+ FluidManagementRow(title: "Downloaded models", detail: "View the model files stored on your Mac.") {
+ Button("Open models folder", systemImage: "folder", action: self.controller.revealPrivateAIModelFolder)
+ .fluidGlassAction()
+ }
+ }
+ }
+ }
+ }
+
+ private func cardControls(_ model: PrivateAIRegisteredModel) -> some View {
+ let files = self.snapshots[model.id]
+ let selected = model.id == self.controller.privateAISelectedModelID
+ let active = selected && self.isVerified && self.controller.privateAILoadState.isLoaded(model.id)
+ let realUpdate = files?.installed == true && self.controller.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailable
+ return VStack(alignment: .leading, spacing: 8) {
+ Divider().overlay(self.theme.palette.cardBorder)
+ if files?.installed == false, let bytes = model.artifact.byteCount, bytes > 0 {
+ Text("Download · ≈\(ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file))")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ if self.controller.privateAILoadState.isDownloading(model.id) {
+ Text(PrivateAIModelDownloadProgressText.detailText(for: self.controller.privateAILoadState.downloadProgress(for: model.id)))
+ .font(self.theme.typography.caption).lineLimit(2)
+ } else if self.controller.privateAILoadState.isLoading(model.id) {
+ Text("Preparing model…").font(self.theme.typography.caption)
+ } else if let failure = self.controller.privateAILoadState.failureMessage(for: model.id) {
+ Text(failure).font(self.theme.typography.caption).foregroundStyle(.red).lineLimit(2).help(failure)
+ }
+ HStack(spacing: 8) {
+ if active {
+ Label("Active", systemImage: "checkmark.circle.fill")
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(Color.fluidGreen)
+ .frame(minWidth: 76, minHeight: 24)
+ .accessibilityLabel("Active model")
+ } else {
+ Button {
+ guard let files else { return }
+ self.controller.previewModel(model.id)
+ self.controller.usePreviewModel(isInstalled: files.installed, onReady: {})
+ } label: {
+ Text(files?.installed == false ? "Download" : "Activate")
+ .font(self.theme.typography.bodyStrong)
+ .frame(minWidth: 76, minHeight: 24)
+ }
+ .fluidGlassAction(prominent: true)
+ .disabled(self.controller.isBusy || files == nil || (files?.installed == false && !model.canDownload))
+ }
+ Spacer(minLength: 0)
+ FluidModelMetrics(modelID: model.id)
+ Menu {
+ if realUpdate {
+ Button("Update model") {
+ self.controller.updatePrivateAIModel(model)
+ }
+ .disabled(!selected || self.controller.isBusy)
+ }
+ Button("Verify model") {
+ self.controller.verifyPrivateAIConnection(model, onCompletion: { error in
+ self.verifiedModelName = model.displayName.replacingOccurrences(of: "Fluid-1", with: "Fluid 1")
+ self.verificationError = error
+ self.showsVerificationResult = true
+ })
+ }
+ .disabled(!selected || files?.installed != true || self.controller.isBusy)
+ if !selected {
+ Text("Activate this model to manage it")
+ }
+ Divider()
+ Button("Delete model…", role: .destructive) {
+ self.pendingDeletion = model
+ self.showsDeleteConfirmation = true
+ }
+ .disabled(!selected || files?.removable != true || self.controller.isBusy)
+ } label: {
+ Image(systemName: "ellipsis").frame(width: 32, height: 32)
+ }
+ .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()
+ .accessibilityLabel("Options for \(model.displayName)")
+ }
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/FluidIntelligenceModelCarousel.swift b/Sources/Fluid/UI/AISettings/FluidIntelligenceModelCarousel.swift
new file mode 100644
index 00000000..8aebdc3a
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/FluidIntelligenceModelCarousel.swift
@@ -0,0 +1,156 @@
+import SwiftUI
+
+/// Pure presentation: the only emitted action is browsing, never activation or persistence.
+struct FluidIntelligenceModelCarousel<Controls: View>: View {
+ @Environment(\.theme) private var theme
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.colorSchemeContrast) private var contrast
+ let models: [PrivateAIRegisteredModel]
+ let previewID: String
+ let selectedID: String
+ var recommendedModelID: String? = nil
+ let onBrowse: (String) -> Void
+ @ViewBuilder let controls: (PrivateAIRegisteredModel) -> Controls
+ @State private var upcomingPreviewID: String?
+
+ private var spacing: AppTheme.Metrics.Spacing { self.theme.metrics.spacing }
+ private var itemIDs: [String] { self.models.map(\.id) + PrivateAIUpcomingModel.allCases.map(\.id) }
+ private var displayedPreviewID: String { self.upcomingPreviewID ?? self.previewID }
+
+ var body: some View {
+ VStack(spacing: self.spacing.sm) {
+ GeometryReader { geometry in
+ let cardWidth = min(AppTheme.Metrics.Showcase.cardMaxWidth, geometry.size.width * 0.44)
+ let sideWidth = min(AppTheme.Metrics.Showcase.sideCardMaxWidth, max(60, (geometry.size.width - cardWidth - self.spacing.md * 2 - 80) / 2))
+ let stride = cardWidth / 2 + sideWidth / 2 + self.spacing.md
+ ZStack {
+ ForEach(self.itemIDs.filter { abs(self.carouselPosition($0)) <= 1 }, id: \.self) { id in
+ let position = self.carouselPosition(id)
+ Group {
+ if let model = self.models.first(where: { $0.id == id }) {
+ FluidModelShowcaseCard(
+ model: model,
+ isPreview: position == 0,
+ isSelected: self.selectedID == model.id,
+ compact: position != 0,
+ isRecommended: self.recommendedModelID == model.id,
+ browse: { self.browse(id) }
+ )
+ } else if let upcoming = PrivateAIUpcomingModel(rawValue: id) {
+ self.upcomingCard(upcoming, compact: position != 0)
+ }
+ }
+ .overlay(alignment: .bottom) {
+ if position == 0, let model = self.models.first(where: { $0.id == id }) {
+ self.controls(model).padding(.horizontal, 16).padding(.bottom, 16)
+ }
+ }
+ .frame(width: position == 0 ? cardWidth : sideWidth, height: AppTheme.Metrics.Showcase.cardHeight)
+ .saturation(position == 0 ? 1 : 0.12)
+ .opacity(position == 0 || self.contrast == .increased ? 1 : 0.65)
+ .scaleEffect(position == 0 ? 1 : 0.90)
+ .offset(x: CGFloat(position) * stride)
+ .zIndex(position == 0 ? 1 : 0)
+ }
+ }
+ .frame(width: geometry.size.width, height: geometry.size.height)
+ .clipped()
+ .overlay(alignment: .leading) { self.carouselArrow(forward: false) }
+ .overlay(alignment: .trailing) { self.carouselArrow(forward: true) }
+ .simultaneousGesture(DragGesture(minimumDistance: 24).onEnded { value in
+ guard abs(value.translation.width) > abs(value.translation.height) else { return }
+ self.advanceCarousel(forward: value.translation.width < 0)
+ })
+ }
+ .frame(height: AppTheme.Metrics.Showcase.stageHeight)
+
+ HStack(spacing: self.spacing.xs) {
+ ForEach(self.itemIDs, id: \.self) { id in
+ Button { self.browse(id) } label: {
+ Circle()
+ .fill(self.displayedPreviewID == id ? FluidBrandColors.blue : self.theme.palette.secondaryText.opacity(0.4))
+ .frame(width: self.displayedPreviewID == id ? 10 : 7, height: self.displayedPreviewID == id ? 10 : 7)
+ .frame(width: 24, height: 24)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Show \(self.title(for: id))")
+ .accessibilityValue(self.displayedPreviewID == id ? "Current page" : "")
+ }
+ }
+ }
+ .onChange(of: self.previewID) { _, _ in self.upcomingPreviewID = nil }
+ }
+
+ private func carouselPosition(_ id: String) -> Int {
+ PrivateAIModelCarouselNavigation.position(of: id, in: self.itemIDs, current: self.displayedPreviewID)
+ }
+
+ private func browse(_ id: String) {
+ withAnimation(self.reduceMotion ? nil : .easeInOut(duration: 0.22)) {
+ if PrivateAIUpcomingModel(rawValue: id) != nil {
+ self.upcomingPreviewID = id
+ } else if self.models.contains(where: { $0.id == id }) {
+ self.upcomingPreviewID = nil
+ self.onBrowse(id)
+ }
+ }
+ }
+
+ private func advanceCarousel(forward: Bool) {
+ guard let id = PrivateAIModelCarouselNavigation.next(in: self.itemIDs, current: self.displayedPreviewID, forward: forward) else { return }
+ self.browse(id)
+ }
+
+ private func carouselArrow(forward: Bool) -> some View {
+ Button { self.advanceCarousel(forward: forward) } label: {
+ Image(systemName: forward ? "chevron.right" : "chevron.left")
+ .font(self.theme.typography.sectionTitle)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .frame(width: 34, height: 34)
+ .contentShape(Circle())
+ }
+ .fluidGlassAction(circular: true)
+ .accessibilityLabel(forward ? "Next model" : "Previous model")
+ .disabled(self.itemIDs.count < 2)
+ }
+
+ private func title(for id: String) -> String {
+ PrivateAIUpcomingModel(rawValue: id)?.title
+ ?? self.models.first(where: { $0.id == id })?.displayName.replacingOccurrences(of: "Fluid-1", with: "Fluid 1")
+ ?? id
+ }
+
+ private func upcomingCard(_ model: PrivateAIUpcomingModel, compact: Bool) -> some View {
+ Button { self.browse(model.id) } label: {
+ VStack(alignment: .leading, spacing: self.spacing.md) {
+ Text("Coming soon")
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ Text(model.title)
+ .font(compact ? self.theme.typography.sectionTitle : self.theme.typography.title)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ Text("Not available yet")
+ .font(self.theme.typography.body)
+ .foregroundStyle(self.theme.palette.tertiaryText)
+ Spacer(minLength: 0)
+ Divider()
+ Label("Coming soon", systemImage: "clock")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ }
+ .padding(self.spacing.xl)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: AppTheme.Metrics.Showcase.cardRadius))
+ .overlay {
+ RoundedRectangle(cornerRadius: AppTheme.Metrics.Showcase.cardRadius)
+ .strokeBorder(self.theme.palette.cardBorder, lineWidth: 1)
+ }
+ .contentShape(RoundedRectangle(cornerRadius: AppTheme.Metrics.Showcase.cardRadius))
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Preview \(model.title), coming soon")
+ .accessibilityHint("Preview only. This model cannot be activated or downloaded.")
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/FluidModelShowcaseCard.swift b/Sources/Fluid/UI/AISettings/FluidModelShowcaseCard.swift
new file mode 100644
index 00000000..07046f3b
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/FluidModelShowcaseCard.swift
@@ -0,0 +1,188 @@
+import SwiftUI
+
+/// Presentation only: model browsing is injected by the carousel.
+struct FluidModelShowcaseCard: View {
+ @Environment(\.theme) private var theme
+ @Environment(\.colorScheme) private var colorScheme
+ @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @Environment(\.colorSchemeContrast) private var contrast
+ @State private var hovered = false
+ @State private var showsInfo = false
+ let model: PrivateAIRegisteredModel
+ let isPreview: Bool
+ let isSelected: Bool
+ let compact: Bool
+ var isRecommended = false
+ let browse: () -> Void
+
+ private var shape: RoundedRectangle {
+ RoundedRectangle(cornerRadius: AppTheme.Metrics.Showcase.cardRadius, style: .continuous)
+ }
+
+ var body: some View {
+ let presentation = PrivateAIModelPresentation.forModel(id: self.model.id)
+ Button(action: self.browse) {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ Color.clear.frame(height: 20)
+ .overlay(alignment: .leading) {
+ if self.isRecommended {
+ Text(self.compact ? "Recommended" : "Recommended for your Mac")
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(FluidBrandColors.blue)
+ .lineLimit(1).minimumScaleFactor(0.8)
+ .padding(.trailing, 24)
+ .help("Based on your Mac’s RAM. You can choose either model.")
+ }
+ }
+ HStack(spacing: 8) {
+ Text(self.model.displayName.replacingOccurrences(of: "Fluid-1", with: "Fluid 1"))
+ .font(self.compact ? self.theme.typography.sectionTitle : self.theme.typography.title)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .lineLimit(2).minimumScaleFactor(0.85)
+ if self.isSelected {
+ Image(systemName: "checkmark.circle.fill")
+ .font(.system(size: 18, weight: .semibold))
+ .foregroundStyle(FluidBrandColors.blue)
+ .accessibilityLabel("Selected")
+ }
+ }
+ ZStack(alignment: .topLeading) {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ Text(presentation.summary)
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.theme.palette.primaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ Text(presentation.useCase)
+ .font(self.theme.typography.body)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .fixedSize(horizontal: false, vertical: true)
+ .lineSpacing(3)
+ }
+ .opacity(self.showsInfo ? 0 : 1)
+ .accessibilityHidden(self.showsInfo)
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ self.infoRow("Languages", value: presentation.language)
+ if let bytes = self.model.artifact.byteCount, bytes > 0 {
+ self.infoRow("Download size", value: "≈\(ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file))")
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .opacity(self.showsInfo ? 1 : 0)
+ .accessibilityHidden(!self.showsInfo)
+ }
+ .animation(self.reduceMotion ? nil : .easeInOut(duration: 0.16), value: self.showsInfo)
+ Spacer(minLength: self.theme.metrics.spacing.sm)
+ // Separate sibling controls are overlaid by the carousel; never nest buttons.
+ Color.clear.frame(height: 64)
+ }
+ .padding(self.theme.metrics.spacing.xl)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
+ .background {
+ self.shape.fill(self.colorScheme == .dark ? Color(red: 0.025, green: 0.04, blue: 0.095) : self.theme.palette.elevatedCardBackground)
+ if !self.reduceTransparency {
+ self.shape.fill(LinearGradient(
+ colors: [FluidBrandColors.blue.opacity(self.isPreview ? 0.16 : 0.08), .clear],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ ))
+ }
+ }
+ .overlay {
+ self.shape.strokeBorder(
+ self.isPreview ? FluidBrandColors.blue.opacity(self.contrast == .increased ? 1 : 0.5) : self.theme.palette.cardBorder,
+ lineWidth: self.contrast == .increased ? 2 : 1
+ )
+ }
+ .shadow(color: .black.opacity(self.colorScheme == .dark ? 0.28 : 0.08), radius: self.isPreview ? 12 : 4, y: self.isPreview ? 8 : 2)
+ .brightness(self.hovered ? 0.01 : 0)
+ .contentShape(self.shape)
+ }
+ .buttonStyle(.plain)
+ .onHover { self.hovered = $0 }
+ .animation(self.reduceMotion ? nil : .easeOut(duration: 0.12), value: self.hovered)
+ .accessibilityLabel("Preview \(self.model.displayName.replacingOccurrences(of: "Fluid-1", with: "Fluid 1"))")
+ .accessibilityValue([self.isPreview ? "Previewed" : "", self.isRecommended ? "Recommended for your Mac" : ""].filter { !$0.isEmpty }.joined(separator: ", "))
+ .accessibilityHint(self.showsInfo ? self.infoAccessibilityDescription : "\(presentation.summary). \(presentation.useCase) Browse without changing the selected model.")
+ .overlay(alignment: .topTrailing) {
+ // Sibling to the browse button: opening details never selects or activates a model.
+ Button { self.showsInfo.toggle() } label: {
+ Image(systemName: self.showsInfo ? "xmark.circle" : "info.circle")
+ .font(.system(size: 19, weight: .regular))
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .frame(width: 32, height: 32)
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .help(self.showsInfo ? "Close model information" : "About \(self.model.displayName)")
+ .accessibilityLabel(self.showsInfo ? "Close information for \(self.model.displayName)" : "About \(self.model.displayName)")
+ .accessibilityValue(self.showsInfo ? "Expanded" : "Collapsed")
+ .padding(14)
+ }
+ }
+
+ private func infoRow(_ title: String, value: String) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: self.theme.metrics.spacing.sm) {
+ Text(title).foregroundStyle(self.theme.palette.secondaryText)
+ Spacer(minLength: 0)
+ Text(value).foregroundStyle(self.theme.palette.primaryText)
+ .multilineTextAlignment(.trailing)
+ }
+ .font(self.theme.typography.caption)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ private var infoAccessibilityDescription: String {
+ let language = PrivateAIModelPresentation.forModel(id: self.model.id).language
+ guard let bytes = self.model.artifact.byteCount, bytes > 0 else { return "Languages: \(language)" }
+ return "Languages: \(language). Download size: approximately \(ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file))."
+ }
+}
+
+struct FluidModelMetrics: View {
+ @Environment(\.theme) private var theme
+ let modelID: String
+
+ var body: some View {
+ let presentation = PrivateAIModelPresentation.forModel(id: self.modelID)
+ if let intelligence = presentation.intelligence, let speed = presentation.speed {
+ VStack(spacing: self.theme.metrics.spacing.xs) {
+ FluidModelMetric(label: "Intelligence", value: intelligence, tint: FluidBrandColors.blue, compact: true)
+ FluidModelMetric(label: "Speed", value: speed, tint: .teal, compact: true)
+ }
+ .frame(width: AppTheme.Metrics.Showcase.compactMetricWidth)
+ .help("Illustrative design preview — not benchmark scores")
+ }
+ }
+}
+
+/// Five bounded static segments: no work beyond rendering immutable preview values.
+private struct FluidModelMetric: View {
+ @Environment(\.theme) private var theme
+ let label: String
+ let value: Int
+ let tint: Color
+ let compact: Bool
+
+ var body: some View {
+ HStack(spacing: self.theme.metrics.spacing.xs) {
+ Text(self.label)
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ .lineLimit(1)
+ .minimumScaleFactor(0.8)
+ .frame(width: self.compact ? 58 : 64, alignment: .leading)
+ HStack(spacing: 3) {
+ ForEach(1...5, id: \.self) { step in
+ Capsule()
+ .fill(step <= self.value ? self.tint : self.theme.palette.secondaryText.opacity(0.25))
+ .frame(maxWidth: .infinity)
+ .frame(height: 3)
+ }
+ }
+ }
+ .allowsHitTesting(false)
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel("\(self.label): illustrative level \(self.value) of 5, not a benchmark score")
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/PrivateAIModelPresentation.swift b/Sources/Fluid/UI/AISettings/PrivateAIModelPresentation.swift
new file mode 100644
index 00000000..9a65bf26
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/PrivateAIModelPresentation.swift
@@ -0,0 +1,48 @@
+import Foundation
+
+/// A RAM-based suggestion only; never selects, loads, downloads, or persists a model.
+enum PrivateAIModelRecommendation {
+ // First accessed from the settings background task; physical RAM cannot change during this process.
+ static let currentModelID = modelID(physicalMemory: ProcessInfo.processInfo.physicalMemory)
+
+ static func modelID(physicalMemory: UInt64) -> String {
+ physicalMemory >= 16 * 1024 * 1024 * 1024 ? "fluid-1-mini-96k-dflash" : "fluid-1-pico-96k-dflash"
+ }
+}
+
+/// UI-only previews. These identifiers are never registered with a runtime or download provider.
+enum PrivateAIUpcomingModel: String, CaseIterable, Identifiable {
+ case quad = "preview-upcoming-quad"
+ case multilingual = "preview-upcoming-multilingual"
+
+ var id: String { self.rawValue }
+ var title: String {
+ switch self {
+ case .quad: "Fluid 1 Quad"
+ case .multilingual: "Fluid 1.1 Multilingual"
+ }
+ }
+}
+
+/// Customer-facing copy only. Registry IDs, downloads, and runtime settings remain authoritative.
+struct PrivateAIModelPresentation {
+ let summary: String
+ let useCase: String
+ var language: String = "On-device"
+ // Illustrative design-preview values, not measured benchmark scores.
+ var intelligence: Int?
+ var speed: Int?
+
+ static func forModel(id: String) -> Self {
+ switch id {
+ case "fluid-1-pico-96k-dflash":
+ Self(summary: "Smallest & fastest", useCase: "Everyday dictation with basic cleanup and formatting.", language: "English only", intelligence: 2, speed: 5)
+ case "fluid-1-mini-96k-dflash":
+ Self(summary: "More capable", useCase: "Better structure, formatting and corrections.", language: "English only", intelligence: 4, speed: 4)
+ case "fluid-1":
+ Self(summary: "The original Fluid model", useCase: "Cleanup and formatting across languages.", language: "Multilingual", intelligence: 4, speed: 2)
+ default:
+ Self(summary: "On-device cleanup", useCase: "Polish your words privately on your Mac.")
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift b/Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift
new file mode 100644
index 00000000..93cfe46c
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift
@@ -0,0 +1,497 @@
+import AppKit
+import Combine
+
+enum PrivateAIModelLoadState: Equatable {
+ case idle
+ case downloading(modelID: String, progress: PrivateAIModelDownloadProgress?)
+ case loading(modelID: String)
+ case loaded(modelID: String, latencyMilliseconds: Int?)
+ case failed(modelID: String, message: String)
+
+ func isLoading(_ modelID: String) -> Bool {
+ if case .loading(modelID) = self { return true }
+ return false
+ }
+
+ func isDownloading(_ modelID: String) -> Bool {
+ if case .downloading(modelID, _) = self { return true }
+ return false
+ }
+
+ func isLoaded(_ modelID: String) -> Bool {
+ if case .loaded(modelID, _) = self { return true }
+ return false
+ }
+
+ func latencyMilliseconds(for modelID: String) -> Int? {
+ if case let .loaded(loadedModelID, latencyMilliseconds) = self, loadedModelID == modelID {
+ return latencyMilliseconds
+ }
+ return nil
+ }
+
+ func failureMessage(for modelID: String) -> String? {
+ if case let .failed(failedModelID, message) = self, failedModelID == modelID {
+ return message
+ }
+ return nil
+ }
+
+ func downloadProgress(for modelID: String) -> PrivateAIModelDownloadProgress? {
+ if case let .downloading(downloadingModelID, progress) = self, downloadingModelID == modelID {
+ return progress
+ }
+ return nil
+ }
+}
+
+/// Retained FI settings state and actions, shared by the existing page and its controls.
+/// The runtime and persistence behavior remains in the existing services and provider view model.
+@MainActor
+final class PrivateAISettingsController: ObservableObject {
+ let viewModel: AIEnhancementSettingsViewModel
+
+ private var settings: SettingsStore { self.viewModel.settings }
+
+ @Published private var session: PrivateAISettingsSession
+
+ var privateAISelectedModelID: String { self.session.selectedModelID }
+ var previewModelID: String { self.session.previewModelID }
+ var isBusy: Bool { self.session.isBusy || self.viewModel.isTestingConnection }
+ @Published var privateAILoadState: PrivateAIModelLoadState = .idle
+ @Published var privateAIModelUpdateStatusByID: [String: PrivateAIModelUpdateStatus] = [:]
+
+ init(viewModel: AIEnhancementSettingsViewModel) {
+ self.viewModel = viewModel
+ self.session = PrivateAISettingsSession(selectedModelID: PrivateAIIntegrationService.configuredModelID)
+ }
+
+ /// Carousel arrows/dots call this; no defaults, provider, or runtime writes.
+ func previewModel(_ modelID: String) {
+ guard let model = PrivateAIModelRegistry.model(id: modelID) else { return }
+ self.session.preview(model.id)
+ }
+
+ func activatePreviewModel() {
+ self.persistPrivateAIModelSelection(self.previewModelID)
+ }
+
+ /// Only the explicit Use/Download action enters this path; browsing remains read-only.
+ func usePreviewModel(isInstalled: Bool, onReady: @escaping () -> Void) {
+ guard !self.isBusy, let model = PrivateAIModelRegistry.model(id: self.previewModelID) else { return }
+ self.persistPrivateAIModelSelection(model.id, loadIfInstalled: false)
+ if isInstalled {
+ self.verifyPrivateAIConnection(model, onReady: onReady)
+ } else {
+ self.downloadPrivateAIModel(model, onReady: onReady)
+ }
+ }
+
+ func synchronizeSelection() {
+ guard !self.isBusy else { return }
+ self.session.select(PrivateAIIntegrationService.configuredModelID)
+ }
+
+ private func beginOperation(for modelID: String) -> UUID? {
+ guard !self.isBusy, modelID == self.privateAISelectedModelID else { return nil }
+ return self.session.begin()
+ }
+
+ func refreshPrivateAIProviderModels() {
+ guard !self.isBusy else { return }
+ let providerKey = self.viewModel.providerKey(for: PrivateAIProviderFeature.shared.providerID)
+ let models = PrivateAIModelRegistry.modelIDs()
+ let selected = PrivateAIModelRegistry.canonicalModelID(for: self.privateAISelectedModelID) ?? PrivateAIModelRegistry.defaultModel.id
+
+ self.session.select(selected)
+ self.viewModel.availableModelsByProvider[providerKey] = models
+ self.viewModel.selectedModelByProvider[providerKey] = selected
+ self.viewModel.settings.availableModelsByProvider = self.viewModel.availableModelsByProvider
+ self.viewModel.settings.selectedModelByProvider = self.viewModel.selectedModelByProvider
+
+ if self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID {
+ self.viewModel.availableModels = models
+ self.viewModel.selectedModel = selected
+ }
+
+ self.refreshPrivateAILoadState()
+ self.refreshPrivateAIModelUpdateStatus(self.selectedPrivateAIModel)
+ self.viewModel.refreshProviderItems()
+ }
+
+ func refreshPrivateAIModelUpdateStatus(_ model: PrivateAIRegisteredModel) {
+ guard !self.session.isBusy else { return }
+ let revision = self.session.revision
+ Task { @MainActor in
+ let status = await PrivateAIIntegrationService.modelUpdateStatus(model)
+ guard self.session.acceptsRead(revision) else { return }
+ self.privateAIModelUpdateStatusByID[model.id] = status
+ }
+ }
+
+ func downloadPrivateAIModel(_ model: PrivateAIRegisteredModel, onReady: (() -> Void)? = nil) {
+ guard let operation = self.beginOperation(for: model.id) else { return }
+ guard model.canDownload else {
+ self.session.finish(operation)
+ self.privateAILoadState = .failed(modelID: model.id, message: "Download URL is not configured yet.")
+ return
+ }
+
+ self.privateAILoadState = .downloading(
+ modelID: model.id,
+ progress: PrivateAIModelDownloadProgress(initialExpectedBytes: model.artifact.byteCount)
+ )
+ Task { @MainActor in
+ defer {
+ self.session.finish(operation)
+ self.refreshPrivateAIModelUpdateStatus(model)
+ }
+ do {
+ DebugLogger.shared.info(
+ "Private provider download button pressed model=\(model.id)",
+ source: "AISettingsView"
+ )
+ _ = try await PrivateAIIntegrationService.prepareModel(model) { progress in
+ await MainActor.run {
+ guard self.session.operationID == operation else { return }
+ self.privateAILoadState = .downloading(
+ modelID: model.id,
+ progress: progress.withFallbackExpectedBytes(model.artifact.byteCount)
+ )
+ }
+ }
+ guard self.privateAISelectedModelID == model.id else { return }
+ self.privateAILoadState = .loading(modelID: model.id)
+ let start = ContinuousClock.now
+ let verified = await self.viewModel.verifyPrivateAIProvider(model: model)
+ let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
+ guard self.privateAISelectedModelID == model.id else { return }
+ if verified {
+ self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
+ onReady?()
+ } else {
+ let message = self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID).isEmpty
+ ? "Model downloaded, but verification failed."
+ : self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID)
+ self.privateAILoadState = .failed(modelID: model.id, message: message)
+ }
+ } catch {
+ guard self.privateAISelectedModelID == model.id else { return }
+ self.privateAILoadState = .failed(
+ modelID: model.id,
+ message: Self.errorMessage(for: error)
+ )
+ }
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ func updatePrivateAIModel(_ model: PrivateAIRegisteredModel) {
+ guard self.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailable,
+ let operation = self.beginOperation(for: model.id)
+ else { return }
+ let wasPreviouslyVerified = PrivateAIProviderPromptFormat.verifiedModelID(settings: self.settings) == model.id
+ self.privateAILoadState = .downloading(
+ modelID: model.id,
+ progress: PrivateAIModelDownloadProgress(initialExpectedBytes: model.artifact.byteCount)
+ )
+ Task { @MainActor in
+ defer {
+ self.session.finish(operation)
+ self.refreshPrivateAIModelUpdateStatus(model)
+ self.viewModel.refreshProviderItems()
+ }
+ do {
+ var verificationStart = ContinuousClock.now
+ let verified = try await PrivateAISettingsUpdateTransaction.run(
+ update: {
+ try await PrivateAIIntegrationService.updateModel(model) { progress in
+ await MainActor.run {
+ guard self.session.operationID == operation else { return }
+ self.privateAILoadState = .downloading(
+ modelID: model.id,
+ progress: progress.withFallbackExpectedBytes(model.artifact.byteCount)
+ )
+ }
+ }
+ },
+ verify: {
+ self.privateAILoadState = .loading(modelID: model.id)
+ verificationStart = .now
+ return await self.viewModel.verifyPrivateAIProvider(model: model)
+ },
+ commit: { await PrivateAIIntegrationService.commitModelUpdate($0) },
+ rollback: { await PrivateAIIntegrationService.rollbackModelUpdate($0) }
+ )
+ if verified {
+ self.privateAILoadState = .loaded(
+ modelID: model.id, latencyMilliseconds: Self.elapsedMilliseconds(since: verificationStart)
+ )
+ } else {
+ let detail = self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID)
+ if wasPreviouslyVerified {
+ self.viewModel.updateConnectionStatus(.success, for: PrivateAIProviderFeature.shared.providerID)
+ }
+ self.privateAILoadState = .failed(
+ modelID: model.id,
+ message: "The new model failed verification. The previous model is still active. \(detail)"
+ )
+ }
+ } catch {
+ self.privateAILoadState = .failed(
+ modelID: model.id,
+ message: "Update failed. The previous model is still active. \(Self.errorMessage(for: error))"
+ )
+ }
+ }
+ }
+
+ /// Explicit callers can request a result; nil means success, otherwise a user-facing failure.
+ func verifyPrivateAIConnection(_ model: PrivateAIRegisteredModel, onReady: (() -> Void)? = nil, onCompletion: ((String?) -> Void)? = nil) {
+ guard let operation = self.beginOperation(for: model.id) else { return }
+ self.privateAILoadState = .loading(modelID: model.id)
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ let start = ContinuousClock.now
+ let verified = await self.viewModel.verifyPrivateAIProvider(model: model)
+ let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
+ guard self.privateAISelectedModelID == model.id else { return }
+ if verified {
+ self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
+ onReady?()
+ onCompletion?(nil)
+ } else {
+ let message = self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID).isEmpty
+ ? "Model verification failed."
+ : self.viewModel.connectionErrorMessage(for: PrivateAIProviderFeature.shared.providerID)
+ self.privateAILoadState = .failed(modelID: model.id, message: message)
+ onCompletion?(message)
+ }
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ var selectedPrivateAIModel: PrivateAIRegisteredModel {
+ PrivateAIModelRegistry.model(id: self.privateAISelectedModelID) ?? PrivateAIModelRegistry.defaultModel
+ }
+
+ func revealPrivateAIModelFolder() {
+ let directoryURL = PrivateAIIntegrationService.modelDirectoryURL
+ do {
+ try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
+ NSWorkspace.shared.open(directoryURL)
+ } catch {
+ DebugLogger.shared.error(
+ "Failed to open Private AI Provider models folder: \(error.localizedDescription)",
+ source: "AISettingsView"
+ )
+ }
+ }
+
+ func refreshPrivateAILoadState() {
+ guard !self.session.isBusy else { return }
+ if case .failed = self.privateAILoadState { return }
+ let revision = self.session.revision
+ Task { @MainActor in
+ let loaded = await PrivateAIIntegrationService.shared.loadedModelState()
+ guard self.session.acceptsRead(revision) else { return }
+ guard let loaded, loaded.state == .ready else {
+ self.privateAILoadState = .idle
+ return
+ }
+
+ self.privateAILoadState = .loaded(modelID: loaded.modelID, latencyMilliseconds: nil)
+ }
+ }
+
+ func loadPrivateAIModel(_ model: PrivateAIRegisteredModel) {
+ guard let operation = self.beginOperation(for: model.id) else { return }
+ guard PrivateAIIntegrationService.isModelInstalled(model) else {
+ self.session.finish(operation)
+ self.privateAILoadState = .failed(modelID: model.id, message: "Model file is not installed.")
+ return
+ }
+
+ self.privateAILoadState = .loading(modelID: model.id)
+ Task { @MainActor in
+ defer {
+ self.session.finish(operation)
+ self.refreshPrivateAIModelUpdateStatus(model)
+ }
+ do {
+ let start = ContinuousClock.now
+ let status = try await PrivateAIIntegrationService.shared.loadModel(model)
+ let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
+ guard self.privateAISelectedModelID == model.id else { return }
+ switch status.state {
+ case .ready:
+ self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
+ default:
+ self.privateAILoadState = .failed(
+ modelID: model.id,
+ message: status.message ?? "Model did not report ready."
+ )
+ }
+ } catch {
+ guard self.privateAISelectedModelID == model.id else { return }
+ self.privateAILoadState = .failed(
+ modelID: model.id,
+ message: Self.errorMessage(for: error)
+ )
+ }
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ func resetPrivateAIVerification(for model: PrivateAIRegisteredModel) {
+ guard let operation = self.beginOperation(for: model.id) else { return }
+ self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
+ self.privateAILoadState = .idle
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ await PrivateAIIntegrationService.shared.unloadCachedRuntime(reason: "Fluid Intelligence verification reset")
+ if PrivateAIIntegrationService.isModelInstalled(model) {
+ self.privateAILoadState = .idle
+ }
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ func deletePrivateAIModel(_ model: PrivateAIRegisteredModel) {
+ guard let operation = self.beginOperation(for: model.id) else { return }
+ guard PrivateAIIntegrationService.canRemoveInstalledModel(model) else {
+ self.session.finish(operation)
+ return
+ }
+ self.privateAILoadState = .loading(modelID: model.id)
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ do {
+ try await PrivateAIIntegrationService.shared.unloadAndRemoveInstalledModel(
+ model,
+ reason: "settings-delete"
+ )
+ self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
+ if self.privateAISelectedModelID == model.id {
+ self.privateAILoadState = .idle
+ }
+ self.viewModel.refreshProviderItems()
+ } catch {
+ guard self.privateAISelectedModelID == model.id else { return }
+ self.privateAILoadState = .failed(modelID: model.id, message: Self.errorMessage(for: error))
+ }
+ }
+ }
+
+ private static func errorMessage(for error: Error) -> String {
+ if let localizedError = error as? LocalizedError,
+ let description = localizedError.errorDescription
+ {
+ return description
+ }
+ return String(describing: error)
+ }
+
+ private static func elapsedMilliseconds(since start: ContinuousClock.Instant) -> Int {
+ let elapsed = start.duration(to: ContinuousClock.now)
+ return Int(elapsed.components.seconds * 1000) + Int(elapsed.components.attoseconds / 1_000_000_000_000_000)
+ }
+
+ func persistPrivateAIModelSelection(_ value: String, loadIfInstalled: Bool = true) {
+ guard let model = PrivateAIModelRegistry.model(id: value), model.id != self.privateAISelectedModelID else { return }
+ let providerKey = self.viewModel.providerKey(for: PrivateAIProviderFeature.shared.providerID)
+ let models = PrivateAIModelRegistry.modelIDs()
+
+ guard !self.isBusy, self.session.select(model.id) else { return }
+ UserDefaults.standard.set(model.id, forKey: PrivateAIIntegrationService.selectedModelDefaultsKey)
+ UserDefaults.standard.removeObject(forKey: PrivateAIIntegrationService.localModelPathDefaultsKey)
+
+ self.viewModel.availableModelsByProvider[providerKey] = models
+ self.viewModel.selectedModelByProvider[providerKey] = model.id
+ self.viewModel.settings.availableModelsByProvider = self.viewModel.availableModelsByProvider
+ self.viewModel.settings.selectedModelByProvider = self.viewModel.selectedModelByProvider
+
+ if self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID {
+ self.viewModel.availableModels = models
+ self.viewModel.selectedModel = model.id
+ }
+ self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
+ self.refreshPrivateAIModelUpdateStatus(model)
+ self.viewModel.refreshProviderItems()
+ if loadIfInstalled, PrivateAIIntegrationService.isModelInstalled(model) {
+ self.loadPrivateAIModel(model)
+ } else {
+ self.privateAILoadState = .idle
+ }
+ }
+
+ func setPrivateAIBackendPreference(_ preference: SettingsStore.PrivateAIBackendPreference) {
+ guard self.settings.privateAIBackendPreference != preference else { return }
+ guard let operation = self.beginOperation(for: self.privateAISelectedModelID) else { return }
+ let modelID = self.privateAISelectedModelID
+
+ self.settings.privateAIBackendPreference = preference
+ UserDefaults.standard.removeObject(forKey: PrivateAIIntegrationService.localModelPathDefaultsKey)
+ self.privateAILoadState = .idle
+ self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
+
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ await PrivateAIIntegrationService.shared.unloadCachedRuntime(
+ reason: "Fluid Intelligence backend changed to \(preference.displayName)"
+ )
+ guard self.privateAISelectedModelID == modelID else { return }
+ let model = self.selectedPrivateAIModel
+ if PrivateAIIntegrationService.isModelInstalled(model) {
+ self.session.finish(operation)
+ self.verifyPrivateAIConnection(model)
+ } else {
+ self.privateAILoadState = .idle
+ self.viewModel.refreshProviderItems()
+ }
+ }
+ }
+
+ func setPrefixCacheEnabled(_ enabled: Bool) {
+ guard self.settings.privateAIPrefixKVCacheEnabled != enabled else { return }
+ guard let operation = self.beginOperation(for: self.privateAISelectedModelID) else { return }
+ self.settings.privateAIPrefixKVCacheEnabled = enabled
+ self.privateAILoadState = .idle
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ await PrivateAIIntegrationService.shared.unloadCachedRuntime(
+ reason: enabled ? "prefix cache enabled" : "prefix cache disabled"
+ )
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ func setBoostEnabled(_ enabled: Bool) {
+ guard self.settings.privateAIBoostEnabled != enabled else { return }
+ guard let operation = self.beginOperation(for: self.privateAISelectedModelID) else { return }
+ self.settings.privateAIBoostEnabled = enabled
+ self.privateAILoadState = .idle
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ await PrivateAIIntegrationService.shared.unloadCachedRuntime(
+ reason: enabled ? "Fluid-1 Boost enabled" : "Fluid-1 Boost disabled"
+ )
+ self.viewModel.refreshProviderItems()
+ }
+ }
+
+ func setContextTokenLimit(_ value: Int) {
+ let clamped = SettingsStore.clampPrivateAIContextTokenLimit(value)
+ guard self.settings.privateAIContextTokenLimit != clamped else { return }
+ guard let operation = self.beginOperation(for: self.privateAISelectedModelID) else { return }
+ self.settings.privateAIContextTokenLimit = clamped
+ self.privateAILoadState = .idle
+ Task { @MainActor in
+ defer { self.session.finish(operation) }
+ await PrivateAIIntegrationService.shared.unloadCachedRuntime(
+ reason: "Fluid Intelligence context changed"
+ )
+ self.viewModel.refreshProviderItems()
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/PrivateAISettingsSession.swift b/Sources/Fluid/UI/AISettings/PrivateAISettingsSession.swift
new file mode 100644
index 00000000..356d9811
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/PrivateAISettingsSession.swift
@@ -0,0 +1,93 @@
+import Foundation
+
+/// Catalog-driven carousel math. Empty and single-model builds never wrap or invent neighbors.
+enum PrivateAIModelCarouselNavigation {
+ static func next(in ids: [String], current: String, forward: Bool) -> String? {
+ guard !ids.isEmpty else { return nil }
+ guard let index = ids.firstIndex(of: current) else { return ids.first }
+ return ids[(index + (forward ? 1 : ids.count - 1)) % ids.count]
+ }
+
+ static func position(of id: String, in ids: [String], current: String) -> Int {
+ guard let index = ids.firstIndex(of: id), !ids.isEmpty else { return 0 }
+ let center = ids.firstIndex(of: current) ?? 0
+ if ids.count == 2 { return index - center }
+ let distance = (index - center + ids.count) % ids.count
+ return distance > ids.count / 2 ? distance - ids.count : distance
+ }
+}
+
+/// Presentation-only choice and a single bounded mutation slot. Browsing never invokes an action.
+struct PrivateAISettingsSession {
+ private(set) var selectedModelID: String
+ private(set) var previewModelID: String
+ private(set) var revision = UUID()
+ private(set) var operationID: UUID?
+
+ var isBusy: Bool { self.operationID != nil }
+
+ init(selectedModelID: String) {
+ self.selectedModelID = selectedModelID
+ self.previewModelID = selectedModelID
+ }
+
+ mutating func preview(_ modelID: String) {
+ self.previewModelID = modelID
+ }
+
+ /// Explicit activation only. The caller validates IDs against the current model catalog.
+ @discardableResult
+ mutating func select(_ modelID: String) -> Bool {
+ guard !self.isBusy else { return false }
+ self.selectedModelID = modelID
+ self.previewModelID = modelID
+ self.revision = UUID()
+ return true
+ }
+
+ mutating func begin() -> UUID? {
+ guard !self.isBusy else { return nil }
+ let token = UUID()
+ self.operationID = token
+ self.revision = UUID()
+ return token
+ }
+
+ mutating func finish(_ token: UUID) {
+ guard self.operationID == token else { return }
+ self.operationID = nil
+ self.revision = UUID()
+ }
+
+ func acceptsRead(_ revision: UUID) -> Bool {
+ !self.isBusy && self.revision == revision
+ }
+}
+
+/// Injectable transaction boundary used by the real update button and deterministic tests.
+/// Keep the mutation slot occupied until commit/rollback has finished, not just verification.
+enum PrivateAISettingsUpdateTransaction {
+ @MainActor
+ static func run<Token>(
+ update: () async throws -> Token,
+ verify: () async -> Bool,
+ commit: (Token) async -> Void,
+ rollback: (Token) async -> Void
+ ) async throws -> Bool {
+ let token = try await update()
+ do {
+ try Task.checkCancellation()
+ let verified = await verify()
+ try Task.checkCancellation()
+ if verified {
+ await commit(token)
+ } else {
+ await rollback(token)
+ }
+ return verified
+ } catch {
+ await rollback(token)
+ throw error
+ }
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/ProviderModelVerificationStore.swift b/Sources/Fluid/UI/AISettings/ProviderModelVerificationStore.swift
new file mode 100644
index 00000000..0ab9d2c7
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/ProviderModelVerificationStore.swift
@@ -0,0 +1,45 @@
+import CryptoKit
+import Foundation
+
+/// Optional successful model checks, separate from legacy provider connection status.
+/// Stores only hashes and timestamps, never API keys, URLs, or request contents.
+@MainActor
+final class ProviderModelVerificationStore {
+ static let defaultsKey = "ProviderModelVerificationsV1"
+ static let maximumEntries = 256
+ private let defaults: UserDefaults
+ private var successes: [String: Double]
+
+ init(defaults: UserDefaults = .standard) {
+ self.defaults = defaults
+ let stored = defaults.dictionary(forKey: Self.defaultsKey) as? [String: Double] ?? [:]
+ self.successes = Dictionary(uniqueKeysWithValues: stored
+ .filter { $0.key.count == 64 && $0.value.isFinite }
+ .sorted { $0.value > $1.value }
+ .prefix(Self.maximumEntries)
+ .map { ($0.key, $0.value) })
+ }
+
+ static func identity(providerID: String, baseURL: String, apiKey: String, model: String) -> String {
+ let fields = [providerID, baseURL, apiKey, model].map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ let data = (try? JSONEncoder().encode(fields)) ?? Data()
+ return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
+ }
+
+ func contains(_ identity: String) -> Bool { self.successes[identity] != nil }
+
+ func recordSuccess(_ identity: String, now: Date = Date()) {
+ self.successes[identity] = now.timeIntervalSince1970
+ while self.successes.count > Self.maximumEntries,
+ let oldest = self.successes.min(by: { $0.value < $1.value })?.key
+ {
+ self.successes.removeValue(forKey: oldest)
+ }
+ self.defaults.set(self.successes, forKey: Self.defaultsKey)
+ }
+
+ func remove(_ identity: String) {
+ guard self.successes.removeValue(forKey: identity) != nil else { return }
+ self.defaults.set(self.successes, forKey: Self.defaultsKey)
+ }
+}
diff --git a/Sources/Fluid/UI/AISettings/ProviderSetupDraft.swift b/Sources/Fluid/UI/AISettings/ProviderSetupDraft.swift
new file mode 100644
index 00000000..76e24152
--- /dev/null
+++ b/Sources/Fluid/UI/AISettings/ProviderSetupDraft.swift
@@ -0,0 +1,24 @@
+import Foundation
+
+/// A local form value, never a live settings binding. Cancel simply discards it.
+struct ProviderSetupDraft {
+ var providerID = ""
+ var name = ""
+ var baseURL = ""
+ var apiKey = ""
+ var model = ""
+
+ var trimmedName: String { self.name.trimmingCharacters(in: .whitespacesAndNewlines) }
+ var trimmedModel: String { self.model.trimmingCharacters(in: .whitespacesAndNewlines) }
+ var trimmedBaseURL: String { self.baseURL.trimmingCharacters(in: .whitespacesAndNewlines) }
+ var requiresAPIKey: Bool { !self.providerID.isEmpty && !["ollama", "lmstudio"].contains(self.providerID) }
+ var isValid: Bool {
+ guard !self.requiresAPIKey || !self.apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return false }
+ guard !self.trimmedName.isEmpty, let url = URL(string: self.trimmedBaseURL),
+ let scheme = url.scheme?.lowercased(), ["http", "https"].contains(scheme),
+ let host = url.host, !host.isEmpty,
+ url.user == nil, url.password == nil
+ else { return false }
+ return true
+ }
+}
diff --git a/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift b/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift
index 5bb97825..56c40b32 100644
--- a/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift
+++ b/Sources/Fluid/UI/AISettingsView+AIConfiguration.swift
@@ -46,7 +46,125 @@ extension AIEnhancementSettingsView {
// MARK: - AI Configuration Card
- var aiConfigurationCard: some View {
+ @ViewBuilder var aiConfigurationCard: some View {
+ if self.selectedConfigurationSection == .providers, PrivateAIProviderFeature.shared.isAvailable {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xl) {
+ FluidIntelligenceLiveSection(
+ controller: self.privateAIController,
+ backendID: self.settings.privateAIBackendPreference.rawValue,
+ isPrimary: self.primaryDefaultProviderID == PrivateAIProviderFeature.shared.providerID,
+ isVerified: self.isPrivateAIModelVerified(self.privateAIController.selectedPrivateAIModel),
+ makePrimary: { self.makePrimaryDefaultProvider(PrivateAIProviderFeature.shared.providerID, isPrivateAI: true) }
+ ) {
+ self.privateAIManagementSettings(isBusy: self.privateAIController.isBusy)
+ }
+ self.addedExternalProvidersSection
+ }
+ .frame(maxWidth: AppTheme.Metrics.Showcase.pageMaxWidth)
+ .frame(maxWidth: .infinity)
+ } else {
+ self.legacyAIConfigurationCard
+ }
+ }
+
+ private var addedExternalProvidersSection: some View {
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
+ HStack {
+ if !self.viewModel.cachedAddedProviderItems.isEmpty {
+ Text("Other providers").font(self.theme.typography.sectionTitle)
+ }
+ Spacer()
+ Button("Add Provider", systemImage: "plus") { self.showingAddProviderSheet = true }
+ .fluidGlassAction()
+ .disabled(self.viewModel.isFetchingModels || self.viewModel.isTestingConnection)
+ }
+ ForEach(self.viewModel.cachedAddedProviderItems) { provider in
+ let item = ProviderItem(id: provider.id, name: provider.name, isBuiltIn: provider.isBuiltIn)
+ let setupIssue = DictationDefaultProvider.setupIssue(
+ requiresAPIKey: !self.viewModel.isLocalEndpoint(self.providerBaseURL(for: item)),
+ hasAPIKey: !self.viewModel.providerAPIKey(for: provider.id).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ hasModel: !self.viewModel.selectedModel(for: provider.id).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ isVerified: self.viewModel.connectionStatus(for: provider.id) == .success,
+ verificationFailed: self.viewModel.connectionStatus(for: provider.id) == .failed
+ )
+ HStack(spacing: self.theme.metrics.spacing.md) {
+ self.providerLogoView(for: item).frame(width: 30, height: 30)
+ Text(provider.name).font(self.theme.typography.bodySmallStrong)
+ Spacer()
+ if self.viewModel.connectionStatus(for: provider.id) == .testing {
+ Text("Verifying…")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ } else if let setupIssue {
+ Label(setupIssue, systemImage: "exclamationmark.circle")
+ .font(self.theme.typography.caption)
+ .foregroundStyle(.red)
+ }
+ ProviderDefaultButton(
+ isCurrent: self.primaryDefaultProviderID == provider.id,
+ isEnabled: self.viewModel.canUseProviderWithoutVerification(provider.id)
+ && !self.viewModel.isFetchingModels && !self.viewModel.isTestingConnection
+ ) {
+ self.makePrimaryDefaultProvider(provider.id, isPrivateAI: false)
+ }
+ Button("Manage") {
+ self.viewModel.configureProvider(provider.id)
+ self.managedExternalProviderID = provider.id
+ }
+ .fluidGlassAction()
+ .disabled(self.viewModel.isFetchingModels || self.viewModel.isTestingConnection)
+ }
+ .padding(self.theme.metrics.spacing.lg)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg, style: .continuous))
+ }
+ }
+ .sheet(isPresented: self.$showingAddProviderSheet) {
+ AddProviderSheet(viewModel: self.viewModel) { id, name in
+ self.providerLogoView(for: ProviderItem(id: id, name: name, isBuiltIn: true))
+ }.appTheme(self.theme)
+ }
+ .sheet(isPresented: Binding(
+ get: { self.managedExternalProviderID != nil },
+ set: { if !$0 { self.closeExternalProviderManager() } }
+ )) {
+ self.externalProviderManager.appTheme(self.theme)
+ }
+ }
+
+ private func closeExternalProviderManager() {
+ guard !self.viewModel.isFetchingModels, !self.viewModel.isTestingConnection else { return }
+ self.viewModel.clearEditProviderDraft()
+ self.viewModel.showingAddModel = false
+ self.viewModel.newModelName = ""
+ self.viewModel.showingReasoningConfig = false
+ self.viewModel.finishConfiguringProvider()
+ self.managedExternalProviderID = nil
+ }
+
+ private var externalProviderManager: some View {
+ FluidManagementSheet(
+ title: self.viewModel.cachedProviderItems.first(where: { $0.id == self.managedExternalProviderID })?.name ?? "Provider",
+ subtitle: "Connection and models.",
+ symbol: "network",
+ dismissDisabled: self.viewModel.isFetchingModels || self.viewModel.isTestingConnection,
+ height: 520,
+ close: self.closeExternalProviderManager
+ ) {
+ if let provider = self.viewModel.cachedProviderItems.first(where: { $0.id == self.managedExternalProviderID }) {
+ let item = ProviderItem(id: provider.id, name: provider.name, isBuiltIn: provider.isBuiltIn)
+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.lg) {
+ self.providerDetailsSection(for: item, managementLayout: true)
+ .disabled(self.viewModel.isFetchingModels || self.viewModel.isTestingConnection)
+ }
+ }
+ }
+ .interactiveDismissDisabled(self.viewModel.isFetchingModels || self.viewModel.isTestingConnection)
+ .onChange(of: self.viewModel.cachedProviderItems.map(\.id)) { _, ids in
+ if let id = self.managedExternalProviderID, !ids.contains(id) { self.closeExternalProviderManager() }
+ }
+ }
+
+ private var legacyAIConfigurationCard: some View {
VStack(spacing: 14) {
ThemedCard(style: .prominent, hoverEffect: false) {
VStack(alignment: .leading, spacing: 16) {
@@ -265,7 +383,9 @@ extension AIEnhancementSettingsView {
var providerStepContent: some View {
VStack(alignment: .leading, spacing: 16) {
- self.verifiedProvidersSection
+ if !PrivateAIProviderFeature.shared.isAvailable || !self.verifiedProviderItems.isEmpty {
+ self.verifiedProvidersSection
+ }
self.allProvidersSection
@@ -421,13 +541,17 @@ extension AIEnhancementSettingsView {
// Use cached provider items from ViewModel for scroll performance
private var verifiedProviderItems: [ProviderItem] {
- self.viewModel.cachedVerifiedProviderItems.map {
+ self.viewModel.cachedVerifiedProviderItems.filter {
+ !PrivateAIProviderFeature.shared.isAvailable || $0.id != PrivateAIProviderFeature.shared.providerID
+ }.map {
ProviderItem(id: $0.id, name: $0.name, isBuiltIn: $0.isBuiltIn)
}
}
private var unverifiedProviderItems: [ProviderItem] {
- self.viewModel.cachedUnverifiedProviderItems.map {
+ self.viewModel.cachedUnverifiedProviderItems.filter {
+ !PrivateAIProviderFeature.shared.isAvailable || $0.id != PrivateAIProviderFeature.shared.providerID
+ }.map {
ProviderItem(id: $0.id, name: $0.name, isBuiltIn: $0.isBuiltIn)
}
}
@@ -584,19 +708,19 @@ extension AIEnhancementSettingsView {
}
private var privateAIRuntimeSection: some View {
- let model = self.selectedPrivateAIModel
+ let model = self.privateAIController.selectedPrivateAIModel
let status = self.privateAIModelStatus(for: model)
let isInstalled = PrivateAIIntegrationService.isModelInstalled(model)
- let isDownloading = self.privateAILoadState.isDownloading(model.id)
- let downloadProgress = self.privateAILoadState.downloadProgress(for: model.id)
- let isLoading = self.privateAILoadState.isLoading(model.id)
- let isLoaded = self.privateAILoadState.isLoaded(model.id)
- let hasLoadFailure = self.privateAILoadState.failureMessage(for: model.id) != nil
+ let isDownloading = self.privateAIController.privateAILoadState.isDownloading(model.id)
+ let downloadProgress = self.privateAIController.privateAILoadState.downloadProgress(for: model.id)
+ let isLoading = self.privateAIController.privateAILoadState.isLoading(model.id)
+ let isLoaded = self.privateAIController.privateAILoadState.isLoaded(model.id)
+ let hasLoadFailure = self.privateAIController.privateAILoadState.failureMessage(for: model.id) != nil
let isVerified = self.isPrivateAIModelVerified(model)
let isTesting = self.viewModel.isTestingConnection && self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID
- let isBusy = isDownloading || isLoading || isTesting
- let hasUpdate = isInstalled && self.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailable
- let canVerify = isInstalled && (!isVerified || hasLoadFailure) && !self.privateAISelectedModelID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ let isBusy = self.privateAIController.isBusy || isDownloading || isLoading || isTesting
+ let hasUpdate = isInstalled && self.privateAIController.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailable
+ let canVerify = isInstalled && (!isVerified || hasLoadFailure) && !self.privateAIController.privateAISelectedModelID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
return VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 8) {
@@ -615,7 +739,7 @@ extension AIEnhancementSettingsView {
)
self.companionIconButton(systemName: "folder", help: "Open downloaded model folder") {
- self.revealPrivateAIModelFolder()
+ self.privateAIController.revealPrivateAIModelFolder()
}
}
@@ -655,7 +779,7 @@ extension AIEnhancementSettingsView {
if !isInstalled {
if model.canDownload {
- Button(action: { self.downloadPrivateAIModel(model) }) {
+ Button(action: { self.privateAIController.downloadPrivateAIModel(model) }) {
HStack(spacing: 6) {
if isDownloading {
ProgressView()
@@ -682,7 +806,7 @@ extension AIEnhancementSettingsView {
.foregroundStyle(.secondary)
}
} else if hasUpdate {
- Button(action: { self.updatePrivateAIModel(model) }) {
+ Button(action: { self.privateAIController.updatePrivateAIModel(model) }) {
HStack(spacing: 6) {
if isDownloading {
ProgressView()
@@ -700,7 +824,7 @@ extension AIEnhancementSettingsView {
.fluidButton(.accent, size: .small)
.disabled(isBusy)
} else if canVerify {
- Button(action: { self.verifyPrivateAIConnection(model) }) {
+ Button(action: { self.privateAIController.verifyPrivateAIConnection(model) }) {
HStack(spacing: 6) {
if isTesting {
ProgressView()
@@ -855,34 +979,14 @@ extension AIEnhancementSettingsView {
private var privateAIPrefixCacheBinding: Binding<Bool> {
Binding(
get: { self.settings.privateAIPrefixKVCacheEnabled },
- set: { enabled in
- guard self.settings.privateAIPrefixKVCacheEnabled != enabled else { return }
- self.settings.privateAIPrefixKVCacheEnabled = enabled
- self.privateAILoadState = .idle
- Task { @MainActor in
- await PrivateAIIntegrationService.shared.unloadCachedRuntime(
- reason: enabled ? "prefix cache enabled" : "prefix cache disabled"
- )
- self.viewModel.refreshProviderItems()
- }
- }
+ set: { self.privateAIController.setPrefixCacheEnabled($0) }
)
}
private var privateAIBoostBinding: Binding<Bool> {
Binding(
get: { self.settings.privateAIBoostEnabled },
- set: { enabled in
- guard self.settings.privateAIBoostEnabled != enabled else { return }
- self.settings.privateAIBoostEnabled = enabled
- self.privateAILoadState = .idle
- Task { @MainActor in
- await PrivateAIIntegrationService.shared.unloadCachedRuntime(
- reason: enabled ? "Fluid-1 Boost enabled" : "Fluid-1 Boost disabled"
- )
- self.viewModel.refreshProviderItems()
- }
- }
+ set: { self.privateAIController.setBoostEnabled($0) }
)
}
@@ -890,7 +994,7 @@ extension AIEnhancementSettingsView {
Binding(
get: { self.settings.privateAIBackendPreference },
set: { preference in
- self.setPrivateAIBackendPreference(preference)
+ self.privateAIController.setPrivateAIBackendPreference(preference)
}
)
}
@@ -909,206 +1013,17 @@ extension AIEnhancementSettingsView {
private var privateAIContextTokenLimitBinding: Binding<Int> {
Binding(
get: { self.settings.privateAIContextTokenLimit },
- set: { value in
- let clamped = SettingsStore.clampPrivateAIContextTokenLimit(value)
- guard self.settings.privateAIContextTokenLimit != clamped else { return }
- self.settings.privateAIContextTokenLimit = clamped
- self.privateAILoadState = .idle
- Task { @MainActor in
- await PrivateAIIntegrationService.shared.unloadCachedRuntime(
- reason: "Fluid Intelligence context changed"
- )
- self.viewModel.refreshProviderItems()
- }
- }
+ set: { self.privateAIController.setContextTokenLimit($0) }
)
}
private var privateAIModelBinding: Binding<String> {
Binding(
- get: { self.privateAISelectedModelID },
- set: { self.persistPrivateAIModelSelection($0) }
+ get: { self.privateAIController.privateAISelectedModelID },
+ set: { self.privateAIController.persistPrivateAIModelSelection($0) }
)
}
- private func refreshPrivateAIProviderModels() {
- let providerKey = self.viewModel.providerKey(for: PrivateAIProviderFeature.shared.providerID)
- let models = PrivateAIModelRegistry.modelIDs()
- let selected = PrivateAIModelRegistry.canonicalModelID(for: self.privateAISelectedModelID) ?? PrivateAIModelRegistry.defaultModel.id
-
- self.privateAISelectedModelID = selected
- self.viewModel.availableModelsByProvider[providerKey] = models
- self.viewModel.selectedModelByProvider[providerKey] = selected
- self.viewModel.settings.availableModelsByProvider = self.viewModel.availableModelsByProvider
- self.viewModel.settings.selectedModelByProvider = self.viewModel.selectedModelByProvider
-
- if self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID {
- self.viewModel.availableModels = models
- self.viewModel.selectedModel = selected
- }
-
- self.refreshPrivateAILoadState()
- self.refreshPrivateAIModelUpdateStatus(self.selectedPrivateAIModel)
- self.viewModel.refreshProviderItems()
- }
-
- func refreshPrivateAIModelUpdateStatus(_ model: PrivateAIRegisteredModel) {
- Task { @MainActor in
- let status = await PrivateAIIntegrationService.modelUpdateStatus(model)
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAIModelUpdateStatusByID[model.id] = status
- }
- }
-
- private func downloadPrivateAIModel(_ model: PrivateAIRegisteredModel) {
- guard model.canDownload else {
- self.privateAILoadState = .failed(modelID: model.id, message: "Download URL is not configured yet.")
- return
- }
-
- guard !self.privateAILoadState.isDownloading(model.id) else { return }
-
- self.privateAILoadState = .downloading(
- modelID: model.id,
- progress: PrivateAIModelDownloadProgress(initialExpectedBytes: model.artifact.byteCount)
- )
- Task { @MainActor in
- do {
- DebugLogger.shared.info(
- "Private provider download button pressed model=\(model.id)",
- source: "AISettingsView"
- )
- _ = try await PrivateAIIntegrationService.prepareModel(model) { progress in
- await MainActor.run {
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .downloading(
- modelID: model.id,
- progress: progress.withFallbackExpectedBytes(model.artifact.byteCount)
- )
- }
- }
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .loading(modelID: model.id)
- let start = ContinuousClock.now
- let verified = await self.viewModel.verifyPrivateAIProvider(model: model)
- let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
- guard self.privateAISelectedModelID == model.id else { return }
- if verified {
- self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
- } else {
- let message = self.viewModel.connectionErrorMessage.isEmpty
- ? "Model downloaded, but verification failed."
- : self.viewModel.connectionErrorMessage
- self.privateAILoadState = .failed(modelID: model.id, message: message)
- }
- } catch {
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .failed(
- modelID: model.id,
- message: Self.errorMessage(for: error)
- )
- }
- self.viewModel.refreshProviderItems()
- }
- }
-
- private func updatePrivateAIModel(_ model: PrivateAIRegisteredModel) {
- guard self.privateAIModelUpdateStatusByID[model.id]?.state == .updateAvailable,
- !self.privateAILoadState.isDownloading(model.id)
- else { return }
-
- let wasPreviouslyVerified = PrivateAIProviderPromptFormat.verifiedModelID(settings: self.settings) == model.id
-
- self.privateAILoadState = .downloading(
- modelID: model.id,
- progress: PrivateAIModelDownloadProgress(initialExpectedBytes: model.artifact.byteCount)
- )
- Task { @MainActor in
- var updateToken: PrivateAIModelUpdateToken?
- do {
- updateToken = try await PrivateAIIntegrationService.updateModel(model) { progress in
- await MainActor.run {
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .downloading(
- modelID: model.id,
- progress: progress.withFallbackExpectedBytes(model.artifact.byteCount)
- )
- }
- }
- guard self.privateAISelectedModelID == model.id else {
- if let updateToken {
- await PrivateAIIntegrationService.rollbackModelUpdate(updateToken)
- }
- return
- }
-
- self.privateAILoadState = .loading(modelID: model.id)
- let start = ContinuousClock.now
- let verified = await self.viewModel.verifyPrivateAIProvider(model: model)
- let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
- guard self.privateAISelectedModelID == model.id else {
- if let updateToken {
- await PrivateAIIntegrationService.rollbackModelUpdate(updateToken)
- }
- return
- }
-
- if verified, let updateToken {
- await PrivateAIIntegrationService.commitModelUpdate(updateToken)
- self.privateAILoadState = .loaded(
- modelID: model.id,
- latencyMilliseconds: latencyMilliseconds
- )
- } else {
- if let updateToken {
- await PrivateAIIntegrationService.rollbackModelUpdate(updateToken)
- }
- if wasPreviouslyVerified {
- self.viewModel.updateConnectionStatus(.success, for: PrivateAIProviderFeature.shared.providerID)
- }
- let detail = self.viewModel.connectionErrorMessage.isEmpty
- ? "The new model failed verification. The previous model is still active."
- : "The new model failed verification. The previous model is still active. \(self.viewModel.connectionErrorMessage)"
- self.privateAILoadState = .failed(modelID: model.id, message: detail)
- }
- } catch {
- if let updateToken {
- await PrivateAIIntegrationService.rollbackModelUpdate(updateToken)
- }
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .failed(
- modelID: model.id,
- message: "Update failed. The previous model is still active. \(Self.errorMessage(for: error))"
- )
- }
- self.refreshPrivateAIModelUpdateStatus(model)
- self.viewModel.refreshProviderItems()
- }
- }
-
- private func verifyPrivateAIConnection(_ model: PrivateAIRegisteredModel) {
- self.privateAILoadState = .loading(modelID: model.id)
- Task { @MainActor in
- let start = ContinuousClock.now
- let verified = await self.viewModel.verifyPrivateAIProvider(model: model)
- let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
- guard self.privateAISelectedModelID == model.id else { return }
- if verified {
- self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
- } else {
- let message = self.viewModel.connectionErrorMessage.isEmpty
- ? "Model verification failed."
- : self.viewModel.connectionErrorMessage
- self.privateAILoadState = .failed(modelID: model.id, message: message)
- }
- self.viewModel.refreshProviderItems()
- }
- }
-
- var selectedPrivateAIModel: PrivateAIRegisteredModel {
- PrivateAIModelRegistry.model(id: self.privateAISelectedModelID) ?? PrivateAIModelRegistry.defaultModel
- }
-
private func privateAIModelDisplayName(_ modelID: String) -> String {
PrivateAIModelRegistry.model(id: modelID)?.displayName ?? modelID
}
@@ -1120,28 +1035,28 @@ extension AIEnhancementSettingsView {
private func privateAIModelStatus(
for model: PrivateAIRegisteredModel
) -> PrivateAIProviderModelStatus {
- if self.privateAILoadState.isDownloading(model.id) {
+ if self.privateAIController.privateAILoadState.isDownloading(model.id) {
return PrivateAIProviderModelStatus(
detail: "Downloading model.",
color: self.theme.palette.accent
)
}
- if self.privateAILoadState.isLoading(model.id) {
+ if self.privateAIController.privateAILoadState.isLoading(model.id) {
return PrivateAIProviderModelStatus(
detail: "Loading...",
color: self.theme.palette.accent
)
}
- if self.privateAILoadState.isLoaded(model.id) {
+ if self.privateAIController.privateAILoadState.isLoaded(model.id) {
return PrivateAIProviderModelStatus(
detail: "For dictation only.",
color: Color.fluidGreen
)
}
- if let message = self.privateAILoadState.failureMessage(for: model.id) {
+ if let message = self.privateAIController.privateAILoadState.failureMessage(for: model.id) {
return PrivateAIProviderModelStatus(
detail: message,
color: .red
@@ -1185,107 +1100,6 @@ extension AIEnhancementSettingsView {
)
}
- private func revealPrivateAIModelFolder() {
- let directoryURL = PrivateAIIntegrationService.modelDirectoryURL
- do {
- try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
- NSWorkspace.shared.open(directoryURL)
- } catch {
- DebugLogger.shared.error(
- "Failed to open Private AI Provider models folder: \(error.localizedDescription)",
- source: "AISettingsView"
- )
- }
- }
-
- func refreshPrivateAILoadState() {
- Task { @MainActor in
- guard let loaded = await PrivateAIIntegrationService.shared.loadedModelState(),
- loaded.state == .ready
- else {
- self.privateAILoadState = .idle
- return
- }
-
- self.privateAILoadState = .loaded(modelID: loaded.modelID, latencyMilliseconds: nil)
- }
- }
-
- private func loadPrivateAIModel(_ model: PrivateAIRegisteredModel) {
- guard PrivateAIIntegrationService.isModelInstalled(model) else {
- self.privateAILoadState = .failed(modelID: model.id, message: "Model file is not installed.")
- return
- }
-
- self.privateAILoadState = .loading(modelID: model.id)
- Task { @MainActor in
- do {
- let start = ContinuousClock.now
- let status = try await PrivateAIIntegrationService.shared.loadModel(model)
- let latencyMilliseconds = Self.elapsedMilliseconds(since: start)
- guard self.privateAISelectedModelID == model.id else { return }
- switch status.state {
- case .ready:
- self.privateAILoadState = .loaded(modelID: model.id, latencyMilliseconds: latencyMilliseconds)
- default:
- self.privateAILoadState = .failed(
- modelID: model.id,
- message: status.message ?? "Model did not report ready."
- )
- }
- } catch {
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .failed(
- modelID: model.id,
- message: Self.errorMessage(for: error)
- )
- }
- self.viewModel.refreshProviderItems()
- }
- }
-
- private func resetPrivateAIVerification(for model: PrivateAIRegisteredModel) {
- self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
- self.privateAILoadState = .idle
- Task { @MainActor in
- await PrivateAIIntegrationService.shared.unloadCachedRuntime(reason: "Fluid Intelligence verification reset")
- if PrivateAIIntegrationService.isModelInstalled(model) {
- self.privateAILoadState = .idle
- }
- self.viewModel.refreshProviderItems()
- }
- }
-
- private func deletePrivateAIModel(_ model: PrivateAIRegisteredModel) {
- guard PrivateAIIntegrationService.canRemoveInstalledModel(model) else { return }
- self.privateAILoadState = .loading(modelID: model.id)
- Task { @MainActor in
- do {
- try await PrivateAIIntegrationService.shared.unloadAndRemoveInstalledModel(
- model,
- reason: "settings-delete"
- )
- self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
- if self.privateAISelectedModelID == model.id {
- self.privateAILoadState = .idle
- }
- self.viewModel.refreshProviderItems()
- } catch {
- guard self.privateAISelectedModelID == model.id else { return }
- self.privateAILoadState = .failed(modelID: model.id, message: Self.errorMessage(for: error))
- }
- }
- }
-
- private static func errorMessage(for error: Error) -> String {
- if let localizedError = error as? LocalizedError,
- let description = localizedError.errorDescription
- {
- return description
- }
- return String(describing: error)
- }
-
private static func downloadButtonText(progress: PrivateAIModelDownloadProgress?) -> String {
PrivateAIModelDownloadProgressText.buttonTitle(for: progress)
}
@@ -1294,64 +1108,7 @@ extension AIEnhancementSettingsView {
PrivateAIModelDownloadProgressText.detailText(for: progress)
}
- private static func elapsedMilliseconds(since start: ContinuousClock.Instant) -> Int {
- let elapsed = start.duration(to: ContinuousClock.now)
- return Int(elapsed.components.seconds * 1000) + Int(elapsed.components.attoseconds / 1_000_000_000_000_000)
- }
-
- private func persistPrivateAIModelSelection(_ value: String) {
- let model = PrivateAIModelRegistry.model(id: value) ?? PrivateAIModelRegistry.defaultModel
- let providerKey = self.viewModel.providerKey(for: PrivateAIProviderFeature.shared.providerID)
- let models = PrivateAIModelRegistry.modelIDs()
-
- self.privateAISelectedModelID = model.id
- UserDefaults.standard.set(model.id, forKey: PrivateAIIntegrationService.selectedModelDefaultsKey)
- UserDefaults.standard.removeObject(forKey: PrivateAIIntegrationService.localModelPathDefaultsKey)
-
- self.viewModel.availableModelsByProvider[providerKey] = models
- self.viewModel.selectedModelByProvider[providerKey] = model.id
- self.viewModel.settings.availableModelsByProvider = self.viewModel.availableModelsByProvider
- self.viewModel.settings.selectedModelByProvider = self.viewModel.selectedModelByProvider
-
- if self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID {
- self.viewModel.availableModels = models
- self.viewModel.selectedModel = model.id
- }
- self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
- self.refreshPrivateAIModelUpdateStatus(model)
- self.viewModel.refreshProviderItems()
- if PrivateAIIntegrationService.isModelInstalled(model) {
- self.loadPrivateAIModel(model)
- } else {
- self.privateAILoadState = .idle
- }
- }
-
- private func setPrivateAIBackendPreference(_ preference: SettingsStore.PrivateAIBackendPreference) {
- guard self.settings.privateAIBackendPreference != preference else { return }
- let modelID = self.privateAISelectedModelID
-
- self.settings.privateAIBackendPreference = preference
- UserDefaults.standard.removeObject(forKey: PrivateAIIntegrationService.localModelPathDefaultsKey)
- self.privateAILoadState = .idle
- self.viewModel.resetVerification(for: PrivateAIProviderFeature.shared.providerID)
-
- Task { @MainActor in
- await PrivateAIIntegrationService.shared.unloadCachedRuntime(
- reason: "Fluid Intelligence backend changed to \(preference.displayName)"
- )
- guard self.privateAISelectedModelID == modelID else { return }
- let model = self.selectedPrivateAIModel
- if PrivateAIIntegrationService.isModelInstalled(model) {
- self.verifyPrivateAIConnection(model)
- } else {
- self.privateAILoadState = .idle
- self.viewModel.refreshProviderItems()
- }
- }
- }
-
- private func providerDetailsSection(for item: ProviderItem) -> AnyView {
+ private func providerDetailsSection(for item: ProviderItem, managementLayout: Bool = false) -> AnyView {
let providerKey = self.viewModel.providerKey(for: item.id)
let isCustom = !ModelRepository.shared.isBuiltIn(item.id)
let baseURL = self.viewModel.openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -1364,6 +1121,7 @@ extension AIEnhancementSettingsView {
let hasName = isCustom ? !(self.viewModel.savedProviders.first { $0.id == item.id }?.name ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty : true
let canFetchModels = hasName && (isLocal ? !baseURL.isEmpty : (hasAPIKey && !baseURL.isEmpty))
let canVerify = hasModels && !self.viewModel.selectedModel.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && canFetchModels
+ let isModelVerified = self.viewModel.isModelVerified(for: item.id)
let apiKeyBinding = Binding(
get: { self.viewModel.providerAPIKey(for: item.id) },
set: { self.viewModel.updateProviderAPIKey($0, for: item.id, persistEmptyValue: true) }
@@ -1381,7 +1139,7 @@ extension AIEnhancementSettingsView {
}
)
- return AnyView(VStack(alignment: .leading, spacing: 10) {
+ return AnyView(VStack(alignment: .leading, spacing: managementLayout ? 20 : 10) {
Group {
if isCustom {
VStack(alignment: .leading, spacing: 8) {
@@ -1419,64 +1177,110 @@ extension AIEnhancementSettingsView {
.foregroundStyle(.secondary)
HStack(alignment: .center, spacing: 8) {
SecureField("Enter API key", text: apiKeyBinding)
- .textFieldStyle(.roundedBorder)
+ .textFieldStyle(.plain)
.font(.system(size: 13))
- .frame(maxWidth: 200)
+ .padding(.horizontal, managementLayout ? 12 : 6)
+ .frame(height: AISettingsLayout.providerRowControlHeight)
+ .frame(maxWidth: managementLayout ? .infinity : 200)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))
+ .overlay(RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm).strokeBorder(self.theme.palette.cardBorder))
.onTapGesture {
self.viewModel.ensureKeychainAccessForAPIKeyEdit()
}
if let websiteInfo = ModelRepository.shared.providerWebsiteURL(for: item.id),
let url = URL(string: websiteInfo.url)
{
- Button(action: { NSWorkspace.shared.open(url) }) {
- HStack(spacing: 4) {
- Image(systemName: websiteInfo.label.contains("Guide") ? "book.fill" : "key.fill")
- .font(.system(size: 10))
- Text(websiteInfo.label)
- .font(.system(size: 11, weight: .medium))
+ if managementLayout {
+ Button(websiteInfo.label, systemImage: "key") { NSWorkspace.shared.open(url) }
+ .buttonStyle(.plain)
+ .font(self.theme.typography.bodyStrong)
+ .foregroundStyle(self.theme.palette.accent)
+ .frame(width: 128, height: AISettingsLayout.providerRowControlHeight)
+ } else {
+ Button(action: { NSWorkspace.shared.open(url) }) {
+ HStack(spacing: 4) {
+ Image(systemName: websiteInfo.label.contains("Guide") ? "book.fill" : "key.fill")
+ .font(.system(size: 10))
+ Text(websiteInfo.label)
+ .font(.system(size: 11, weight: .medium))
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 5)
+ .background(
+ RoundedRectangle(cornerRadius: 6, style: .continuous)
+ .fill(self.theme.palette.accent)
+ )
+ .foregroundStyle(.white)
}
- .padding(.horizontal, 10)
- .padding(.vertical, 5)
- .background(
- RoundedRectangle(cornerRadius: 6, style: .continuous)
- .fill(self.theme.palette.accent)
- )
- .foregroundStyle(.white)
+ .buttonStyle(.plain)
}
- .buttonStyle(.plain)
}
}
}
- HStack(spacing: 8) {
+ (managementLayout ? AnyLayout(VStackLayout(alignment: .leading, spacing: 6)) : AnyLayout(HStackLayout(spacing: 8))) {
Text("Model")
.font(.system(size: 12, weight: .medium))
.foregroundStyle(.secondary)
- .frame(width: 50, alignment: .leading)
+ .frame(width: managementLayout ? nil : 50, alignment: .leading)
- SearchableModelPicker(
- models: models,
- selectedModel: self.modelBinding(for: item.id),
- selectionEnabled: hasModels,
- controlWidth: 180,
- controlHeight: AISettingsLayout.providerRowControlHeight
- )
+ HStack(spacing: 8) {
+ SearchableModelPicker(
+ models: models,
+ selectedModel: self.modelBinding(for: item.id),
+ selectionEnabled: hasModels,
+ controlWidth: managementLayout ? 720 - 56 - 2 * AISettingsLayout.providerRowControlHeight - 32 : 180,
+ controlHeight: AISettingsLayout.providerRowControlHeight
+ )
- self.companionIconButton(
- isRefreshing: isRefreshing,
- disabled: isRefreshing || !canFetchModels,
- opacity: canFetchModels ? 1 : 0.45,
- help: "Refresh model list"
- ) {
- self.viewModel.configureProvider(item.id)
- Task { await self.viewModel.fetchModelsForCurrentProvider() }
+ self.companionIconButton(
+ isRefreshing: isRefreshing,
+ disabled: isRefreshing || !canFetchModels,
+ opacity: canFetchModels ? 1 : 0.45,
+ help: "Refresh model list"
+ ) {
+ self.viewModel.configureProvider(item.id)
+ Task { await self.viewModel.fetchModelsForCurrentProvider() }
+ }
+ if managementLayout {
+ self.companionIconButton(systemName: "plus", help: "Add model") {
+ self.viewModel.newModelName = ""
+ self.viewModel.showingAddModel.toggle()
+ }
+ .accessibilityLabel("Add model")
+ }
}
}
- HStack(spacing: 8) {
- Color.clear
- .frame(width: 50, alignment: .leading)
- self.reasoningButton(for: item.id)
+ if managementLayout, self.viewModel.showingAddModel {
+ self.addModelSection
+ }
+
+ if managementLayout {
+ VStack(alignment: .leading, spacing: 6) {
+ Text("Reasoning")
+ .font(self.theme.typography.captionStrong)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ HStack(spacing: 8) {
+ Text(self.viewModel.isReasoningEnabled(for: item.id) ? "Enabled" : "Not enabled")
+ .font(self.theme.typography.body)
+ .foregroundStyle(self.theme.palette.secondaryText)
+ Spacer()
+ Button("Configure…", systemImage: "gearshape") {
+ self.viewModel.configureProvider(item.id)
+ self.viewModel.openReasoningConfig()
+ }
+ .fluidButton(.compact, size: .small)
+ }
+ .padding(10)
+ .background(self.theme.palette.cardBackground, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm))
+ .overlay(RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm).strokeBorder(self.theme.palette.cardBorder))
+ }
+ } else {
+ HStack(spacing: 8) {
+ Color.clear.frame(width: 50, alignment: .leading)
+ self.reasoningButton(for: item.id)
+ }
}
if self.viewModel.showingReasoningConfig && self.viewModel.selectedProviderID == item.id {
@@ -1506,24 +1310,34 @@ extension AIEnhancementSettingsView {
}
if canVerify {
- Button(action: {
- Task { await self.viewModel.testAPIConnection() }
- }) {
- HStack(spacing: 6) {
- if self.viewModel.isTestingConnection {
- ProgressView()
- .controlSize(.mini)
- .fixedSize()
- } else {
- Image(systemName: "checkmark.shield")
- .font(.system(size: 12))
+ if isModelVerified {
+ Label("Model verified", systemImage: "checkmark.circle.fill")
+ .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.")
+ } else {
+ Button(action: {
+ Task { await self.viewModel.testAPIConnection() }
+ }) {
+ HStack(spacing: 6) {
+ if self.viewModel.isTestingConnection {
+ ProgressView()
+ .controlSize(.mini)
+ .fixedSize()
+ } else {
+ Image(systemName: "checkmark.shield")
+ .font(.system(size: 12))
+ }
+ Text(self.viewModel.isTestingConnection ? "Verifying…" : "Verify model")
+ .font(self.theme.typography.bodyStrong)
}
- Text(self.viewModel.isTestingConnection ? "Verifying..." : "Verify Connection")
- .font(.system(size: 13, weight: .semibold))
}
+ .fluidGlassAction(prominent: true)
+ .disabled(self.viewModel.isTestingConnection)
+ .help("Optional: send a small request to test this model. You can use it without running this check.")
+ .frame(maxWidth: managementLayout ? .infinity : nil, alignment: .trailing)
}
- .fluidButton(.accent, size: .small)
- .disabled(self.viewModel.isTestingConnection)
} else {
HStack(spacing: 6) {
Image(systemName: "info.circle")
@@ -1650,17 +1464,17 @@ extension AIEnhancementSettingsView {
let isDefaultProvider = isPrivateAIProvider
? primaryPromptSelection == .privateAI
: primaryPromptSelection == .default && item.id == self.settings.selectedProviderID
- let fluidModel = self.selectedPrivateAIModel
+ let fluidModel = self.privateAIController.selectedPrivateAIModel
let fluidStatus = self.privateAIModelStatus(for: fluidModel)
let isFluidInstalled = PrivateAIIntegrationService.isModelInstalled(fluidModel)
- let isFluidDownloading = self.privateAILoadState.isDownloading(fluidModel.id)
- let fluidDownloadProgress = self.privateAILoadState.downloadProgress(for: fluidModel.id)
- let isFluidLoading = self.privateAILoadState.isLoading(fluidModel.id)
- let hasFluidLoadFailure = self.privateAILoadState.failureMessage(for: fluidModel.id) != nil
- let hasFluidUpdate = self.privateAIModelUpdateStatusByID[fluidModel.id]?.state == .updateAvailable
+ let isFluidDownloading = self.privateAIController.privateAILoadState.isDownloading(fluidModel.id)
+ let fluidDownloadProgress = self.privateAIController.privateAILoadState.downloadProgress(for: fluidModel.id)
+ let isFluidLoading = self.privateAIController.privateAILoadState.isLoading(fluidModel.id)
+ let hasFluidLoadFailure = self.privateAIController.privateAILoadState.failureMessage(for: fluidModel.id) != nil
+ let hasFluidUpdate = self.privateAIController.privateAIModelUpdateStatusByID[fluidModel.id]?.state == .updateAvailable
let isFluidVerified = self.isPrivateAIModelVerified(fluidModel)
let isFluidTesting = self.viewModel.isTestingConnection && self.viewModel.selectedProviderID == PrivateAIProviderFeature.shared.providerID
- let isFluidBusy = isFluidDownloading || isFluidLoading || isFluidTesting
+ let isFluidBusy = self.privateAIController.isBusy || isFluidDownloading || isFluidLoading || isFluidTesting
let isRefreshing = self.viewModel.isFetchingModels && self.viewModel.selectedProviderID == item.id
let baseURL = self.providerBaseURL(for: item).trimmingCharacters(in: .whitespacesAndNewlines)
let isLocal = self.viewModel.isLocalEndpoint(baseURL)
@@ -1727,7 +1541,7 @@ extension AIEnhancementSettingsView {
)
self.companionIconButton(systemName: "folder", help: "Open downloaded model folder") {
- self.revealPrivateAIModelFolder()
+ self.privateAIController.revealPrivateAIModelFolder()
}
.frame(width: iconColumnWidth, height: AISettingsLayout.providerRowControlHeight)
@@ -1736,7 +1550,7 @@ extension AIEnhancementSettingsView {
systemName: "arrow.down.circle",
help: "Update and verify model"
) {
- self.updatePrivateAIModel(fluidModel)
+ self.privateAIController.updatePrivateAIModel(fluidModel)
}
.disabled(isFluidBusy)
.frame(width: iconColumnWidth, height: AISettingsLayout.providerRowControlHeight)
@@ -1987,12 +1801,29 @@ extension AIEnhancementSettingsView {
self.viewModel.connectionStatus = self.viewModel.connectionStatus(for: providerID)
}
+ // Match the main shortcut's routing without reading API keys or resolving an
+ // app-specific override in the view. Merely opening Manage never selects it.
+ private var primaryDefaultProviderID: String {
+ let selection = self.viewModel.dictationPromptSelection(for: .primary)
+ return DictationDefaultProvider.providerID(
+ selection: selection,
+ configuration: self.settings.dictationPromptConfiguration(for: selection),
+ selectedProviderID: self.settings.selectedProviderID,
+ privateProviderID: PrivateAIProviderFeature.shared.providerID
+ )
+ }
+
private func makePrimaryDefaultProvider(_ providerID: String, isPrivateAI: Bool) {
+ guard providerID != self.primaryDefaultProviderID,
+ !self.viewModel.isFetchingModels, !self.viewModel.isTestingConnection else { return }
if isPrivateAI {
+ guard !self.privateAIController.isBusy, self.viewModel.isPrivateAIPromptAvailable() else { return }
self.viewModel.setDictationPromptSelection(.privateAI, for: .primary)
return
}
+ guard self.viewModel.canUseProviderWithoutVerification(providerID),
+ self.viewModel.saveProviderAPIKeys(invalidating: providerID) else { return }
self.activateProvider(providerID)
var defaultConfiguration = self.settings.dictationPromptConfiguration(for: .default)
@@ -2070,20 +1901,56 @@ extension AIEnhancementSettingsView {
ModelRepository.shared.builtInProvidersList()
}
+ private func privateAIManagementSettings(
+ isBusy: Bool
+ ) -> some View {
+ VStack(alignment: .leading, spacing: 20) {
+ FluidManagementGroup(title: "Performance") {
+ Group {
+ VStack(alignment: .leading, spacing: 20) {
+ FluidManagementRow(title: "Backend", detail: self.settings.privateAIBackendPreference.detail) {
+ self.privateAIBackendPicker(isBusy: isBusy).frame(width: 200)
+ }
+ Divider()
+ FluidManagementRow(title: "Dictation window", detail: "\(self.privateAIContextCueText). Longer windows use more memory.") {
+ self.privateAIContextControl(isBusy: isBusy)
+ }
+ Divider()
+ FluidManagementRow(title: "Faster first result", detail: "Keep the model ready between dictations.") {
+ Toggle("Faster first result", isOn: self.privateAIPrefixCacheBinding)
+ .labelsHidden().toggleStyle(.switch).disabled(isBusy)
+ }
+ if self.privateAIShowsBoostRow {
+ Divider()
+ FluidManagementRow(title: "Faster results", detail: "Extra local acceleration. Uses more memory.") {
+ Toggle("Faster results", isOn: self.privateAIBoostBinding)
+ .labelsHidden().toggleStyle(.switch).disabled(isBusy)
+ }
+ }
+ }
+ .padding(.top, 16)
+ }
+ .font(self.theme.typography.bodyStrong)
+ }
+ }
+ }
+
func privateAIEditProviderSection(
model: PrivateAIRegisteredModel,
isInstalled: Bool,
isBusy: Bool,
- isVerified: Bool
+ isVerified: Bool,
+ removalAllowed: Bool? = nil,
+ onDone: (() -> Void)? = nil
) -> some View {
- let canDelete = isInstalled && PrivateAIIntegrationService.canRemoveInstalledModel(model)
+ let canDelete = isInstalled && (removalAllowed ?? PrivateAIIntegrationService.canRemoveInstalledModel(model))
return VStack(alignment: .leading, spacing: 14) {
HStack(spacing: 8) {
Image(systemName: "pencil.circle.fill")
.font(.system(size: 14))
.foregroundStyle(self.theme.palette.accent)
- Text("Edit Provider")
+ Text(onDone == nil ? "Edit Provider" : "Advanced settings")
.font(.system(size: 14, weight: .semibold))
Spacer()
}
@@ -2145,8 +2012,8 @@ extension AIEnhancementSettingsView {
HStack(spacing: 8) {
if isVerified {
Button {
- self.resetPrivateAIVerification(for: model)
- self.viewModel.clearEditProviderDraft()
+ self.privateAIController.resetPrivateAIVerification(for: model)
+ if onDone == nil { self.viewModel.clearEditProviderDraft() }
} label: {
HStack(spacing: 5) {
Image(systemName: "arrow.counterclockwise")
@@ -2155,12 +2022,13 @@ extension AIEnhancementSettingsView {
.font(.caption)
}
.fluidCompactButton(foreground: .red, borderColor: .red.opacity(0.6))
+ .disabled(isBusy)
}
if canDelete {
Button(role: .destructive) {
- self.deletePrivateAIModel(model)
- self.viewModel.clearEditProviderDraft()
+ self.privateAIController.deletePrivateAIModel(model)
+ if onDone == nil { self.viewModel.clearEditProviderDraft() }
} label: {
HStack(spacing: 6) {
Image(systemName: "trash")
@@ -2174,15 +2042,17 @@ extension AIEnhancementSettingsView {
Spacer(minLength: 0)
- Button {
- self.viewModel.clearEditProviderDraft()
- } label: {
- HStack(spacing: 6) {
- Image(systemName: "checkmark")
- Text("Done")
+ if onDone == nil {
+ Button {
+ self.viewModel.clearEditProviderDraft()
+ } label: {
+ HStack(spacing: 6) {
+ Image(systemName: "checkmark")
+ Text("Done")
+ }
}
+ .fluidButton(.glass, size: .compact)
}
- .fluidButton(.glass, size: .compact)
}
}
}
@@ -2687,22 +2557,22 @@ extension AIEnhancementSettingsView {
return VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 12) {
Button(action: { Task { await self.viewModel.testAPIConnection() } }) {
- Text(self.viewModel.isTestingConnection ? "Verifying..." : "Verify Connection")
+ Text(self.viewModel.isTestingConnection ? "Verifying…" : (self.viewModel.isModelVerified(for: self.viewModel.selectedProviderID) ? "Model verified" : "Verify model"))
.font(.caption)
.fontWeight(.semibold)
}
.fluidCompactButton(isReady: true)
.frame(minWidth: AISettingsLayout.primaryActionMinWidth, minHeight: AISettingsLayout.controlHeight)
- .disabled(self.viewModel.isTestingConnection ||
+ .disabled(self.viewModel.isTestingConnection || self.viewModel.isModelVerified(for: self.viewModel.selectedProviderID) ||
(!self.viewModel.isLocalEndpoint(self.viewModel.openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)) &&
selectedProviderAPIKey.isEmpty))
}
// Connection Status Display
- if self.viewModel.connectionStatus == .success {
+ if self.viewModel.isModelVerified(for: self.viewModel.selectedProviderID) {
HStack(spacing: 8) {
Image(systemName: "checkmark.circle.fill").foregroundStyle(Color.fluidGreen).font(.caption)
- Text("Connection verified").font(.caption).foregroundStyle(Color.fluidGreen)
+ Text("Model verified").font(.caption).foregroundStyle(Color.fluidGreen)
}
} else if self.viewModel.connectionStatus == .failed {
HStack(spacing: 8) {
diff --git a/Sources/Fluid/UI/AISettingsView.swift b/Sources/Fluid/UI/AISettingsView.swift
index 816d9e81..a8268a35 100644
--- a/Sources/Fluid/UI/AISettingsView.swift
+++ b/Sources/Fluid/UI/AISettingsView.swift
@@ -104,6 +104,7 @@ struct AISettingsView: View {
@StateObject private var voiceViewModel: VoiceEngineSettingsViewModel
@StateObject private var enhancementViewModel: AIEnhancementSettingsViewModel
+ @StateObject private var privateAIController: PrivateAISettingsController
@State private var selectedEnhancementSection: AIEnhancementConfigurationSection = .providers
init(appServices: AppServices, menuBarManager: MenuBarManager, theme: AppTheme) {
@@ -114,11 +115,13 @@ struct AISettingsView: View {
settings: SettingsStore.shared,
appServices: appServices
))
- _enhancementViewModel = StateObject(wrappedValue: AIEnhancementSettingsViewModel(
+ let enhancementModel = AIEnhancementSettingsViewModel(
settings: SettingsStore.shared,
menuBarManager: menuBarManager,
promptTest: DictationPromptTestCoordinator.shared
- ))
+ )
+ _enhancementViewModel = StateObject(wrappedValue: enhancementModel)
+ _privateAIController = StateObject(wrappedValue: PrivateAISettingsController(viewModel: enhancementModel))
}
var body: some View {
@@ -131,6 +134,7 @@ struct AISettingsView: View {
)
AIEnhancementSettingsView(
viewModel: self.enhancementViewModel,
+ privateAIController: self.privateAIController,
settings: self.enhancementViewModel.settings,
promptTest: self.enhancementViewModel.promptTest,
theme: self.theme,
diff --git a/Tests/DictationDefaultProviderTests.swift b/Tests/DictationDefaultProviderTests.swift
new file mode 100644
index 00000000..21386b3f
--- /dev/null
+++ b/Tests/DictationDefaultProviderTests.swift
@@ -0,0 +1,35 @@
+import Foundation
+
+// Minimal settings types let the production read-only resolver run without launching the app.
+enum SettingsStore {
+ enum DictationPromptSelection: Equatable { case off, `default`, privateAI, profile(String) }
+ struct DictationPromptConfiguration { var providerID: String; var modelName: String }
+}
+
+@main
+enum DictationDefaultProviderTests {
+ static func main() {
+ func resolve(_ selection: SettingsStore.DictationPromptSelection, _ global: String, _ provider: String = "", _ model: String = "") -> String {
+ DictationDefaultProvider.providerID(
+ selection: selection, configuration: .init(providerID: provider, modelName: model),
+ selectedProviderID: global, privateProviderID: "fluid-1"
+ )
+ }
+ precondition(resolve(.off, "openai", "openrouter", "model") == "")
+ precondition(resolve(.privateAI, "openai") == "fluid-1")
+ precondition(resolve(.default, "openai") == "openai")
+ precondition(resolve(.default, "openai", " openrouter ", " model ") == "openrouter")
+ precondition(resolve(.profile("style"), "openai", "custom-provider", "model") == "custom-provider")
+ precondition(resolve(.default, "fluid-1") == "fluid-1")
+ precondition(resolve(.profile("style"), "fluid-1") == "")
+ precondition(resolve(.default, "fluid-1", "openai", "") == "")
+ precondition(resolve(.default, "openai", "openrouter", "") == "openai")
+ precondition(resolve(.default, "openai", "", "model") == "openai")
+ precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: false, hasModel: true, isVerified: true, verificationFailed: false) == "API key missing")
+ precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: false, hasAPIKey: false, hasModel: true, isVerified: true, verificationFailed: false) == nil)
+ precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: false, isVerified: false, verificationFailed: false) == "Choose a model")
+ precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: true, isVerified: false, verificationFailed: false) == nil, "Optional verification must not block a configured provider")
+ precondition(DictationDefaultProvider.setupIssue(requiresAPIKey: true, hasAPIKey: true, hasModel: true, isVerified: false, verificationFailed: true) == "Verification failed")
+ print("PASS: 10 default-provider cases and 5 setup-status cases")
+ }
+}
diff --git a/Tests/PasteClipboardTests.swift b/Tests/PasteClipboardTests.swift
new file mode 100644
index 00000000..f3a9f1c0
--- /dev/null
+++ b/Tests/PasteClipboardTests.swift
@@ -0,0 +1,46 @@
+import AppKit
+
+@main
+enum PasteClipboardTests {
+ static func main() {
+ self.testClipboardPreservation()
+ print("PASS: rich clipboard round-trip, empty clipboard, newer and identical-text user copies preserved")
+ }
+
+ static func testClipboardPreservation() {
+ let board = NSPasteboard(name: NSPasteboard.Name("fluidvoice.paste-tests.\(UUID().uuidString)"))
+ defer { board.releaseGlobally() }
+ let original = NSPasteboardItem()
+ original.setString("original", forType: .string)
+ original.setData(Data([0, 1, 2, 255]), forType: .rtf)
+ let second = NSPasteboardItem()
+ second.setData(Data([3, 4, 5]), forType: .png)
+ board.clearContents()
+ precondition(board.writeObjects([original, second]))
+ let preserved = PreservedPasteboardSnapshot(board)
+ board.clearContents()
+ board.setString("dictated", forType: .string)
+ let owned = board.changeCount
+ precondition(preserved.restore(to: board, ifUnchangedSince: owned))
+ precondition(PreservedPasteboardSnapshot(board).items == preserved.items, "All item representations must round-trip")
+
+ board.clearContents()
+ board.setString("dictated", forType: .string)
+ let oldGeneration = board.changeCount
+ board.clearContents()
+ board.setString("dictated", forType: .string)
+ let userCopy = board.changeCount
+ precondition(!preserved.restore(to: board, ifUnchangedSince: oldGeneration), "Same text copied again belongs to the user")
+ precondition(board.changeCount == userCopy && board.string(forType: .string) == "dictated")
+ board.clearContents()
+ board.setString("new user copy", forType: .string)
+ precondition(!preserved.restore(to: board, ifUnchangedSince: oldGeneration))
+ precondition(board.string(forType: .string) == "new user copy")
+
+ board.clearContents()
+ let empty = PreservedPasteboardSnapshot(board)
+ board.setString("temporary", forType: .string)
+ precondition(empty.restore(to: board, ifUnchangedSince: board.changeCount))
+ precondition(board.string(forType: .string) == nil, "An originally empty clipboard must end empty")
+ }
+}
diff --git a/Tests/PrivateAISettingsBoundaryTests.swift b/Tests/PrivateAISettingsBoundaryTests.swift
new file mode 100644
index 00000000..36ea4186
--- /dev/null
+++ b/Tests/PrivateAISettingsBoundaryTests.swift
@@ -0,0 +1,156 @@
+import Foundation
+
+/// Standalone, deterministic tests of the production boundary. No app launch, defaults, keys or models.
+@main
+struct PrivateAISettingsBoundaryTests {
+ enum Failure: Error { case expected }
+
+ @MainActor
+ static func main() async throws {
+ var checks = 0
+ func check(_ condition: Bool, _ message: String) {
+ precondition(condition, message)
+ checks += 1
+ }
+ for gigabytes: UInt64 in [4, 8, 12] {
+ check(PrivateAIModelRecommendation.modelID(physicalMemory: gigabytes * 1024 * 1024 * 1024) == "fluid-1-pico-96k-dflash", "Below 16 GB recommends Pico")
+ }
+ for gigabytes: UInt64 in [16, 24, 32, 64, 128] {
+ check(PrivateAIModelRecommendation.modelID(physicalMemory: gigabytes * 1024 * 1024 * 1024) == "fluid-1-mini-96k-dflash", "16 GB and above recommends Mini")
+ }
+ check(PrivateAIModelRecommendation.modelID(physicalMemory: 16 * 1024 * 1024 * 1024 - 1) == "fluid-1-pico-96k-dflash", "Recommendation uses the exact 16 GB boundary")
+
+ check(PrivateAIModelCarouselNavigation.next(in: [], current: "missing", forward: true) == nil, "Empty catalog has no navigation target")
+ check(PrivateAIModelCarouselNavigation.next(in: ["mini"], current: "mini", forward: false) == "mini", "One model never fabricates a neighbor")
+ check(PrivateAIModelCarouselNavigation.next(in: ["pico", "mini"], current: "mini", forward: true) == "pico", "Two-model carousel wraps forward")
+ check(PrivateAIModelCarouselNavigation.next(in: ["pico", "mini"], current: "pico", forward: false) == "mini", "Two-model carousel wraps backward")
+ check(PrivateAIModelCarouselNavigation.next(in: ["pico", "mini"], current: "deleted", forward: true) == "pico", "Stale preview recovers to a real model")
+ check(PrivateAIModelCarouselNavigation.position(of: "pico", in: ["pico", "mini", "full"], current: "mini") == -1, "Three-model carousel places the previous card left")
+ check(PrivateAIModelCarouselNavigation.position(of: "full", in: ["pico", "mini", "full"], current: "mini") == 1, "Three-model carousel places the next card right")
+ var session = PrivateAISettingsSession(selectedModelID: "mini")
+ let initialRevision = session.revision
+ for id in ["pico", "mini", "pico"] { session.preview(id) }
+ check(session.previewModelID == "pico", "Preview follows browsing")
+ check(session.selectedModelID == "mini", "Browsing must not activate")
+ check(session.revision == initialRevision, "Browsing must not invalidate active work")
+ check(session.acceptsRead(initialRevision), "Read-only browsing retains current status")
+ check(session.select(session.previewModelID), "Explicit activation is accepted")
+ check(session.selectedModelID == "pico", "Activation changes selection")
+ check(!session.acceptsRead(initialRevision), "Old model status must be rejected")
+
+ let beforeOperation = session.revision
+ guard let first = session.begin() else { preconditionFailure("Expected first operation") }
+ check(session.begin() == nil, "Duplicate operation must not start")
+ check(!session.select("mini"), "Model activation must wait during mutation")
+ session.preview("mini")
+ check(session.previewModelID == "mini" && session.selectedModelID == "pico", "Browsing remains available during work")
+ check(!session.acceptsRead(beforeOperation), "Old refresh cannot erase loading/progress")
+ session.finish(UUID())
+ check(session.isBusy, "Foreign completion cannot release the current operation")
+ session.finish(first)
+ check(!session.isBusy, "Completion releases mutation slot")
+ check(!session.acceptsRead(beforeOperation), "Pre-operation refresh stays stale after completion")
+ guard let second = session.begin() else { preconditionFailure("Expected second operation") }
+ session.finish(first)
+ check(session.isBusy, "Late first completion cannot release second operation")
+ session.finish(second)
+
+ var events: [String] = []
+ let success = try await PrivateAISettingsUpdateTransaction.run(
+ update: { events.append("download"); return 7 },
+ verify: { events.append("verify"); return true },
+ commit: { check($0 == 7, "Commit exact update token"); events.append("commit") },
+ rollback: { _ in events.append("rollback") }
+ )
+ check(success && events == ["download", "verify", "commit"], "Success commits once, never rolls back")
+
+ events = []
+ let failedVerification = try await PrivateAISettingsUpdateTransaction.run(
+ update: { events.append("download"); return 8 },
+ verify: { events.append("verify"); return false },
+ commit: { _ in events.append("commit") },
+ rollback: { check($0 == 8, "Rollback exact update token"); events.append("rollback") }
+ )
+ check(!failedVerification && events == ["download", "verify", "rollback"], "Verification failure preserves previous artifact")
+
+ events = []
+ guard let failedOperation = session.begin() else { preconditionFailure("Expected failure operation") }
+ do {
+ defer { session.finish(failedOperation) }
+ _ = try await PrivateAISettingsUpdateTransaction.run(
+ update: { () async throws -> Int in events.append("download"); throw Failure.expected },
+ verify: { events.append("verify"); return true },
+ commit: { _ in events.append("commit") },
+ rollback: { _ in events.append("rollback") }
+ )
+ preconditionFailure("Download error must propagate")
+ } catch Failure.expected {}
+ check(events == ["download"], "Failed download must not verify/commit or roll back a nonexistent token")
+ check(!session.isBusy && session.select("mini"), "Failure permits retry/activation")
+
+ events = []
+ let cancelled = Task { @MainActor in
+ try await PrivateAISettingsUpdateTransaction.run(
+ update: {
+ withUnsafeCurrentTask { $0?.cancel() }
+ events.append("download")
+ return 9
+ },
+ verify: { events.append("verify"); return true },
+ commit: { _ in events.append("commit") },
+ rollback: { _ in events.append("rollback") }
+ )
+ }
+ do {
+ _ = try await cancelled.value
+ preconditionFailure("Cancellation must propagate")
+ } catch is CancellationError {}
+ check(events == ["download", "rollback"], "Cancellation after staging rolls back without verification")
+
+ events = []
+ let cancelDuringVerification = Task { @MainActor in
+ try await PrivateAISettingsUpdateTransaction.run(
+ update: { 10 },
+ verify: {
+ withUnsafeCurrentTask { $0?.cancel() }
+ return true
+ },
+ commit: { _ in events.append("commit") },
+ rollback: { _ in events.append("rollback") }
+ )
+ }
+ do {
+ _ = try await cancelDuringVerification.value
+ preconditionFailure("Cancellation must propagate")
+ } catch is CancellationError {}
+ check(events == ["rollback"], "Cancellation during verification never commits")
+
+ guard let rollbackOperation = session.begin() else { preconditionFailure("Expected rollback operation") }
+ _ = try await PrivateAISettingsUpdateTransaction.run(
+ update: { 11 },
+ verify: { false },
+ commit: { _ in preconditionFailure("Must not commit") },
+ rollback: { _ in
+ await Task.yield()
+ check(session.isBusy && session.begin() == nil, "Slot stays occupied across asynchronous rollback")
+ check(!session.select("pico"), "Selection cannot race rollback")
+ }
+ )
+ session.finish(rollbackOperation)
+ check(!session.isBusy, "Rollback completion allows another operation")
+ await PrivateAIControllerChecks.run(check: check)
+ let section = try String(contentsOfFile: "Sources/Fluid/UI/AISettings/FluidIntelligenceLiveSection.swift", encoding: .utf8)
+ check(section.contains("Label(\"Active\", systemImage: \"checkmark.circle.fill\")"), "Active is informational, not a disabled action")
+ check(!section.contains("onReady: self.makePrimary"), "Model activation must not silently assign the main shortcut")
+ check(!section.contains("modelPanel") && !section.contains("Model details…"), "Model menu never opens a duplicate management sheet")
+ check(!section.contains("Reset verification") && !section.contains("Troubleshooting"), "Model menu exposes no reset or troubleshooting submenu")
+ check(section.contains(".alert(\"Delete downloaded model?\""), "Deletion requires explicit confirmation")
+ check(section.components(separatedBy: "Open models folder").count == 2, "Shared Manage sheet owns the only folder action")
+ check(section.contains("if files?.installed == false, let bytes"), "Download size is visible before installation")
+ let card = try String(contentsOfFile: "Sources/Fluid/UI/AISettings/FluidModelShowcaseCard.swift", encoding: .utf8)
+ check(!card.contains(".popover("), "Model information stays inside its card")
+ check(card.contains("Button { self.showsInfo.toggle() }"), "Information toggles only local presentation state")
+ check(card.contains("self.reduceMotion ? nil") && card.contains("ZStack(alignment: .topLeading)"), "Inline information respects reduced motion and shares stable content bounds")
+ print("Passed \(checks) FI boundary/controller assertions")
+ }
+}
diff --git a/Tests/PrivateAISettingsControllerDoubles.swift b/Tests/PrivateAISettingsControllerDoubles.swift
new file mode 100644
index 00000000..b37e644d
--- /dev/null
+++ b/Tests/PrivateAISettingsControllerDoubles.swift
@@ -0,0 +1,271 @@
+import Foundation
+
+// Test-only adapters. Compile the actual controller against these, never against user preferences,
+// Keychain, downloads or inference. The normal app build separately checks the real adapters.
+struct PrivateAIModelDownloadProgress: Equatable, Sendable {
+ init(initialExpectedBytes: Int?) {}
+ func withFallbackExpectedBytes(_ bytes: Int?) -> Self { self }
+}
+struct PrivateAIRegisteredModel: Sendable {
+ let id: String
+ var canDownload = true
+ var artifact: Artifact { Artifact() }
+ struct Artifact { var byteCount: Int? = 10 }
+}
+struct PrivateAIModelUpdateStatus {
+ enum State { case current, updateAvailable }
+ var state: State
+}
+struct PrivateAIModelUpdateToken: Sendable { let id = UUID() }
+struct PrivateAIStatus { enum State { case ready, failed }; var state: State; var message: String? }
+enum PrivateAIModelRegistry {
+ static let defaultModel = PrivateAIRegisteredModel(id: "mini")
+ static func model(id: String) -> PrivateAIRegisteredModel? {
+ modelIDs().contains(id) ? PrivateAIRegisteredModel(id: id) : nil
+ }
+ static func modelIDs() -> [String] { ["mini", "pico"] }
+ static func canonicalModelID(for id: String) -> String? { model(id: id)?.id }
+}
+struct PrivateAIProviderFeature { static let shared = Self(); let providerID = "fi" }
+enum PrivateAIProviderPromptFormat {
+ static func verifiedModelID(settings: SettingsStore) -> String? { "mini" }
+}
+final class SettingsStore {
+ enum PrivateAIBackendPreference { case auto, mlx; var displayName: String { "test" } }
+ var privateAIBackendPreference: PrivateAIBackendPreference = .auto
+ var privateAIPrefixKVCacheEnabled = false
+ var privateAIBoostEnabled = false
+ var privateAIContextTokenLimit = 1024
+ var selectedModelByProvider = ["external": "external-model"]
+ var availableModelsByProvider = ["external": ["external-model"]]
+ static func clampPrivateAIContextTokenLimit(_ value: Int) -> Int { max(1, value) }
+}
+@MainActor
+final class UserDefaults {
+ static let standard = UserDefaults()
+ var writes = 0
+ func set(_ value: String, forKey key: String) { writes += 1 }
+ func removeObject(forKey key: String) { writes += 1 }
+}
+@MainActor
+final class AIEnhancementSettingsViewModel {
+ enum ConnectionStatus { case success }
+ let settings = SettingsStore()
+ var selectedProviderID = "external"
+ var availableModelsByProvider = ["external": ["external-model"]]
+ var selectedModelByProvider = ["external": "external-model"]
+ var availableModels = ["external-model"]
+ var selectedModel = "external-model"
+ var isTestingConnection = false
+ var verificationCount = 0
+ var resetCount = 0
+ var verified = true
+ func providerKey(for id: String) -> String { id }
+ func refreshProviderItems() {}
+ func connectionErrorMessage(for id: String) -> String { "test failure" }
+ func resetVerification(for id: String) { resetCount += 1 }
+ func updateConnectionStatus(_ status: ConnectionStatus, for id: String) {}
+ func verifyPrivateAIProvider(model: PrivateAIRegisteredModel) async -> Bool {
+ verificationCount += 1
+ return verified
+ }
+}
+struct DebugLogger {
+ static let shared = Self()
+ func info(_ message: String, source: String) {}
+ func error(_ message: String, source: String) {}
+}
+@MainActor
+final class PrivateAIIntegrationService {
+ struct LoadedModelState { var state: PrivateAIStatus.State; var modelID: String }
+ static let shared = PrivateAIIntegrationService()
+ static var configuredModelID = "mini"
+ static let selectedModelDefaultsKey = "test-selection"
+ static let localModelPathDefaultsKey = "test-path"
+ static let modelDirectoryURL = URL(fileURLWithPath: "/tmp/test-not-used")
+ static var installed = false
+ static var downloads = 0
+ static var loads = 0
+ static var commits = 0
+ static var rollbacks = 0
+ static var removals = 0
+ static var failDownload = false
+ static var lastProgress: (@Sendable (PrivateAIModelDownloadProgress) async -> Void)?
+ static var readContinuation: CheckedContinuation<LoadedModelState?, Never>?
+ static var suspendRead = false
+ static var loadContinuation: CheckedContinuation<PrivateAIStatus, Never>?
+ static var suspendLoad = false
+ static func isModelInstalled(_ model: PrivateAIRegisteredModel) -> Bool { installed }
+ static func canRemoveInstalledModel(_ model: PrivateAIRegisteredModel) -> Bool { installed }
+ static func modelUpdateStatus(_ model: PrivateAIRegisteredModel) async -> PrivateAIModelUpdateStatus { .init(state: .current) }
+ static func prepareModel(
+ _ model: PrivateAIRegisteredModel,
+ progressHandler: (@Sendable (PrivateAIModelDownloadProgress) async -> Void)? = nil
+ ) async throws -> URL {
+ downloads += 1
+ lastProgress = progressHandler
+ if failDownload { throw PrivateAISettingsBoundaryTests.Failure.expected }
+ await progressHandler?(.init(initialExpectedBytes: 10))
+ return modelDirectoryURL
+ }
+ static func updateModel(
+ _ model: PrivateAIRegisteredModel,
+ progressHandler: (@Sendable (PrivateAIModelDownloadProgress) async -> Void)? = nil
+ ) async throws -> PrivateAIModelUpdateToken {
+ _ = try await prepareModel(model, progressHandler: progressHandler)
+ return .init()
+ }
+ static func commitModelUpdate(_ token: PrivateAIModelUpdateToken) async { commits += 1 }
+ static func rollbackModelUpdate(_ token: PrivateAIModelUpdateToken) async { rollbacks += 1 }
+ func loadedModelState() async -> LoadedModelState? {
+ if Self.suspendRead { return await withCheckedContinuation { Self.readContinuation = $0 } }
+ return nil
+ }
+ func loadModel(_ model: PrivateAIRegisteredModel) async throws -> PrivateAIStatus {
+ Self.loads += 1
+ if Self.suspendLoad { return await withCheckedContinuation { Self.loadContinuation = $0 } }
+ return .init(state: .ready)
+ }
+ func unloadCachedRuntime(reason: String) async {}
+ func unloadAndRemoveInstalledModel(_ model: PrivateAIRegisteredModel, reason: String) async throws { Self.removals += 1 }
+}
+
+@MainActor
+enum PrivateAIControllerChecks {
+ static func eventually(_ predicate: () -> Bool) async {
+ for _ in 0..<10000 {
+ if predicate() { return }
+ await Task.yield()
+ }
+ preconditionFailure("Controlled task did not reach expected state")
+ }
+
+ static func run(check: (Bool, String) -> Void) async {
+ let vm = AIEnhancementSettingsViewModel()
+ let controller = PrivateAISettingsController(viewModel: vm)
+ for _ in 0..<50 { controller.previewModel("pico"); controller.previewModel("mini") }
+ controller.previewModel("pico")
+ controller.previewModel("invalid")
+ check(controller.previewModelID == "pico" && controller.privateAISelectedModelID == "mini", "Controller preview remains separate and rejects invalid IDs")
+ check(UserDefaults.standard.writes == 0 && vm.resetCount == 0, "Preview makes no persistence/verification writes")
+ check(PrivateAIIntegrationService.loads == 0 && PrivateAIIntegrationService.downloads == 0, "Preview does not load/download")
+ controller.activatePreviewModel()
+ check(controller.privateAISelectedModelID == "pico" && UserDefaults.standard.writes == 2, "Explicit activation persists through existing path")
+ check(vm.selectedProviderID == "external" && vm.selectedModel == "external-model", "FI selection must not change external editor/global provider")
+ check(vm.settings.selectedModelByProvider["external"] == "external-model", "FI selection preserves external saved model")
+
+ let writesBeforeCardRead = UserDefaults.standard.writes
+ controller.refreshPrivateAIModelUpdateStatus(PrivateAIRegisteredModel(id: "mini"))
+ await eventually { controller.privateAIModelUpdateStatusByID["mini"] != nil }
+ check(controller.privateAIModelUpdateStatusByID["mini"]?.state == .current, "Inactive card receives its own update status")
+ check(controller.privateAISelectedModelID == "pico" && UserDefaults.standard.writes == writesBeforeCardRead, "Card update read never selects or persists another model")
+ let verificationBeforeInactiveAction = vm.verificationCount
+ controller.verifyPrivateAIConnection(PrivateAIRegisteredModel(id: "mini"))
+ check(!controller.isBusy && vm.verificationCount == verificationBeforeInactiveAction, "Inactive maintenance cannot run against the selected runtime")
+
+ PrivateAIIntegrationService.failDownload = true
+ let pico = PrivateAIRegisteredModel(id: "pico")
+ controller.downloadPrivateAIModel(pico)
+ controller.downloadPrivateAIModel(pico)
+ controller.persistPrivateAIModelSelection("mini")
+ check(controller.isBusy && controller.privateAISelectedModelID == "pico", "Busy controller rejects duplicate action/model switching")
+ await eventually { !controller.isBusy }
+ check(PrivateAIIntegrationService.downloads == 1 && vm.verificationCount == 0, "Failed download never verifies and only starts once")
+ check(controller.privateAILoadState.failureMessage(for: "pico") != nil, "Failure is visible and releases busy state")
+ PrivateAIIntegrationService.failDownload = false
+ controller.downloadPrivateAIModel(pico)
+ await eventually { !controller.isBusy }
+ check(controller.privateAILoadState.isLoaded("pico") && vm.verificationCount == 1, "Download retry verifies and completes")
+ await PrivateAIIntegrationService.lastProgress?(.init(initialExpectedBytes: 10))
+ check(controller.privateAILoadState.isLoaded("pico"), "Late progress from finished download cannot replace ready state")
+
+ controller.privateAIModelUpdateStatusByID["pico"] = .init(state: .updateAvailable)
+ vm.verified = false
+ controller.updatePrivateAIModel(pico)
+ await eventually { !controller.isBusy }
+ check(PrivateAIIntegrationService.rollbacks == 1 && PrivateAIIntegrationService.commits == 0, "Real controller update path rolls back failed verification")
+ check(controller.privateAILoadState.failureMessage(for: "pico") != nil, "Update verification failure remains visible")
+ check(controller.privateAILoadState.failureMessage(for: "pico")?.contains("test failure") == true, "Update error includes provider-specific detail, not literal interpolation")
+
+ let writesBeforeNoop = UserDefaults.standard.writes
+ let previewBeforeUpcoming = controller.previewModelID
+ let selectionBeforeUpcoming = controller.privateAISelectedModelID
+ for upcoming in PrivateAIUpcomingModel.allCases {
+ controller.previewModel(upcoming.id)
+ controller.persistPrivateAIModelSelection(upcoming.id)
+ check(PrivateAIModelRegistry.model(id: upcoming.id) == nil, "Coming-soon previews are not runtime models")
+ }
+ check(controller.previewModelID == previewBeforeUpcoming && controller.privateAISelectedModelID == selectionBeforeUpcoming, "Coming-soon identifiers cannot alter runtime selection")
+ check(UserDefaults.standard.writes == writesBeforeNoop, "Coming-soon identifiers never persist")
+ controller.persistPrivateAIModelSelection("invalid")
+ controller.persistPrivateAIModelSelection("pico")
+ check(UserDefaults.standard.writes == writesBeforeNoop, "Invalid/redundant selection must not persist or reset verification")
+ controller.downloadPrivateAIModel(.init(id: "pico", canDownload: false))
+ check(!controller.isBusy, "Missing download configuration releases operation slot")
+ controller.deletePrivateAIModel(pico)
+ check(!controller.isBusy, "Non-removable model deletion releases operation slot")
+ PrivateAIIntegrationService.installed = true
+ controller.deletePrivateAIModel(.init(id: "mini"))
+ check(!controller.isBusy && PrivateAIIntegrationService.removals == 0, "Stale deletion confirmation cannot delete another selection")
+ let writesBeforeDeletion = UserDefaults.standard.writes
+ controller.deletePrivateAIModel(pico)
+ controller.deletePrivateAIModel(pico)
+ await eventually { !controller.isBusy }
+ check(PrivateAIIntegrationService.removals == 1 && controller.privateAILoadState == .idle, "Confirmed deletion runs once and returns to idle")
+ check(UserDefaults.standard.writes == writesBeforeDeletion && vm.selectedProviderID == "external", "Deletion does not change model selection or shortcut provider")
+ PrivateAIIntegrationService.installed = false
+
+ PrivateAIIntegrationService.suspendRead = true
+ controller.privateAILoadState = .idle
+ controller.refreshPrivateAILoadState()
+ await eventually { PrivateAIIntegrationService.readContinuation != nil }
+ PrivateAIIntegrationService.installed = true
+ PrivateAIIntegrationService.suspendLoad = true
+ controller.loadPrivateAIModel(pico)
+ await eventually { PrivateAIIntegrationService.loadContinuation != nil }
+ PrivateAIIntegrationService.readContinuation?.resume(returning: nil)
+ PrivateAIIntegrationService.readContinuation = nil
+ for _ in 0..<20 { await Task.yield() }
+ check(controller.privateAILoadState.isLoading("pico") && controller.isBusy, "Late idle read cannot erase a newer load")
+ controller.previewModel("mini")
+ controller.activatePreviewModel()
+ check(controller.privateAISelectedModelID == "pico" && controller.previewModelID == "mini", "Pending load permits preview but not activation")
+ PrivateAIIntegrationService.loadContinuation?.resume(returning: .init(state: .ready))
+ PrivateAIIntegrationService.loadContinuation = nil
+ await eventually { !controller.isBusy }
+ check(controller.privateAILoadState.isLoaded("pico"), "Load completion stays attached to activated model, not preview")
+ var activations = 0
+ vm.verified = false
+ controller.usePreviewModel(isInstalled: true) { activations += 1 }
+ controller.usePreviewModel(isInstalled: true) { activations += 1 }
+ await eventually { !controller.isBusy }
+ check(activations == 0, "Failed activation must not switch shortcut routing")
+ controller.refreshPrivateAILoadState()
+ for _ in 0..<20 { await Task.yield() }
+ check(controller.privateAILoadState.failureMessage(for: "mini") != nil, "Passive runtime refresh preserves failed activation")
+ vm.verified = true
+ controller.usePreviewModel(isInstalled: true) { activations += 1 }
+ await eventually { !controller.isBusy }
+ check(activations == 1 && controller.privateAILoadState.isLoaded("mini"), "Explicit activation calls routing once after successful verification")
+ check(vm.selectedProviderID == "external" && vm.selectedModel == "external-model", "Activation preserves external editor configuration")
+ var completionCount = 0
+ var reportedError: String?
+ let writesBeforeVerification = UserDefaults.standard.writes
+ controller.verifyPrivateAIConnection(.init(id: "mini"), onCompletion: { error in
+ completionCount += 1
+ reportedError = error
+ })
+ controller.verifyPrivateAIConnection(.init(id: "mini"), onCompletion: { _ in completionCount += 100 })
+ await eventually { !controller.isBusy }
+ check(completionCount == 1 && reportedError == nil, "Manual verification reports success once; duplicate clicks do not report")
+ vm.verified = false
+ controller.verifyPrivateAIConnection(.init(id: "mini"), onCompletion: { error in
+ completionCount += 1
+ reportedError = error
+ })
+ await eventually { !controller.isBusy }
+ check(completionCount == 2 && reportedError?.contains("test failure") == true, "Manual verification reports the actual failure")
+ controller.verifyPrivateAIConnection(.init(id: "pico"), onCompletion: { _ in completionCount += 100 })
+ check(completionCount == 2 && UserDefaults.standard.writes == writesBeforeVerification, "Inactive verification has no result or persistence side effects")
+ }
+}
diff --git a/Tests/ProviderModelVerificationStoreTests.swift b/Tests/ProviderModelVerificationStoreTests.swift
new file mode 100644
index 00000000..2c1d32fd
--- /dev/null
+++ b/Tests/ProviderModelVerificationStoreTests.swift
@@ -0,0 +1,39 @@
+import Foundation
+
+@main
+enum ProviderModelVerificationStoreTests {
+ @MainActor
+ static func main() {
+ let defaults = UserDefaults(suiteName: "fluidvoice.model-verification-tests.\(UUID().uuidString)")!
+ defer { defaults.removeObject(forKey: ProviderModelVerificationStore.defaultsKey) }
+ let store = ProviderModelVerificationStore(defaults: defaults)
+ func identity(_ model: String, key: String = "secret", endpoint: String = "https://example.com/v1", provider: String = "openrouter") -> String {
+ ProviderModelVerificationStore.identity(providerID: provider, baseURL: endpoint, apiKey: key, model: model)
+ }
+ let first = identity("model-a")
+ let second = identity("model-b")
+ precondition(!store.contains(first))
+ store.recordSuccess(first)
+ precondition(store.contains(first) && !store.contains(second), "Changing models must not reuse another model's check")
+ store.recordSuccess(second)
+ precondition(store.contains(first) && store.contains(second), "Switching back should remember success")
+ let reloaded = ProviderModelVerificationStore(defaults: defaults)
+ precondition(reloaded.contains(first) && reloaded.contains(second), "Success must survive relaunch")
+ precondition(!store.contains(identity("model-a", key: "changed")))
+ precondition(!store.contains(identity("model-a", endpoint: "https://other.example/v1")))
+ precondition(!store.contains(identity("model-a", provider: "other-provider")))
+ precondition(identity(" model-a ") == first)
+ store.remove(first)
+ precondition(!store.contains(first) && store.contains(second), "Failed recheck affects only its model identity")
+ for index in 0..<300 {
+ store.recordSuccess(identity("model-\(index)"), now: Date(timeIntervalSince1970: Double(index)))
+ }
+ let saved = defaults.dictionary(forKey: ProviderModelVerificationStore.defaultsKey)!
+ precondition(saved.count == ProviderModelVerificationStore.maximumEntries)
+ precondition(saved.keys.allSatisfy { $0.count == 64 && !$0.contains("secret") })
+ precondition(!store.contains(identity("model-0")) && store.contains(identity("model-299")))
+ defaults.set(["bad": Double.nan], forKey: ProviderModelVerificationStore.defaultsKey)
+ precondition(!ProviderModelVerificationStore(defaults: defaults).contains(first))
+ print("PASS: per-model persistence, model/key/endpoint/provider isolation, failure removal, bounded history and invalid data")
+ }
+}
diff --git a/Tests/ProviderSetupBoundaryTests.swift b/Tests/ProviderSetupBoundaryTests.swift
new file mode 100644
index 00000000..950511fe
--- /dev/null
+++ b/Tests/ProviderSetupBoundaryTests.swift
@@ -0,0 +1,110 @@
+import Foundation
+
+// Compile the production draft/save adapter against isolated settings and Keychain doubles.
+final class UserDefaults {
+ static let standard = UserDefaults()
+ var values: [String: [String]] = [:]
+ // Match Foundation UserDefaults, including an absent key.
+ // swiftlint:disable:next discouraged_optional_collection
+ func stringArray(forKey key: String) -> [String]? { values[key] }
+ func set(_ value: [String], forKey key: String) { values[key] = value }
+}
+struct PrivateAIProviderFeature {
+ static let shared = PrivateAIProviderFeature()
+ let providerID = "fluid"
+}
+struct ModelRepository {
+ static let shared = ModelRepository()
+ func isBuiltIn(_ id: String) -> Bool { ["openai", "ollama", "fluid"].contains(id) }
+ func defaultModels(for id: String) -> [String] { ["default-model"] }
+}
+final class SettingsStore {
+ struct SavedProvider {
+ var id = UUID().uuidString
+ let name: String
+ let baseURL: String
+ let models: [String]
+ }
+ struct Configuration { let providerID: String }
+ var selectedProviderID = "fluid"
+ var dictationPromptConfigurations: [String: Configuration] = [:]
+ var verifiedProviderFingerprints: [String: String] = [:]
+}
+final class AIEnhancementSettingsViewModel {
+ struct ProviderItemData {
+ let id: String
+ let name: String
+ let isBuiltIn: Bool
+ }
+ let settings = SettingsStore()
+ var isTestingConnection = false
+ var isFetchingModels = false
+ var providerAPIKeys: [String: String] = [:]
+ var savedProviders: [SettingsStore.SavedProvider] = []
+ var availableModelsByProvider: [String: [String]] = [:]
+ var selectedModelByProvider: [String: String] = ["fluid": "mini"]
+ var cachedAddedProviderItems: [ProviderItemData] = []
+ var failKeychain = false
+ var saves = 0
+ func providerKey(for id: String) -> String { id }
+ func providerAPIKey(for id: String) -> String { providerAPIKeys[id] ?? "" }
+ func updateProviderAPIKey(_ value: String, for id: String) { providerAPIKeys[id] = value }
+ func saveProviderAPIKeys(invalidating id: String) -> Bool { !failKeychain }
+ func refreshProviderItems() {
+ let items = [ProviderItemData(id: "openai", name: "OpenAI", isBuiltIn: true),
+ ProviderItemData(id: "ollama", name: "Ollama", isBuiltIn: true),
+ ProviderItemData(id: "fluid", name: "Fluid", isBuiltIn: true)]
+ + savedProviders.map { ProviderItemData(id: $0.id, name: $0.name, isBuiltIn: false) }
+ cachedAddedProviderItems = addedProviderItems(from: items)
+ }
+ func saveSavedProviders() { saves += 1; refreshProviderItems() }
+}
+
+@main enum ProviderSetupBoundaryTests {
+ static func main() throws {
+ var count = 0
+ func check(_ value: Bool, _ message: String) {
+ precondition(value, message)
+ count += 1
+ }
+ let vm = AIEnhancementSettingsViewModel()
+ vm.refreshProviderItems()
+ check(vm.cachedAddedProviderItems.isEmpty, "Fresh catalog stays hidden")
+ var draft = ProviderSetupDraft(name: "Local", baseURL: "http://localhost:1234/v1", model: "tiny")
+ check(draft.isValid && vm.saves == 0, "Editing a valid draft has no persistence effects")
+ draft.baseURL = "file:///tmp/model"
+ check(!draft.isValid && !vm.addProvider(draft), "Reject non-HTTP endpoints without persistence")
+ draft.baseURL = "https://user:[email protected]"
+ check(!draft.isValid, "Reject credentials embedded in URL")
+ draft.baseURL = "http://localhost:1234/v1"
+ draft.apiKey = "test-key"
+ vm.failKeychain = true
+ check(!vm.addProvider(draft) && vm.savedProviders.isEmpty && vm.providerAPIKeys.isEmpty && vm.saves == 0,
+ "Keychain failure keeps records, keys, and model maps unchanged")
+ vm.failKeychain = false
+ check(vm.addProvider(draft) && vm.savedProviders.count == 1, "Explicit Add saves a custom provider")
+ check(vm.settings.selectedProviderID == "fluid" && vm.selectedModelByProvider["fluid"] == "mini", "Adding does not change current route/model")
+ check(vm.addProvider(draft) && vm.savedProviders.count == 2, "Same display name cannot overwrite another provider")
+ check(vm.cachedAddedProviderItems.count == 2, "Saved custom providers appear without verification")
+ let builtIn = ProviderSetupDraft(providerID: "ollama", name: "Ollama", baseURL: "http://localhost:11434/v1")
+ check(vm.addProvider(builtIn), "Keyless local provider can be added")
+ check(!vm.addProvider(builtIn), "Duplicate built-in Add is rejected")
+ check(vm.cachedAddedProviderItems.contains { $0.id == "ollama" }, "Keyless provider remains visible via explicit membership")
+ vm.providerAPIKeys["openai"] = "expired-key"
+ vm.refreshProviderItems()
+ check(vm.cachedAddedProviderItems.contains { $0.id == "openai" }, "Unverified legacy credentials remain discoverable")
+ vm.providerAPIKeys.removeValue(forKey: "openai")
+ vm.settings.dictationPromptConfigurations["legacy"] = .init(providerID: "openai")
+ vm.refreshProviderItems()
+ check(vm.cachedAddedProviderItems.contains { $0.id == "openai" }, "Referenced provider stays visible after credentials disappear")
+ vm.isFetchingModels = true
+ check(!vm.addProvider(draft), "In-flight editor request blocks another Add")
+ let source = try String(contentsOfFile: "Sources/Fluid/UI/AISettingsView+AIConfiguration.swift", encoding: .utf8)
+ let manager = source.components(separatedBy: "private var externalProviderManager: some View")[1]
+ .components(separatedBy: "private var legacyAIConfigurationCard")[0]
+ check(!manager.contains("Use for shortcut") && !manager.contains("Edit details"), "External manager has no duplicate editor or shortcut assignment action")
+ check(source.contains(".onSubmit {") && source.contains("self.viewModel.addNewModel()"), "Manual model input retains Enter-to-add behavior")
+ check(source.contains(".accessibilityLabel(\"Add model\")"), "Model add button remains accessible")
+ print("Passed \(count) provider setup assertions")
+ }
+}
diff --git a/output/imagegen/external-provider-concepts/01-aligned-rows.png b/output/imagegen/external-provider-concepts/01-aligned-rows.png
new file mode 100644
index 00000000..3a684d05
Binary files /dev/null and b/output/imagegen/external-provider-concepts/01-aligned-rows.png differ
diff --git a/output/imagegen/external-provider-concepts/02-stacked-fields.png b/output/imagegen/external-provider-concepts/02-stacked-fields.png
new file mode 100644
index 00000000..9db4593a
Binary files /dev/null and b/output/imagegen/external-provider-concepts/02-stacked-fields.png differ
diff --git a/output/imagegen/external-provider-concepts/03-compact-panel.png b/output/imagegen/external-provider-concepts/03-compact-panel.png
new file mode 100644
index 00000000..b8ac80a0
Binary files /dev/null and b/output/imagegen/external-provider-concepts/03-compact-panel.png differ
diff --git a/output/imagegen/external-provider-concepts/04-footer-bar.png b/output/imagegen/external-provider-concepts/04-footer-bar.png
new file mode 100644
index 00000000..8c22690e
Binary files /dev/null and b/output/imagegen/external-provider-concepts/04-footer-bar.png differ
diff --git a/output/imagegen/external-provider-concepts/05-two-groups.png b/output/imagegen/external-provider-concepts/05-two-groups.png
new file mode 100644
index 00000000..b226fe99
Binary files /dev/null and b/output/imagegen/external-provider-concepts/05-two-groups.png differ
diff --git a/output/imagegen/external-provider-concepts/README.md b/output/imagegen/external-provider-concepts/README.md
new file mode 100644
index 00000000..ef24cf6f
--- /dev/null
+++ b/output/imagegen/external-provider-concepts/README.md
@@ -0,0 +1,15 @@
+# External provider layout concepts
+
+Generated with the built-in image-generation tool from the supplied OpenAI settings screenshot. Preview concepts only; no app implementation changed.
+
+## Shared prompt
+
+High-fidelity dark macOS OpenAI settings dialog. Simple, symmetric charcoal surfaces, restrained blue accents, system typography, equal margins and consistent control heights. Preserve API Key (masked dots only), Get API Key, Model babbage-002 with adjacent refresh and plus, Reasoning, Not enabled, Configure, Verify Connection and Done. No shortcuts, extra tabs, marketing, or invented features. Concept label outside the dialog.
+
+## Variant prompts and files
+
+- [Option 1 — Aligned rows](01-aligned-rows.png): One understated inset group with three horizontal rows, identical fixed left label column and aligned right control region. API key masked field and secondary Get API Key; Model selector with refresh and plus adjacent; Reasoning with Not enabled and Configure. Fine separators. Verify Connection bottom right below group.
+- [Option 2 — Stacked fields](02-stacked-fields.png): Two clean full-width stacked fields with labels above: API Key and Model. API key row masked field and Get API Key small text action; Model row selector refresh plus. Third full-width Reasoning row with Not enabled and Configure on the right. Verify Connection bottom right. No nested box and no redundant section heading.
+- [Option 3 — Compact panel](03-compact-panel.png): Small dense but comfortable dialog, no large empty margins. API key and Model labels left in a consistent grid. Refresh plus at right end of model row. Reasoning inline below aligned with inputs, small Configure button and Not enabled label. Verify Connection at bottom right, all controls same height. Restrained native Mac utility aesthetic.
+- [Option 4 — Footer bar](04-footer-bar.png): Elegant macOS sheet with comfortable aligned fields, API Key field and Get API Key; Model selector with refresh and plus; Reasoning Configure and Not enabled in a tidy row. Fixed thin footer separated by a hairline contains secondary Done at left and blue Verify Connection at right; no duplicate Done in header. One continuous flat content surface.
+- [Option 5 — Two quiet groups](05-two-groups.png): Two understated inset groups with same exact width and inset. First is Connection containing masked API key input with Get API Key. Second is Model containing model picker with refresh and plus, then a divider and Reasoning Not enabled with Configure. Verify Connection right aligned below groups. Header Done top right. Keep compact and no extra options.
diff --git a/output/imagegen/fluid-card-concepts/01-quiet-native.png b/output/imagegen/fluid-card-concepts/01-quiet-native.png
new file mode 100644
index 00000000..b1a2366a
Binary files /dev/null and b/output/imagegen/fluid-card-concepts/01-quiet-native.png differ
diff --git a/output/imagegen/fluid-card-concepts/02-horizontal.png b/output/imagegen/fluid-card-concepts/02-horizontal.png
new file mode 100644
index 00000000..b7f00ba3
Binary files /dev/null and b/output/imagegen/fluid-card-concepts/02-horizontal.png differ
diff --git a/output/imagegen/fluid-card-concepts/03-editorial.png b/output/imagegen/fluid-card-concepts/03-editorial.png
new file mode 100644
index 00000000..4c143336
Binary files /dev/null and b/output/imagegen/fluid-card-concepts/03-editorial.png differ
diff --git a/output/imagegen/fluid-card-concepts/04-footer-rail.png b/output/imagegen/fluid-card-concepts/04-footer-rail.png
new file mode 100644
index 00000000..321f32dd
Binary files /dev/null and b/output/imagegen/fluid-card-concepts/04-footer-rail.png differ
diff --git a/output/imagegen/fluid-card-concepts/05-soft-panel.png b/output/imagegen/fluid-card-concepts/05-soft-panel.png
new file mode 100644
index 00000000..8e45e59a
Binary files /dev/null and b/output/imagegen/fluid-card-concepts/05-soft-panel.png differ
diff --git a/output/imagegen/fluid-card-concepts/README.md b/output/imagegen/fluid-card-concepts/README.md
new file mode 100644
index 00000000..9378caeb
--- /dev/null
+++ b/output/imagegen/fluid-card-concepts/README.md
@@ -0,0 +1,23 @@
+# Fluid model card concepts
+
+Generated with the built-in image generation tool, using the supplied card screenshot as a reference. Preview concepts only; none is implemented in the app.
+
+## Images
+
+- [Quiet native](01-quiet-native.png)
+- [Horizontal utility](02-horizontal.png)
+- [Editorial](03-editorial.png)
+- [Footer rail](04-footer-rail.png)
+- [Soft panel](05-soft-panel.png)
+
+## Prompt set
+
+Shared specification: High-fidelity, flat, front-facing native macOS model-card mockup. Single card on charcoal canvas, dark navy/blue identity, crisp typography, no device frame. Preserve exact copy: Fluid 1 Pico; Smallest & fastest; Everyday dictation with basic cleanup and formatting.; Intelligence; Speed; Activate. Retain info and overflow controls. Intelligence uses two of five segments, Speed five of five, as illustrative design indicators rather than benchmark percentages. Inactive state: Activate is the primary action, with no selected checkmark. Avoid large circles, rings, illustrations, excessive glow, oversized empty space and additional marketing text. Make the card smaller, quieter, clearer and more symmetrical.
+
+1. Quiet native: Compact portrait, matte charcoal-navy, subtle border, 18px corners, 22px semibold title, compact description, small stacked metrics at bottom-right, blue rounded-rectangle Activate at bottom-left.
+2. Horizontal utility: Compact landscape, copy in left two-thirds, small aligned metrics in right third, footer Activate left and overflow right, info top-right, muted navy and 16px corners.
+3. Editorial: Almost-black blue compact portrait with thin blue top accent. Tight title/subtitle/body hierarchy. Two equal-width metric groups side by side, labels above thin segments. Quiet separator, Activate right and overflow left.
+4. Footer rail: Refined navy card, title and info in header, grouped copy. Lower utility rail places Activate left and tiny stacked metrics right, vertically balanced. Overflow near info, subtle gradient, 20px corners.
+5. Soft panel: Graphite with faint navy tint, header title/info/overflow, small metrics beside descriptive content in a secondary column, slim full-width Activate footer, consistent 20px padding.
+
+Image generation can vary exact proportions and indicator details; these are visual directions, not final UI specifications.
diff --git a/scripts/test_dictation_default_provider.sh b/scripts/test_dictation_default_provider.sh
new file mode 100644
index 00000000..8b7865a0
--- /dev/null
+++ b/scripts/test_dictation_default_provider.sh
@@ -0,0 +1,9 @@
+#!/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-default-provider.XXXXXX)
+xcrun swiftc -parse-as-library Sources/Fluid/UI/AISettings/DictationDefaultProvider.swift Tests/DictationDefaultProviderTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/scripts/test_paste_clipboard.sh b/scripts/test_paste_clipboard.sh
new file mode 100644
index 00000000..56a8275e
--- /dev/null
+++ b/scripts/test_paste_clipboard.sh
@@ -0,0 +1,9 @@
+#!/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-clipboard-tests.XXXXXX)
+xcrun swiftc -O -parse-as-library Sources/Fluid/Services/PreservedPasteboardSnapshot.swift Tests/PasteClipboardTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/scripts/test_private_ai_settings_boundary.sh b/scripts/test_private_ai_settings_boundary.sh
new file mode 100644
index 00000000..51a01f1d
--- /dev/null
+++ b/scripts/test_private_ai_settings_boundary.sh
@@ -0,0 +1,18 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+if [ ! -d "$task_developer_dir/Platforms/MacOSX.platform" ]; then
+ echo "Select a full Xcode with DEVELOPER_DIR before running these tests." >&2
+ exit 1
+fi
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-fi-boundary.XXXXXX)
+xcrun swiftc -parse-as-library \
+ Sources/Fluid/UI/AISettings/PrivateAISettingsSession.swift \
+ Sources/Fluid/UI/AISettings/PrivateAIModelPresentation.swift \
+ Sources/Fluid/UI/AISettings/PrivateAISettingsController.swift \
+ Tests/PrivateAISettingsControllerDoubles.swift \
+ Tests/PrivateAISettingsBoundaryTests.swift \
+ -o "$task_test_dir/boundary-tests"
+"$task_test_dir/boundary-tests"
diff --git a/scripts/test_provider_model_verification.sh b/scripts/test_provider_model_verification.sh
new file mode 100644
index 00000000..9860ced2
--- /dev/null
+++ b/scripts/test_provider_model_verification.sh
@@ -0,0 +1,9 @@
+#!/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-model-verification.XXXXXX)
+xcrun swiftc -parse-as-library Sources/Fluid/UI/AISettings/ProviderModelVerificationStore.swift Tests/ProviderModelVerificationStoreTests.swift -o "$task_test_dir/tests"
+"$task_test_dir/tests"
diff --git a/scripts/test_provider_setup_boundary.sh b/scripts/test_provider_setup_boundary.sh
new file mode 100644
index 00000000..e2e4c594
--- /dev/null
+++ b/scripts/test_provider_setup_boundary.sh
@@ -0,0 +1,16 @@
+#!/bin/sh
+set -eu
+cd "$(dirname "$0")/.."
+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"
+if [ ! -d "$task_developer_dir/Platforms/MacOSX.platform" ]; then
+ echo "Select a full Xcode with DEVELOPER_DIR before running these tests." >&2
+ exit 1
+fi
+export DEVELOPER_DIR="$task_developer_dir"
+task_test_dir=$(mktemp -d /tmp/fluidvoice-provider-setup.XXXXXX)
+xcrun swiftc -parse-as-library \
+ Sources/Fluid/UI/AISettings/ProviderSetupDraft.swift \
+ Sources/Fluid/UI/AISettings/AIEnhancementSettingsViewModel+ProviderSetup.swift \
+ Tests/ProviderSetupBoundaryTests.swift \
+ -o "$task_test_dir/provider-tests"
+"$task_test_dir/provider-tests"