Skip to content

Open source CapCut alternative.

TypeScript

feat(app): transcribe voice input on-device with Gemini fallback

David Le0f147179d842
diff --git a/apps/Donkey/Sources/Donkey/AppleSpeechVoiceTranscriptionRuntime.swift b/apps/Donkey/Sources/Donkey/AppleSpeechVoiceTranscriptionRuntime.swift
new file mode 100644
index 00000000..3e366eb7
--- /dev/null
+++ b/apps/Donkey/Sources/Donkey/AppleSpeechVoiceTranscriptionRuntime.swift
@@ -0,0 +1,268 @@
+import AVFoundation
+import DonkeyAI
+import Foundation
+import Speech
+
+/// On-device speech-to-text using Apple's local APIs, the preferred transcription
+/// path. There are no network calls and audio never leaves the machine.
+///
+/// - macOS 26+: the modern `SpeechAnalyzer` / `SpeechTranscriber`, which transcribe
+/// a whole audio file with an on-device locale model (downloaded on first use).
+/// - macOS 14–25: `SFSpeechRecognizer` with `requiresOnDeviceRecognition`, the
+/// on-device path available before SpeechAnalyzer shipped.
+///
+/// Any failure — model/recognizer unavailable, not authorized, or empty output —
+/// is surfaced as a thrown error so the composing runtime can fall back to Gemini.
+public struct AppleSpeechVoiceTranscriptionRuntime: LocalVoiceTranscriptionRuntime {
+ public init() {}
+
+ /// Download the on-device locale model ahead of time so the first voice command
+ /// doesn't pay a multi-second model install under the "Transcribing…" state.
+ /// Fire-and-forget; failures are ignored (the live path retries and falls back).
+ public static func prewarm() {
+ Task.detached(priority: .utility) {
+ if #available(macOS 26, *) {
+ guard let locale = try? await resolvedSpeechAnalyzerLocale(preferred: Locale.current) else {
+ return
+ }
+ let transcriber = SpeechTranscriber(
+ locale: locale,
+ transcriptionOptions: [],
+ reportingOptions: [],
+ attributeOptions: []
+ )
+ try? await ensureModelInstalled(transcriber, locale: locale)
+ }
+ }
+ }
+
+ public func transcribe(
+ audio: LocalVoiceAudioBuffer,
+ model: AIModelRegistryEntry
+ ) async throws -> LocalVoiceTranscript {
+ let fileURL = try Self.writeTemporaryAudioFile(audio)
+ defer { try? FileManager.default.removeItem(at: fileURL) }
+
+ if #available(macOS 26, *) {
+ let resolved = try await Self.resolvedSpeechAnalyzerLocale(preferred: Locale.current)
+ let text = try await Self.runSpeechAnalyzer(fileURL: fileURL, locale: resolved)
+ return try Self.transcript(
+ text: text,
+ language: resolved.identifier,
+ backend: "apple-speechanalyzer"
+ )
+ }
+
+ let result = try await Self.runLegacyRecognizer(
+ fileURL: fileURL,
+ preferred: Locale.current,
+ timeoutMS: model.timeoutMS
+ )
+ return try Self.transcript(
+ text: result.text,
+ language: result.language,
+ backend: "apple-sfspeech"
+ )
+ }
+
+ // MARK: - SpeechAnalyzer (macOS 26+)
+
+ @available(macOS 26, *)
+ private static func resolvedSpeechAnalyzerLocale(preferred: Locale) async throws -> Locale {
+ let supported = await SpeechTranscriber.supportedLocales
+ let supportedIDs = Set(supported.map { $0.identifier(.bcp47) })
+ if supportedIDs.contains(preferred.identifier(.bcp47)) {
+ return preferred
+ }
+ let english = Locale(identifier: "en-US")
+ if supportedIDs.contains(english.identifier(.bcp47)) {
+ return english
+ }
+ throw LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("apple-speechanalyzer-locale-unsupported")
+ }
+
+ @available(macOS 26, *)
+ private static func runSpeechAnalyzer(fileURL: URL, locale: Locale) async throws -> String {
+ let transcriber = SpeechTranscriber(
+ locale: locale,
+ transcriptionOptions: [],
+ reportingOptions: [],
+ attributeOptions: []
+ )
+ try await ensureModelInstalled(transcriber, locale: locale)
+
+ let analyzer = SpeechAnalyzer(modules: [transcriber])
+ let audioFile = try AVAudioFile(forReading: fileURL)
+
+ let collector = Task { () throws -> AttributedString in
+ var text = AttributedString()
+ for try await result in transcriber.results {
+ text += result.text
+ }
+ return text
+ }
+
+ do {
+ if let lastSample = try await analyzer.analyzeSequence(from: audioFile) {
+ try await analyzer.finalizeAndFinish(through: lastSample)
+ } else {
+ await analyzer.cancelAndFinishNow()
+ }
+ } catch {
+ collector.cancel()
+ throw error
+ }
+
+ let attributed = try await collector.value
+ return String(attributed.characters)
+ }
+
+ @available(macOS 26, *)
+ private static func ensureModelInstalled(_ transcriber: SpeechTranscriber, locale: Locale) async throws {
+ let installed = await SpeechTranscriber.installedLocales
+ guard !installed.contains(where: { $0.identifier(.bcp47) == locale.identifier(.bcp47) }) else {
+ return
+ }
+ if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) {
+ try await request.downloadAndInstall()
+ }
+ }
+
+ // MARK: - SFSpeechRecognizer (macOS 14–25)
+
+ private static func runLegacyRecognizer(
+ fileURL: URL,
+ preferred: Locale,
+ timeoutMS: Int
+ ) async throws -> (text: String, language: String) {
+ try await requestLegacyAuthorization()
+
+ guard let recognizer = SFSpeechRecognizer(locale: preferred)
+ ?? SFSpeechRecognizer(locale: Locale(identifier: "en-US")),
+ recognizer.isAvailable else {
+ throw LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("apple-sfspeech-unavailable")
+ }
+ guard recognizer.supportsOnDeviceRecognition else {
+ throw LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("apple-sfspeech-no-on-device")
+ }
+
+ let request = SFSpeechURLRecognitionRequest(url: fileURL)
+ request.requiresOnDeviceRecognition = true
+ request.shouldReportPartialResults = false
+
+ let text: String = try await withCheckedThrowingContinuation { continuation in
+ let resume = SingleResume(continuation)
+ let task = recognizer.recognitionTask(with: request) { result, error in
+ if let error {
+ resume.fail(error)
+ return
+ }
+ guard let result, result.isFinal else { return }
+ resume.succeed(result.bestTranscription.formattedString)
+ }
+ // SFSpeechRecognizer can stall without ever invoking the handler; bound it
+ // so a hung recognition throws and falls through to Gemini instead of
+ // leaving the UI stuck on "Transcribing…".
+ resume.start(task: task, timeoutMS: timeoutMS)
+ }
+ return (text, recognizer.locale.identifier)
+ }
+
+ private static func requestLegacyAuthorization() async throws {
+ switch SFSpeechRecognizer.authorizationStatus() {
+ case .authorized:
+ return
+ case .notDetermined:
+ let status = await withCheckedContinuation { continuation in
+ SFSpeechRecognizer.requestAuthorization { continuation.resume(returning: $0) }
+ }
+ guard status == .authorized else {
+ throw LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("apple-sfspeech-unauthorized")
+ }
+ default:
+ throw LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("apple-sfspeech-unauthorized")
+ }
+ }
+
+ /// Guards a checked continuation so the recognition handler — which can fire
+ /// more than once, or not at all — resumes it exactly once, and enforces a
+ /// timeout that cancels a stalled recognition.
+ private final class SingleResume: @unchecked Sendable {
+ private let continuation: CheckedContinuation<String, Error>
+ private let lock = NSLock()
+ private var resumed = false
+ private var task: SFSpeechRecognitionTask?
+ private var timeoutTask: Task<Void, Never>?
+
+ init(_ continuation: CheckedContinuation<String, Error>) {
+ self.continuation = continuation
+ }
+
+ func start(task: SFSpeechRecognitionTask, timeoutMS: Int) {
+ lock.lock()
+ if resumed {
+ lock.unlock()
+ task.cancel()
+ return
+ }
+ self.task = task
+ timeoutTask = Task { [weak self] in
+ try? await Task.sleep(nanoseconds: UInt64(max(1, timeoutMS)) * 1_000_000)
+ self?.fail(LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("apple-sfspeech-timeout"))
+ }
+ lock.unlock()
+ }
+
+ func succeed(_ value: String) { finish(.success(value)) }
+
+ func fail(_ error: Error) { finish(.failure(error)) }
+
+ private func finish(_ result: Result<String, Error>) {
+ lock.lock()
+ guard !resumed else {
+ lock.unlock()
+ return
+ }
+ resumed = true
+ let task = self.task
+ let timeoutTask = self.timeoutTask
+ lock.unlock()
+
+ // A failure (including timeout) means recognition isn't done; stop it so
+ // it doesn't keep running after we've moved on.
+ if case .failure = result {
+ task?.cancel()
+ }
+ timeoutTask?.cancel()
+ continuation.resume(with: result)
+ }
+ }
+
+ // MARK: - Shared helpers
+
+ private static func transcript(
+ text: String,
+ language: String,
+ backend: String
+ ) throws -> LocalVoiceTranscript {
+ let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else {
+ throw LocalVoiceTranscriptionRuntimeError.emptyTranscript
+ }
+ return LocalVoiceTranscript(
+ text: trimmed,
+ language: language,
+ confidence: 1,
+ metadata: ["transcript.backend": backend]
+ )
+ }
+
+ private static func writeTemporaryAudioFile(_ audio: LocalVoiceAudioBuffer) throws -> URL {
+ let fileExtension = audio.format.lowercased()
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent("donkey-voice-\(UUID().uuidString)")
+ .appendingPathExtension(fileExtension)
+ try audio.data.write(to: url, options: .atomic)
+ return url
+ }
+}
diff --git a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
index c8e77796..8ebcd6dd 100644
--- a/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
+++ b/apps/Donkey/Sources/Donkey/DonkeyAppDelegate.swift
@@ -112,7 +112,19 @@ final class DonkeyAppDelegate: NSObject, NSApplicationDelegate {
private func startOverlaySurfaces() {
guard overlayController == nil else { return }
- let model = UserQueryOverlayModel()
+ // Voice button transcription: Apple's on-device speech is preferred; Gemini is
+ // the automatic fallback when the local path is unavailable or fails.
+ let voiceTranscriber = LocalVoiceTranscriptionAdapter(
+ runtime: FallbackVoiceTranscriptionRuntime(runtimes: [
+ AppleSpeechVoiceTranscriptionRuntime(),
+ GeminiVoiceTranscriptionRuntime()
+ ])
+ )
+ let model = UserQueryOverlayModel(voiceTranscriber: voiceTranscriber)
+
+ // Warm the on-device speech model in the background so the first voice command
+ // isn't blocked behind a model download.
+ AppleSpeechVoiceTranscriptionRuntime.prewarm()
let controller = UserQueryOverlayController(model: model)
overlayController = controller
controller.show()
diff --git a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
index 4c9c3939..79c8baf2 100644
--- a/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
+++ b/apps/Donkey/Sources/DonkeyAI/AIModelRegistry.swift
@@ -149,6 +149,26 @@ public struct AIModelRegistry: Codable, Equatable, Sendable {
"lastVerifiedAt": "2026-05-25",
"docsSource": "Donkey backend inference API"
]
+ ),
+ AIModelRegistryEntry(
+ id: "local-voice-transcription-apple-on-device",
+ role: .voiceTranscription,
+ provider: .localRuntime,
+ modelID: "apple-on-device",
+ endpoint: URL(string: "local://apple/speech-on-device")!,
+ capabilities: [.audioInput],
+ timeoutMS: 15_000,
+ promptVersion: "voice-transcription-v1",
+ evalStatus: .candidate,
+ docsURL: URL(string: "donkey://docs/guides/agent-harness")!,
+ rollbackID: nil,
+ metadata: [
+ // Apple's on-device speech is the routed entry; the injected runtime
+ // falls back to Gemini when it is unavailable or fails.
+ "localOnly": "true",
+ "fallbackProvider": "gemini",
+ "lastVerifiedAt": "2026-06-18"
+ ]
)
]
)
diff --git a/apps/Donkey/Sources/DonkeyAI/FallbackVoiceTranscriptionRuntime.swift b/apps/Donkey/Sources/DonkeyAI/FallbackVoiceTranscriptionRuntime.swift
new file mode 100644
index 00000000..73fa5b10
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/FallbackVoiceTranscriptionRuntime.swift
@@ -0,0 +1,37 @@
+import Foundation
+
+/// Tries a list of transcription runtimes in order, advancing to the next one on a
+/// thrown error or an empty transcript and returning the first non-empty result.
+///
+/// This is how "Apple on-device primary, Gemini automatic fallback" is composed:
+/// the router still selects a single registry entry so the adapter's tracing is
+/// unchanged, and this runtime owns the provider order. A user cancellation stops
+/// the chain immediately rather than falling through to the next provider.
+public struct FallbackVoiceTranscriptionRuntime: LocalVoiceTranscriptionRuntime {
+ private let runtimes: [any LocalVoiceTranscriptionRuntime]
+
+ public init(runtimes: [any LocalVoiceTranscriptionRuntime]) {
+ self.runtimes = runtimes
+ }
+
+ public func transcribe(
+ audio: LocalVoiceAudioBuffer,
+ model: AIModelRegistryEntry
+ ) async throws -> LocalVoiceTranscript {
+ var lastError: Error?
+ for runtime in runtimes {
+ do {
+ let transcript = try await runtime.transcribe(audio: audio, model: model)
+ if !transcript.text.isEmpty {
+ return transcript
+ }
+ lastError = LocalVoiceTranscriptionRuntimeError.emptyTranscript
+ } catch is CancellationError {
+ throw CancellationError()
+ } catch {
+ lastError = error
+ }
+ }
+ throw lastError ?? LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("fallback-no-runtimes")
+ }
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/GeminiVoiceTranscriptionRuntime.swift b/apps/Donkey/Sources/DonkeyAI/GeminiVoiceTranscriptionRuntime.swift
new file mode 100644
index 00000000..b046760e
--- /dev/null
+++ b/apps/Donkey/Sources/DonkeyAI/GeminiVoiceTranscriptionRuntime.swift
@@ -0,0 +1,140 @@
+import Foundation
+
+/// Transcribes captured audio with Gemini's `generateContent`, used as the
+/// automatic fallback when Apple's on-device speech path is unavailable or fails.
+///
+/// Auth mirrors the always-on Gemini Live session (see `GeminiLiveConnectionFactory`):
+///
+/// - **Developer API** (`GEMINI_API_KEY` set): post directly to
+/// `generativelanguage.googleapis.com` with the key in the query string. Dev-only —
+/// a client-held key.
+/// - **Vertex AI** (no key): mint a short-lived OAuth token via the backend
+/// (`DonkeyBackendInferenceClient.mintLiveConnection`) and post to the Vertex
+/// `generateContent` endpoint with a bearer token. The long-lived credential
+/// stays on the backend. This is the production path.
+public struct GeminiVoiceTranscriptionRuntime: LocalVoiceTranscriptionRuntime {
+ /// Turn-based transcription model. A fast flash model is plenty for short voice
+ /// commands; override with `GEMINI_TRANSCRIPTION_MODEL`.
+ public static let defaultModel = "gemini-2.5-flash"
+
+ private static let prompt =
+ "Transcribe this audio verbatim. Return only the transcript text with no commentary, labels, or quotation marks. If there is no speech, return an empty string."
+
+ private let apiKey: String?
+ private let model: String
+ private let httpClient: any AIHTTPClient
+ private let environment: [String: String]
+
+ public init(
+ apiKey: String? = nil,
+ model: String? = nil,
+ httpClient: any AIHTTPClient = URLSessionAIHTTPClient(),
+ environment: [String: String] = ProcessInfo.processInfo.environment
+ ) {
+ self.apiKey = GeminiGenerateContent.trimmed(apiKey ?? environment["GEMINI_API_KEY"])
+ self.model = GeminiGenerateContent.trimmed(model ?? environment["GEMINI_TRANSCRIPTION_MODEL"]) ?? Self.defaultModel
+ self.httpClient = httpClient
+ self.environment = environment
+ }
+
+ public func transcribe(
+ audio: LocalVoiceAudioBuffer,
+ model entry: AIModelRegistryEntry
+ ) async throws -> LocalVoiceTranscript {
+ let request: URLRequest
+ if let apiKey {
+ request = try developerAPIRequest(apiKey: apiKey, audio: audio)
+ } else {
+ request = try await vertexRequest(audio: audio)
+ }
+
+ let (data, response) = try await httpClient.send(request)
+ guard (200..<300).contains(response.statusCode) else {
+ let body = String(data: data, encoding: .utf8) ?? ""
+ throw GeminiVoiceTranscriptionError.requestFailed(
+ status: response.statusCode,
+ body: String(body.prefix(240))
+ )
+ }
+
+ guard let text = GeminiGenerateContent.candidateText(data)?.trimmingCharacters(in: .whitespacesAndNewlines),
+ !text.isEmpty else {
+ throw LocalVoiceTranscriptionRuntimeError.emptyTranscript
+ }
+
+ return LocalVoiceTranscript(
+ text: text,
+ confidence: 1,
+ metadata: [
+ "transcript.backend": "gemini",
+ "transcript.model": model
+ ]
+ )
+ }
+
+ private func developerAPIRequest(apiKey: String, audio: LocalVoiceAudioBuffer) throws -> URLRequest {
+ var components = URLComponents(
+ string: "https://generativelanguage.googleapis.com/v1beta/models/\(model):generateContent"
+ )
+ components?.queryItems = [URLQueryItem(name: "key", value: apiKey)]
+ guard let url = components?.url else { throw GeminiVoiceTranscriptionError.invalidURL }
+
+ var request = URLRequest(url: url)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = try Self.requestBody(audio: audio)
+ return request
+ }
+
+ private func vertexRequest(audio: LocalVoiceAudioBuffer) async throws -> URLRequest {
+ let configuration = try DonkeyBackendInferenceConfiguration.fromEnvironment(environment)
+ let backend = DonkeyBackendInferenceClient(configuration: configuration, httpClient: httpClient)
+ let auth = try await GeminiVertexVisionPlanner.mintAuth(backend: backend)
+
+ guard let url = GeminiGenerateContent.vertexURL(
+ project: auth.project,
+ location: auth.location,
+ model: model
+ ) else { throw GeminiVoiceTranscriptionError.invalidURL }
+
+ var request = URLRequest(url: url)
+ request.httpMethod = "POST"
+ request.setValue("Bearer \(auth.token)", forHTTPHeaderField: "Authorization")
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = try Self.requestBody(audio: audio)
+ return request
+ }
+
+ private static func requestBody(audio: LocalVoiceAudioBuffer) throws -> Data {
+ let body: [String: Any] = [
+ "contents": [[
+ "role": "user",
+ "parts": [
+ ["text": prompt],
+ ["inlineData": [
+ "mimeType": mimeType(for: audio.format),
+ "data": audio.data.base64EncodedString()
+ ]]
+ ]
+ ]],
+ "generationConfig": ["temperature": 0]
+ ]
+ return try JSONSerialization.data(withJSONObject: body)
+ }
+
+ private static func mimeType(for format: String) -> String {
+ switch format.lowercased() {
+ case "flac": return "audio/flac"
+ case "mp3": return "audio/mp3"
+ case "aac": return "audio/aac"
+ case "ogg": return "audio/ogg"
+ case "aiff": return "audio/aiff"
+ default: return "audio/wav"
+ }
+ }
+}
+
+public enum GeminiVoiceTranscriptionError: Error, Equatable, Sendable {
+ case invalidURL
+ case requestFailed(status: Int, body: String)
+}
diff --git a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
index c3f09545..60a9bd28 100644
--- a/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
+++ b/apps/Donkey/Sources/DonkeyAI/LocalVoiceTranscriptionAdapter.swift
@@ -377,6 +377,12 @@ public struct LocalVoiceTranscriptionAdapter: Sendable {
values["transcript.confidence"] = String(transcript.confidence)
values["transcript.language"] = transcript.language ?? ""
values["transcript.segmentCount"] = String(transcript.segments.count)
+ // Surface which backend actually answered (apple-speechanalyzer / apple-sfspeech / gemini)
+ // so the trace reflects reality: a fallback to a network backend is not local-only.
+ values.merge(transcript.metadata) { _, new in new }
+ if let backend = transcript.metadata["transcript.backend"] {
+ values["localOnly"] = backend.hasPrefix("apple") ? "true" : "false"
+ }
}
return values
}
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
index 0765ed31..12597299 100644
--- a/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/AIHarnessAdapterTests.swift
@@ -108,22 +108,27 @@ struct AIHarnessAdapterTests {
}
@Test
- func voiceTranscriptionRouteHasNoDefaultLocalModel() throws {
+ func voiceTranscriptionRouteSelectsAppleOnDeviceLocalModel() throws {
let router = AIModelRouter(registry: .defaultHybridPlanner)
- #expect(throws: AIModelRouteError.noMatchingModel) {
- _ = try router.route(
- AIModelRouteRequest(
- jobType: .voiceTranscription,
- privacyMode: .privacySensitive,
- requiredCapabilities: [.audioInput]
- )
+ let selected = try router.route(
+ AIModelRouteRequest(
+ jobType: .voiceTranscription,
+ privacyMode: .privacySensitive,
+ requiredCapabilities: [.audioInput]
)
- }
+ )
+
+ #expect(selected.id == "local-voice-transcription-apple-on-device")
+ #expect(selected.role == .voiceTranscription)
+ #expect(selected.provider == .localRuntime)
+ #expect(selected.capabilities.contains(.audioInput))
}
@Test
- func voiceTranscriptionRouteHasNoWhisperFallbackWhenParakeetFailed() throws {
+ func voiceTranscriptionRouteHasNoRegistryFallbackWhenOnDeviceFailed() throws {
+ // The Gemini fallback lives in the injected runtime, not the registry, so once
+ // the on-device entry is excluded there is no other model to route to.
let router = AIModelRouter(registry: .defaultHybridPlanner)
#expect(throws: AIModelRouteError.noMatchingModel) {
@@ -131,7 +136,7 @@ struct AIHarnessAdapterTests {
AIModelRouteRequest(
jobType: .voiceTranscription,
privacyMode: .privacySensitive,
- failedModelEntryIDs: ["local-voice-transcription-parakeet-tdt-0.6b-v3"],
+ failedModelEntryIDs: ["local-voice-transcription-apple-on-device"],
requiredCapabilities: [.audioInput]
)
)
diff --git a/apps/Donkey/Tests/DonkeyRuntimeTests/VoiceTranscriptionRuntimeTests.swift b/apps/Donkey/Tests/DonkeyRuntimeTests/VoiceTranscriptionRuntimeTests.swift
new file mode 100644
index 00000000..6f9e7ce3
--- /dev/null
+++ b/apps/Donkey/Tests/DonkeyRuntimeTests/VoiceTranscriptionRuntimeTests.swift
@@ -0,0 +1,208 @@
+import DonkeyAI
+import DonkeyContracts
+import DonkeyRuntime
+import Foundation
+import Testing
+
+@Suite
+struct VoiceTranscriptionRuntimeTests {
+ // MARK: - Fallback ordering
+
+ @Test
+ func fallbackUsesSecondRuntimeWhenFirstThrows() async throws {
+ let runtime = FallbackVoiceTranscriptionRuntime(runtimes: [
+ ThrowingVoiceRuntime(error: LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("apple")),
+ StaticVoiceRuntime(text: "from gemini")
+ ])
+
+ let transcript = try await runtime.transcribe(audio: Self.audio(), model: Self.entry())
+
+ #expect(transcript.text == "from gemini")
+ }
+
+ @Test
+ func fallbackUsesSecondRuntimeWhenFirstReturnsEmpty() async throws {
+ let runtime = FallbackVoiceTranscriptionRuntime(runtimes: [
+ StaticVoiceRuntime(text: ""),
+ StaticVoiceRuntime(text: "from gemini")
+ ])
+
+ let transcript = try await runtime.transcribe(audio: Self.audio(), model: Self.entry())
+
+ #expect(transcript.text == "from gemini")
+ }
+
+ @Test
+ func fallbackStopsAtFirstSuccess() async throws {
+ let second = CountingVoiceRuntime(text: "second")
+ let runtime = FallbackVoiceTranscriptionRuntime(runtimes: [
+ StaticVoiceRuntime(text: "first"),
+ second
+ ])
+
+ let transcript = try await runtime.transcribe(audio: Self.audio(), model: Self.entry())
+
+ #expect(transcript.text == "first")
+ #expect(await second.callCount == 0)
+ }
+
+ @Test
+ func fallbackRethrowsLastErrorWhenAllFail() async {
+ let runtime = FallbackVoiceTranscriptionRuntime(runtimes: [
+ ThrowingVoiceRuntime(error: LocalVoiceTranscriptionRuntimeError.runtimeUnavailable("apple")),
+ ThrowingVoiceRuntime(error: LocalVoiceTranscriptionRuntimeError.emptyTranscript)
+ ])
+
+ await #expect(throws: LocalVoiceTranscriptionRuntimeError.emptyTranscript) {
+ _ = try await runtime.transcribe(audio: Self.audio(), model: Self.entry())
+ }
+ }
+
+ @Test
+ func fallbackStopsImmediatelyOnCancellation() async {
+ let second = CountingVoiceRuntime(text: "second")
+ let runtime = FallbackVoiceTranscriptionRuntime(runtimes: [
+ ThrowingVoiceRuntime(error: CancellationError()),
+ second
+ ])
+
+ await #expect(throws: CancellationError.self) {
+ _ = try await runtime.transcribe(audio: Self.audio(), model: Self.entry())
+ }
+ #expect(await second.callCount == 0)
+ }
+
+ // MARK: - Gemini request shape
+
+ @Test
+ func geminiDeveloperAPIRequestSendsInlineWavAndDecodesTranscript() async throws {
+ let http = FakeVoiceHTTPClient(
+ data: Data(#"{"candidates":[{"content":{"parts":[{"text":" hello world "}]}}]}"#.utf8),
+ statusCode: 200
+ )
+ let runtime = GeminiVoiceTranscriptionRuntime(
+ apiKey: "test-key",
+ model: "gemini-test",
+ httpClient: http,
+ environment: [:]
+ )
+
+ let transcript = try await runtime.transcribe(
+ audio: Self.audio(data: Data([1, 2, 3])),
+ model: Self.entry()
+ )
+
+ #expect(transcript.text == "hello world")
+ #expect(transcript.metadata["transcript.backend"] == "gemini")
+ #expect(transcript.metadata["transcript.model"] == "gemini-test")
+
+ let request = try #require(http.requests.first)
+ let urlString = try #require(request.url?.absoluteString)
+ #expect(urlString.contains("generativelanguage.googleapis.com/v1beta/models/gemini-test:generateContent"))
+ #expect(urlString.contains("key=test-key"))
+ #expect(request.value(forHTTPHeaderField: "Authorization") == nil)
+
+ let body = try #require(request.httpBody)
+ let json = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any])
+ let parts = try #require(
+ ((json["contents"] as? [[String: Any]])?.first?["parts"]) as? [[String: Any]]
+ )
+ let inlineData = try #require(parts.compactMap { $0["inlineData"] as? [String: Any] }.first)
+ #expect(inlineData["mimeType"] as? String == "audio/wav")
+ #expect(inlineData["data"] as? String == Data([1, 2, 3]).base64EncodedString())
+ }
+
+ @Test
+ func geminiThrowsEmptyTranscriptWhenNoText() async {
+ let http = FakeVoiceHTTPClient(
+ data: Data(#"{"candidates":[{"content":{"parts":[{"text":" "}]}}]}"#.utf8),
+ statusCode: 200
+ )
+ let runtime = GeminiVoiceTranscriptionRuntime(
+ apiKey: "test-key",
+ httpClient: http,
+ environment: [:]
+ )
+
+ await #expect(throws: LocalVoiceTranscriptionRuntimeError.emptyTranscript) {
+ _ = try await runtime.transcribe(audio: Self.audio(), model: Self.entry())
+ }
+ }
+
+ // MARK: - Fixtures
+
+ private static func audio(data: Data = Data([0, 1, 2, 3])) -> LocalVoiceAudioBuffer {
+ LocalVoiceAudioBuffer(
+ id: "audio-fixture",
+ format: "wav",
+ sampleRateHz: 16_000,
+ channelCount: 1,
+ durationMS: 250,
+ data: data
+ )
+ }
+
+ private static func entry() -> AIModelRegistryEntry {
+ AIModelRegistryEntry(
+ id: "local-voice-transcription-apple-on-device",
+ role: .voiceTranscription,
+ provider: .localRuntime,
+ modelID: "apple-on-device",
+ endpoint: URL(string: "local://apple/speech-on-device")!,
+ capabilities: [.audioInput],
+ timeoutMS: 15_000,
+ promptVersion: "voice-transcription-v1",
+ evalStatus: .candidate,
+ docsURL: URL(string: "donkey://docs/guides/agent-harness")!
+ )
+ }
+}
+
+private struct ThrowingVoiceRuntime: LocalVoiceTranscriptionRuntime {
+ let error: Error
+
+ func transcribe(audio: LocalVoiceAudioBuffer, model: AIModelRegistryEntry) async throws -> LocalVoiceTranscript {
+ throw error
+ }
+}
+
+private struct StaticVoiceRuntime: LocalVoiceTranscriptionRuntime {
+ let text: String
+
+ func transcribe(audio: LocalVoiceAudioBuffer, model: AIModelRegistryEntry) async throws -> LocalVoiceTranscript {
+ LocalVoiceTranscript(text: text, confidence: 1)
+ }
+}
+
+private actor CountingVoiceRuntime: LocalVoiceTranscriptionRuntime {
+ private let text: String
+ private(set) var callCount = 0
+
+ init(text: String) {
+ self.text = text
+ }
+
+ func transcribe(audio: LocalVoiceAudioBuffer, model: AIModelRegistryEntry) async throws -> LocalVoiceTranscript {
+ callCount += 1
+ return LocalVoiceTranscript(text: text, confidence: 1)
+ }
+}
+
+private final class FakeVoiceHTTPClient: AIHTTPClient, @unchecked Sendable {
+ let data: Data
+ let statusCode: Int
+ private(set) var requests: [URLRequest] = []
+
+ init(data: Data, statusCode: Int) {
+ self.data = data
+ self.statusCode = statusCode
+ }
+
+ func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
+ requests.append(request)
+ return (
+ data,
+ HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: nil, headerFields: nil)!
+ )
+ }
+}
diff --git a/scripts/package-donkey-app.sh b/scripts/package-donkey-app.sh
index 82b861e1..b9b1f31d 100755
--- a/scripts/package-donkey-app.sh
+++ b/scripts/package-donkey-app.sh
@@ -302,6 +302,8 @@ cat > "$CONTENTS_DIR/Info.plist" <<PLIST
</array>
<key>NSMicrophoneUsageDescription</key>
<string>Donkey uses the microphone for user-requested voice input.</string>
+ <key>NSSpeechRecognitionUsageDescription</key>
+ <string>Donkey transcribes your voice input on-device to turn it into a command.</string>
<key>NSScreenCaptureUsageDescription</key>
<string>Donkey captures bounded screenshots for user-requested app context.</string>
<key>NSAppleEventsUsageDescription</key>
diff --git a/scripts/run-donkey-dev.sh b/scripts/run-donkey-dev.sh
index 83e0c6f2..69a72480 100755
--- a/scripts/run-donkey-dev.sh
+++ b/scripts/run-donkey-dev.sh
@@ -377,6 +377,8 @@ write_info_plist() {
</array>
<key>NSMicrophoneUsageDescription</key>
<string>Donkey uses the microphone for user-requested voice input.</string>
+ <key>NSSpeechRecognitionUsageDescription</key>
+ <string>Donkey transcribes your voice input on-device to turn it into a command.</string>
<key>NSScreenCaptureUsageDescription</key>
<string>Donkey captures bounded screenshots for user-requested app context.</string>
<key>NSAppleEventsUsageDescription</key>