From 69c7a427bb6dd5c1dc17d8ebe94dfc4aabe72768 Mon Sep 17 00:00:00 2001 From: Boris Gorbylev Date: Thu, 3 Dec 2026 01:08:16 +0300 Subject: [PATCH 1/2] fix(macos): run on_stop after diarization and summary --- Sources/verbemo/Sessions/PostProcessor.swift | 52 +++++++---- .../verbemo/Sessions/SessionCommands.swift | 5 +- .../Transcription/DiarizationState.swift | 9 ++ Sources/verbemo/Transcription/StopHook.swift | 38 ++++---- .../TranscriptionCoordinator.swift | 84 ++++++++--------- .../DiarizationLifecycleTests.swift | 93 ++++++++++++++++++- docs/configuration.md | 13 ++- 7 files changed, 206 insertions(+), 88 deletions(-) diff --git a/Sources/verbemo/Sessions/PostProcessor.swift b/Sources/verbemo/Sessions/PostProcessor.swift index dfa719f9..52534416 100644 --- a/Sources/verbemo/Sessions/PostProcessor.swift +++ b/Sources/verbemo/Sessions/PostProcessor.swift @@ -170,11 +170,12 @@ enum PostProcessor { /// say which steps it is exercising instead of inheriting whatever the /// machine owner has turned on this week. @discardableResult - static func finish(_ dir: URL, policy: Policy = .configured, retryFailed: Bool = false) async -> Work { + static func finish(_ dir: URL, policy: Policy = .configured, retryFailed: Bool = false, + stopHook: StopHook.Command? = nil) async -> Work { do { let root = try validatedSessionRoot(for: dir) return try await ProcessingOperations.shared.run(session: root, kind: .postProcessing) { - try await finishWork(dir, policy: policy, retryFailed: retryFailed) + try await finishWork(dir, policy: policy, retryFailed: retryFailed, stopHook: stopHook) } } catch is CancellationError { return Work() @@ -224,11 +225,12 @@ enum PostProcessor { } /// The button and command share the explicit retry and its outcome; the sweep uses finish. - static func finishManually(_ dir: URL, policy: Policy = .configured) async -> Completion { + static func finishManually(_ dir: URL, policy: Policy = .configured, + stopHook: StopHook.Command? = nil) async -> Completion { do { let root = try validatedSessionRoot(for: dir) return try await ProcessingOperations.shared.run(session: root, kind: .postProcessing) { - let result = try await finishManuallyWork(dir, policy: policy) + let result = try await finishManuallyWork(dir, policy: policy, stopHook: stopHook) if !result.succeeded { ProcessingOperations.shared.reportFailure(result.described) } return result } @@ -244,8 +246,9 @@ enum PostProcessor { } } - private static func finishManuallyWork(_ dir: URL, policy: Policy) async throws -> Completion { - let work = try await finishWork(dir, policy: policy, retryFailed: true) + private static func finishManuallyWork(_ dir: URL, policy: Policy, + stopHook: StopHook.Command?) async throws -> Completion { + let work = try await finishWork(dir, policy: policy, retryFailed: true, stopHook: stopHook) if let refusal = manualSummaryRefusal(dir) { return refusal } guard !work.isEmpty else { return .nothingToDo } let meta = SessionState.read(dir) ?? [:] @@ -270,7 +273,8 @@ enum PostProcessor { return .deferred } - private static func finishWork(_ dir: URL, policy: Policy, retryFailed: Bool) async throws -> Work { + private static func finishWork(_ dir: URL, policy: Policy, retryFailed: Bool, + stopHook: StopHook.Command?) async throws -> Work { ProcessingOperations.shared.stage(.postProcessing, artifactDirectory: dir) try Task.checkCancellation() if let reason = Config.unreadableReason { throw Refusal.configUnreadable(reason) } @@ -280,10 +284,29 @@ enum PostProcessor { if let reason = Config.unreadableReason { throw Refusal.configUnreadable(reason) } guard !TranscriptVersions.isRequested(root), !TranscriptVersions.isRequested(dir), !FileManager.default.fileExists(atPath: root.appendingPathComponent(".recording.json").path), - DiarizationState.persisted(in: dir).isFinal else { + !FileManager.default.fileExists(atPath: dir.appendingPathComponent(TranscriptVersions.journalDirectory).path) + else { + throw SummaryRegenerationError.unavailable("A finished transcript is required before post-processing.") + } + let diarization = DiarizationState.persisted(in: dir) + guard diarization.isFinal else { + // A disabled, deferred or failed speaker pass cannot advance to naming + // and summary today. It can still deliver its current transcript. + if let stopHook, case .valid(let state) = diarization, !state.blocksStopHook { + await StopHook.fireWhileClaimedIfOwed(dir, command: stopHook) + } throw SummaryRegenerationError.unavailable("A finished transcript is required before post-processing.") } + let work = try await finishClaimed(dir, policy: policy, retryFailed: retryFailed) + if let stopHook { + await StopHook.fireWhileClaimedIfOwed(dir, command: stopHook) + try Task.checkCancellation() + } + return work + } + + private static func finishClaimed(_ dir: URL, policy: Policy, retryFailed: Bool) async throws -> Work { let work = outstanding(dir, policy: policy, retryFailed: retryFailed) guard !work.isEmpty else { return work } @@ -358,14 +381,11 @@ enum PostProcessor { var finished = 0 for dir in SessionInventory.sessionFolders(in: root) { guard !Task.isCancelled else { break } - let work = try? await ProcessingOperations.shared.run(session: dir, kind: .postProcessing) { - let work = await finish(dir) - try Task.checkCancellation() - await StopHook.fireIfOwed(dir) - try Task.checkCancellation() - return work - } - if let work, !work.isEmpty { finished += 1 } + // Leave a first automatic speaker attempt to the transcription queue. + // Recheck under the claim in finishWork before the hook can run. + if DiarizationState.read(dir)?.blocksStopHook == true { continue } + let work = await finish(dir, stopHook: { Config.onStop() }) + if !work.isEmpty { finished += 1 } } return finished } diff --git a/Sources/verbemo/Sessions/SessionCommands.swift b/Sources/verbemo/Sessions/SessionCommands.swift index 9926bf46..91533626 100644 --- a/Sources/verbemo/Sessions/SessionCommands.swift +++ b/Sources/verbemo/Sessions/SessionCommands.swift @@ -222,8 +222,9 @@ struct ProcessSession: ParsableCommand { } case .finish: - let result = try runBlocking { await PostProcessor.finishManually(dir) } - _ = try runBlocking { await StopHook.fireIfOwed(dir) } + let result = try runBlocking { + await PostProcessor.finishManually(dir, stopHook: { Config.onStop() }) + } print("\n" + result.description) if !result.succeeded { throw ExitCode(1) } diff --git a/Sources/verbemo/Transcription/DiarizationState.swift b/Sources/verbemo/Transcription/DiarizationState.swift index 3488c41e..e0af246b 100644 --- a/Sources/verbemo/Transcription/DiarizationState.swift +++ b/Sources/verbemo/Transcription/DiarizationState.swift @@ -70,6 +70,15 @@ struct DiarizationState: Codable, Equatable { var confirmedSpeakers = 0 var hasUnknown = false + var isPendingFirstAttempt: Bool { status == .pending && attempts == 0 } + + var blocksStopHook: Bool { + // The claim covers live attempts. The saved state also protects the gap + // before the first attempt and its recovery after an interruption. + let firstAttemptUnfinished = isPendingFirstAttempt || (status == .running && attempts == 1) + return firstAttemptUnfinished && (request.explicit || Config.localDiarizationEnabled()) + } + var hasFailedAttempt: Bool { status == .failed || (status == .pending && attempts > 0 && reason?.isEmpty == false) } diff --git a/Sources/verbemo/Transcription/StopHook.swift b/Sources/verbemo/Transcription/StopHook.swift index 00ab4c88..f235d238 100644 --- a/Sources/verbemo/Transcription/StopHook.swift +++ b/Sources/verbemo/Transcription/StopHook.swift @@ -5,15 +5,11 @@ import Foundation /// /// The contract, which is the whole of this type: /// -/// - It fires **once per transcript**, when the session's post-processing has -/// had its pass: names and summary written, or turned off, or given up on, -/// or deferred for want of a model. A summary that arrives on a later sweep -/// does not fire it a second time — a Mac with no model to reach would -/// otherwise never run the hook at all. -/// - It never fires while any verbemo — this one or another — is still naming -/// or summarizing the session. Whichever finishes that work fires it: the -/// transcription queue, the sweep at launch and on the network's return, -/// `verbemo process`. +/// - It fires **once per transcript**, after immediate diarization and the +/// current naming and summary pass. Disabled, failed or deferred work can +/// leave partial results. A later retry does not fire the hook again. +/// - The transcription queue, a sweep, or `verbemo process` holds the session +/// claim through the end of post-processing and the hook itself. /// - With transcription off it fires once the recording has been archived. /// - A session retired without a transcript does not fire it. /// - Transcribing a session again owes the hook again. @@ -30,6 +26,8 @@ import Foundation /// what keeps the first sweep after an update from running the hook over /// every recording on the disk. enum StopHook { + typealias Command = @Sendable () -> String? + static let key = "on_stop_hook" static let owed = "owed" static let fired = "fired" @@ -50,23 +48,27 @@ enum StopHook { @discardableResult static func fireIfOwed(_ dir: URL, command: @autoclosure @Sendable () -> String? = Config.onStop()) async -> Bool { guard !Task.isCancelled, SessionState.value(dir, key) as? String == owed else { return false } - if let reason = Config.unreadableReason { - appendSessionLog( - "on_stop hook waits — config.json can't be read (\(reason))", to: dir) - return false - } - // Taken, not just looked at: two processes finishing the same folder - // at the same moment must not both decide the hook is theirs. A - // session somebody else holds is theirs to fire when they let go. do { try SessionClaim.acquire(dir, stage: .finish) } catch { return false } defer { SessionClaim.release(dir) } + return await fireWhileClaimedIfOwed(dir, command: command) + } + + /// The caller holds the session claim from post-processing through hook exit. + @discardableResult + static func fireWhileClaimedIfOwed(_ dir: URL, command: Command) async -> Bool { guard !Task.isCancelled, SessionState.value(dir, key) as? String == owed else { return false } + let configuredCommand = command() + if let reason = Config.unreadableReason { + appendSessionLog( + "on_stop hook waits — config.json can't be read (\(reason))", to: dir) + return false + } SessionState.update(dir, with: [key: fired]) - guard let command = command() else { return false } + guard let command = configuredCommand else { return false } await run(command, in: dir) return true } diff --git a/Sources/verbemo/Transcription/TranscriptionCoordinator.swift b/Sources/verbemo/Transcription/TranscriptionCoordinator.swift index 504014a9..ebed7b4c 100644 --- a/Sources/verbemo/Transcription/TranscriptionCoordinator.swift +++ b/Sources/verbemo/Transcription/TranscriptionCoordinator.swift @@ -505,21 +505,14 @@ actor TranscriptionCoordinator { !TranscriptVersions.isRequested(dir), let state = DiarizationState.read(dir), state.isOutstanding { guard Config.localDiarizationEnabled() || state.request.explicit else { - throw AlreadyTranscribed() - } - do { - if try await runDiarization(dir, explicit: state.request.explicit) { - await PostProcessor.finish(dir) - try Task.checkCancellation() - notifyUser( - title: localised("verbemo — speakers updated", "verbemo — говорящие обновлены"), - body: dir.lastPathComponent, opening: dir) - } - } catch is CancellationError { throw CancellationError() } - catch { - operations.reportFailure(String(describing: error)) - log(dir, "diarization remains unfinished: \(error)") + await PostProcessor.finish(dir, stopHook: onStop) + try Task.checkCancellation() + return } + let updated = try await attemptDiarization(dir, state: state) + await PostProcessor.finish(dir, stopHook: onStop) + try Task.checkCancellation() + if updated { notifySpeakersUpdated(dir) } return } var fallbackUsed = false @@ -567,40 +560,46 @@ actor TranscriptionCoordinator { engine: engine.name, provenance: engine.model)), .fallbackUsed: .flag(fallbackUsed), ]) - if DiarizationState.read(dir)?.isFinal == false { + var updatedSpeakers = false + let state = DiarizationState.read(dir) + if let state, !state.isFinal { notifyUser( title: localised("verbemo — transcript ready; speakers pending", "verbemo — расшифровка готова; говорящие определяются"), body: dir.lastPathComponent, opening: dir) - await StopHook.fireIfOwed(dir, command: onStop()) - try Task.checkCancellation() - if let state = DiarizationState.read(dir), - state.status == .pending && state.attempts == 0 { - do { - if try await runDiarization(dir, explicit: state.request.explicit) { - await PostProcessor.finish(dir) - try Task.checkCancellation() - notifyUser( - title: localised("verbemo — speakers updated", "verbemo — говорящие обновлены"), - body: dir.lastPathComponent, opening: dir) - } - } catch is CancellationError { throw CancellationError() } - catch { - operations.reportFailure(String(describing: error)) - log(dir, "diarization remains unfinished: \(error)") - } + if state.isPendingFirstAttempt { + updatedSpeakers = try await attemptDiarization(dir, state: state) } - } else { - await PostProcessor.finish(dir) - try Task.checkCancellation() + } + + await PostProcessor.finish(dir, stopHook: onStop) + try Task.checkCancellation() + if updatedSpeakers { + notifySpeakersUpdated(dir) + } else if state?.isFinal != false { notifyUser( title: localised("verbemo — transcript ready", "verbemo — расшифровка готова"), body: dir.lastPathComponent, opening: dir) - await StopHook.fireIfOwed(dir, command: onStop()) - try Task.checkCancellation() } } + private func attemptDiarization(_ dir: URL, state: DiarizationState) async throws -> Bool { + do { + return try await runDiarization(dir, explicit: state.request.explicit) + } catch is CancellationError { + throw CancellationError() + } catch { + operations.reportFailure(String(describing: error)) + log(dir, "diarization remains unfinished: \(error)") + return false + } + } + + private func notifySpeakersUpdated(_ dir: URL) { + notifyUser(title: localised("verbemo — speakers updated", "verbemo — говорящие обновлены"), + body: dir.lastPathComponent, opening: dir) + } + private func releaseEngine() async { await engines.release() } @@ -664,7 +663,7 @@ actor TranscriptionCoordinator { do { let updated = try await runDiarization(dir, explicit: true, expectedRequest: request) if updated { - await PostProcessor.finish(dir) + await PostProcessor.finish(dir, stopHook: onStop) try Task.checkCancellation() } await releaseEngine() @@ -739,10 +738,9 @@ actor TranscriptionCoordinator { } let updated = try await runDiarization(dir, explicit: true) if updated { - await PostProcessor.finish(dir) + await PostProcessor.finish(dir, stopHook: onStop) try Task.checkCancellation() - notifyUser(title: localised("verbemo — speakers updated", "verbemo — говорящие обновлены"), - body: dir.lastPathComponent, opening: dir) + notifySpeakersUpdated(dir) } } @@ -876,9 +874,7 @@ actor TranscriptionCoordinator { SessionClaim.release(dir) throw error } - await PostProcessor.finish(dir) - try Task.checkCancellation() - await StopHook.fireIfOwed(dir, command: onStop()) + await PostProcessor.finish(dir, stopHook: onStop) try Task.checkCancellation() } diff --git a/Tests/verbemoTests/Transcription/DiarizationLifecycleTests.swift b/Tests/verbemoTests/Transcription/DiarizationLifecycleTests.swift index 3f2c1e55..dc1928cc 100644 --- a/Tests/verbemoTests/Transcription/DiarizationLifecycleTests.swift +++ b/Tests/verbemoTests/Transcription/DiarizationLifecycleTests.swift @@ -81,6 +81,91 @@ struct DiarizationLifecycleTests { }) } + @Test("The hook sees the finished speaker and summary files, including after recovery", + arguments: [nil, .pending, .running] as [DiarizationState.Status?]) + func hookSeesFinishedFiles(savedStatus: DiarizationState.Status?) async throws { + let recordings = try TestRecordings() + defer { recordings.remove() } + let dir = try recordings.session("hook-artifacts") + let script = recordings.root.appendingPathComponent("snapshot.sh") + try Data(""" + #!/bin/sh + printf 'called\\n' >> hook.log + for file in transcript.json speakers.json summary.md; do + if [ -f "$file" ]; then cp "$file" "hook-$file"; fi + done + """.utf8).write(to: script) + let command = "/bin/sh '\(script.path)'" + let model = FakeModel.working("codex-cli") + let home = Home.withModels([model]) + defer { try? FileManager.default.removeItem(at: home.url) } + try home.writeConfig([ + "offline_echo_cancellation": false, + "transcription": ["local_diarization": true], + "speaker_names": ["enabled": true], + "summary": ["enabled": true, "backend": "codex-cli"], + "on_stop": command, + ]) + let engine = Self.wordEngine() + let runtime = FaultRuntime(failures: 0) + let coordinator = TranscriptionCoordinator( + engine: engine, diarizerFactory: { _ in runtime }, modelFingerprint: { _ in "test-model" }) + + try await Home.$scoped.withValue(home) { + if let savedStatus { + // A restart finds a provisional transcript before or during its first speaker pass. + try Transcript(engine: engine.name, model: engine.model, + created_at: "2026-09-28T09:00:00Z", segments: [ + .init(speaker: "them", start_ms: 0, end_ms: 1000, text: "remote") + ]).write(to: dir) + var state = DiarizationState(request: .init(engine: engine.name, threshold: 0.5), + status: savedStatus) + if savedStatus == .running { state.beginInference(fingerprint: "interrupted") } + try state.write(to: dir) + StopHook.owe(dir) + await PostProcessor.sweep(root: recordings.root) + #expect(SessionState.value(dir, StopHook.key) as? String == StopHook.owed) + #expect(!FileManager.default.fileExists(atPath: dir.appendingPathComponent("hook.log").path)) + } + + try await coordinator.transcribeNow(dir) + #expect(DiarizationState.read(dir)?.status == .completed) + for file in ["transcript.json", "speakers.json", "summary.md"] { + let current = try Data(contentsOf: dir.appendingPathComponent(file)) + let snapshot = try? Data(contentsOf: dir.appendingPathComponent("hook-" + file)) + #expect(snapshot == current, "Hook did not receive the finished \(file)") + } + await PostProcessor.sweep(root: recordings.root) + #expect(try String(contentsOf: dir.appendingPathComponent("hook.log"), encoding: .utf8) == "called\n") + } + } + + @Test("Turning off diarization releases the hook for a saved provisional transcript") + func disablingDiarizationReleasesHook() async throws { + let recordings = try TestRecordings() + defer { recordings.remove() } + let dir = try recordings.session("disabled") + let engine = Self.wordEngine() + try Transcript(engine: engine.name, model: engine.model, + created_at: "2026-09-28T09:00:00Z", segments: [ + .init(speaker: "them", start_ms: 0, end_ms: 1000, text: "remote") + ]).write(to: dir) + try DiarizationState(request: .init(engine: engine.name, threshold: 0.5), + status: .pending).write(to: dir) + StopHook.owe(dir) + try Home.current.writeConfig(["transcription": ["local_diarization": false]]) + let runtime = FaultRuntime(failures: 0) + let coordinator = TranscriptionCoordinator( + engine: engine, onStop: { "exec /bin/sh -c ': > hook.log' hook" }, + diarizerFactory: { _ in runtime }, modelFingerprint: { _ in "test-model" }) + + try await coordinator.transcribeNow(dir) + + #expect(await runtime.count() == 0) + #expect(DiarizationState.read(dir)?.status == .pending) + #expect(FileManager.default.fileExists(atPath: dir.appendingPathComponent("hook.log").path)) + } + @Test("An inference fault preserves provisional text and audio; retry reuses ASR") func inferenceFaultThenRetry() async throws { let recordings = try TestRecordings() @@ -156,11 +241,17 @@ struct DiarizationLifecycleTests { defer { recordings.remove() } let dir = try recordings.session("missing-runtime") let coordinator = TranscriptionCoordinator( - engine: Self.wordEngine(), diarizerFactory: { _ in UnavailableRuntime() }, + engine: Self.wordEngine(), + onStop: { "exec /bin/sh -c 'cp meta.json hook-meta.json' hook" }, + diarizerFactory: { _ in UnavailableRuntime() }, modelFingerprint: { _ in "test-model" }) try await coordinator.transcribeNow(dir) + let snapshot = try Data(contentsOf: dir.appendingPathComponent("hook-meta.json")) + let meta = try #require(JSONSerialization.jsonObject(with: snapshot) as? [String: Any]) + let hookDiarization = try #require(meta[DiarizationState.key] as? [String: Any]) + #expect(hookDiarization["status"] as? String == "deferred") #expect(DiarizationState.read(dir)?.status == .deferred) #expect(DiarizationState.read(dir)?.attempts == 0) #expect(PostProcessor.readTranscript(dir)?.segments.contains { $0.speaker == "them" } == true) diff --git a/docs/configuration.md b/docs/configuration.md index 365d5924..09f7035d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -95,13 +95,12 @@ only values that differ from the defaults. A compact example: and unreadable configuration revoke access and active transfers. The `verbemo mcp [--output-dir ]` stdio bridge reads these settings; it does not start the app. See [MCP connections](mcp.md). -- `on_stop` gets the session folder as its only argument and runs once per - transcript, after naming and summarizing have had their pass — done, - turned off, failed, or deferred for want of a model (a summary that arrives - later does not run it again). It never runs while an verbemo is still - finishing the session, and a crash in between is made good by the next - launch. With transcription off it runs once the recording is archived; a - recording that could not be transcribed does not run it. +- On macOS, `on_stop` gets the session folder as its only argument and runs + once per transcript. It waits for diarization that starts immediately and for + the current naming and summary pass. If processing is disabled, fails, or is + deferred, the hook receives the files available at that point. Later retries + do not call it again. With transcription off it runs once the recording is + archived. A recording that could not be transcribed does not run it. - `transcription.*` covers `enabled`, `engine`, `cloud`, `local_engine`, `model`, and `language`. `local_engine` is `parakeet` by default, `whisper`, or `gigaam`; Whisper downloads about 550 MB once. GigaAM v3 downloads about 260 MB and runs From 4a232ebbeb2bc9b8c84a759ae1a7ffa074661279 Mon Sep 17 00:00:00 2001 From: Boris Gorbylev Date: Thu, 3 Dec 2026 01:11:36 +0300 Subject: [PATCH 2/2] fix(macos): release on_stop when the first speaker pass cannot finish --- .../Transcription/DiarizationState.swift | 12 +++-- .../TranscriptionCoordinator.swift | 23 +++++++- .../DiarizationLifecycleTests.swift | 53 +++++++++++++++++++ 3 files changed, 83 insertions(+), 5 deletions(-) diff --git a/Sources/verbemo/Transcription/DiarizationState.swift b/Sources/verbemo/Transcription/DiarizationState.swift index e0af246b..0ce744cc 100644 --- a/Sources/verbemo/Transcription/DiarizationState.swift +++ b/Sources/verbemo/Transcription/DiarizationState.swift @@ -72,11 +72,15 @@ struct DiarizationState: Codable, Equatable { var isPendingFirstAttempt: Bool { status == .pending && attempts == 0 } + var isFirstAttemptUnfinished: Bool { + isPendingFirstAttempt || (status == .running && attempts == 1) + } + var blocksStopHook: Bool { - // The claim covers live attempts. The saved state also protects the gap - // before the first attempt and its recovery after an interruption. - let firstAttemptUnfinished = isPendingFirstAttempt || (status == .running && attempts == 1) - return firstAttemptUnfinished && (request.explicit || Config.localDiarizationEnabled()) + // The claim covers live attempts. The saved state protects a first + // attempt that the automatic queue can start or resume. + isFirstAttemptUnfinished && Config.transcriptionEnabled() + && (request.explicit || Config.localDiarizationEnabled()) } var hasFailedAttempt: Bool { diff --git a/Sources/verbemo/Transcription/TranscriptionCoordinator.swift b/Sources/verbemo/Transcription/TranscriptionCoordinator.swift index ebed7b4c..aec36f8a 100644 --- a/Sources/verbemo/Transcription/TranscriptionCoordinator.swift +++ b/Sources/verbemo/Transcription/TranscriptionCoordinator.swift @@ -889,7 +889,7 @@ actor TranscriptionCoordinator { throw DiarizationUnavailable(reason: "a replacement transcript is already queued") } TranscriptionScratch.remove(in: dir) - guard var state = DiarizationState.read(dir), + guard let state = DiarizationState.read(dir), let provisional = PostProcessor.readTranscript(dir) else { return false } if let expectedRequest, state.request != expectedRequest { throw DiarizationUnavailable(reason: "the waiting speaker request changed") @@ -898,6 +898,27 @@ actor TranscriptionCoordinator { return false } if !explicit && !Config.localDiarizationEnabled() { return false } + do { + return try await completeDiarization(dir, explicit: explicit, state: state, provisional: provisional) + } catch is CancellationError { + throw CancellationError() + } catch { + try Task.checkCancellation() + // Validation or staging can fail before the inference path records an + // outcome. Persist it while still holding the claim so a failed first + // pass cannot leave the hook waiting for work that has already ended. + if var current = DiarizationState.read(dir), current.isFirstAttemptUnfinished { + current.status = .partial + current.reason = "speaker pass failed: \(error)" + try current.write(to: dir) + } + throw error + } + } + + private func completeDiarization(_ dir: URL, explicit: Bool, state initialState: DiarizationState, + provisional: Transcript) async throws -> Bool { + var state = initialState let currentMeta = try SessionMeta.read(from: dir) let range = try TranscriptVersions.appliedRange(in: dir) guard let track = currentMeta.tracks.first(where: { diff --git a/Tests/verbemoTests/Transcription/DiarizationLifecycleTests.swift b/Tests/verbemoTests/Transcription/DiarizationLifecycleTests.swift index dc1928cc..f9cdf434 100644 --- a/Tests/verbemoTests/Transcription/DiarizationLifecycleTests.swift +++ b/Tests/verbemoTests/Transcription/DiarizationLifecycleTests.swift @@ -166,6 +166,59 @@ struct DiarizationLifecycleTests { #expect(FileManager.default.fileExists(atPath: dir.appendingPathComponent("hook.log").path)) } + @Test("The sweep releases the hook when automatic transcription is disabled") + func disablingTranscriptionReleasesHook() async throws { + let recordings = try TestRecordings() + defer { recordings.remove() } + let dir = try recordings.session("transcription-disabled") + try Transcript(engine: "parakeet", model: "fixture", + created_at: "2026-09-28T09:00:00Z", segments: [ + .init(speaker: "them", start_ms: 0, end_ms: 1000, text: "remote") + ]).write(to: dir) + try DiarizationState(request: .init(engine: "parakeet", threshold: 0.5, explicit: true), + status: .pending).write(to: dir) + StopHook.owe(dir) + try Home.current.writeConfig([ + "transcription": ["enabled": false, "local_diarization": true], + "on_stop": "exec /bin/sh -c ': > hook.log' hook", + ]) + + await PostProcessor.sweep(root: recordings.root) + + #expect(DiarizationState.read(dir)?.status == .pending) + #expect(FileManager.default.fileExists(atPath: dir.appendingPathComponent("hook.log").path)) + } + + @Test("A failed source validation releases the hook for an interrupted first speaker pass") + func invalidSavedSourceReleasesHook() async throws { + let recordings = try TestRecordings() + defer { recordings.remove() } + let dir = try recordings.session("invalid-saved-source") + let engine = Self.wordEngine() + let runtime = FaultRuntime(failures: 1) + let coordinator = TranscriptionCoordinator( + engine: engine, onStop: { "exec /bin/sh -c ': > hook.log' hook" }, + diarizerFactory: { _ in runtime }, modelFingerprint: { _ in "test-model" }) + + // Use the ordinary ASR path to generate provisional text and its cache, + // then recreate the on-disk state from before inference started. + try await coordinator.transcribeNow(dir) + let state = try #require(DiarizationState.read(dir)) + let hookLog = dir.appendingPathComponent("hook.log") + try FileManager.default.removeItem(at: hookLog) + try DiarizationState(request: state.request, status: .pending).write(to: dir) + StopHook.owe(dir) + try TestAudio.writeTone(to: dir.appendingPathComponent("mic.caf"), seconds: 1, frequency: 330) + let provisional = try Data(contentsOf: dir.appendingPathComponent("transcript.json")) + + try await coordinator.transcribeNow(dir) + + #expect(await runtime.count() == 1) + #expect(DiarizationState.read(dir)?.status == .partial) + #expect(FileManager.default.fileExists(atPath: hookLog.path)) + #expect(try Data(contentsOf: dir.appendingPathComponent("transcript.json")) == provisional) + } + @Test("An inference fault preserves provisional text and audio; retry reuses ASR") func inferenceFaultThenRetry() async throws { let recordings = try TestRecordings()