diff --git a/README.md b/README.md index 300775e..8d6284a 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ In **Settings → General**, click the shortcut, then press your new key combina 3. Speak, then press the shortcut again. Keep the selected field and cursor unchanged while transcription runs. 4. If insertion cannot be verified or the destination changed, ClearFlow keeps the transcript on the clipboard for manual paste. Check the app’s status for details. -The recording limit is 4 minutes 55 seconds. Cancel with the overlay’s ×; pressing the shortcut while processing cancels delivery. Retry returns text for review and never pastes at an old cursor. +There is no elapsed-time cutoff: recording continues until you finish or cancel. After you finish, longer recordings are transcribed sequentially in parts of at most four minutes and combined into one result. Nothing is uploaded or inserted while you are recording. A word spanning a part boundary may be less accurate. Device interruptions or disk errors can still stop capture and are reported as errors; saved audio can be retried when available. Cancel with the overlay’s ×; pressing the shortcut while processing cancels delivery. Retry returns text for review and never pastes at an old cursor. [Full local setup, custom storage, startup at login, remote Mac and troubleshooting](local-stt/README.md). @@ -78,7 +78,7 @@ Deploy the supplied Worker in **your own account**, generate your own secret, an - The only bundled endpoint is loopback. Audio and vocabulary go only to the address you explicitly configure. No automatic provider fallback. - Local Whisper holds request audio in memory and does not log audio or transcripts. Setup downloads dependencies/model weights; runtime uses the local model with Hugging Face offline mode. -- Recording uses temporary WAV files, deleted on normal finish/cancel. A crash can leave a temporary file. Failed requests may keep audio in memory for retry. +- Recording uses temporary WAV files, deleted after successful transcription or cancellation. A crash can leave a temporary file. Failed requests retain the temporary recording file for retry until you cancel, start a new recording or quit. - Field content is read locally to guard insertion and is not uploaded. Known secure fields are rejected. - History is memory-only by default. Opt-in saved history stores up to 50 transcripts on your Mac. Clipboard fallback leaves the transcript available until replaced. - Your endpoint is stored in macOS preferences; the token is stored in Keychain. Keep credentials, recordings, personal endpoints and runtime data out of Git. diff --git a/Sources/ClearFlow/AudioCapture.swift b/Sources/ClearFlow/AudioCapture.swift index 5950524..b833af6 100644 --- a/Sources/ClearFlow/AudioCapture.swift +++ b/Sources/ClearFlow/AudioCapture.swift @@ -1,10 +1,28 @@ import Foundation import AVFoundation +protocol AudioRecording: AnyObject { + var delegate: AVAudioRecorderDelegate? { get set } + var isMeteringEnabled: Bool { get set } + var currentTime: TimeInterval { get } + func updateMeters() + func averagePower(forChannel channel: Int) -> Float + func prepareToRecord() -> Bool + func record() -> Bool + func record(forDuration duration: TimeInterval) -> Bool + func stop() +} +extension AVAudioRecorder: AudioRecording {} + @MainActor final class AudioCapture: NSObject, AVAudioRecorderDelegate { - private var recorder: AVAudioRecorder? + private var recorder: AudioRecording? + private let makeRecorder: (URL, [String: Any]) throws -> AudioRecording + init(makeRecorder: @escaping (URL, [String: Any]) throws -> AudioRecording = { try AVAudioRecorder(url: $0, settings: $1) }) { + self.makeRecorder = makeRecorder + super.init() + } private var file: URL? - var onAutomaticStop: (() -> Void)? + var onUnexpectedStop: ((String) -> Void)? var seconds: Double { recorder?.currentTime ?? 0 } var level: Double { guard let recorder else { return 0 } @@ -21,23 +39,23 @@ import AVFoundation AVNumberOfChannelsKey: 1, AVLinearPCMBitDepthKey: 16, AVLinearPCMIsBigEndianKey: false, AVLinearPCMIsFloatKey: false ] - let r = try AVAudioRecorder(url: url, settings: settings) + let r = try makeRecorder(url, settings) r.delegate = self; r.isMeteringEnabled = true - guard r.prepareToRecord(), r.record(forDuration: 295) else { + guard r.prepareToRecord(), r.record() else { try? FileManager.default.removeItem(at: url) throw AppError.message("The microphone could not start. Check the selected input in System Settings.") } recorder = r; file = url } - func stop() throws -> Data { + func stop() throws -> RecordedAudio { guard let recorder, let file else { throw AppError.message("No recording is active.") } recorder.delegate = nil recorder.stop() self.recorder = nil; self.file = nil - defer { try? FileManager.default.removeItem(at: file) } - let data = try Data(contentsOf: file) - guard data.count > 8044 else { throw AppError.message("That recording was too short. Speak for at least a moment.") } - return data + let recording = RecordedAudio(url: file) + let size = try FileManager.default.attributesOfItem(atPath: file.path)[.size] as? NSNumber + guard (size?.intValue ?? 0) > 8044 else { throw AppError.message("That recording was too short. Speak for at least a moment.") } + return recording } func cancel() { recorder?.delegate = nil; recorder?.stop(); recorder = nil @@ -45,9 +63,22 @@ import AVFoundation file = nil } nonisolated func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { - Task { @MainActor [weak self] in self?.onAutomaticStop?() } + Task { @MainActor [weak self] in + guard let self, self.recorder === recorder else { return } + self.onUnexpectedStop?("The microphone stopped unexpectedly. Check your input device and available disk space.") + } } nonisolated func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) { - Task { @MainActor [weak self] in self?.onAutomaticStop?() } + Task { @MainActor [weak self] in + guard let self, self.recorder === recorder else { return } + self.onUnexpectedStop?("The microphone stopped unexpectedly. Check your input device and available disk space.") + } } } + +/// Owns the temporary recording through transcription and retry; removes it on release. +final class RecordedAudio { + let url: URL + init(url: URL) { self.url = url } + deinit { try? FileManager.default.removeItem(at: url) } +} diff --git a/Sources/ClearFlow/ClearFlowApp.swift b/Sources/ClearFlow/ClearFlowApp.swift index b08505a..a23c0f2 100644 --- a/Sources/ClearFlow/ClearFlowApp.swift +++ b/Sources/ClearFlow/ClearFlowApp.swift @@ -30,8 +30,7 @@ import ClearFlowCore let path = args[2], endpoint = AppSettings.endpoint, token = TokenStore.read() Task.detached { do { - let data = try Data(contentsOf: URL(fileURLWithPath: path)) - let reply = try await TranscriptionClient.transcribe(audio: data, id: UUID(), endpoint: endpoint, + let reply = try await TranscriptionClient.transcribe(file: URL(fileURLWithPath: path), id: UUID(), endpoint: endpoint, token: token, language: "en", vocabulary: "") print(reply.text); exit(0) } catch { fputs("\(error.localizedDescription)\n", stderr); exit(1) } diff --git a/Sources/ClearFlow/DictationModel.swift b/Sources/ClearFlow/DictationModel.swift index a399b0c..118efbf 100644 --- a/Sources/ClearFlow/DictationModel.swift +++ b/Sources/ClearFlow/DictationModel.swift @@ -60,7 +60,7 @@ import ClearFlowCore private var currentID: UUID? private var target: InsertionTarget? private var captureIssue: String? - private var pendingAudio: Data? + private var pendingAudio: RecordedAudio? private var ticker: Timer? private var requestTask: Task? private var workspaceObserver: NSObjectProtocol? @@ -85,7 +85,13 @@ import ClearFlowCore app.processIdentifier != ProcessInfo.processInfo.processIdentifier else { return } Task { @MainActor [weak self] in self?.lastExternalApp = app } } - capture.onAutomaticStop = { [weak self] in self?.stop() } + capture.onUnexpectedStop = { [weak self] message in + guard let self, self.mode == .recording else { return } + self.ticker?.invalidate(); self.ticker = nil + self.pendingAudio = try? self.capture.stop() + self.gate.cancel(); self.mode = .error; self.level = 0 + self.status = message + (self.pendingAudio == nil ? " Please start again." : " Retry to transcribe the saved audio.") + } } func refreshPermissions() { guard !demoMode else { return } @@ -164,14 +170,17 @@ import ClearFlowCore gate.cancel(); mode = .error; status = error.localizedDescription } } - private func transcribe(_ audio: Data, id: UUID) { + private func transcribe(_ audio: RecordedAudio, id: UUID) { mode = .transcribing; status = "Turning speech into text…"; level = 0 let endpoint = AppSettings.endpoint, token = TokenStore.read() let language = AppSettings.language, vocabulary = AppSettings.vocabulary requestTask = Task { do { - let reply = try await TranscriptionClient.transcribe(audio: audio, id: id, endpoint: endpoint, - token: token, language: language, vocabulary: vocabulary) + let reply = try await TranscriptionClient.transcribe(file: audio.url, id: id, endpoint: endpoint, + token: token, language: language, vocabulary: vocabulary, + progress: { [weak self] part, count in + await self?.transcriptionProgress(part: part, count: count, id: id) + }) guard !Task.isCancelled, gate.acceptResult(id) else { return } let text = reply.text.trimmingCharacters(in: .whitespacesAndNewlines) guard !text.isEmpty else { @@ -193,6 +202,10 @@ import ClearFlowCore } } } + private func transcriptionProgress(part: Int, count: Int, id: UUID) { + guard currentID == id, mode == .transcribing else { return } + status = count > 1 ? "Transcribing part \(part) of \(count)…" : "Turning speech into text…" + } func retry() { guard let audio = pendingAudio, !busy else { return } gate.cancel(); let id = UUID() diff --git a/Sources/ClearFlow/TranscriptionClient.swift b/Sources/ClearFlow/TranscriptionClient.swift index 8f6dc54..c539c27 100644 --- a/Sources/ClearFlow/TranscriptionClient.swift +++ b/Sources/ClearFlow/TranscriptionClient.swift @@ -18,6 +18,13 @@ struct ErrorEnvelope: Decodable { let error: Detail } +struct TranscriptionServiceError: LocalizedError { + let status: Int + let code: String + let message: String + var errorDescription: String? { message } +} + enum TranscriptionClient { static let session: URLSession = { let config = URLSessionConfiguration.ephemeral @@ -28,7 +35,7 @@ enum TranscriptionClient { return URLSession(configuration: config, delegate: NoRedirectDelegate.shared, delegateQueue: nil) }() static func transcribe(audio: Data, id: UUID, endpoint: String, token: String, - language: String, vocabulary: String) async throws -> TranscriptionReply { + language: String, vocabulary: String, session: URLSession = session) async throws -> TranscriptionReply { guard let base = Endpoint.validated(endpoint), !token.isEmpty else { throw AppError.message("Set your service address and access token in Settings.") } @@ -51,7 +58,8 @@ enum TranscriptionClient { guard let http = response as? HTTPURLResponse else { throw AppError.message("No response from the transcription service.") } guard http.statusCode == 200 else { let remote = try? JSONDecoder().decode(ErrorEnvelope.self, from: data) - throw AppError.message(remote?.error.message ?? "Transcription failed (HTTP \(http.statusCode)).") + throw TranscriptionServiceError(status: http.statusCode, code: remote?.error.code ?? "UNKNOWN", + message: remote?.error.message ?? "Transcription failed (HTTP \(http.statusCode)).") } let reply = try JSONDecoder().decode(TranscriptionReply.self, from: data) guard reply.requestId.lowercased() == id.uuidString.lowercased() else { @@ -59,6 +67,32 @@ enum TranscriptionClient { } return reply } + static func transcribe(file: URL, id: UUID, endpoint: String, token: String, + language: String, vocabulary: String, session: URLSession = session, + progress: @Sendable (Int, Int) async -> Void = { _, _ in }) async throws -> TranscriptionReply { + let chunks = try WAVChunks(url: file) + var text: [String] = [] + var duration = 0.0 + var model = "" + for index in 0.. String { guard let base = Endpoint.validated(endpoint) else { throw AppError.message("Enter HTTPS, or HTTP on localhost.") } let (_, response) = try await session.data(from: base.appendingPathComponent("health")) diff --git a/Sources/ClearFlow/Views.swift b/Sources/ClearFlow/Views.swift index f71187c..b114579 100644 --- a/Sources/ClearFlow/Views.swift +++ b/Sources/ClearFlow/Views.swift @@ -364,7 +364,7 @@ private struct FlowSettings: View { SecureField(model.hasToken ? "Saved in Keychain — leave blank to keep" : "Private service token", text: $model.token) .textFieldStyle(.roundedBorder).padding(.top, 10) Button("Check connection") { model.testConnection() }.buttonStyle(FlowButton()).padding(.top, 20) - Text("Transcription begins when you finish speaking. Up to 4 minutes 55 seconds per recording.") + Text("Recording continues until you stop or cancel. Longer recordings are transcribed in parts after you stop.") .font(.system(size: 12)).foregroundStyle(FlowTheme.muted).lineSpacing(3).padding(.top, 20) } } diff --git a/Sources/ClearFlowCore/WAVChunks.swift b/Sources/ClearFlowCore/WAVChunks.swift new file mode 100644 index 0000000..7c8c382 --- /dev/null +++ b/Sources/ClearFlowCore/WAVChunks.swift @@ -0,0 +1,88 @@ +import Foundation + +/// Reads only one request-sized PCM segment at a time, even for long recordings. +public struct WAVChunks { + public enum Failure: LocalizedError { + case invalid, tooShort + public var errorDescription: String? { + switch self { + case .invalid: return "The recording is not a complete 16 kHz mono PCM16 WAV file." + case .tooShort: return "That recording was too short. Speak for at least a moment." + } + } + } + public let url: URL + public let count: Int + public let frames: Int + private let dataOffset: UInt64 + private let framesPerChunk: Int + public init(url: URL) throws { + self.url = url + let file = try FileHandle(forReadingFrom: url) + defer { try? file.close() } + let size = try file.seekToEnd() + try file.seek(toOffset: 0) + let header = try file.read(upToCount: 12) ?? Data() + guard header.count == 12, header.prefix(4) == Data("RIFF".utf8), + header.suffix(4) == Data("WAVE".utf8), UInt64(header.u32(4)) + 8 == size else { throw Failure.invalid } + var offset: UInt64 = 12 + var formatSeen = false + var audio: (UInt64, Int)? + var chunks = 0 + while offset < size { + chunks += 1 + guard chunks <= 1024, offset + 8 <= size else { throw Failure.invalid } + try file.seek(toOffset: offset) + let chunk = try file.read(upToCount: 8) ?? Data() + guard chunk.count == 8 else { throw Failure.invalid } + let length = UInt64(chunk.u32(4)) + let start = offset + 8 + guard start + length + length % 2 <= size else { throw Failure.invalid } + if chunk.prefix(4) == Data("fmt ".utf8) { + guard !formatSeen, length >= 16 else { throw Failure.invalid } + let fmt = try file.read(upToCount: 16) ?? Data() + guard fmt.count == 16, fmt.u16(0) == 1, fmt.u16(2) == 1, + fmt.u32(4) == 16000, fmt.u32(8) == 32000, + fmt.u16(12) == 2, fmt.u16(14) == 16 else { throw Failure.invalid } + formatSeen = true + } else if chunk.prefix(4) == Data("data".utf8) { + guard audio == nil, length % 2 == 0 else { throw Failure.invalid } + audio = (start, Int(length / 2)) + } + offset = start + length + length % 2 + } + guard formatSeen, let audio else { throw Failure.invalid } + guard audio.1 >= 4000 else { throw Failure.tooShort } + dataOffset = audio.0 + frames = audio.1 + let maxFrames = 240 * 16000 + count = (frames + maxFrames - 1) / maxFrames + // Balance the segments so a tiny remainder never becomes a rejected <0.25s request. + framesPerChunk = (frames + count - 1) / count + } + public func chunk(at index: Int) throws -> Data { + guard index >= 0, index < count else { throw Failure.invalid } + let start = index * framesPerChunk + let length = min(framesPerChunk, frames - start) * 2 + let file = try FileHandle(forReadingFrom: url) + defer { try? file.close() } + try file.seek(toOffset: dataOffset + UInt64(start * 2)) + let pcm = try file.read(upToCount: length) ?? Data() + guard pcm.count == length else { throw Failure.invalid } + var wav = Data("RIFF".utf8) + wav.appendLE(UInt32(length + 36)); wav.append(Data("WAVEfmt ".utf8)) + wav.appendLE(UInt32(16)); wav.appendLE(UInt16(1)); wav.appendLE(UInt16(1)) + wav.appendLE(UInt32(16000)); wav.appendLE(UInt32(32000)) + wav.appendLE(UInt16(2)); wav.appendLE(UInt16(16)) + wav.append(Data("data".utf8)); wav.appendLE(UInt32(length)); wav.append(pcm) + return wav + } +} +private extension Data { + func u16(_ offset: Int) -> UInt16 { UInt16(self[offset]) | UInt16(self[offset + 1]) << 8 } + func u32(_ offset: Int) -> UInt32 { UInt32(u16(offset)) | UInt32(u16(offset + 2)) << 16 } + mutating func appendLE(_ value: T) { + var little = value.littleEndian + Swift.withUnsafeBytes(of: &little) { append(contentsOf: $0) } + } +} diff --git a/Tests/AudioCaptureChecks.swift b/Tests/AudioCaptureChecks.swift new file mode 100644 index 0000000..c3a9df8 --- /dev/null +++ b/Tests/AudioCaptureChecks.swift @@ -0,0 +1,44 @@ +import Foundation +import AVFoundation + +final class ClockRecorder: AudioRecording { + var delegate: AVAudioRecorderDelegate? + var isMeteringEnabled = false + var currentTime: TimeInterval = 0 + var deadline = Double.infinity + var active = false + func prepareToRecord() -> Bool { true } + func record() -> Bool { currentTime = 0; active = true; return true } + func record(forDuration duration: TimeInterval) -> Bool { deadline = duration; return record() } + func updateMeters() {} + func averagePower(forChannel channel: Int) -> Float { -30 } + func advance(to time: Double) { currentTime = min(time, deadline); if time >= deadline { active = false } } + func stop() { active = false } +} +@main enum AudioCaptureChecks { + @MainActor static func main() throws { + let recorder = ClockRecorder() + var file: URL? + let capture = AudioCapture { url, _ in + file = url + try Data(repeating: 0, count: 32044).write(to: url) + return recorder + } + try capture.start() + recorder.advance(to: 3600) + guard recorder.active, capture.seconds == 3600 else { + fputs("FAIL: capture stopped before the user stopped it (simulated 60-minute clock).\n", stderr) + exit(1) + } + capture.cancel() + guard !recorder.active else { fatalError("Cancel must stop the recorder") } + guard !FileManager.default.fileExists(atPath: file!.path) else { fatalError("Cancel must delete audio") } + try capture.start() + var audio: RecordedAudio? = try capture.stop() + guard !recorder.active, FileManager.default.fileExists(atPath: audio!.url.path) else { fatalError("Explicit stop must retain audio for transcription") } + let saved = audio!.url + audio = nil + guard !FileManager.default.fileExists(atPath: saved.path) else { fatalError("Releasing a completed/cancelled request must delete temporary audio") } + print("PASS: capture remains active at 60 minutes (simulated clock); explicit stop/cancel and temporary file lifetime") + } +} diff --git a/Tests/LongTranscriptionChecks.swift b/Tests/LongTranscriptionChecks.swift new file mode 100644 index 0000000..d0ec124 --- /dev/null +++ b/Tests/LongTranscriptionChecks.swift @@ -0,0 +1,129 @@ +import Foundation +import ClearFlowCore + +func require(_ condition: @autoclosure () -> Bool, _ message: String) { + if !condition() { fatalError(message) } +} +func appendLE(_ value: T, to data: inout Data) { + var little = value.littleEndian + withUnsafeBytes(of: &little) { data.append(contentsOf: $0) } +} +func wav(frames: Int, metadata: Bool = false) -> Data { + var data = Data("RIFF".utf8) + appendLE(UInt32(frames * 2 + 36 + (metadata ? 12 : 0)), to: &data) + data.append(Data("WAVE".utf8)) + if metadata { data.append(Data("JUNK".utf8)); appendLE(UInt32(3), to: &data); data.append(contentsOf: [1, 2, 3, 0]) } + data.append(Data("fmt ".utf8)); appendLE(UInt32(16), to: &data) + appendLE(UInt16(1), to: &data); appendLE(UInt16(1), to: &data) + appendLE(UInt32(16000), to: &data); appendLE(UInt32(32000), to: &data) + appendLE(UInt16(2), to: &data); appendLE(UInt16(16), to: &data) + data.append(Data("data".utf8)); appendLE(UInt32(frames * 2), to: &data) + // Varied samples make dropped/reordered bytes visible across boundaries. + data.append(contentsOf: (0..<(frames * 2)).map { UInt8($0 % 251) }) + return data +} +final class StubService: URLProtocol { + static var handler: ((URLRequest) throws -> (Int, Data))! + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + do { + let (status, body) = try Self.handler(request) + client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: status, + httpVersion: nil, headerFields: ["Content-Type": "application/json"])!, cacheStoragePolicy: .notAllowed) + client?.urlProtocol(self, didLoad: body) + client?.urlProtocolDidFinishLoading(self) + } catch { client?.urlProtocol(self, didFailWithError: error) } + } + override func stopLoading() {} +} +func payload(_ request: URLRequest) throws -> [String: Any] { + var data = request.httpBody ?? Data() + if data.isEmpty, let stream = request.httpBodyStream { + stream.open(); defer { stream.close() } + var buffer = [UInt8](repeating: 0, count: 65536) + while stream.hasBytesAvailable { + let n = stream.read(&buffer, maxLength: buffer.count) + guard n > 0 else { break }; data.append(contentsOf: buffer.prefix(n)) + } + } + return try JSONSerialization.jsonObject(with: data) as! [String: Any] +} +@main enum LongTranscriptionChecks { + static func main() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let file = directory.appendingPathComponent("long.wav") + let original = wav(frames: 601 * 16000, metadata: true) + try original.write(to: file) + let chunks = try WAVChunks(url: file) + require(chunks.count == 3, "601 seconds must be split into three safe requests") + var pcm = Data() + for i in 0..= 8044, "A tiny final remainder must not create an invalid request") + let bad = directory.appendingPathComponent("bad.wav") + try original.dropLast().write(to: bad) + do { _ = try WAVChunks(url: bad); fatalError("Truncated WAV was accepted") } catch WAVChunks.Failure.invalid {} + try wav(frames: 3999).write(to: bad) + do { _ = try WAVChunks(url: bad); fatalError("Short WAV was accepted") } catch WAVChunks.Failure.tooShort {} + + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [StubService.self] + let session = URLSession(configuration: config) + defer { session.invalidateAndCancel() } + var calls = 0 + var ids = Set() + StubService.handler = { request in + let body = try payload(request) + let id = body["requestId"] as! String + require(ids.insert(id).inserted, "Segments need distinct IDs") + let audio = Data(base64Encoded: body["audio"] as! String)! + require(audio.count <= 240 * 32000 + 44, "Client sent an oversized request") + require(request.url?.host == "localhost", "Never switch endpoints") + calls += 1 + if calls == 2 { return (422, Data("{\"error\":{\"code\":\"NO_SPEECH\",\"message\":\"Silence\"}}".utf8)) } + return (200, try JSONSerialization.data(withJSONObject: ["text": "Part \(calls).", "requestId": id, "model": "fixture", "durationMs": 1])) + } + let id = UUID() + let result = try await TranscriptionClient.transcribe(file: file, id: id, endpoint: "http://localhost:8768", token: "fixture-token", language: "en", vocabulary: "", session: session) + require(result.text == "Part 1. Part 3." && result.requestId == id.uuidString && calls == 3, "Combine ordered speech and skip only silent segments") + + calls = 0 + StubService.handler = { request in + calls += 1 + let id = try payload(request)["requestId"] as! String + if calls == 2 { return (500, Data("{\"error\":{\"code\":\"FAILED\",\"message\":\"Failure\"}}".utf8)) } + return (200, try JSONSerialization.data(withJSONObject: ["text": "First", "requestId": id, "model": "fixture", "durationMs": 1])) + } + do { + _ = try await TranscriptionClient.transcribe(file: file, id: UUID(), endpoint: "http://localhost:8768", token: "fixture-token", language: "en", vocabulary: "", session: session) + fatalError("Failed segment must not return partial text as a completed result") + } catch let error as TranscriptionServiceError { require(error.status == 500 && calls == 2, "Stop after a failed segment") } + + calls = 0 + let task = Task { + try await TranscriptionClient.transcribe(file: file, id: UUID(), endpoint: "http://localhost:8768", token: "fixture-token", language: "en", vocabulary: "", session: session, + progress: { _, _ in withUnsafeCurrentTask { $0?.cancel() } }) + } + do { _ = try await task.value; fatalError("Cancellation must not return a transcript") } catch is CancellationError {} + require(calls == 0, "Cancellation stops requests before upload") + let between = Task { + try await TranscriptionClient.transcribe(file: file, id: UUID(), endpoint: "http://localhost:8768", token: "fixture-token", language: "en", vocabulary: "", session: session, + progress: { part, _ in if part == 2 { withUnsafeCurrentTask { $0?.cancel() } } }) + } + do { _ = try await between.value; fatalError("Cancellation between segments must not deliver partial text") } catch is CancellationError {} + require(calls == 1, "No second upload after cancellation") + print("PASS: 601-second WAV segmentation, exact sample coverage, short remainder, invalid files, ordered aggregation, silent segment, failure and cancellation") + } +} diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 2835171..16e8ae4 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -11,7 +11,7 @@ cp assets/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns" python3 - "$APP" "http://127.0.0.1:8768" <<'PY' import pathlib,plistlib,sys app=pathlib.Path(sys.argv[1]) -info={"CFBundleName":"ClearFlow","CFBundleDisplayName":"ClearFlow","CFBundleIdentifier":"org.clearflow.app","CFBundleExecutable":"ClearFlow","CFBundlePackageType":"APPL","CFBundleShortVersionString":"0.4.5","CFBundleVersion":"13","LSMinimumSystemVersion":"14.0","LSUIElement":False,"CFBundleIconFile":"AppIcon","NSHighResolutionCapable":True,"NSMicrophoneUsageDescription":"ClearFlow records your voice only when you start dictation, then sends it to the transcription service you configure.","ClearFlowEndpoint":sys.argv[2]} +info={"CFBundleName":"ClearFlow","CFBundleDisplayName":"ClearFlow","CFBundleIdentifier":"org.clearflow.app","CFBundleExecutable":"ClearFlow","CFBundlePackageType":"APPL","CFBundleShortVersionString":"0.4.6","CFBundleVersion":"14","LSMinimumSystemVersion":"14.0","LSUIElement":False,"CFBundleIconFile":"AppIcon","NSHighResolutionCapable":True,"NSMicrophoneUsageDescription":"ClearFlow records your voice only when you start dictation, then sends it to the transcription service you configure.","ClearFlowEndpoint":sys.argv[2]} (app/"Contents/Info.plist").write_bytes(plistlib.dumps(info)) PY # Remove linker debug records containing the build machine absolute source paths. diff --git a/scripts/test-audio.sh b/scripts/test-audio.sh new file mode 100755 index 0000000..cc05427 --- /dev/null +++ b/scripts/test-audio.sh @@ -0,0 +1,13 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")/.." +swift build --product ClearFlow +BUILD_DIR="$(swift build --show-bin-path)" +swiftc -parse-as-library -I "$BUILD_DIR/Modules" "$BUILD_DIR"/ClearFlowCore.build/*.o \ + Sources/ClearFlow/SettingsStore.swift Sources/ClearFlow/AudioCapture.swift Tests/AudioCaptureChecks.swift \ + -o "$BUILD_DIR/AudioCaptureChecks" +"$BUILD_DIR/AudioCaptureChecks" +swiftc -parse-as-library -I "$BUILD_DIR/Modules" "$BUILD_DIR"/ClearFlowCore.build/*.o \ + Sources/ClearFlow/SettingsStore.swift Sources/ClearFlow/TranscriptionClient.swift Tests/LongTranscriptionChecks.swift \ + -o "$BUILD_DIR/LongTranscriptionChecks" +"$BUILD_DIR/LongTranscriptionChecks" diff --git a/scripts/test-native.sh b/scripts/test-native.sh index ca20843..aad182b 100755 --- a/scripts/test-native.sh +++ b/scripts/test-native.sh @@ -5,3 +5,5 @@ cd "$(dirname "$0")/.." # executable checks exercise the production core without requiring full Xcode. swift run ClearFlowCoreChecks swift build --product ClearFlow + +scripts/test-audio.sh