Open History to see the last commit
1import Foundation
2import Observation
3
4enum FeatureVoiceInputPhase: Equatable {
5 case idle
6 case preparing
7 case recording
8 case transcribing
9 case error
10}
11
12enum FeatureVoiceInputErrorAction: Equatable {
13 case retry
14 case settings
15}
16
17struct FeatureVoiceDraftSnapshot: Equatable {
18 let ownerID: String
19 let text: String
20 let revision: UInt64
21 let selection: NSRange
22}
23
24struct FeatureVoiceTranscriptCommit: Equatable, Identifiable {
25 let id = UUID()
26 let text: String
27 let caretLocation: Int
28}
29
30enum FeatureVoiceTranscriptCommitResult: Equatable {
31 case commit(FeatureVoiceTranscriptCommit)
32 case empty
33 case stale
34}
35
36enum FeatureVoiceTranscriptResolver {
37 static func resolve(
38 captured: FeatureVoiceDraftSnapshot,
39 current: FeatureVoiceDraftSnapshot?,
40 transcript: String,
41 localeIdentifier: String
42 ) -> FeatureVoiceTranscriptCommitResult {
43 guard let current,
44 current.ownerID == captured.ownerID,
45 current.text == captured.text,
46 current.revision == captured.revision,
47 captured.selection.location >= 0,
48 captured.selection.length >= 0,
49 captured.selection.location <= captured.text.utf16.count,
50 captured.selection.length <= captured.text.utf16.count
51 - captured.selection.location,
52 Range(captured.selection, in: captured.text) != nil else {
53 return .stale
54 }
55
56 let replacement = transcript.trimmingCharacters(in: .whitespacesAndNewlines)
57 guard !replacement.isEmpty else { return .empty }
58
59 var insertion = replacement
60 let normalizedLocale = localeIdentifier
61 .replacingOccurrences(of: "_", with: "-")
62 .lowercased()
63 if captured.selection.length == 0,
64 normalizedLocale == "en" || normalizedLocale.hasPrefix("en-") {
65 let text = captured.text as NSString
66 let location = captured.selection.location
67 let left = location > 0 ? text.character(at: location - 1) : nil
68 let right = location < text.length ? text.character(at: location) : nil
69 let leftNeedsSpace = left.map(Self.leftBoundaryCharacters.contains) == true
70 && (right == nil || right.map(Self.isWhitespace) == true)
71 let rightNeedsSpace = right.map(Self.rightBoundaryCharacters.contains) == true
72 && (left == nil || left.map(Self.isWhitespace) == true)
73 insertion = "\(leftNeedsSpace ? " " : "")\(replacement)\(rightNeedsSpace ? " " : "")"
74 }
75
76 let nextText = (captured.text as NSString).replacingCharacters(
77 in: captured.selection,
78 with: insertion
79 )
80 return .commit(FeatureVoiceTranscriptCommit(
81 text: nextText,
82 caretLocation: captured.selection.location + insertion.utf16.count
83 ))
84 }
85
86 private static let leftBoundaryCharacters = Set(
87 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.!?,:;)]}'\""
88 .utf16
89 )
90 private static let rightBoundaryCharacters = Set(
91 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789([{'\""
92 .utf16
93 )
94
95 private static func isWhitespace(_ codeUnit: unichar) -> Bool {
96 guard let scalar = UnicodeScalar(codeUnit) else { return false }
97 return CharacterSet.whitespacesAndNewlines.contains(scalar)
98 }
99}
100
101enum FeatureVoiceMicrophonePermission: Equatable {
102 case granted
103 case denied
104}
105
106@MainActor
107protocol FeatureVoiceInputAdapter: AnyObject {
108 var isSupported: Bool { get }
109 var localeIdentifier: String { get }
110
111 func prepare() async throws
112 func requestMicrophonePermission() async -> FeatureVoiceMicrophonePermission
113 func startRecording(maximumDuration: TimeInterval) throws
114 func stopRecording() async throws -> URL
115 func transcribe(recordingURL: URL) async throws -> String
116 func cancelTranscription() async
117 func cleanup() async
118}
119
120@MainActor
121private enum FeatureVoiceInputOperationGate {
122 static var owner: UUID?
123
124 static func acquire(_ candidate: UUID) -> Bool {
125 guard owner == nil else { return false }
126 owner = candidate
127 return true
128 }
129
130 static func release(_ candidate: UUID) {
131 if owner == candidate { owner = nil }
132 }
133}
134
135@MainActor
136@Observable
137final class FeatureVoiceInputController {
138 static let maximumRecordingDuration: TimeInterval = 5 * 60
139
140 private(set) var phase: FeatureVoiceInputPhase = .idle
141 private(set) var errorMessage: String?
142 private(set) var errorAction: FeatureVoiceInputErrorAction?
143 private(set) var recordingStartedAt: Date?
144 private(set) var pendingCommit: FeatureVoiceTranscriptCommit?
145
146 @ObservationIgnored private let adapter: any FeatureVoiceInputAdapter
147 @ObservationIgnored private var currentDraft: FeatureVoiceDraftSnapshot?
148 @ObservationIgnored private var capturedDraft: FeatureVoiceDraftSnapshot?
149 @ObservationIgnored private var operationID: UUID?
150 @ObservationIgnored private var operationTask: Task<Void, Never>?
151 @ObservationIgnored private var recordingLimitTask: Task<Void, Never>?
152
153 init(adapter: any FeatureVoiceInputAdapter = FeatureVoiceInputAdapterFactory.make()) {
154 self.adapter = adapter
155 }
156
157 var isSupported: Bool { adapter.isSupported }
158
159 var isBusy: Bool {
160 phase == .preparing || phase == .recording || phase == .transcribing
161 }
162
163 func updateDraft(_ snapshot: FeatureVoiceDraftSnapshot) {
164 currentDraft = snapshot
165 }
166
167 func updateSelection(_ selection: NSRange) {
168 guard let currentDraft else { return }
169 self.currentDraft = FeatureVoiceDraftSnapshot(
170 ownerID: currentDraft.ownerID,
171 text: currentDraft.text,
172 revision: currentDraft.revision,
173 selection: selection
174 )
175 }
176
177 func start() {
178 guard phase == .idle || phase == .error else { return }
179 guard adapter.isSupported else {
180 setError("Voice transcription requires a supported device with iOS 26 or later.", nil)
181 return
182 }
183 guard let currentDraft else {
184 setError("This draft is no longer available.", .retry)
185 return
186 }
187
188 let id = UUID()
189 guard FeatureVoiceInputOperationGate.acquire(id) else {
190 setError("Another voice recording is still finishing.", .retry)
191 return
192 }
193
194 operationID = id
195 capturedDraft = currentDraft
196 pendingCommit = nil
197 setPhase(.preparing)
198 operationTask = Task { [weak self] in
199 await self?.prepareAndStartRecording(id: id)
200 }
201 }
202
203 func stop() {
204 guard phase == .recording, let id = operationID else { return }
205 recordingLimitTask?.cancel()
206 recordingLimitTask = nil
207 recordingStartedAt = nil
208 setPhase(.transcribing)
209 operationTask = Task { [weak self] in
210 await self?.stopAndTranscribe(id: id)
211 }
212 }
213
214 func cancel() {
215 switch phase {
216 case .idle:
217 return
218 case .error:
219 clearError()
220 case .preparing:
221 invalidateOperation()
222 setPhase(.idle)
223 case .recording:
224 guard let id = operationID else {
225 setPhase(.idle)
226 return
227 }
228 invalidateOperation()
229 setPhase(.idle)
230 operationTask = Task { [weak self] in
231 await self?.cleanupAndRelease(id: id)
232 }
233 case .transcribing:
234 invalidateOperation()
235 setPhase(.idle)
236 Task { [weak self] in
237 await self?.adapter.cancelTranscription()
238 }
239 }
240 }
241
242 func ownerChanged(to snapshot: FeatureVoiceDraftSnapshot) {
243 if currentDraft?.ownerID != snapshot.ownerID {
244 pendingCommit = nil
245 if phase != .idle { cancel() }
246 }
247 currentDraft = snapshot
248 }
249
250 func appMovedToBackground() {
251 if isBusy { cancel() }
252 }
253
254 func recordingWasInterrupted() {
255 guard phase == .recording, let id = operationID else { return }
256 invalidateOperation()
257 setError("Voice recording was interrupted.", .retry)
258 operationTask = Task { [weak self] in
259 await self?.cleanupAndRelease(id: id)
260 }
261 }
262
263 func consumePendingCommit() {
264 pendingCommit = nil
265 }
266
267 func waitForCurrentOperation() async {
268 await operationTask?.value
269 }
270
271 private func prepareAndStartRecording(id: UUID) async {
272 do {
273 // Locale resolution and asset installation happen before the app
274 // asks for microphone access. A permission prompt must not hide a
275 // long asset download.
276 try await adapter.prepare()
277 guard isCurrent(id) else {
278 await cleanupAndRelease(id: id)
279 return
280 }
281
282 guard await adapter.requestMicrophonePermission() == .granted else {
283 await cleanupAndRelease(id: id)
284 if operationID == id {
285 setError("Microphone access is required for voice input.", .settings)
286 operationID = nil
287 }
288 return
289 }
290 guard isCurrent(id), draftContentMatches(capturedDraft, currentDraft) else {
291 await cleanupAndRelease(id: id)
292 if operationID == id {
293 setError("This draft is no longer available.", .retry)
294 operationID = nil
295 }
296 return
297 }
298
299 try adapter.startRecording(maximumDuration: Self.maximumRecordingDuration)
300 guard isCurrent(id) else {
301 await cleanupAndRelease(id: id)
302 return
303 }
304 recordingStartedAt = .now
305 setPhase(.recording)
306 scheduleRecordingLimit(for: id)
307 } catch {
308 await cleanupAndRelease(id: id)
309 if operationID == id {
310 operationID = nil
311 setError("Could not prepare voice input.", .retry)
312 }
313 }
314 }
315
316 private func stopAndTranscribe(id: UUID) async {
317 do {
318 let recordingURL = try await adapter.stopRecording()
319 guard isCurrent(id), let capturedDraft else {
320 await cleanupAndRelease(id: id)
321 return
322 }
323
324 let transcript = try await adapter.transcribe(recordingURL: recordingURL)
325 guard isCurrent(id) else {
326 await cleanupAndRelease(id: id)
327 return
328 }
329
330 let result = FeatureVoiceTranscriptResolver.resolve(
331 captured: capturedDraft,
332 current: currentDraft,
333 transcript: transcript,
334 localeIdentifier: adapter.localeIdentifier
335 )
336 await cleanupAndRelease(id: id)
337 guard operationID == id else { return }
338 operationID = nil
339 self.capturedDraft = nil
340 switch result {
341 case let .commit(commit):
342 pendingCommit = commit
343 setPhase(.idle)
344 case .empty:
345 setError("No speech was detected.", .retry)
346 case .stale:
347 setError(
348 "The draft changed while voice input was running. The transcript was not added.",
349 .retry
350 )
351 }
352 } catch {
353 await cleanupAndRelease(id: id)
354 if operationID == id {
355 operationID = nil
356 setError("Could not transcribe this recording.", .retry)
357 }
358 }
359 }
360
361 private func scheduleRecordingLimit(for id: UUID) {
362 recordingLimitTask?.cancel()
363 recordingLimitTask = Task { [weak self] in
364 try? await Task.sleep(for: .seconds(Self.maximumRecordingDuration))
365 guard !Task.isCancelled, let self, self.isCurrent(id) else { return }
366 self.stop()
367 }
368 }
369
370 private func invalidateOperation() {
371 operationID = nil
372 capturedDraft = nil
373 recordingStartedAt = nil
374 recordingLimitTask?.cancel()
375 recordingLimitTask = nil
376 }
377
378 private func cleanupAndRelease(id: UUID) async {
379 await adapter.cleanup()
380 FeatureVoiceInputOperationGate.release(id)
381 }
382
383 private func isCurrent(_ id: UUID) -> Bool {
384 operationID == id
385 }
386
387 private func draftContentMatches(
388 _ captured: FeatureVoiceDraftSnapshot?,
389 _ current: FeatureVoiceDraftSnapshot?
390 ) -> Bool {
391 guard let captured, let current else { return false }
392 return captured.ownerID == current.ownerID
393 && captured.text == current.text
394 && captured.revision == current.revision
395 }
396
397 private func setPhase(_ phase: FeatureVoiceInputPhase) {
398 self.phase = phase
399 if phase != .error {
400 errorMessage = nil
401 errorAction = nil
402 }
403 }
404
405 private func setError(_ message: String, _ action: FeatureVoiceInputErrorAction?) {
406 phase = .error
407 errorMessage = message
408 errorAction = action
409 recordingStartedAt = nil
410 }
411
412 private func clearError() {
413 errorMessage = nil
414 errorAction = nil
415 setPhase(.idle)
416 }
417}