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 // The asset download can take minutes on cellular. Cancel it so
222 // the operation gate releases and the mic button works again.
223 operationTask?.cancel()
224 invalidateOperation()
225 setPhase(.idle)
226 case .recording:
227 guard let id = operationID else {
228 setPhase(.idle)
229 return
230 }
231 invalidateOperation()
232 setPhase(.idle)
233 operationTask = Task { [weak self] in
234 await self?.cleanupAndRelease(id: id)
235 }
236 case .transcribing:
237 invalidateOperation()
238 setPhase(.idle)
239 Task { [weak self] in
240 await self?.adapter.cancelTranscription()
241 }
242 }
243 }
244
245 func ownerChanged(to snapshot: FeatureVoiceDraftSnapshot) {
246 if currentDraft?.ownerID != snapshot.ownerID {
247 pendingCommit = nil
248 if phase != .idle { cancel() }
249 }
250 currentDraft = snapshot
251 }
252
253 func appMovedToBackground() {
254 if isBusy { cancel() }
255 }
256
257 func recordingWasInterrupted() {
258 guard phase == .recording, let id = operationID else { return }
259 invalidateOperation()
260 setError("Voice recording was interrupted.", .retry)
261 operationTask = Task { [weak self] in
262 await self?.cleanupAndRelease(id: id)
263 }
264 }
265
266 func consumePendingCommit() {
267 pendingCommit = nil
268 }
269
270 func waitForCurrentOperation() async {
271 await operationTask?.value
272 }
273
274 private func prepareAndStartRecording(id: UUID) async {
275 do {
276 // Locale resolution and asset installation happen before the app
277 // asks for microphone access. A permission prompt must not hide a
278 // long asset download.
279 try await adapter.prepare()
280 guard isCurrent(id) else {
281 await cleanupAndRelease(id: id)
282 return
283 }
284
285 guard await adapter.requestMicrophonePermission() == .granted else {
286 await cleanupAndRelease(id: id)
287 if operationID == id {
288 setError("Microphone access is required for voice input.", .settings)
289 operationID = nil
290 }
291 return
292 }
293 guard isCurrent(id), draftContentMatches(capturedDraft, currentDraft) else {
294 await cleanupAndRelease(id: id)
295 if operationID == id {
296 setError("This draft is no longer available.", .retry)
297 operationID = nil
298 }
299 return
300 }
301
302 try adapter.startRecording(maximumDuration: Self.maximumRecordingDuration)
303 guard isCurrent(id) else {
304 await cleanupAndRelease(id: id)
305 return
306 }
307 recordingStartedAt = .now
308 setPhase(.recording)
309 scheduleRecordingLimit(for: id)
310 } catch {
311 await cleanupAndRelease(id: id)
312 if operationID == id {
313 operationID = nil
314 setError("Could not prepare voice input.", .retry)
315 }
316 }
317 }
318
319 private func stopAndTranscribe(id: UUID) async {
320 do {
321 let recordingURL = try await adapter.stopRecording()
322 guard isCurrent(id), let capturedDraft else {
323 await cleanupAndRelease(id: id)
324 return
325 }
326
327 let transcript = try await adapter.transcribe(recordingURL: recordingURL)
328 guard isCurrent(id) else {
329 await cleanupAndRelease(id: id)
330 return
331 }
332
333 let result = FeatureVoiceTranscriptResolver.resolve(
334 captured: capturedDraft,
335 current: currentDraft,
336 transcript: transcript,
337 localeIdentifier: adapter.localeIdentifier
338 )
339 await cleanupAndRelease(id: id)
340 guard operationID == id else { return }
341 operationID = nil
342 self.capturedDraft = nil
343 switch result {
344 case let .commit(commit):
345 pendingCommit = commit
346 setPhase(.idle)
347 case .empty:
348 setError("No speech was detected.", .retry)
349 case .stale:
350 setError(
351 "The draft changed while voice input was running. The transcript was not added.",
352 .retry
353 )
354 }
355 } catch {
356 await cleanupAndRelease(id: id)
357 if operationID == id {
358 operationID = nil
359 setError("Could not transcribe this recording.", .retry)
360 }
361 }
362 }
363
364 private func scheduleRecordingLimit(for id: UUID) {
365 recordingLimitTask?.cancel()
366 recordingLimitTask = Task { [weak self] in
367 try? await Task.sleep(for: .seconds(Self.maximumRecordingDuration))
368 guard !Task.isCancelled, let self, self.isCurrent(id) else { return }
369 self.stop()
370 }
371 }
372
373 private func invalidateOperation() {
374 operationID = nil
375 capturedDraft = nil
376 recordingStartedAt = nil
377 recordingLimitTask?.cancel()
378 recordingLimitTask = nil
379 }
380
381 private func cleanupAndRelease(id: UUID) async {
382 await adapter.cleanup()
383 FeatureVoiceInputOperationGate.release(id)
384 }
385
386 private func isCurrent(_ id: UUID) -> Bool {
387 operationID == id
388 }
389
390 private func draftContentMatches(
391 _ captured: FeatureVoiceDraftSnapshot?,
392 _ current: FeatureVoiceDraftSnapshot?
393 ) -> Bool {
394 guard let captured, let current else { return false }
395 return captured.ownerID == current.ownerID
396 && captured.text == current.text
397 && captured.revision == current.revision
398 }
399
400 private func setPhase(_ phase: FeatureVoiceInputPhase) {
401 self.phase = phase
402 if phase != .error {
403 errorMessage = nil
404 errorAction = nil
405 }
406 }
407
408 private func setError(_ message: String, _ action: FeatureVoiceInputErrorAction?) {
409 phase = .error
410 errorMessage = message
411 errorAction = action
412 recordingStartedAt = nil
413 }
414
415 private func clearError() {
416 errorMessage = nil
417 errorAction = nil
418 setPhase(.idle)
419 }
420}