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
fix(feedback): validate submissions and require delivery receipts
altic-devb544e4338c6c
diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxprojindex 1b85af48..a987c33c 100644--- a/Fluid.xcodeproj/project.pbxproj+++ b/Fluid.xcodeproj/project.pbxproj@@ -18,6 +18,7 @@7C9A71022F58B00000FB7CAF /* TranscribeCpp in Frameworks */ = {isa = PBXBuildFile; productRef = 7C9A71012F58B00000FB7CAF /* TranscribeCpp */; };7C91B0012F42AA0100C0DEF0 /* HotkeyShortcutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C91B0022F42AA0100C0DEF0 /* HotkeyShortcutTests.swift */; };DAB600000000000000000001 /* DashboardLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAB600000000000000000002 /* DashboardLayoutTests.swift */; };+ FEB700000000000000000001 /* FeedbackClientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEB700000000000000000002 /* FeedbackClientTests.swift */; };7C91B0A12F42AA0100C0DEF0 /* DeliveryTargetAssessmentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C91B0A22F42AA0100C0DEF0 /* DeliveryTargetAssessmentTests.swift */; };C0DE89000000000000000002 /* SettingsNavigationStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE89000000000000000001 /* SettingsNavigationStateTests.swift */; };7CDB0A2D2F3C4D5600FB7CAD /* DictationE2ETests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CDB0A292F3C4D5600FB7CAD /* DictationE2ETests.swift */; };@@ -205,6 +206,7 @@7C078D8F2E3B339200FB7CAC /* FluidVoice Debug.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "FluidVoice Debug.app"; sourceTree = BUILT_PRODUCTS_DIR; };7C91B0022F42AA0100C0DEF0 /* HotkeyShortcutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HotkeyShortcutTests.swift; sourceTree = "<group>"; };DAB600000000000000000002 /* DashboardLayoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashboardLayoutTests.swift; sourceTree = "<group>"; };+ FEB700000000000000000002 /* FeedbackClientTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FeedbackClientTests.swift; sourceTree = "<group>"; };7C91B0A22F42AA0100C0DEF0 /* DeliveryTargetAssessmentTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeliveryTargetAssessmentTests.swift; sourceTree = "<group>"; };C0DE89000000000000000001 /* SettingsNavigationStateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsNavigationStateTests.swift; sourceTree = "<group>"; };7CDB0A202F3C4D5600FB7CAD /* FluidDictationIntegrationTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = FluidDictationIntegrationTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };@@ -356,6 +358,7 @@CD1C7A0000000000000000B1 /* CustomDictionaryManualEntryTests.swift */,7C91B0022F42AA0100C0DEF0 /* HotkeyShortcutTests.swift */,DAB600000000000000000002 /* DashboardLayoutTests.swift */,+ FEB700000000000000000002 /* FeedbackClientTests.swift */,7C91B0A22F42AA0100C0DEF0 /* DeliveryTargetAssessmentTests.swift */,C0DE89000000000000000001 /* SettingsNavigationStateTests.swift */,343B29013F4441D6A797D12D /* LLMClientRequestBodyTests.swift */,@@ -706,6 +709,7 @@CD1C7A0000000000000000B2 /* CustomDictionaryManualEntryTests.swift in Sources */,7C91B0012F42AA0100C0DEF0 /* HotkeyShortcutTests.swift in Sources */,DAB600000000000000000001 /* DashboardLayoutTests.swift in Sources */,+ FEB700000000000000000001 /* FeedbackClientTests.swift in Sources */,7C91B0A12F42AA0100C0DEF0 /* DeliveryTargetAssessmentTests.swift in Sources */,C0DE89000000000000000002 /* SettingsNavigationStateTests.swift in Sources */,86CAA2D4EF18433096185602 /* LLMClientRequestBodyTests.swift in Sources */,@@ -1297,6 +1301,8 @@revision = 932842b7eb9728597b69750270e0d8896668dbd4;};};++7C3697872ED70F9C005874CE /* XCRemoteSwiftPackageReference "DynamicNotchKit" */ = {isa = XCRemoteSwiftPackageReference;repositoryURL = "https://github.com/altic-dev/DynamicNotchKit.git";diff --git a/Sources/Fluid/Services/FeedbackClient.swift b/Sources/Fluid/Services/FeedbackClient.swiftnew file mode 100644index 00000000..c7e3200d--- /dev/null+++ b/Sources/Fluid/Services/FeedbackClient.swift@@ -0,0 +1,126 @@+import Foundation++enum FeedbackCategory: String, CaseIterable {+ case issue = "Report an issue"+ case idea = "Suggest an idea"+ case other = "Something else"++ var icon: String {+ switch self {+ case .issue: "flag"+ case .idea: "lightbulb"+ case .other: "bubble.left"+ }+ }++ var prompt: String {+ switch self {+ case .issue: "What happened?"+ case .idea: "What would you like to do?"+ case .other: "What would you like us to know?"+ }+ }++ var hint: String {+ switch self {+ case .issue: "What were you trying to do? What happened instead? A few steps help us reproduce it."+ case .idea: "Tell us what would make your day easier, and how you’d use it."+ case .other: "The small details count. Share what’s working—or what isn’t."+ }+ }+}++struct FeedbackSubmission: Encodable {+ static let messageLimit = 4500+ let email: String+ let message: String+ let category: FeedbackCategory+ let appDetails: String?++ static var appDetails: String {+ let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "Unknown"+ let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "Unknown"+ return "FluidVoice \(version) (\(build))\nmacOS: \(ProcessInfo.processInfo.operatingSystemVersionString)"+ }++ static func isValidEmail(_ value: String) -> Bool {+ let email = value.trimmingCharacters(in: .whitespacesAndNewlines)+ return email.utf16.count <= 254 && email.range(+ of: #"^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+\-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$"#,+ options: [.caseInsensitive, .regularExpression]+ ) != nil+ }++ var content: String {+ var text = "[\(self.category.rawValue)]\n\(self.message.trimmingCharacters(in: .whitespacesAndNewlines))"+ if let appDetails { text += "\n\n--- App details ---\n\(appDetails)" }+ return text+ }++ var isValid: Bool {+ Self.isValidEmail(self.email)+ && !self.message.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ && self.message.utf16.count <= Self.messageLimit+ && self.content.utf16.count <= 5000+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(self.email.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), forKey: .email)+ try container.encode(self.content, forKey: .feedback)+ }++ private enum CodingKeys: String, CodingKey {+ case email = "email_id"+ case feedback+ }+}++struct FeedbackClient {+ var session: URLSession = .shared++ func send(_ submission: FeedbackSubmission) async throws {+ guard submission.isValid else { throw Failure.invalid }+ guard let url = URL(string: "https://altic.dev/api/fluid/feedback") else { throw Failure.invalid }+ var request = URLRequest(url: url, timeoutInterval: 30)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.setValue("application/json", forHTTPHeaderField: "Accept")+ request.httpBody = try JSONEncoder().encode(submission)+ do {+ let (data, response) = try await self.session.data(for: request)+ guard let response = response as? HTTPURLResponse else { throw Failure.unconfirmed }+ switch response.statusCode {+ case 200...299:+ // A redirected HTML page is not a delivery receipt.+ let receipt = try? JSONDecoder().decode(Receipt.self, from: data)+ guard receipt?.message == "Feedback submitted successfully" else { throw Failure.unconfirmed }+ case 429: throw Failure.rateLimited+ case 400...499: throw Failure.rejected+ default: throw Failure.server+ }+ } catch let failure as Failure {+ throw failure+ } catch {+ // A timeout can happen after storage. Never automatically retry a POST.+ throw Failure.connection+ }+ }++ private struct Receipt: Decodable { let message: String }++ enum Failure: LocalizedError {+ case invalid, rateLimited, rejected, server, connection, unconfirmed++ var errorDescription: String? {+ switch self {+ case .invalid: "Add a valid email and a message within the character limit."+ case .rateLimited: "Too many messages at once. Please wait a minute, then try again. Your draft is still here."+ case .rejected: "The server couldn’t accept this message. Check your email and message length. Your draft is still here."+ case .server: "Feedback is temporarily unavailable. Please try again later. Your draft is still here."+ case .connection: "Delivery couldn’t be confirmed. Check your connection before retrying; your message may already have arrived. Your draft is still here."+ case .unconfirmed: "We couldn’t confirm delivery. Your draft is still here; please try again later."+ }+ }+ }+}diff --git a/Sources/Fluid/UI/FeedbackView.swift b/Sources/Fluid/UI/FeedbackView.swiftindex 068f5642..0f357b22 100644--- a/Sources/Fluid/UI/FeedbackView.swift+++ b/Sources/Fluid/UI/FeedbackView.swift@@ -1,324 +1,233 @@-//-// FeedbackView.swift-// fluid-//-// Extracted from ContentView.swift to reduce monolithic architecture.-// Created: 2025-12-14-//--import AppKitimport SwiftUIstruct FeedbackView: View {@Environment(\.theme) private var theme-- // MARK: - State Variables (moved from ContentView)-- @State private var feedbackText: String = ""- @State private var feedbackEmail: String = ""- @State private var includeDebugLogs: Bool = false- @State private var isSendingFeedback: Bool = false- @State private var showFeedbackConfirmation: Bool = false- @State private var showFeedbackError: Bool = false- @State private var feedbackErrorMessage: String = ""- @State private var appear: Bool = false+ @Environment(\.accessibilityReduceTransparency) private var reduceTransparency+ @State private var category: FeedbackCategory = .issue+ @State private var message = ""+ @State private var email = ""+ @State private var includeDetails = false+ @State private var sending = false+ @State private var sent = false+ @State private var error: String?++ private var draft: FeedbackSubmission {+ FeedbackSubmission(+ email: self.email,+ message: self.message,+ category: self.category,+ appDetails: self.includeDetails ? FeedbackSubmission.appDetails : nil+ )+ }var body: some View {ScrollView {- VStack(alignment: .leading, spacing: 20) {- // Header- VStack(alignment: .leading, spacing: 8) {- HStack {- Image(systemName: "envelope.fill")- .font(.fluidSystem(size: 32))- .foregroundStyle(self.theme.palette.accent)- VStack(alignment: .leading) {- Text("Send Feedback")- .font(.fluidSystem(size: 28, weight: .bold))- Text("Help us improve FluidVoice")- .font(.fluidSystem(size: 16))- .foregroundStyle(.secondary)- }- }+ VStack(alignment: .leading, spacing: self.theme.metrics.spacing.xxl) {+ VStack(alignment: .leading, spacing: 10) {+ Text("Make FluidVoice better.").font(self.theme.typography.displayTitle)+ Text("Something getting in your way? Have an idea? Tell us.")+ .font(self.theme.typography.statement).foregroundStyle(.secondary)}- .padding(.bottom, 8)-- // Friendly Message & GitHub CTA- ThemedCard(style: .prominent, hoverEffect: false) {- VStack(alignment: .leading, spacing: 12) {- HStack(spacing: 12) {- Image(systemName: "heart.fill")- .font(.fluidSystem(size: 28))- .foregroundStyle(.pink)-- VStack(alignment: .leading, spacing: 4) {- Text("We'd love to hear from you!")- .font(.fluidSystem(size: 18, weight: .semibold))- .foregroundStyle(self.theme.palette.primaryText)-- Text("Your feedback helps us make FluidVoice even better")- .font(.fluidSystem(size: 14))- .foregroundStyle(self.theme.palette.secondaryText)- }- }-- Divider()- .padding(.vertical, 4)-- HStack(spacing: 12) {- Image(systemName: "star.fill")- .font(.fluidSystem(size: 24))- .foregroundStyle(.yellow)-- VStack(alignment: .leading, spacing: 6) {- Text("Loving FluidVoice?")- .font(.fluidSystem(size: 16, weight: .semibold))- .foregroundStyle(self.theme.palette.primaryText)-- Text("Give us a star on GitHub, or support continued free development to help make local dictation even better.")- .font(.fluidSystem(size: 13))- .foregroundStyle(self.theme.palette.secondaryText)- .fixedSize(horizontal: false, vertical: true)- }-- Spacer()-- HStack(spacing: 10) {- if let githubURL = URL(string: "https://github.com/altic-dev/Fluid-oss") {- Link(destination: githubURL) {- HStack(spacing: 8) {- Image(systemName: "star.fill")- Text("Star on GitHub")- .fontWeight(.semibold)- }- .font(.fluidSystem(size: 14))- .padding(.horizontal, 20)- .padding(.vertical, 10)- }- .fluidButton(.glass, size: .medium)- .buttonHoverEffect()- }+ FluidGlassControlGroup { self.starInvitation }+ if self.sent { self.confirmation } else { self.form }+ self.footer+ }+ .frame(maxWidth: 760, alignment: .leading)+ .padding(self.theme.metrics.spacing.xxl)+ .frame(maxWidth: .infinity, alignment: .center)+ }+ }- if let sponsorURL = URL(string: "https://github.com/sponsors/altic-dev") {- Link(destination: sponsorURL) {- HStack(spacing: 8) {- Image(systemName: "heart.fill")- Text("Support FluidVoice")- .fontWeight(.semibold)- }- .font(.fluidSystem(size: 14))- .padding(.horizontal, 20)- .padding(.vertical, 10)- }- .fluidButton(.glass, size: .medium)- .buttonHoverEffect()- .help("Sponsor Altic on GitHub")- }- }- }+ private var form: some View {+ ThemedCard(style: .standard, padding: self.theme.metrics.spacing.xxl) {+ VStack(alignment: .leading, spacing: 24) {+ VStack(alignment: .leading, spacing: 12) {+ Text("What’s on your mind?").font(self.theme.typography.sectionTitle)+ ViewThatFits(in: .horizontal) {+ HStack(spacing: 8) { self.categories }+ VStack(alignment: .leading, spacing: 8) { self.categories }}- .padding(20)}-- // Feedback Form- ThemedCard(style: .standard, hoverEffect: false) {- VStack(alignment: .leading, spacing: 16) {- VStack(alignment: .leading, spacing: 12) {- Text("Email")- .font(.fluidSystem(.headline))- .fontWeight(.semibold)-- TextField("[email protected]", text: self.$feedbackEmail)- .textFieldStyle(.roundedBorder)- .font(.fluidSystem(size: 14))-- Text("Feedback")- .font(.fluidSystem(.headline))- .fontWeight(.semibold)- .padding(.top, 8)-- TextEditor(text: self.$feedbackText)- .font(.fluidSystem(size: 14))- .frame(height: 120)- .padding(12)- .background(RoundedRectangle(cornerRadius: 8)- .fill(self.theme.palette.contentBackground)- .overlay(RoundedRectangle(cornerRadius: 8)- .strokeBorder(self.theme.palette.cardBorder.opacity(0.45), lineWidth: 1.2)))- .scrollContentBackground(.hidden)- .overlay(- Group {- if self.feedbackText.isEmpty {- Text("Share your thoughts, report bugs, or suggest features...")- .font(.fluidSystem(.subheadline))- .foregroundStyle(.secondary)- .padding(.leading, 4)- }- }- .allowsHitTesting(false)- )-- // Debug logs option- Toggle("Include debug logs", isOn: self.$includeDebugLogs)- .toggleStyle(GlassToggleStyle())-- // Send Button- HStack {- Spacer()-- Button(action: {- Task {- await self.sendFeedback()- }- }) {- HStack(spacing: 8) {- if self.isSendingFeedback {- ProgressView()- .fixedSize()- .scaleEffect(0.8)- } else {- Image(systemName: "paperplane.fill")- }- Text(self.isSendingFeedback ? "Sending..." : "Send Feedback")- .fontWeight(.semibold)- }- .padding(.horizontal, 20)- .padding(.vertical, 10)- }- .fluidButton(.glass, size: .medium)- .disabled(self.feedbackText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||- self.feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ||- self.isSendingFeedback)- .buttonHoverEffect()- }- }+ self.messageField+ VStack(alignment: .leading, spacing: 8) {+ Text("Your email").font(self.theme.typography.bodyStrong)+ TextField("Your email", text: self.$email, prompt: Text("[email protected]").foregroundColor(self.theme.palette.secondaryText))+ .textFieldStyle(.plain).font(self.theme.typography.body)+ .padding(12).fluidOnboardingEditorSurface()+ .accessibilityLabel("Your email")+ Text(self.email.isEmpty || FeedbackSubmission.isValidEmail(self.email)+ ? "So we can follow up about your feedback."+ : "Enter a valid email address, like [email protected].")+ .font(self.theme.typography.caption).foregroundStyle(.secondary)+ }+ Divider()+ HStack(spacing: 16) {+ VStack(alignment: .leading, spacing: 5) {+ Text("Include app details").font(self.theme.typography.bodyStrong)+ Text("App version and macOS version only. No recordings or logs.")+ .font(self.theme.typography.caption).foregroundStyle(.secondary)}- .padding(20)+ Spacer(minLength: 0)+ Toggle("Include app details", isOn: self.$includeDetails)+ .labelsHidden().toggleStyle(.switch).fixedSize()+ .accessibilityLabel("Include app and macOS versions")+ }+ if self.includeDetails {+ Text(FeedbackSubmission.appDetails)+ .font(self.theme.typography.codeCaption).foregroundStyle(.secondary)+ .textSelection(.enabled)+ }+ if let error = self.error {+ Label(error, systemImage: "exclamationmark.circle")+ .font(self.theme.typography.bodySmall)+ .foregroundStyle(self.theme.palette.warning)+ .fixedSize(horizontal: false, vertical: true)+ }+ ViewThatFits(in: .horizontal) {+ HStack(spacing: 16) { self.deliveryNote; Spacer(minLength: 0); self.sendButton }+ VStack(alignment: .leading, spacing: 12) { self.deliveryNote; self.sendButton }}- .modifier(CardAppearAnimation(delay: 0.1, appear: self.$appear))}- .padding(24)+ .disabled(self.sending)}- .onAppear {- self.appear = true- }- .alert("Feedback Sent", isPresented: self.$showFeedbackConfirmation) {- Button("OK") {}- } message: {- Text("Thank you for helping us improve FluidVoice.")- }- .alert("Feedback Failed", isPresented: self.$showFeedbackError) {- Button("Try Again") {- Task {- await self.sendFeedback()+ }++ private var messageField: some View {+ VStack(alignment: .leading, spacing: 10) {+ Text(self.category.prompt).font(self.theme.typography.bodyStrong)+ ZStack(alignment: .topLeading) {+ TextEditor(text: self.$message)+ .font(self.theme.typography.body).scrollContentBackground(.hidden)+ .padding(10).frame(minHeight: 180, maxHeight: 240)+ .accessibilityLabel(self.category.prompt)+ if self.message.isEmpty {+ Text(self.category.hint).font(self.theme.typography.body)+ .foregroundStyle(.secondary)+ .padding(.horizontal, 15).padding(.vertical, 18)+ .allowsHitTesting(false)}}- Button("Cancel", role: .cancel) {}- } message: {- Text(self.feedbackErrorMessage)+ .fluidOnboardingEditorSurface()+ HStack(alignment: .top) {+ Text("Please leave out passwords and private information.")+ Spacer(minLength: 8)+ Text("\(self.message.utf16.count) / \(FeedbackSubmission.messageLimit)")+ .monospacedDigit().fixedSize()+ }+ .font(self.theme.typography.caption).foregroundStyle(.secondary)+ if self.message.utf16.count > FeedbackSubmission.messageLimit {+ Text("Please shorten your message before sending.")+ .font(self.theme.typography.caption).foregroundStyle(self.theme.palette.warning)+ }}}- // MARK: - Feedback Functions+ private var deliveryNote: some View {+ Text(self.sending ? "Sending your feedback…" : "Sent directly to the FluidVoice team.")+ .font(self.theme.typography.caption).foregroundStyle(.secondary)+ }- private func sendFeedback() async {- guard !self.feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,- !self.feedbackText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty- else {- return+ private var sendButton: some View {+ Button { Task { await self.submit() } } label: {+ HStack(spacing: 8) {+ if self.sending { ProgressView().controlSize(.small) }+ Text(self.error == nil ? "Send feedback" : "Try again")+ Image(systemName: "arrow.up.right")+ }}+ .fluidGlassAction(prominent: true)+ .disabled(!self.draft.isValid || self.sending)+ }- await MainActor.run {- self.isSendingFeedback = true+ private var categories: some View {+ ForEach(FeedbackCategory.allCases, id: \.self) { category in+ Button { self.category = category } label: {+ Label(category.rawValue, systemImage: category.icon)+ .font(self.theme.typography.bodySmallStrong)+ .padding(.horizontal, 14).padding(.vertical, 10)+ .background(Color.primary.opacity(self.category == category ? 0.10 : 0.025), in: Capsule())+ .overlay(Capsule().strokeBorder(self.theme.palette.cardBorder.opacity(self.category == category ? 1 : 0.4)))+ .contentShape(Capsule())+ }+ .buttonStyle(.plain)+ .accessibilityAddTraits(self.category == category ? .isSelected : [])}+ }- let feedbackData = self.createFeedbackData()- let success = await submitFeedback(data: feedbackData)-- await MainActor.run {- self.isSendingFeedback = false- if success {- // Show confirmation and clear form- self.showFeedbackConfirmation = true- self.feedbackText = ""- self.feedbackEmail = ""- self.includeDebugLogs = false- } else {- // Show error to user - inputs are preserved for retry- self.feedbackErrorMessage = "We couldn't send your feedback. Please check your internet connection and try again."- self.showFeedbackError = true+ private var confirmation: some View {+ ThemedCard(style: .standard, padding: self.theme.metrics.spacing.xxl) {+ VStack(alignment: .leading, spacing: 16) {+ Image(systemName: "checkmark.circle").font(self.theme.typography.displayTitle)+ Text("Thank you. Your feedback is in.").font(self.theme.typography.title)+ Text("We’ve received your message. If we need more details, we can reach you by email.")+ .font(self.theme.typography.body).foregroundStyle(.secondary)+ Button("Send another message") { self.sent = false }.fluidGlassAction()}+ .frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 24)}}- private func createFeedbackData() -> [String: Any] {- var feedbackContent = self.feedbackText.trimmingCharacters(in: .whitespacesAndNewlines)-- if self.includeDebugLogs {- feedbackContent += "\n\n--- Debug Information ---\n"- feedbackContent += "App Version: \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown")\n"- feedbackContent += "Build: \(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "Unknown")\n"- feedbackContent += "macOS Version: \(ProcessInfo.processInfo.operatingSystemVersionString)\n"- feedbackContent += "Date: \(Date().formatted())\n\n"-- // Add recent log entries- let logFileURL = FileLogger.shared.currentLogFileURL()- if FileManager.default.fileExists(atPath: logFileURL.path) {- do {- let logContent = try String(contentsOf: logFileURL)- let lines = logContent.components(separatedBy: .newlines)- let recentLines = Array(lines.suffix(30)) // Last 30 lines- feedbackContent += "Recent Log Entries:\n"- feedbackContent += recentLines.joined(separator: "\n")- } catch {- feedbackContent += "Could not read log file: \(error.localizedDescription)\n"- }+ @ViewBuilder private var starInvitation: some View {+ if #available(macOS 26, *), !self.reduceTransparency {+ self.starInvitationContent+ .padding(self.theme.metrics.spacing.xl)+ .glassEffect(.regular, in: RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg))+ } else {+ ThemedCard(style: .subtle, padding: self.theme.metrics.spacing.xl) {+ self.starInvitationContent}}-- return [- "email_id": self.feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines),- "feedback": feedbackContent,- ]}- private func submitFeedback(data: [String: Any]) async -> Bool {- guard let url = URL(string: "https://altic.dev/api/fluid/feedback") else {- DebugLogger.shared.error("Invalid feedback API URL", source: "FeedbackView")- return false+ private var starInvitationContent: some View {+ ViewThatFits(in: .horizontal) {+ HStack(spacing: 24) { self.starMessage; Spacer(minLength: 0); self.starButton }+ VStack(alignment: .leading, spacing: 16) { self.starMessage; self.starButton }}+ .frame(maxWidth: .infinity, alignment: .leading)+ }- do {- var request = URLRequest(url: url)- request.httpMethod = "POST"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.httpBody = try JSONSerialization.data(withJSONObject: data)+ @ViewBuilder private var footer: some View {+ if let url = URL(string: "https://github.com/sponsors/altic-dev") {+ Link("Support development ↗", destination: url)+ .font(self.theme.typography.caption).foregroundStyle(.secondary)+ }+ }- let (_, response) = try await URLSession.shared.data(for: request)+ private var starMessage: some View {+ VStack(alignment: .leading, spacing: 6) {+ Text("Enjoying FluidVoice?").font(self.theme.typography.sectionTitle)+ Text("A star helps more people discover FluidVoice.")+ .font(self.theme.typography.bodySmall).foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ }- if let httpResponse = response as? HTTPURLResponse {- let success = (200...299).contains(httpResponse.statusCode)- if success {- DebugLogger.shared.info("Feedback submitted successfully", source: "FeedbackView")- } else {- DebugLogger.shared.error(- "Feedback submission failed with status: \(httpResponse.statusCode)",- source: "FeedbackView"- )- }- return success+ @ViewBuilder private var starButton: some View {+ if let url = URL(string: "https://github.com/altic-dev/Fluid-oss") {+ Link(destination: url) {+ Label("Star on GitHub", systemImage: "star")+ .fixedSize()}- return false- } catch {- DebugLogger.shared.error(- "Network error submitting feedback: \(error.localizedDescription)",- source: "FeedbackView"- )- return false+ .fluidGlassAction()+ .help("Open the GitHub repository to give FluidVoice a star")}}-}-#Preview {- FeedbackView()+ @MainActor private func submit() async {+ guard !self.sending, self.draft.isValid else { return }+ let submission = self.draft+ self.sending = true+ self.error = nil+ defer { self.sending = false }+ do {+ try await FeedbackClient().send(submission)+ self.sent = true+ self.message = ""+ self.email = ""+ self.includeDetails = false+ } catch {+ self.error = error.localizedDescription+ }+ }}diff --git a/Tests/FluidDictationIntegrationTests/FeedbackClientTests.swift b/Tests/FluidDictationIntegrationTests/FeedbackClientTests.swiftnew file mode 100644index 00000000..4d835fca--- /dev/null+++ b/Tests/FluidDictationIntegrationTests/FeedbackClientTests.swift@@ -0,0 +1,115 @@+@testable import FluidVoice_Debug+import XCTest++final class FeedbackClientTests: XCTestCase {+ private var draft: FeedbackSubmission {+ FeedbackSubmission(email: " [email protected] ", message: " Test message ", category: .issue, appDetails: nil)+ }++ func testPayloadPreservesBackendContractAndOptIn() throws {+ let data = try JSONEncoder().encode(self.draft)+ let object = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: String])+ XCTAssertEqual(Set(object.keys), ["email_id", "feedback"])+ XCTAssertEqual(object["email_id"], "[email protected]")+ XCTAssertEqual(object["feedback"], "[Report an issue]\nTest message")+ XCTAssertFalse(self.draft.content.contains("macOS"))+ let detailed = FeedbackSubmission(email: "[email protected]", message: "hello", category: .idea, appDetails: "macOS test")+ XCTAssertTrue(detailed.content.contains("macOS test"))+ }++ func testValidationMatchesServerLimitsIncludingEmoji() {+ XCTAssertFalse(FeedbackSubmission.isValidEmail(email), email)+ }+ XCTAssertTrue(FeedbackSubmission.isValidEmail(" [email protected] "))+ for message in [" \n", String(repeating: "a", count: 4501), String(repeating: "😀", count: 2251)] {+ XCTAssertFalse(FeedbackSubmission(email: "[email protected]", message: message, category: .issue, appDetails: nil).isValid)+ }+ XCTAssertTrue(FeedbackSubmission(email: "[email protected]", message: String(repeating: "a", count: 4500), category: .issue, appDetails: FeedbackSubmission.appDetails).isValid)+ XCTAssertFalse(FeedbackSubmission(email: "[email protected]", message: "hello", category: .issue, appDetails: String(repeating: "x", count: 5000)).isValid)+ }++ func testSuccessRequiresReceiptAndUsesExpectedRequest() async throws {+ let client = self.client { request in+ XCTAssertEqual(request.url?.absoluteString, "https://altic.dev/api/fluid/feedback")+ XCTAssertEqual(request.httpMethod, "POST")+ XCTAssertEqual(request.value(forHTTPHeaderField: "Content-Type"), "application/json")+ XCTAssertEqual(request.timeoutInterval, 30)+ return (200, #"{"message":"Feedback submitted successfully"}"#)+ }+ defer { client.session.invalidateAndCancel() }+ try await client.send(self.draft)+ }++ func testHTTPFailuresAndFalseSuccess() async {+ for (status, body, expected) in [+ (429, "{}", FeedbackClient.Failure.rateLimited),+ (400, "{}", .rejected), (500, "{}", .server),+ (200, "<html>Sign in</html>", .unconfirmed), (200, "{}", .unconfirmed),+ ] {+ let client = self.client { _ in (status, body) }+ do {+ try await client.send(self.draft)+ XCTFail("Expected a failure for \(status)")+ } catch {+ XCTAssertEqual(error.localizedDescription, expected.localizedDescription)+ }+ client.session.invalidateAndCancel()+ }+ }++ func testTimeoutDoesNotAutomaticallyRetry() async {+ var requests = 0+ let client = self.client { _ in+ requests += 1+ throw URLError(.timedOut)+ }+ defer { client.session.invalidateAndCancel() }+ do {+ try await client.send(self.draft)+ XCTFail("Expected timeout")+ } catch {+ XCTAssertEqual(error.localizedDescription, FeedbackClient.Failure.connection.localizedDescription)+ }+ XCTAssertEqual(requests, 1)+ XCTAssertEqual(self.draft.message, " Test message ")+ }++ func testInvalidDraftNeverHitsNetwork() async {+ let client = self.client { _ in XCTFail("No network expected"); return (200, "{}") }+ defer { client.session.invalidateAndCancel() }+ do {+ try await client.send(FeedbackSubmission(email: "invalid", message: "hello", category: .issue, appDetails: nil))+ XCTFail("Expected validation failure")+ } catch {+ XCTAssertEqual(error.localizedDescription, FeedbackClient.Failure.invalid.localizedDescription)+ }+ }++ private func client(_ handler: @escaping (URLRequest) throws -> (Int, String)) -> FeedbackClient {+ FeedbackURLProtocol.handler = handler+ let config = URLSessionConfiguration.ephemeral+ config.protocolClasses = [FeedbackURLProtocol.self]+ return FeedbackClient(session: URLSession(configuration: config))+ }+}++private class FeedbackURLProtocol: URLProtocol {+ static var handler: ((URLRequest) throws -> (Int, String))?+ override class func canInit(with request: URLRequest) -> Bool { true }+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }+ override func startLoading() {+ do {+ guard let handler = Self.handler, let url = self.request.url else { throw URLError(.badURL) }+ let (status, body) = try handler(self.request)+ guard let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: nil) else { throw URLError(.badServerResponse) }+ self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ self.client?.urlProtocol(self, didLoad: Data(body.utf8))+ self.client?.urlProtocolDidFinishLoading(self)+ } catch {+ self.client?.urlProtocol(self, didFailWithError: error)+ }+ }++ override func stopLoading() {}+}