diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index a868851d5c9da..4d4dbc6e56728 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -449,6 +449,10 @@ const config: ExpoConfig = { extraPods: [ { name: "GoogleUtilities", modular_headers: true }, { name: "RecaptchaInterop", modular_headers: true }, + { + name: "TranscribeCpp", + podspec: "../modules/t3-voice-transcription/ios/vendor/TranscribeCpp.podspec.json", + }, ], }, }, diff --git a/apps/mobile/fingerprint.config.js b/apps/mobile/fingerprint.config.js index e62be49dd5a33..3f8f2ec7a3e76 100644 --- a/apps/mobile/fingerprint.config.js +++ b/apps/mobile/fingerprint.config.js @@ -22,5 +22,10 @@ module.exports = { filePath: "../../native/apple-speech/AppleSpeechEngine.swift", reasons: ["appleSpeech"], }, + { + type: "file", + filePath: "../server/src/speech/catalog.json", + reasons: ["deviceSpeechCatalog"], + }, ], }; diff --git a/apps/mobile/modules/t3-voice-transcription/THIRD_PARTY_NOTICES.md b/apps/mobile/modules/t3-voice-transcription/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000000000..eb8b95b179e47 --- /dev/null +++ b/apps/mobile/modules/t3-voice-transcription/THIRD_PARTY_NOTICES.md @@ -0,0 +1,98 @@ +# transcribe.cpp v0.4.1 for iOS + +## LICENSE + +MIT License + +Copyright (c) 2026 The transcribe.cpp authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## LICENSE.ggml + +MIT License + +Copyright (c) 2023-2026 The ggml authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## LICENSE.miniz + +Copyright 2013-2014 RAD Game Tools and Valve Software +Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + +All Rights Reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +## LICENSE.silero_vad + +MIT License + +Copyright (c) 2020-present Silero Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/apps/mobile/modules/t3-voice-transcription/ios/DeviceSpeechCatalog.swift b/apps/mobile/modules/t3-voice-transcription/ios/DeviceSpeechCatalog.swift new file mode 100644 index 0000000000000..b3cdd15fabe50 --- /dev/null +++ b/apps/mobile/modules/t3-voice-transcription/ios/DeviceSpeechCatalog.swift @@ -0,0 +1,70 @@ +import CTranscribe +import Foundation +import os + +struct DeviceSpeechModel: Decodable, Sendable { + struct Accuracy: Decodable, Sendable { + let grade: String + let errorPercent: Double + } + + struct Benchmark: Decodable, Sendable { + let accuracy: [String: Accuracy] + } + + let id: String + let name: String + let description: String + let languages: [String] + let revision: String + let filename: String + let size: Int + let sha256: String + let benchmark: Benchmark + + var payload: [String: Any] { + [ + "id": id, "name": name, "description": description, "languages": languages, "size": size, + "benchmark": [ + "accuracy": benchmark.accuracy.mapValues { ["grade": $0.grade, "errorPercent": $0.errorPercent] }, + "secondsPer30s": ["accelerated": NSNull()], + ], + ] + } + + func fits(availableMemory: Int) -> Bool { + // Budget for another copy of the weights and graph/audio buffers. + let buffers = 512 * 1024 * 1024 + return size > 0 && availableMemory >= buffers && size <= (availableMemory - buffers) / 2 + } +} + +enum DeviceSpeechCatalog { + private struct Manifest: Decodable { + let engineVersion: String + let models: [DeviceSpeechModel] + } + + static let models: [DeviceSpeechModel] = { + guard let resources = Bundle.main.url(forResource: "T3SpeechModels", withExtension: "bundle"), + let url = Bundle(url: resources)?.url(forResource: "catalog", withExtension: "json"), + let data = try? Data(contentsOf: url), + let catalog = try? JSONDecoder().decode(Manifest.self, from: data), + let version = transcribe_version(), catalog.engineVersion == String(cString: version) + else { return [] } + return catalog.models + }() + + static let availableModels = { + let budget = availableMemory + return models.filter { $0.fits(availableMemory: budget) } + }() + + static var availableMemory: Int { + #if os(iOS) && !targetEnvironment(simulator) + Int(clamping: os_proc_available_memory()) + #else + Int(clamping: ProcessInfo.processInfo.physicalMemory) + #endif + } +} diff --git a/apps/mobile/modules/t3-voice-transcription/ios/DeviceSpeechEngine.swift b/apps/mobile/modules/t3-voice-transcription/ios/DeviceSpeechEngine.swift new file mode 100644 index 0000000000000..f8eb7223568ce --- /dev/null +++ b/apps/mobile/modules/t3-voice-transcription/ios/DeviceSpeechEngine.swift @@ -0,0 +1,127 @@ +import CTranscribe +import Foundation +import Synchronization + +final class SpeechInferenceCancellation: Sendable { + private let cancelled = Mutex(false) + + var isCancelled: Bool { cancelled.withLock { $0 } } + + func cancel() { + cancelled.withLock { $0 = true } + } + + func check() throws { + if isCancelled { throw CancellationError() } + } +} + +enum DeviceSpeechEngine { + struct Transcript: Sendable { + let text: String + let language: String? + + var payload: [String: String] { + var result = ["text": text] + result["language"] = language + return result + } + } + + private struct Failure: Error { + let status: transcribe_status + } + + static func transcribe(file: URL, model: URL, cancellation: SpeechInferenceCancellation) throws + -> Transcript + { + try cancellation.check() + let samples = try VoiceRecordingPCM.float32(file: file, checkCancellation: cancellation.check) + do { + return try run(samples, model: model, backend: TRANSCRIBE_BACKEND_AUTO, cancellation: cancellation) + } catch let error as Failure where error.status == TRANSCRIBE_ERR_BACKEND { + return try run(samples, model: model, backend: TRANSCRIBE_BACKEND_CPU, cancellation: cancellation) + } + } + + private static func run( + _ samples: [Float], model: URL, backend: transcribe_backend_request, + cancellation: SpeechInferenceCancellation + ) throws -> Transcript { + try cancellation.check() + + var loadParameters = transcribe_model_load_params() + transcribe_model_load_params_init(&loadParameters) + loadParameters.backend = backend + var opened: OpaquePointer? + try check(transcribe_open(model.path, &loadParameters, nil, &opened)) + guard let session = opened else { throw CocoaError(.fileReadCorruptFile) } + defer { transcribe_session_free(session) } + try cancellation.check() + + // The run can call back on this pointer until it returns. Clear it before releasing the retain. + let context = Unmanaged.passRetained(cancellation) + transcribe_set_abort_callback( + session, + { data in + guard let data else { return false } + return Unmanaged.fromOpaque(data).takeUnretainedValue() + .isCancelled + }, context.toOpaque()) + defer { + transcribe_set_abort_callback(session, nil, nil) + context.release() + } + + var parameters = transcribe_run_params() + transcribe_run_params_init(¶meters) + parameters.timestamps = TRANSCRIBE_TIMESTAMPS_NONE + let hint = try languageHint(session) + let status = samples.withUnsafeBufferPointer { buffer in + if let hint { + return hint.withCString { value in + parameters.language = value + return transcribe_run(session, buffer.baseAddress, Int32(buffer.count), ¶meters) + } + } + return transcribe_run(session, buffer.baseAddress, Int32(buffer.count), ¶meters) + } + try cancellation.check() + try check(status) + guard !transcribe_was_truncated(session) else { throw CocoaError(.fileReadTooLarge) } + let language = transcribe_detected_language(session).flatMap { code in + let language = String(cString: code) + return language.isEmpty ? nil : language + } + return Transcript( + text: transcribe_full_text(session).map { String(cString: $0) } ?? "", + language: language ?? hint) + } + + private static func languageHint(_ session: OpaquePointer) throws -> String? { + var capabilities = transcribe_capabilities() + transcribe_capabilities_init(&capabilities) + try check(transcribe_model_get_capabilities(transcribe_get_model(session), &capabilities)) + guard !capabilities.supports_language_detect, let languages = capabilities.languages else { + return nil + } + let codes = (0.. Void + + private let directory = URL.applicationSupportDirectory.appending( + path: "SpeechModels", directoryHint: .isDirectory) + private func modelURL(_ model: DeviceSpeechModel) -> URL { + directory.appending(path: "\(model.sha256).gguf") + } + private var download: (modelId: String, revision: Int, task: Task)? + private var inference: (modelId: String, id: String, cancellation: SpeechInferenceCancellation)? + private var earlyCancellation: String? + private var states: [String: State] = [:] + private var revision = 0 + private var storagePrepared = false + + private var current: Snapshot { Snapshot(states: states, revision: revision) } + + private func model(_ id: String) throws -> DeviceSpeechModel { + guard let model = DeviceSpeechCatalog.availableModels.first(where: { $0.id == id }) else { + throw CocoaError(.featureUnsupported) + } + return model + } + + func snapshot(publish: Publish) -> Snapshot { + prepareStorage() + let previous = states + for model in DeviceSpeechCatalog.availableModels where model.id != download?.modelId { + let ready = Self.isCompleteFile(modelURL(model), size: model.size) + if ready || states[model.id] != .failed { + states[model.id] = ready ? .ready : .missing + } + } + if states != previous { + revision += 1 + publish(current) + } + return current + } + + func startDownload(_ modelId: String, publish: @escaping Publish) throws { + let model = try model(modelId) + guard download == nil, snapshot(publish: publish).states[modelId] != .ready else { return } + setState(.downloading(percent: 0), for: modelId, publish: publish) + let revision = revision + download = (modelId, revision, Task { await install(model, revision: revision, publish: publish) }) + } + + func cancelDownload(_ modelId: String, publish: Publish) { + guard let download, download.modelId == modelId else { return } + setState(.cancelling, for: modelId, publish: publish) + download.task.cancel() + } + + func remove(_ modelId: String, publish: Publish) throws { + guard download?.modelId != modelId, inference?.modelId != modelId else { + throw CocoaError(.fileLocking) + } + let model = try model(modelId) + try Self.removeIfPresent(modelURL(model)) + setState(.missing, for: modelId, publish: publish) + } + + func prepareStorage() { + guard !storagePrepared else { return } + storagePrepared = true + guard !DeviceSpeechCatalog.models.isEmpty else { return } + if !FileManager.default.fileExists(atPath: directory.path) { + let previous = URL.applicationSupportDirectory.appending(path: "ParakeetUltra") + try? FileManager.default.moveItem(at: previous, to: directory) + } + guard let files = try? FileManager.default.contentsOfDirectory( + at: directory, includingPropertiesForKeys: nil) + else { return } + let current = Set(DeviceSpeechCatalog.models.map { modelURL($0).lastPathComponent }) + for file in files where file.pathExtension == "gguf" && !current.contains(file.lastPathComponent) { + try? Self.removeIfPresent(file) + } + } + + func stop() { + download?.task.cancel() + inference?.cancellation.cancel() + } + + func transcribe(modelId: String, id: String, file: URL) async throws + -> DeviceSpeechEngine.Transcript + { + if earlyCancellation == id { + earlyCancellation = nil + throw CancellationError() + } + guard inference == nil else { throw CocoaError(.fileLocking) } + let model = try model(modelId) + prepareStorage() + guard Self.isCompleteFile(modelURL(model), size: model.size) else { + throw CocoaError(.fileNoSuchFile) + } + guard model.fits(availableMemory: DeviceSpeechCatalog.availableMemory) else { + throw POSIXError(.ENOMEM) + } + + let cancellation = SpeechInferenceCancellation() + inference = (modelId, id, cancellation) + defer { inference = nil } + let url = modelURL(model) + return try await Task.detached(priority: .userInitiated) { + try DeviceSpeechEngine.transcribe(file: file, model: url, cancellation: cancellation) + }.value + } + + func cancelInference(id: String) { + if let inference, inference.id == id { + inference.cancellation.cancel() + return + } + // Expo can deliver the cancellation before the async transcription reaches the actor. + earlyCancellation = id + } + + private func install(_ model: DeviceSpeechModel, revision: Int, publish: @escaping Publish) async { + let result: State + do { + var directory = directory + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + var values = URLResourceValues() + values.isExcludedFromBackup = true + try directory.setResourceValues(values) + try Task.checkCancellation() + + let url = URL( + string: + "https://huggingface.co/\(model.id)/resolve/\(model.revision)/\(model.filename)" + )! + let progress = DownloadProgress(size: Int64(model.size)) { [weak self] percent in + Task { await self?.reportProgress(percent, revision: revision, publish: publish) } + } + let session = URLSession(configuration: .ephemeral) + defer { session.finishTasksAndInvalidate() } + let (temporary, response) = try await session.download(from: url, delegate: progress) + defer { try? Self.removeIfPresent(temporary) } + try Task.checkCancellation() + guard (response as? HTTPURLResponse)?.statusCode == 200, + Self.isCompleteFile(temporary, size: model.size) + else { + throw CocoaError(.fileReadCorruptFile) + } + setState(.verifying, for: model.id, publish: publish) + try await Self.verifyChecksum(temporary, sha256: model.sha256) + try Task.checkCancellation() + + guard rename(temporary.path, modelURL(model).path) == 0 else { + throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) + } + result = .ready + } catch { + result = Task.isCancelled ? .missing : .failed + } + download = nil + setState(result, for: model.id, publish: publish) + } + + private func reportProgress(_ percent: Int, revision: Int, publish: Publish) { + guard let download, download.revision == revision, + case .downloading(let previous) = states[download.modelId], + percent > previous + else { return } + setState(.downloading(percent: percent), for: download.modelId, publish: publish) + } + + private func setState(_ next: State, for modelId: String, publish: Publish) { + guard states[modelId] != next else { return } + revision += 1 + states[modelId] = next + publish(current) + } + + private static func isCompleteFile(_ file: URL, size: Int) -> Bool { + guard let values = try? file.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) else { + return false + } + return values.isRegularFile == true && values.fileSize == size + } + + private static func removeIfPresent(_ url: URL) throws { + do { + try FileManager.default.removeItem(at: url) + } catch let error as CocoaError where error.code == .fileNoSuchFile { + return + } + } + + @concurrent + private static func verifyChecksum(_ file: URL, sha256 expected: String) async throws { + let handle = try FileHandle(forReadingFrom: file) + defer { try? handle.close() } + var sha256 = SHA256() + while let chunk = try handle.read(upToCount: 1024 * 1024), !chunk.isEmpty { + try Task.checkCancellation() + sha256.update(data: chunk) + } + guard sha256.finalize().map({ String(format: "%02x", $0) }).joined() == expected else { + throw CocoaError(.fileReadCorruptFile) + } + } +} + +private final class DownloadProgress: NSObject, URLSessionDownloadDelegate { + let size: Int64 + let report: @Sendable (Int) -> Void + private let percent = Mutex(0) + + init(size: Int64, report: @escaping @Sendable (Int) -> Void) { + self.size = size + self.report = report + } + + func urlSession( + _ session: URLSession, downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL + ) {} + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64 + ) { + guard totalBytesWritten <= size, totalBytesExpectedToWrite <= size else { + downloadTask.cancel() + return + } + let next = Int(totalBytesWritten * 100 / size) + let changed = percent.withLock { + guard next > $0 else { return false } + $0 = next + return true + } + if changed { report(next) } + } +} diff --git a/apps/mobile/modules/t3-voice-transcription/ios/Resources/catalog.json b/apps/mobile/modules/t3-voice-transcription/ios/Resources/catalog.json new file mode 120000 index 0000000000000..9b0d998113ac0 --- /dev/null +++ b/apps/mobile/modules/t3-voice-transcription/ios/Resources/catalog.json @@ -0,0 +1 @@ +../../../../../server/src/speech/catalog.json \ No newline at end of file diff --git a/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscription.podspec b/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscription.podspec index 946a2c70de075..90c60261e0f15 100644 --- a/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscription.podspec +++ b/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscription.podspec @@ -1,13 +1,15 @@ Pod::Spec.new do |s| s.name = 'T3VoiceTranscription' s.version = '1.0.0' - s.summary = 'Local recording conversion for T3 Code dictation.' + s.summary = 'On-device transcription and recording conversion for T3 Code dictation.' s.author = 'T3 Tools' s.homepage = 'https://t3tools.com' s.platform = :ios, '18.0' s.source = { :path => '.' } s.static_framework = true s.dependency 'ExpoModulesCore' + s.dependency 'TranscribeCpp' s.source_files = '*.swift' + s.resource_bundles = { 'T3SpeechModels' => ['Resources/catalog.json'] } s.frameworks = 'AudioToolbox' end diff --git a/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscriptionModule.swift b/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscriptionModule.swift index f975854669dfc..ad1c81392ccf9 100644 --- a/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscriptionModule.swift +++ b/apps/mobile/modules/t3-voice-transcription/ios/T3VoiceTranscriptionModule.swift @@ -1,10 +1,26 @@ -import AudioToolbox import ExpoModulesCore import Foundation public class T3VoiceTranscriptionModule: Module { + private let models = DeviceSpeechModelStore() + + private func publishModelStates(_ snapshot: DeviceSpeechModelStore.Snapshot) { + sendEvent("deviceSpeechModelStates", snapshot.payload) + } + public func definition() -> ModuleDefinition { Name("T3VoiceTranscription") + Events("deviceSpeechModelStates") + + OnCreate { + let models = self.models + Task { await models.prepareStorage() } + } + + OnDestroy { + let models = self.models + Task { await models.stop() } + } Function("isAppleSpeechAvailable") { if #available(iOS 26, *) { return AppleSpeechEngine.isAvailable } @@ -20,44 +36,43 @@ public class T3VoiceTranscriptionModule: Module { } } - AsyncFunction("transcribeWithAppleSpeech") { (uri: URL, locale: String) async throws -> String in + AsyncFunction("transcribeWithAppleSpeech") { + (uri: URL, locale: String) async throws -> String in guard #available(iOS 26, *) else { throw CocoaError(.featureUnsupported) } return try await AppleSpeechEngine.transcribe(locale, file: uri) } AsyncFunction("decodeRecording") { (uri: URL) throws -> Data in - guard uri.isFileURL else { throw CocoaError(.fileReadUnsupportedScheme) } - var opened: ExtAudioFileRef? - try check(ExtAudioFileOpenURL(uri as CFURL, &opened)) - guard let file = opened else { throw CocoaError(.fileReadCorruptFile) } - defer { ExtAudioFileDispose(file) } - var format = AudioStreamBasicDescription( - mSampleRate: 16_000, mFormatID: kAudioFormatLinearPCM, - mFormatFlags: kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked, - mBytesPerPacket: 2, mFramesPerPacket: 1, mBytesPerFrame: 2, - mChannelsPerFrame: 1, mBitsPerChannel: 16, mReserved: 0) - let formatSize = UInt32(MemoryLayout.size) - try check(ExtAudioFileSetProperty(file, kExtAudioFileProperty_ClientDataFormat, formatSize, &format)) - var pcm = Data() - var chunk = [Int16](repeating: 0, count: 8192) - try chunk.withUnsafeMutableBytes { bytes in - while true { - var frames = UInt32(bytes.count / 2) - var buffers = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer( - mNumberChannels: 1, mDataByteSize: UInt32(bytes.count), mData: bytes.baseAddress)) - try check(ExtAudioFileRead(file, &frames, &buffers)) - if frames == 0 { break } - let count = Int(frames) * 2 - guard pcm.count + count <= 16_000 * 2 * 301 else { throw CocoaError(.fileReadTooLarge) } - pcm.append(contentsOf: bytes.prefix(count)) - } + try VoiceRecordingPCM.signed16(file: uri) + } + + Function("getDeviceSpeechCatalog") { DeviceSpeechCatalog.availableModels.map(\.payload) } + + AsyncFunction("getDeviceSpeechModelStates") { () async -> [String: Any] in + await self.models.snapshot(publish: self.publishModelStates).payload + } + + AsyncFunction("startDeviceSpeechModelDownload") { (modelId: String) async throws in + try await self.models.startDownload(modelId) { [weak self] snapshot in + self?.publishModelStates(snapshot) } - guard !pcm.isEmpty else { throw CocoaError(.fileReadCorruptFile) } - return pcm } - } -} -private func check(_ status: OSStatus) throws { - guard status == noErr else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) } + AsyncFunction("cancelDeviceSpeechModelDownload") { (modelId: String) async in + await self.models.cancelDownload(modelId, publish: self.publishModelStates) + } + + AsyncFunction("removeDeviceSpeechModel") { (modelId: String) async throws in + try await self.models.remove(modelId, publish: self.publishModelStates) + } + + AsyncFunction("transcribeWithDeviceSpeechModel") { + (modelId: String, id: String, uri: URL) async throws -> [String: String] in + try await self.models.transcribe(modelId: modelId, id: id, file: uri).payload + } + + AsyncFunction("cancelDeviceSpeechInference") { (id: String) async in + await self.models.cancelInference(id: id) + } + } } diff --git a/apps/mobile/modules/t3-voice-transcription/ios/VoiceRecordingPCM.swift b/apps/mobile/modules/t3-voice-transcription/ios/VoiceRecordingPCM.swift new file mode 100644 index 0000000000000..044adce1ab639 --- /dev/null +++ b/apps/mobile/modules/t3-voice-transcription/ios/VoiceRecordingPCM.swift @@ -0,0 +1,67 @@ +import AudioToolbox +import Foundation + +enum VoiceRecordingPCM { + static func signed16(file: URL) throws -> Data { + var pcm = Data() + try read(file: file, zero: Int16(0), flags: kAudioFormatFlagIsSignedInteger) { + pcm.append(contentsOf: UnsafeRawBufferPointer($0)) + } + return pcm + } + + static func float32(file: URL, checkCancellation: () throws -> Void) throws -> [Float] { + var pcm: [Float] = [] + try read(file: file, zero: Float(0), flags: kAudioFormatFlagIsFloat) { + try checkCancellation() + pcm.append(contentsOf: $0) + } + return pcm + } + + private static func read( + file uri: URL, + zero: Sample, + flags: AudioFormatFlags, + consume: (UnsafeBufferPointer) throws -> Void + ) throws { + guard uri.isFileURL else { throw CocoaError(.fileReadUnsupportedScheme) } + var opened: ExtAudioFileRef? + try check(ExtAudioFileOpenURL(uri as CFURL, &opened)) + guard let file = opened else { throw CocoaError(.fileReadCorruptFile) } + defer { ExtAudioFileDispose(file) } + + let sampleRate = 16_000 + let bytesPerSample = UInt32(MemoryLayout.stride) + var format = AudioStreamBasicDescription( + mSampleRate: Double(sampleRate), mFormatID: kAudioFormatLinearPCM, + mFormatFlags: flags | kAudioFormatFlagIsPacked, + mBytesPerPacket: bytesPerSample, mFramesPerPacket: 1, mBytesPerFrame: bytesPerSample, + mChannelsPerFrame: 1, mBitsPerChannel: bytesPerSample * 8, mReserved: 0) + let formatSize = UInt32(MemoryLayout.size) + try check( + ExtAudioFileSetProperty(file, kExtAudioFileProperty_ClientDataFormat, formatSize, &format)) + + var chunk = [Sample](repeating: zero, count: 8192) + var frameCount = 0 + try chunk.withUnsafeMutableBufferPointer { samples in + while true { + var frames = UInt32(samples.count) + var buffers = AudioBufferList( + mNumberBuffers: 1, + mBuffers: AudioBuffer( + mNumberChannels: 1, mDataByteSize: frames * bytesPerSample, mData: samples.baseAddress)) + try check(ExtAudioFileRead(file, &frames, &buffers)) + if frames == 0 { break } + frameCount += Int(frames) + guard frameCount <= sampleRate * 301 else { throw CocoaError(.fileReadTooLarge) } + try consume(UnsafeBufferPointer(start: samples.baseAddress, count: Int(frames))) + } + } + guard frameCount > 0 else { throw CocoaError(.fileReadCorruptFile) } + } + + private static func check(_ status: OSStatus) throws { + guard status == noErr else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) } + } +} diff --git a/apps/mobile/modules/t3-voice-transcription/ios/vendor/TranscribeCpp.podspec.json b/apps/mobile/modules/t3-voice-transcription/ios/vendor/TranscribeCpp.podspec.json new file mode 100644 index 0000000000000..740d56cdfc98b --- /dev/null +++ b/apps/mobile/modules/t3-voice-transcription/ios/vendor/TranscribeCpp.podspec.json @@ -0,0 +1,15 @@ +{ + "name": "TranscribeCpp", + "version": "0.4.1", + "summary": "On-device speech recognition for T3 Code dictation.", + "homepage": "https://github.com/handy-computer/transcribe.cpp", + "authors": "transcribe.cpp contributors", + "license": { "type": "MIT", "file": "CTranscribe.xcframework/LICENSE" }, + "platforms": { "ios": "18.0" }, + "source": { + "http": "https://github.com/handy-computer/transcribe.cpp/releases/download/v0.4.1/TranscribeCpp.xcframework.zip", + "sha256": "fb5646e564036a6c49659e3efcf72eb567af20da31b8569045c9a08181d35126" + }, + "prepare_command": "mv TranscribeCpp.xcframework CTranscribe.xcframework", + "vendored_frameworks": "CTranscribe.xcframework" +} diff --git a/apps/mobile/src/features/settings/DeviceVoiceEngineSection.tsx b/apps/mobile/src/features/settings/DeviceVoiceEngineSection.tsx new file mode 100644 index 0000000000000..019249640881d --- /dev/null +++ b/apps/mobile/src/features/settings/DeviceVoiceEngineSection.tsx @@ -0,0 +1,139 @@ +import { useAtomValue } from "@effect/atom-react"; +import { useNavigation } from "@react-navigation/native"; +import { useGT } from "gt-react-native"; + +import * as Dialog from "../../components/ui/Dialog"; +import { ListChoiceRow } from "../../components/ui/ListChoiceRow"; +import { ListRow } from "../../components/ui/ListRow"; +import { formatBytes } from "../../lib/formatBytes"; +import { + deviceSpeechCatalog, + deviceSpeechModelActions, + deviceSpeechModelStatesAtom, +} from "../../native/deviceSpeechModels"; +import { saveMobilePreferences } from "../../state/preferences"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { + iosVoiceModelAtom, + localVoiceTranscriberAtom, + useGlobalVoiceInput, +} from "../voice-input/VoiceInputProvider"; +import { SettingsSection } from "./components/SettingsSection"; +import { isDownloading, type VoiceModel, type VoiceModelList } from "./VoiceModelSection"; + +export function useDeviceVoiceModels() { + const gt = useGT(); + const activeId = useAtomValue(iosVoiceModelAtom); + const catalog = useAtomValue(deviceSpeechModelStatesAtom); + const { isBusy } = useGlobalVoiceInput(); + const savePreferences = useAtomCommand(saveMobilePreferences); + const actions = deviceSpeechModelActions; + + const models = deviceSpeechCatalog.map((model): VoiceModel => { + const state = catalog.kind === "ready" ? catalog.states[model.id] : undefined; + return { + ...model, + active: activeId === model.id, + state: + state?.kind === "ready" + ? "installed" + : state?.kind === "missing" || !state + ? "downloadable" + : state.kind, + ...(state?.kind === "downloading" ? { downloaded: (model.size * state.percent) / 100 } : {}), + }; + }); + + const select = async (id: string | null) => { + if (id === activeId) return; + const result = await savePreferences({ deviceVoiceModelId: id }); + if (result._tag === "Failure") Dialog.alert(gt("Could not save transcription choice")); + }; + + const voice: VoiceModelList = { + models, + loading: catalog.kind === "checking", + canManage: catalog.kind === "ready" && activeId !== undefined && actions !== null, + busy: isBusy, + downloading: models.some(isDownloading), + download: (model) => { + if (!actions) return; + Dialog.confirm({ + title: gt("Download {model}?", { model: model.name }), + message: gt("Download {size} for offline dictation.", { size: formatBytes(model.size) }), + confirmText: gt("Download", { $context: "verb" }), + onConfirm: () => + void actions + .download(model.id) + .catch(() => Dialog.alert(gt("Could not download the model"))), + }); + }, + select: (model) => void select(model.id), + cancel: (model) => + void actions?.cancel(model.id).catch(() => Dialog.alert(gt("Could not cancel the download"))), + remove: (model) => { + if (!actions) return; + Dialog.confirm({ + title: gt("Remove {model}?", { model: model.name }), + message: gt("Download the model again to use it for dictation."), + confirmText: gt("Remove", { $context: "verb" }), + destructive: true, + onConfirm: () => + void actions.remove(model.id).catch(() => Dialog.alert(gt("Could not remove the model"))), + }); + }, + }; + return { voice, activeId, select }; +} + +export function DeviceVoiceEngineSection() { + const gt = useGT(); + const navigation = useNavigation(); + const apple = useAtomValue(localVoiceTranscriberAtom); + const { voice, activeId, select } = useDeviceVoiceModels(); + const appleSpeech = "Apple Speech"; + const active = voice.models.find((model) => model.active); + const pending = voice.models.find(isDownloading); + + let detail = gt("Transcription models"); + if (pending?.state === "downloading") { + detail = gt("Downloading {model} · {percent}%", { + model: pending.name, + percent: Math.round(((pending.downloaded ?? 0) / pending.size) * 100), + }); + } else if (pending?.state === "verifying") { + detail = gt("Verifying {model}…", { model: pending.name }); + } else if (pending?.state === "cancelling") { + detail = gt("Cancelling download…"); + } else if (active?.state === "installed") { + detail = gt("Local model · {size}", { size: formatBytes(active.size) }); + } else if (!voice.models.some((model) => model.state === "installed")) { + detail = gt("No model installed · Choose one to download"); + } + + return ( + + void select(null)} + /> + {voice.models.length > 0 ? ( + navigation.navigate("SettingsVoiceModels", { source: "device" })} + /> + ) : null} + + ); +} diff --git a/apps/mobile/src/features/settings/SettingsVoiceModelsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsVoiceModelsRouteScreen.tsx index 003e02f3add2d..9b84fa5b42d46 100644 --- a/apps/mobile/src/features/settings/SettingsVoiceModelsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsVoiceModelsRouteScreen.tsx @@ -15,39 +15,62 @@ import { cn } from "../../lib/cn"; import { useEnvironments } from "../../state/environments"; import { voiceSpeechBenchmarksAtom } from "../voice-input/voiceDestination"; import { PullRequestSearchSheet } from "../pull-requests/PullRequestSearchSheet"; -import { useVoiceModels, VoiceModelRow } from "./VoiceModelSection"; +import { useDeviceVoiceModels } from "./DeviceVoiceEngineSection"; +import { useVoiceModels, VoiceModelRow, type VoiceModelList } from "./VoiceModelSection"; -export function SettingsVoiceModelsRouteScreen({ - route, -}: StaticScreenProps<{ readonly environmentId: EnvironmentId }>) { +type VoiceModelsSource = + | { readonly source: "device" } + | { readonly source: "environment"; readonly environmentId: EnvironmentId }; + +export function SettingsVoiceModelsRouteScreen({ route }: StaticScreenProps) { + return route.params.source === "device" ? ( + + ) : ( + + ); +} + +function DeviceVoiceModelsSheet() { + const { voice } = useDeviceVoiceModels(); + return ; +} + +function EnvironmentVoiceModelsSheet({ environmentId }: { readonly environmentId: EnvironmentId }) { const gt = useGT(); const { environments } = useEnvironments(); const label = - environments.find((environment) => environment.environmentId === route.params.environmentId) - ?.label ?? gt("This environment"); - const voice = useVoiceModels(route.params.environmentId, label); + environments.find((environment) => environment.environmentId === environmentId)?.label ?? + gt("This environment"); + const voice = useVoiceModels(environmentId, label); const benchmarks = new Map( ( - AsyncResult.getOrElse( - useAtomValue(voiceSpeechBenchmarksAtom(route.params.environmentId)), - () => null, - )?.models ?? [] + AsyncResult.getOrElse(useAtomValue(voiceSpeechBenchmarksAtom(environmentId)), () => null) + ?.models ?? [] ).map((model) => [model.id, model.benchmark]), ); + const models = voice.models.map((model) => { + const benchmark = benchmarks.get(model.id); + return benchmark ? { ...model, benchmark } : model; + }); + return ; +} + +function VoiceModelsSheet({ + voice, + label, +}: { + readonly voice: VoiceModelList; + readonly label?: string; +}) { + const gt = useGT(); const language = new Intl.DateTimeFormat().resolvedOptions().locale.split("-")[0]!.toLowerCase(); const [query, setQuery] = useState(""); const needle = query.trim().toLowerCase(); - // Catalog order, not state order: re-sorting when a download finishes would move rows under a tap. - const models = voice.models - .map((model) => { - const benchmark = benchmarks.get(model.id); - return benchmark ? { ...model, benchmark } : model; - }) - .filter((model) => - `${model.name} ${model.description} ${model.languages.join(" ")}` - .toLowerCase() - .includes(needle), - ); + const models = voice.models.filter((model) => + `${model.name} ${model.description} ${model.languages.join(" ")}` + .toLowerCase() + .includes(needle), + ); return ( This connection can’t change settings on {label}. @@ -101,7 +124,9 @@ export function SettingsVoiceModelsRouteScreen({ detail={ needle ? gt("Try another name or language.") - : gt("{environment} has no models to list.", { environment: label }) + : label === undefined + ? gt("Transcription unavailable") + : gt("{environment} has no models to list.", { environment: label }) } variant="plain" /> diff --git a/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx index 6e18e2146dd92..a7b31aa6ff97f 100644 --- a/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsVoiceRouteScreen.tsx @@ -34,6 +34,7 @@ import { } from "../voice-input/voiceDestination"; import { LocalModelChoice } from "./VoiceModelSection"; import { CloudVoiceChoice } from "./CloudVoiceSection"; +import { DeviceVoiceEngineSection } from "./DeviceVoiceEngineSection"; import type { VoiceGrant } from "../voice-input/voiceGrantStorage"; import type { EnvironmentId } from "@t3tools/contracts"; import { ThreadSwipeable } from "../home/thread-swipe-actions"; @@ -112,15 +113,6 @@ const KINDS: Record< }, }; -const UNAVAILABLE_EXPLANATION = - Platform.OS === "android" - ? msg( - "Dictation on this device needs Android 12 or later and Google speech services that support your language. Your keyboard’s voice typing is separate.", - ) - : msg( - "Dictation on this device needs iOS 26 or later, a supported device, and a supported language. Your keyboard’s dictation is separate.", - ); - function saveDestination(id: EnvironmentId | null) { try { chooseVoiceDestination(id); @@ -340,8 +332,15 @@ export function SettingsVoiceRouteScreen() { } /> ) : null} - {!grant && transcriber === null ? ( - {m(UNAVAILABLE_EXPLANATION)} + {!grant && !sheetEnvironment && Platform.OS === "ios" ? : null} + {!grant && Platform.OS === "android" && transcriber === null ? ( + + {m( + msg( + "Dictation on this device needs Android 12 or later and Google speech services that support your language. Your keyboard’s voice typing is separate.", + ), + )} + ) : null} {permission === "ask" || permission === "denied" ? ( <> diff --git a/apps/mobile/src/features/settings/VoiceModelSection.tsx b/apps/mobile/src/features/settings/VoiceModelSection.tsx index 7a745bb970ea8..de11d6cffb995 100644 --- a/apps/mobile/src/features/settings/VoiceModelSection.tsx +++ b/apps/mobile/src/features/settings/VoiceModelSection.tsx @@ -33,8 +33,28 @@ import { voiceSpeechStatusAtom, } from "../voice-input/voiceDestination"; -const isDownloading = (model: EnvironmentSpeechModel) => - model.state === "downloading" || model.state === "verifying"; +export type VoiceModel = Pick< + EnvironmentSpeechModel, + "id" | "name" | "description" | "size" | "languages" | "benchmark" | "active" | "downloaded" +> & { + readonly state: EnvironmentSpeechModel["state"] | "cancelling" | "failed"; +}; + +export type VoiceModelList = { + readonly models: ReadonlyArray; + readonly loading: boolean; + readonly canManage: boolean; + readonly requested?: string | null; + readonly busy: boolean; + readonly downloading: boolean; + download(model: VoiceModel): void; + select(model: VoiceModel): void; + cancel(model: VoiceModel): void; + remove?(model: VoiceModel): void; +}; + +export const isDownloading = (model: VoiceModel) => + model.state === "downloading" || model.state === "verifying" || model.state === "cancelling"; export function useVoiceModels(environmentId: EnvironmentId, label: string) { const gt = useGT(); @@ -86,7 +106,7 @@ export function useVoiceModels(environmentId: EnvironmentId, label: string) { busy, downloading, label, - download: (model: EnvironmentSpeechModel) => { + download: (model: VoiceModel) => { if (!ready) return; Dialog.confirm({ title: gt("Download {model}?", { model: model.name }), @@ -103,13 +123,13 @@ export function useVoiceModels(environmentId: EnvironmentId, label: string) { ), }); }, - select: (model: EnvironmentSpeechModel) => { + select: (model: VoiceModel) => { if (!ready || model.active) return; void run(gt("Could not select the model"), () => runSpeech(selectEnvironmentSpeechModel(connection, model.id)), ); }, - cancel: (model: EnvironmentSpeechModel) => { + cancel: (model: VoiceModel) => { if (!ready) return; void run(gt("Could not cancel the download"), () => runSpeech(cancelEnvironmentSpeechModelDownload(connection, model.id)), @@ -118,8 +138,6 @@ export function useVoiceModels(environmentId: EnvironmentId, label: string) { }; } -export type VoiceModels = ReturnType; - const languageNames = new Map(); function languageLabel(code: string, locale: string) { if (typeof Intl.DisplayNames !== "function") return code.toUpperCase(); @@ -129,7 +147,7 @@ function languageLabel(code: string, locale: string) { return names.of(code) ?? code.toUpperCase(); } -function ModelStats(props: { readonly model: EnvironmentSpeechModel; readonly language: string }) { +function ModelStats(props: { readonly model: VoiceModel; readonly language: string }) { const { model, language } = props; const locale = useLocale(); const data = model.benchmark; @@ -226,8 +244,8 @@ function DownloadedGlyph() { } export function VoiceModelRow(props: { - readonly model: EnvironmentSpeechModel; - readonly voice: VoiceModels; + readonly model: VoiceModel; + readonly voice: VoiceModelList; readonly separated: boolean; /** The language whose benchmark score to show, when the model has one. */ readonly language: string; @@ -235,8 +253,8 @@ export function VoiceModelRow(props: { const gt = useGT(); const { model, voice, separated } = props; const meta = ; - if (model.state === "installed") - return ( + if (model.state === "installed") { + const choice = ( } label={model.name} @@ -248,6 +266,23 @@ export function VoiceModelRow(props: { onPress={() => voice.select(model)} /> ); + return voice.remove ? ( + + {choice} + + voice.remove?.(model)} + /> + + + ) : ( + choice + ); + } const progress = model.downloaded === undefined ? undefined : model.downloaded / model.size; if (isDownloading(model) || voice.requested === model.id) return ( @@ -258,11 +293,13 @@ export function VoiceModelRow(props: { description={ model.state === "verifying" ? gt("Verifying download…") - : gt("{percent}% downloaded · Tap to cancel", { - percent: Math.round((progress ?? 0) * 100), - }) + : model.state === "cancelling" + ? gt("Cancelling download…") + : gt("{percent}% downloaded · Tap to cancel", { + percent: Math.round((progress ?? 0) * 100), + }) } - disabled={!voice.canManage || voice.busy} + disabled={!voice.canManage || voice.busy || model.state === "cancelling"} onPress={() => voice.cancel(model)} /> voice.download(model)} @@ -298,7 +337,10 @@ export function LocalModelChoice(props: { const voice = useVoiceModels(props.environmentId, props.label); const { status } = voice; const open = () => - navigation.navigate("SettingsVoiceModels", { environmentId: props.environmentId }); + navigation.navigate("SettingsVoiceModels", { + source: "environment", + environmentId: props.environmentId, + }); if (!voice.connection || !status || !status.supported) return ( ({ + models: [ + { + id: "handy-computer/parakeet-ultra-gguf", + name: "Parakeet Ultra", + description: "Multilingual dictation", + size: 740_363_168, + languages: ["uk", "en"], + }, + { + id: "handy-computer/whisper-small-gguf", + name: "Whisper Small", + description: "Multilingual dictation", + size: 269_751_136, + languages: ["uk", "en"], + }, + ] as const, + snapshot: vi.fn<() => Promise>(), + listen: vi.fn<(name: string, listener: (snapshot: unknown) => void) => { remove(): void }>( + () => ({ remove() {} }), + ), + transcribe: + vi.fn< + (modelId: string, id: string, uri: string) => Promise<{ text: string; language?: string }> + >(), + cancel: vi.fn<(id: string) => Promise>(async () => {}), +})); + +vi.mock("expo", () => ({ + requireOptionalNativeModule: () => ({ + getDeviceSpeechCatalog: () => native.models, + getDeviceSpeechModelStates: native.snapshot, + addListener: native.listen, + transcribeWithDeviceSpeechModel: native.transcribe, + cancelDeviceSpeechInference: native.cancel, + }), +})); vi.mock("react-native", () => ({ Platform: { OS: "ios" }, AppState: { addEventListener: () => ({ remove() {} }) }, @@ -23,6 +60,7 @@ vi.mock("expo-audio", () => ({ setAudioModeAsync: vi.fn(async () => {}), setIsAudioActiveAsync: async () => {}, })); +vi.mock("../../lib/uuid", () => ({ uuidv4: () => "test-voice-request" })); vi.mock("../../native/voiceRecorder", () => ({ createVoiceRecorder: vi.fn() })); vi.mock("../../native/voiceTranscription", () => ({ getLocalVoiceTranscriber: async () => null })); vi.mock("../../state/preferences", async () => { @@ -35,21 +73,34 @@ vi.mock("./voiceDestination", async () => { }); import { setAudioModeAsync } from "expo-audio"; -import type { MicrophoneEntry } from "../../lib/microphonePriority"; +import { + deviceSpeechModelStatesAtom, + deviceSpeechTranscriber, +} from "../../native/deviceSpeechModels"; import { createVoiceRecorder } from "../../native/voiceRecorder"; +import type { Preferences } from "../../persistence/mobile-preferences"; import { mobilePreferencesAtom } from "../../state/preferences"; -import { localVoiceTranscriberAtom, voiceInputAtom } from "./VoiceInputProvider"; +import { + localVoiceTranscriberAtom, + voiceInputAtom, + voiceInputAvailableAtom, +} from "./VoiceInputProvider"; import { createVoiceInputTarget } from "./voiceInputSession"; -it("uses the loaded microphone order when recording starts before preferences hydrate", async () => { - const registry = AtomRegistry.make(); - const preferences = mobilePreferencesAtom as Atom.Writable< - AsyncResult.AsyncResult<{ microphones: ReadonlyArray }>, - AsyncResult.AsyncResult<{ microphones: ReadonlyArray }> - >; - // Startup either subscribes to pending preferences or activates audio before they load. - const startup = Promise.withResolvers(); - vi.mocked(setAudioModeAsync).mockImplementation(async () => startup.resolve()); +const preferences = mobilePreferencesAtom as Atom.Writable< + AsyncResult.AsyncResult, + AsyncResult.AsyncResult +>; +const [parakeet, whisper] = native.models; + +function modelSnapshot(revision: number, first: "ready" | "missing") { + return { + revision, + states: { [parakeet.id]: { kind: first }, [whisper.id]: { kind: "ready" } }, + }; +} + +function mockRecorder() { const setInput = vi.fn(); vi.mocked(createVoiceRecorder, { partial: true }).mockReturnValue({ uri: "file:///voice.m4a", @@ -69,6 +120,16 @@ it("uses the loaded microphone order when recording starts before preferences hy setInput, release() {}, }); + return setInput; +} + +it("uses the loaded microphone order when recording starts before preferences hydrate", async () => { + const registry = AtomRegistry.make(); + const preferencesSubscribedOrAudioModeSet = Promise.withResolvers(); + vi.mocked(setAudioModeAsync).mockImplementation(async () => + preferencesSubscribedOrAudioModeSet.resolve(), + ); + const setInput = mockRecorder(); registry.set(localVoiceTranscriberAtom, { prepare: async () => ({ locale: "en-US", transcribe: async () => "" }), }); @@ -77,14 +138,14 @@ it("uses the loaded microphone order when recording starts before preferences hy using _subscribe = vi .spyOn(registry, "subscribe") .mockImplementation((atom, listener, options) => { - if (atom === preferences) startup.resolve(); + if (atom === preferences) preferencesSubscribedOrAudioModeSet.resolve(); return subscribe(atom, listener, options); }); try { const start = session.start( createVoiceInputTarget("draft", () => "", vi.fn(), { start: 0, end: 0 }), ); - await startup.promise; + await preferencesSubscribedOrAudioModeSet.promise; registry.set( preferences, AsyncResult.success({ @@ -106,3 +167,104 @@ it("uses the loaded microphone order when recording starts before preferences hy registry.dispose(); } }); + +it("keeps the chosen model for the recording, then uses the next selection", async () => { + const registry = AtomRegistry.make(); + mockRecorder(); + native.snapshot.mockResolvedValue(modelSnapshot(1, "ready")); + native.transcribe.mockImplementation(async (modelId) => + modelId === parakeet.id ? { text: "Світ.", language: "uk" } : { text: "Hi.", language: "en" }, + ); + registry.set(localVoiceTranscriberAtom, { + prepare: async () => ({ locale: "en-US", transcribe: async () => "Hello." }), + }); + const { session } = registry.get(voiceInputAtom); + const hydrating = Promise.withResolvers(); + const subscribe = registry.subscribe.bind(registry); + using _subscribe = vi + .spyOn(registry, "subscribe") + .mockImplementation((atom, listener, options) => { + if (atom === preferences) hydrating.resolve(); + return subscribe(atom, listener, options); + }); + const commit = vi.fn(); + const target = createVoiceInputTarget("draft", () => "", commit, { start: 0, end: 0 }); + const ukrainianDraft = createVoiceInputTarget("draft", () => "Вітаю", commit, { + start: 5, + end: 5, + }); + try { + expect(registry.get(voiceInputAvailableAtom)).toBe(false); + const start = session.start(ukrainianDraft); + await hydrating.promise; + registry.set(preferences, AsyncResult.success({ deviceVoiceModelId: parakeet.id })); + await start; + expect(session.controller.currentState.phase).toBe("recording"); + registry.set(preferences, AsyncResult.success({ deviceVoiceModelId: whisper.id })); + await session.controller.stop(); + expect(commit.mock.calls.map(([text]) => text)).toEqual(["Вітаю Світ."]); + + await session.start(target); + await session.controller.stop(); + expect(commit.mock.calls.map(([text]) => text)).toEqual(["Вітаю Світ.", "Hi."]); + expect(native.transcribe.mock.calls.slice(-2).map(([id]) => id)).toEqual([ + parakeet.id, + whisper.id, + ]); + + registry.set(preferences, AsyncResult.success({ deviceVoiceModelId: null })); + await session.start(target); + await session.controller.stop(); + expect(commit.mock.lastCall?.[0]).toEqual("Hello."); + } finally { + session.controller.cancel(); + registry.dispose(); + } +}); + +it("keeps a removed selection unavailable until a different model or Apple Speech is chosen", async () => { + const registry = AtomRegistry.make(); + const initial = Promise.withResolvers(); + native.snapshot.mockReturnValue(initial.promise); + registry.set(preferences, AsyncResult.success({ deviceVoiceModelId: parakeet.id })); + registry.set(localVoiceTranscriberAtom, { + prepare: async () => ({ locale: "en-US", transcribe: async () => "Hello." }), + }); + try { + expect(registry.get(voiceInputAvailableAtom)).toBe(false); + const emit = native.listen.mock.lastCall?.[1]; + expect(emit).toBeDefined(); + emit?.(modelSnapshot(2, "ready")); + expect(registry.get(voiceInputAvailableAtom)).toBe(true); + initial.resolve(modelSnapshot(1, "missing")); + await initial.promise; + expect(registry.get(deviceSpeechModelStatesAtom)).toMatchObject({ + kind: "ready", + states: modelSnapshot(2, "ready").states, + }); + + emit?.(modelSnapshot(3, "missing")); + expect(registry.get(voiceInputAvailableAtom)).toBe(false); + registry.set(preferences, AsyncResult.success({ deviceVoiceModelId: whisper.id })); + expect(registry.get(voiceInputAvailableAtom)).toBe(true); + registry.set(preferences, AsyncResult.success({ deviceVoiceModelId: null })); + expect(registry.get(voiceInputAvailableAtom)).toBe(true); + } finally { + registry.dispose(); + } +}); + +it("discards a cancelled local transcript after the native operation settles", async () => { + native.snapshot.mockResolvedValue(modelSnapshot(1, "ready")); + const recording = Promise.withResolvers<{ text: string }>(); + native.transcribe.mockReturnValue(recording.promise); + const controller = new AbortController(); + const options = { signal: controller.signal }; + const prepared = await deviceSpeechTranscriber(parakeet).prepare(options); + const result = prepared.transcribe("file:///voice.m4a", options); + const id = native.transcribe.mock.lastCall?.[1]; + controller.abort(); + expect(native.cancel).toHaveBeenCalledWith(id); + recording.resolve({ text: "Late transcript." }); + await expect(result).rejects.toMatchObject({ code: "cancelled" }); +}); diff --git a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx index 882191260a8cd..e959a856c558f 100644 --- a/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx +++ b/apps/mobile/src/features/voice-input/VoiceInputProvider.tsx @@ -7,6 +7,7 @@ import { useSyncExternalStore } from "react"; import { Platform } from "react-native"; import { Effect } from "effect"; import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity"; +import { msg } from "gt-react-native"; import { makeMutable } from "react-native-reanimated"; import { @@ -16,11 +17,18 @@ import { rememberMicrophones, } from "../../lib/microphonePriority"; import { getLocalVoiceTranscriber } from "../../native/voiceTranscription"; +import { + deviceSpeechCatalog, + deviceSpeechModelStatesAtom, + deviceSpeechTranscriber, +} from "../../native/deviceSpeechModels"; import { createVoiceRecorder } from "../../native/voiceRecorder"; +import { m } from "../../i18n/messages"; import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences"; import { getNativeShowcaseScene } from "../showcase/nativeShowcaseScene"; import { voiceInputBlocksSubmission, + VoiceTranscriptionError, type VoiceTranscriber, } from "@t3tools/client-runtime/voice-input"; import { createLazyVoiceRecorder } from "./lazyVoiceRecorder"; @@ -66,9 +74,23 @@ export const localVoiceTranscriberAtom = makePermissionStatusAtom< read: () => getLocalVoiceTranscriber().catch(() => null), }).pipe(Atom.keepAlive); -const voiceInputAvailableAtom = Atom.make((get) => { +export const iosVoiceModelAtom = Atom.make((get): string | null | undefined => { + const preferences = get(mobilePreferencesAtom); + if (!AsyncResult.isSuccess(preferences)) return undefined; + return preferences.value.deviceVoiceModelId ?? null; +}); + +export const voiceInputAvailableAtom = Atom.make((get) => { const route = get(voiceRouteAtom); if (route) return route.transcriber !== null; + if (Platform.OS === "ios") { + const id = get(iosVoiceModelAtom); + if (id === undefined) return false; + if (id !== null) { + const catalog = get(deviceSpeechModelStatesAtom); + return catalog.kind === "ready" && catalog.states[id]?.kind === "ready"; + } + } const transcriber = get(localVoiceTranscriberAtom); return transcriber !== null && transcriber !== "checking"; }); @@ -79,8 +101,16 @@ const voiceInputAvailableAtom = Atom.make((get) => { */ export const voiceInputAtom = Atom.make((get) => { const registry = get.registry; - // Mounted so the recorder can read known microphones synchronously. get.mount(mobilePreferencesAtom); + const systemTranscriber = () => { + const transcriber = registry.get(localVoiceTranscriberAtom); + return transcriber === "checking" ? null : transcriber; + }; + const iosTranscriber = (id: string | null) => { + if (id === null) return systemTranscriber(); + const model = deviceSpeechCatalog.find((entry) => entry.id === id); + return model ? deviceSpeechTranscriber(model) : null; + }; const audioLevels = makeMutable>( Array(VOICE_WAVEFORM_SAMPLE_COUNT).fill(0), ); @@ -123,8 +153,25 @@ export const voiceInputAtom = Atom.make((get) => { getTranscriber: () => { const route = registry.get(voiceRouteAtom); if (route) return route.transcriber; - const transcriber = registry.get(localVoiceTranscriberAtom); - return transcriber === "checking" ? null : transcriber; + if (Platform.OS !== "ios") return systemTranscriber(); + const id = registry.get(iosVoiceModelAtom); + if (id !== undefined) return iosTranscriber(id); + return { + prepare: async (options) => { + const preferences = await Effect.runPromise( + AtomRegistry.getResult(registry, mobilePreferencesAtom), + { signal: options.signal }, + ); + const transcriber = iosTranscriber(preferences.deviceVoiceModelId ?? null); + if (!transcriber) { + throw new VoiceTranscriptionError({ + code: "unavailable", + message: m(msg("Voice transcription is not available.")), + }); + } + return transcriber.prepare(options); + }, + }; }, requestPermission: permission.requestPermission, configureRecording: async () => { diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index c8c0ea9bf09de..949392ed7aac6 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -5627,5 +5627,15 @@ "eb287395a09cd288": "Verbindungs-Traces senden", "6787f93bbf6ce0b6": "Hilft dem T3 Code-Team, Verbindungsprobleme zu beheben. Traces enthalten Zeiten, Fehlertypen, eine ID für diese App-Sitzung und die App-Version, nie deine Threads, Prompts oder deinen Code. Du kannst das unter Einstellungen > Über T3 Code > Diagnose ändern.", "0b1e4aecbd38e0cf": "Wenn die App über {product} eine Verbindung zu einem Computer herstellt, sendet sie dem T3 Code-Team, wie lange jeder Schritt gedauert hat, den Fehlertyp, eine ID für diese App-Sitzung und die App-Version. Traces enthalten nie deine Threads, Prompts oder deinen Code.", - "e0856d6a402ad821": "Die Richtlinie von {organization} erlaubt keine Worktree-Layout-Befehle von Projekten." + "e0856d6a402ad821": "Die Richtlinie von {organization} erlaubt keine Worktree-Layout-Befehle von Projekten.", + "f248baa236fb70ca": "Download {model} in Settings → Voice to use it for dictation.", + "7ac0f48b44b95f3f": "Download {size} for offline dictation.", + "68f05c5e4e67c24d": "Remove {model}?", + "9be40a016dc63138": "Download the model again to use it for dictation.", + "16182194d9202688": "Remove", + "bbed5949ca5cade3": "Could not remove the model", + "a4be2da8ba636a75": "Cancelling download…", + "31187edd3f8e47a3": "Method on this device", + "651cb409bda342a8": "Remove {model}", + "1fa254d98545ab8e": "Download failed. Try again." } diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 50ad5757a578a..14f10a811406b 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -5629,5 +5629,15 @@ "eb287395a09cd288": "Send connection traces", "6787f93bbf6ce0b6": "Helps the T3 Code team fix connection problems. Traces hold timings, error types, an ID for this app session, and the app version, never your threads, prompts, or code. You can change this in Settings > About T3 Code > Diagnostics.", "0b1e4aecbd38e0cf": "When the app connects to a computer through {product}, it sends the T3 Code team how long each step took, any error type, an ID for this app session, and the app version. Traces never include your threads, prompts, or code.", - "e0856d6a402ad821": "{organization}'s policy does not allow project worktree layout commands." + "e0856d6a402ad821": "{organization}'s policy does not allow project worktree layout commands.", + "f248baa236fb70ca": "Download {model} in Settings → Voice to use it for dictation.", + "7ac0f48b44b95f3f": "Download {size} for offline dictation.", + "68f05c5e4e67c24d": "Remove {model}?", + "9be40a016dc63138": "Download the model again to use it for dictation.", + "16182194d9202688": "Remove", + "bbed5949ca5cade3": "Could not remove the model", + "a4be2da8ba636a75": "Cancelling download…", + "31187edd3f8e47a3": "Method on this device", + "651cb409bda342a8": "Remove {model}", + "1fa254d98545ab8e": "Download failed. Try again." } diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index c56584398f989..f0c2a81ce94d7 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -5621,5 +5621,15 @@ "eb287395a09cd288": "Enviar trazas de conexión", "6787f93bbf6ce0b6": "Ayuda al equipo de T3 Code a solucionar problemas de conexión. Las trazas incluyen tiempos, tipos de error, un ID de esta sesión de la app y la versión de la app, nunca tus hilos, prompts ni código. Puedes cambiarlo en Ajustes > Acerca de T3 Code > Diagnóstico.", "0b1e4aecbd38e0cf": "Cuando la app se conecta a un ordenador mediante {product}, envía al equipo de T3 Code cuánto tardó cada paso, el tipo de error, un ID de esta sesión de la app y la versión de la app. Las trazas nunca incluyen tus hilos, prompts ni código.", - "e0856d6a402ad821": "La política de {organization} no permite comandos de diseño de worktrees de proyectos." + "e0856d6a402ad821": "La política de {organization} no permite comandos de diseño de worktrees de proyectos.", + "f248baa236fb70ca": "Download {model} in Settings → Voice to use it for dictation.", + "7ac0f48b44b95f3f": "Download {size} for offline dictation.", + "68f05c5e4e67c24d": "Remove {model}?", + "9be40a016dc63138": "Download the model again to use it for dictation.", + "16182194d9202688": "Remove", + "bbed5949ca5cade3": "Could not remove the model", + "a4be2da8ba636a75": "Cancelling download…", + "31187edd3f8e47a3": "Method on this device", + "651cb409bda342a8": "Remove {model}", + "1fa254d98545ab8e": "Download failed. Try again." } diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index f9d8a800334a4..ba2b2a15fdb41 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -5621,5 +5621,15 @@ "eb287395a09cd288": "Envoyer les traces de connexion", "6787f93bbf6ce0b6": "Aide l’équipe T3 Code à résoudre les problèmes de connexion. Les traces contiennent des durées, des types d’erreur, un identifiant de cette session de l’app et la version de l’app, jamais vos fils, prompts ni votre code. Modifiable dans Réglages > À propos de T3 Code > Diagnostic.", "0b1e4aecbd38e0cf": "Quand l’app se connecte à un ordinateur via {product}, elle envoie à l’équipe T3 Code la durée de chaque étape, le type d’erreur, un identifiant de cette session de l’app et la version de l’app. Les traces n’incluent jamais vos fils, prompts ni votre code.", - "e0856d6a402ad821": "La politique de {organization} n’autorise pas les commandes de disposition des worktrees des projets." + "e0856d6a402ad821": "La politique de {organization} n’autorise pas les commandes de disposition des worktrees des projets.", + "f248baa236fb70ca": "Download {model} in Settings → Voice to use it for dictation.", + "7ac0f48b44b95f3f": "Download {size} for offline dictation.", + "68f05c5e4e67c24d": "Remove {model}?", + "9be40a016dc63138": "Download the model again to use it for dictation.", + "16182194d9202688": "Remove", + "bbed5949ca5cade3": "Could not remove the model", + "a4be2da8ba636a75": "Cancelling download…", + "31187edd3f8e47a3": "Method on this device", + "651cb409bda342a8": "Remove {model}", + "1fa254d98545ab8e": "Download failed. Try again." } diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index ca50625d8a5d3..96a6dd3741399 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -5601,5 +5601,15 @@ "eb287395a09cd288": "接続トレースを送信", "6787f93bbf6ce0b6": "T3 Code チームが接続の問題を修正するのに役立ちます。トレースには所要時間、エラーの種類、このアプリセッションの ID、アプリのバージョンが含まれ、スレッド、プロンプト、コードは含まれません。設定 > T3 Code について > 診断 で変更できます。", "0b1e4aecbd38e0cf": "アプリが {product} 経由でコンピューターに接続すると、各ステップの所要時間、エラーの種類、このアプリセッションの ID、アプリのバージョンを T3 Code チームに送信します。トレースにスレッド、プロンプト、コードは含まれません。", - "e0856d6a402ad821": "{organization} のポリシーでは、プロジェクトのワークツリーレイアウトコマンドは許可されていません。" + "e0856d6a402ad821": "{organization} のポリシーでは、プロジェクトのワークツリーレイアウトコマンドは許可されていません。", + "f248baa236fb70ca": "Download {model} in Settings → Voice to use it for dictation.", + "7ac0f48b44b95f3f": "Download {size} for offline dictation.", + "68f05c5e4e67c24d": "Remove {model}?", + "9be40a016dc63138": "Download the model again to use it for dictation.", + "16182194d9202688": "Remove", + "bbed5949ca5cade3": "Could not remove the model", + "a4be2da8ba636a75": "Cancelling download…", + "31187edd3f8e47a3": "Method on this device", + "651cb409bda342a8": "Remove {model}", + "1fa254d98545ab8e": "Download failed. Try again." } diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 567a09e845da5..85089ddf8d769 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -5607,5 +5607,15 @@ "eb287395a09cd288": "연결 트레이스 보내기", "6787f93bbf6ce0b6": "T3 Code 팀이 연결 문제를 해결하는 데 도움이 됩니다. 트레이스에는 소요 시간, 오류 유형, 이 앱 세션의 ID, 앱 버전이 포함되며 스레드, 프롬프트, 코드는 포함되지 않습니다. 설정 > T3 Code 정보 > 진단에서 변경할 수 있습니다.", "0b1e4aecbd38e0cf": "앱이 {product}를 통해 컴퓨터에 연결하면 각 단계에 걸린 시간, 오류 유형, 이 앱 세션의 ID, 앱 버전을 T3 Code 팀에 보냅니다. 트레이스에는 스레드, 프롬프트, 코드가 포함되지 않습니다.", - "e0856d6a402ad821": "{organization}의 정책상 프로젝트의 워크트리 레이아웃 명령을 사용할 수 없습니다." + "e0856d6a402ad821": "{organization}의 정책상 프로젝트의 워크트리 레이아웃 명령을 사용할 수 없습니다.", + "f248baa236fb70ca": "Download {model} in Settings → Voice to use it for dictation.", + "7ac0f48b44b95f3f": "Download {size} for offline dictation.", + "68f05c5e4e67c24d": "Remove {model}?", + "9be40a016dc63138": "Download the model again to use it for dictation.", + "16182194d9202688": "Remove", + "bbed5949ca5cade3": "Could not remove the model", + "a4be2da8ba636a75": "Cancelling download…", + "31187edd3f8e47a3": "Method on this device", + "651cb409bda342a8": "Remove {model}", + "1fa254d98545ab8e": "Download failed. Try again." } diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index aad95138c9e75..c91029a8b9229 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -5621,5 +5621,15 @@ "eb287395a09cd288": "Enviar traces de conexão", "6787f93bbf6ce0b6": "Ajuda a equipe do T3 Code a corrigir problemas de conexão. Os traces incluem tempos, tipos de erro, um ID desta sessão do app e a versão do app, nunca suas conversas, prompts ou código. Você pode mudar isso em Configurações > Sobre o T3 Code > Diagnóstico.", "0b1e4aecbd38e0cf": "Quando o app se conecta a um computador pelo {product}, ele envia à equipe do T3 Code quanto tempo cada etapa levou, o tipo de erro, um ID desta sessão do app e a versão do app. Os traces nunca incluem suas conversas, prompts ou código.", - "e0856d6a402ad821": "A política de {organization} não permite comandos de layout de worktree de projetos." + "e0856d6a402ad821": "A política de {organization} não permite comandos de layout de worktree de projetos.", + "f248baa236fb70ca": "Download {model} in Settings → Voice to use it for dictation.", + "7ac0f48b44b95f3f": "Download {size} for offline dictation.", + "68f05c5e4e67c24d": "Remove {model}?", + "9be40a016dc63138": "Download the model again to use it for dictation.", + "16182194d9202688": "Remove", + "bbed5949ca5cade3": "Could not remove the model", + "a4be2da8ba636a75": "Cancelling download…", + "31187edd3f8e47a3": "Method on this device", + "651cb409bda342a8": "Remove {model}", + "1fa254d98545ab8e": "Download failed. Try again." } diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index d43dc2f5e83a0..2a5c94dfc9d4e 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -5701,5 +5701,15 @@ "eb287395a09cd288": "Отправлять трассировки подключения", "6787f93bbf6ce0b6": "Помогает команде T3 Code устранять проблемы с подключением. Трассировки содержат время, типы ошибок, ID этого сеанса приложения и версию приложения, но никогда ваши треды, промпты или код. Это можно изменить в разделе Настройки > О T3 Code > Диагностика.", "0b1e4aecbd38e0cf": "Когда приложение подключается к компьютеру через {product}, оно отправляет команде T3 Code длительность каждого шага, тип ошибки, ID этого сеанса приложения и версию приложения. Трассировки никогда не содержат ваши треды, промпты или код.", - "e0856d6a402ad821": "Политика {organization} запрещает команды раскладки рабочих деревьев проектов." + "e0856d6a402ad821": "Политика {organization} запрещает команды раскладки рабочих деревьев проектов.", + "f248baa236fb70ca": "Download {model} in Settings → Voice to use it for dictation.", + "7ac0f48b44b95f3f": "Download {size} for offline dictation.", + "68f05c5e4e67c24d": "Remove {model}?", + "9be40a016dc63138": "Download the model again to use it for dictation.", + "16182194d9202688": "Remove", + "bbed5949ca5cade3": "Could not remove the model", + "a4be2da8ba636a75": "Cancelling download…", + "31187edd3f8e47a3": "Method on this device", + "651cb409bda342a8": "Remove {model}", + "1fa254d98545ab8e": "Download failed. Try again." } diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index a3e1735bcc113..ea021a90c9a08 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -5627,5 +5627,15 @@ "eb287395a09cd288": "Skicka anslutningsspårningar", "6787f93bbf6ce0b6": "Hjälper T3 Code-teamet att åtgärda anslutningsproblem. Spårningar innehåller tider, feltyper, ett ID för den här appsessionen och appversionen, aldrig dina trådar, prompter eller din kod. Du kan ändra det under Inställningar > Om T3 Code > Diagnostik.", "0b1e4aecbd38e0cf": "När appen ansluter till en dator via {product} skickar den hur lång tid varje steg tog, feltypen, ett ID för den här appsessionen och appversionen till T3 Code-teamet. Spårningar innehåller aldrig dina trådar, prompter eller din kod.", - "e0856d6a402ad821": "Policyn för {organization} tillåter inte projekts layoutkommandon för worktrees." + "e0856d6a402ad821": "Policyn för {organization} tillåter inte projekts layoutkommandon för worktrees.", + "f248baa236fb70ca": "Download {model} in Settings → Voice to use it for dictation.", + "7ac0f48b44b95f3f": "Download {size} for offline dictation.", + "68f05c5e4e67c24d": "Remove {model}?", + "9be40a016dc63138": "Download the model again to use it for dictation.", + "16182194d9202688": "Remove", + "bbed5949ca5cade3": "Could not remove the model", + "a4be2da8ba636a75": "Cancelling download…", + "31187edd3f8e47a3": "Method on this device", + "651cb409bda342a8": "Remove {model}", + "1fa254d98545ab8e": "Download failed. Try again." } diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 4f3e235e444bb..e3ba76bf24c28 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -5611,5 +5611,15 @@ "eb287395a09cd288": "发送连接追踪", "6787f93bbf6ce0b6": "帮助 T3 Code 团队修复连接问题。追踪数据包含耗时、错误类型、此应用会话的 ID 和应用版本,绝不包含你的线程、提示词或代码。可在 设置 > 关于 T3 Code > 诊断 中更改。", "0b1e4aecbd38e0cf": "当应用通过 {product} 连接到电脑时,会向 T3 Code 团队发送每一步的耗时、错误类型、此应用会话的 ID 和应用版本。追踪数据绝不包含你的线程、提示词或代码。", - "e0856d6a402ad821": "{organization} 的策略不允许使用项目的工作树布局命令。" + "e0856d6a402ad821": "{organization} 的策略不允许使用项目的工作树布局命令。", + "f248baa236fb70ca": "Download {model} in Settings → Voice to use it for dictation.", + "7ac0f48b44b95f3f": "Download {size} for offline dictation.", + "68f05c5e4e67c24d": "Remove {model}?", + "9be40a016dc63138": "Download the model again to use it for dictation.", + "16182194d9202688": "Remove", + "bbed5949ca5cade3": "Could not remove the model", + "a4be2da8ba636a75": "Cancelling download…", + "31187edd3f8e47a3": "Method on this device", + "651cb409bda342a8": "Remove {model}", + "1fa254d98545ab8e": "Download failed. Try again." } diff --git a/apps/mobile/src/native/deviceSpeechModels.ts b/apps/mobile/src/native/deviceSpeechModels.ts new file mode 100644 index 0000000000000..973a2805293c2 --- /dev/null +++ b/apps/mobile/src/native/deviceSpeechModels.ts @@ -0,0 +1,150 @@ +import { + VoiceTranscriptionError, + throwIfVoiceTranscriptionAborted, + type VoiceTranscriber, +} from "@t3tools/client-runtime/voice-input"; +import { EnvironmentSpeechModel } from "@t3tools/contracts"; +import { Option } from "effect"; +import * as Schema from "effect/Schema"; +import { Atom } from "effect/reactivity"; +import { requireOptionalNativeModule, type EventSubscription } from "expo"; +import { msg } from "gt-react-native"; +import { Platform } from "react-native"; +import { m } from "../i18n/messages"; +import { subscribeAppActive } from "../lib/appState"; +import { uuidv4 } from "../lib/uuid"; + +const NativeState = Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("downloading"), + percent: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 100 })), + }), + Schema.Struct({ + kind: Schema.Literals(["missing", "verifying", "cancelling", "ready", "failed"]), + }), +]); +const decodeSnapshot = Schema.decodeUnknownOption( + Schema.Struct({ revision: Schema.Int, states: Schema.Record(Schema.String, NativeState) }), +); +const Model = Schema.Struct({ + id: Schema.String, + name: Schema.String, + description: Schema.String, + size: Schema.Int.check(Schema.isGreaterThan(0)), + languages: Schema.Array(Schema.String), + benchmark: EnvironmentSpeechModel.fields.benchmark, +}); +type Model = typeof Model.Type; +type CatalogState = + | { readonly kind: "checking" | "unavailable" } + | { readonly kind: "ready"; readonly states: Readonly> }; + +interface DeviceSpeechModule { + addListener( + event: "deviceSpeechModelStates", + listener: (snapshot: unknown) => void, + ): EventSubscription; + getDeviceSpeechCatalog?: () => unknown; + getDeviceSpeechModelStates(): Promise; + startDeviceSpeechModelDownload(modelId: string): Promise; + cancelDeviceSpeechModelDownload(modelId: string): Promise; + removeDeviceSpeechModel(modelId: string): Promise; + transcribeWithDeviceSpeechModel( + modelId: string, + id: string, + uri: string, + ): Promise<{ readonly text: string; readonly language?: string }>; + cancelDeviceSpeechInference(id: string): Promise; +} + +const native = + Platform.OS === "ios" + ? requireOptionalNativeModule("T3VoiceTranscription") + : null; +export const deviceSpeechCatalog = Option.getOrElse( + Schema.decodeUnknownOption(Schema.Array(Model))(native?.getDeviceSpeechCatalog?.()), + () => [], +); + +export const deviceSpeechModelStatesAtom = Atom.make((get) => { + if (!native || deviceSpeechCatalog.length === 0) return { kind: "unavailable" }; + + let revision = -1; + const accept = (payload: unknown) => { + const snapshot = decodeSnapshot(payload); + if (Option.isNone(snapshot) || snapshot.value.revision <= revision) return; + revision = snapshot.value.revision; + get.setSelf({ kind: "ready", states: snapshot.value.states }); + }; + const refresh = () => { + void native.getDeviceSpeechModelStates().then(accept, () => { + if (revision === -1) get.setSelf({ kind: "unavailable" }); + }); + }; + const events = native.addListener("deviceSpeechModelStates", accept); + get.addFinalizer(() => events.remove()); + get.addFinalizer(subscribeAppActive(refresh)); + refresh(); + return { kind: "checking" }; +}).pipe(Atom.keepAlive, Atom.withLabel("mobile:device-speech-models")); + +export const deviceSpeechModelActions = + native && deviceSpeechCatalog.length > 0 + ? { + download: (id: string) => native.startDeviceSpeechModelDownload(id), + cancel: (id: string) => native.cancelDeviceSpeechModelDownload(id), + remove: (id: string) => native.removeDeviceSpeechModel(id), + } + : null; + +export const deviceSpeechTranscriber = (model: Model): VoiceTranscriber => ({ + prepare: async ({ signal }) => { + throwIfVoiceTranscriptionAborted(signal); + const snapshot = + native && deviceSpeechCatalog.length > 0 + ? decodeSnapshot(await native.getDeviceSpeechModelStates()) + : Option.none(); + throwIfVoiceTranscriptionAborted(signal); + if (!native || Option.isNone(snapshot) || snapshot.value.states[model.id]?.kind !== "ready") { + throw new VoiceTranscriptionError({ + code: "unavailable", + message: m( + msg("Download {model} in Settings → Voice to use it for dictation.", { + model: model.name, + }), + ), + }); + } + let locale = "auto"; + return { + get locale() { + return locale; + }, + transcribe: async (uri, { signal }) => { + throwIfVoiceTranscriptionAborted(signal); + const id = uuidv4(); + let cancellation: Promise | undefined; + const abort = () => { + cancellation = native.cancelDeviceSpeechInference(id).catch(() => {}); + }; + signal.addEventListener("abort", abort, { once: true }); + try { + const transcript = await native.transcribeWithDeviceSpeechModel(model.id, id, uri); + throwIfVoiceTranscriptionAborted(signal); + locale = transcript.language ?? "auto"; + return transcript.text; + } catch (error) { + throwIfVoiceTranscriptionAborted(signal); + throw new VoiceTranscriptionError({ + code: "transcription-failed", + message: m(msg("Voice transcription failed.")), + cause: error, + }); + } finally { + signal.removeEventListener("abort", abort); + await cancellation; + } + }, + }; + }, +}); diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts index 98ee4cf34499e..71bfe0876f013 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -169,6 +169,7 @@ export interface Preferences { /** The client `language` setting: a locale code or "system". Unset means English. */ readonly language?: string; readonly microphones?: ReadonlyArray; + readonly deviceVoiceModelId?: string | null; readonly projectGroupingEnabled?: boolean; readonly projectGroupingMode?: SidebarProjectGroupingMode; readonly toolCallVisibility?: ToolCallVisibility; @@ -263,6 +264,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { followUpBehavior?: FollowUpBehavior; language?: string; microphones?: ReadonlyArray; + deviceVoiceModelId?: string | null; projectGroupingEnabled?: boolean; projectGroupingMode?: SidebarProjectGroupingMode; toolCallVisibility?: ToolCallVisibility; @@ -391,6 +393,11 @@ function sanitizePreferences(parsed: Preferences): Preferences { preferences.followUpBehavior = parsed.followUpBehavior; } if (typeof parsed.language === "string") preferences.language = parsed.language; + if (typeof parsed.deviceVoiceModelId === "string" || parsed.deviceVoiceModelId === null) { + preferences.deviceVoiceModelId = parsed.deviceVoiceModelId; + } else if ("deviceVoiceEngine" in parsed && parsed.deviceVoiceEngine === "parakeet-ultra") { + preferences.deviceVoiceModelId = "handy-computer/parakeet-ultra-gguf"; + } if (Array.isArray(parsed.microphones)) { preferences.microphones = parsed.microphones.flatMap((entry): MicrophoneEntry[] => { if (typeof entry !== "object" || entry === null || !isMicrophoneKind(entry.kind)) return []; diff --git a/docs/user/composer.md b/docs/user/composer.md index 53017052a2a01..1684eaeb762c0 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -229,8 +229,15 @@ Use the composer's microphone to record, then confirm to transcribe. Text is inserted where your selection was when recording started, ready for you to review and edit before sending. -By default, audio stays on the phone. Local transcription needs a supported iPhone -with iOS 26 or later, or Android 12 or later with compatible Google speech services. +By default, audio stays on the phone. iPhone uses Apple Speech by default, which +requires a supported device with iOS 26 or later. In **Settings → Voice**, choose +**This device**, then open **Local model** to view the models that fit the app's +available memory. The model picker shows benchmark accuracy by language. +Download a model and select it to dictate offline. Models with language detection +detect the spoken language. Other models use a supported device language when +available. Switch models or remove downloaded models from the same list, or choose +**Apple Speech** in **Voice**. +On-device dictation on Android requires Android 12 or later with compatible Google speech services. To use a paired environment instead, open **Settings → Voice → Transcribe on**, choose the environment, and confirm. Finished recordings go only to that environment, even when a draft belongs to another one. This also works on phones without local @@ -241,7 +248,7 @@ under the environment in **Settings → Voice** and confirm which provider may r On Android, keep T3 Code open while recording and transcribing. On-device dictation may need a network connection to download a speech model the -first time. After that it works offline for that language. iPhone dictates in the +first time. After that it works offline for that language. Apple Speech uses the first of your preferred languages (**Settings → General → Language & Region**) that Apple’s speech model supports. If none is supported, it tries the app’s language. Android transcribes on the device while you diff --git a/packages/client-runtime/src/voice-input/controller.test.ts b/packages/client-runtime/src/voice-input/controller.test.ts index 15f5fea3aac76..f20cfa73e7b39 100644 --- a/packages/client-runtime/src/voice-input/controller.test.ts +++ b/packages/client-runtime/src/voice-input/controller.test.ts @@ -232,6 +232,8 @@ describe("environment voice input", () => { describe("resolveTranscriptCommit", () => { it.each([ ["Hello", "world", "Hello world"], + ["Вітаю", "світ", "Вітаю світ"], + ["Γεια", "σου", "Γεια σου"], ["Hello", "世界", "Hello世界"], ["Hello", "𝟚", "Hello 𝟚"], ["你好", "世界", "你好世界"], diff --git a/packages/client-runtime/src/voice-input/controller.ts b/packages/client-runtime/src/voice-input/controller.ts index 372bfd2a9ad08..81be5049eabdd 100644 --- a/packages/client-runtime/src/voice-input/controller.ts +++ b/packages/client-runtime/src/voice-input/controller.ts @@ -133,6 +133,11 @@ type TranscriptCommitResult = | { readonly kind: "empty" }; const WORD_SPACELESS_LANGUAGES = new Set(["ja", "zh", "yue", "th", "lo", "km", "my"]); +const AUTO_WORD_CHARACTERS = String.raw`\p{Script=Latin}\p{Script=Cyrillic}\p{Script=Greek}\p{N}`; +const AUTO_LEFT_EDGE = new RegExp(String.raw`(?:[${AUTO_WORD_CHARACTERS}]|[.!?,:;)\]}'"])$`, "u"); +const AUTO_RIGHT_EDGE = new RegExp(`^(?:[${AUTO_WORD_CHARACTERS}]|[([{'"])`, "u"); +const AUTO_WORD_START = new RegExp(`^[${AUTO_WORD_CHARACTERS}]`, "u"); +const AUTO_WORD_END = new RegExp(`[${AUTO_WORD_CHARACTERS}]$`, "u"); const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff; const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff; @@ -191,14 +196,14 @@ export function resolveTranscriptCommit( const auto = language === "auto"; const left = text.slice(Math.max(0, start - 2), start); const right = text.slice(start, start + 2); - const leftEdge = auto ? /[A-Za-z0-9.!?,:;)\]}'"]$/ : /(?:\p{L}|\p{M}|\p{N}|[.!?,:;)\]}'"])$/u; - const rightEdge = auto ? /^[A-Za-z0-9([{'"]/ : /^[\p{L}\p{M}\p{N}([{'"]/u; + const leftEdge = auto ? AUTO_LEFT_EDGE : /(?:\p{L}|\p{M}|\p{N}|[.!?,:;)\]}'"])$/u; + const rightEdge = auto ? AUTO_RIGHT_EDGE : /^[\p{L}\p{M}\p{N}([{'"]/u; const leftNeedsBoundary = - (!auto || /^[\p{Script=Latin}\p{N}]/u.test(replacement)) && + (!auto || AUTO_WORD_START.test(replacement)) && leftEdge.test(left) && (!right || /^\s/.test(right)); const rightNeedsBoundary = - (!auto || /(?:\p{Script=Latin}|\p{N})$/u.test(replacement)) && + (!auto || AUTO_WORD_END.test(replacement)) && rightEdge.test(right) && (!left || /\s$/.test(left)); insertion = `${leftNeedsBoundary ? " " : ""}${replacement}${rightNeedsBoundary ? " " : ""}`; diff --git a/third-party-licenses.config.json b/third-party-licenses.config.json index 3f5ed2ff2c4de..c66eb5216c0a3 100644 --- a/third-party-licenses.config.json +++ b/third-party-licenses.config.json @@ -1,5 +1,14 @@ { "customNotices": [ + { + "bundles": ["ios"], + "includeInBundles": ["mobile"], + "license": "MIT", + "name": "transcribe.cpp for iOS", + "version": "0.4.1", + "sourceUrl": "https://github.com/handy-computer/transcribe.cpp/tree/v0.4.1", + "noticeFile": "apps/mobile/modules/t3-voice-transcription/THIRD_PARTY_NOTICES.md" + }, { "bundles": ["desktop", "mobile"], "license": "MIT",