diff --git a/Sources/verbemo/Sessions/PostProcessor.swift b/Sources/verbemo/Sessions/PostProcessor.swift index 48e148f8..3c0e3372 100644 --- a/Sources/verbemo/Sessions/PostProcessor.swift +++ b/Sources/verbemo/Sessions/PostProcessor.swift @@ -152,27 +152,93 @@ enum PostProcessor { /// machine owner has turned on this week. @discardableResult static func finish(_ dir: URL, policy: Policy = .configured, retryFailed: Bool = false) async -> Work { - // Both steps hand the transcript to a model chosen by the config, so - // they wait while it cannot be read — see `Config.Unreadable`. - if let reason = Config.unreadableReason { - appendSessionLog( - "post-processing waits — config.json can't be read (\(reason))", to: dir) + do { + return try await finishWork(dir, policy: policy, retryFailed: retryFailed) + } catch { + appendSessionLog("post-processing skipped — \(error)", to: dir) return Work() } + } + + enum Completion { + case completed, failed, deferred, nothingToDo + case refused(String, String) + + var succeeded: Bool { + switch self { case .completed, .nothingToDo: return true; default: return false } + } + var description: String { + switch self { + case .completed: return "Processing completed." + case .failed: return "Processing failed again. See transcribe.log in the recording folder; fix the cause and try Finish processing again." + case .deferred: return "Processing deferred. See transcribe.log in the recording folder; it can retry when the backend is available." + case .nothingToDo: return "Everything that can be done here is already done." + case .refused(let english, _): return english + } + } + var described: String { + switch self { + case .completed: return localised(description, "Обработка завершена.") + case .failed: return localised(description, "Снова не удалось завершить обработку. Причина — в transcribe.log в папке записи. После исправления нажмите «Доделать» ещё раз.") + case .deferred: return localised(description, "Обработка отложена. Подробности — в transcribe.log в папке записи. Повтор возможен, когда сервис станет доступен.") + case .nothingToDo: return localised(description, "Всё, что можно было сделать, уже сделано.") + case .refused(_, let translated): return translated + } + } + } + + /// 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 { do { - try SessionClaim.acquire(dir, stage: .finish) + let work = try await finishWork(dir, policy: policy, retryFailed: true) + guard !work.isEmpty else { return .nothingToDo } + let meta = SessionState.read(dir) ?? [:] + let missingNames = work.names && !FileManager.default.fileExists(atPath: dir.appendingPathComponent(SpeakerNames.file).path) + let missingSummary = work.summary && !hasCurrentSummary(dir, meta: meta) + guard missingNames || missingSummary else { return .completed } + if let reason = Config.unreadableReason { + let english = "Processing paused — config.json can't be read (\(reason)). Completed stages are preserved." + return .refused(english, localised(english, + "Обработка приостановлена: не читается config.json (\(reason)). Готовые результаты сохранены.")) + } + if (work.names && !Config.speakerNames().enabled) + || (work.summary && MeetingEgress.route(for: .summary) == nil) { + let english = "Processing settings changed during the attempt. Completed stages are preserved." + return .refused(english, localised(english, + "Настройки обработки изменились во время попытки. Готовые результаты сохранены.")) + } + if (missingNames && meta[SessionState.Key.speakersStatus] as? String == SessionState.failed) + || (missingSummary && meta[SessionState.Key.summaryStatus] as? String == SessionState.failed) { + return .failed + } + return .deferred } catch { appendSessionLog("post-processing skipped — \(error)", to: dir) - return Work() + if let busy = error as? SessionClaim.Busy { return .refused(busy.description, busy.described) } + if let refusal = error as? Refusal { return .refused(refusal.description, refusal.described) } + return .refused("Processing could not start. See transcribe.log in the recording folder.", + localised("Processing could not start. See transcribe.log in the recording folder.", + "Не удалось начать обработку. Подробности — в transcribe.log в папке записи.")) + } + } + + private static func finishWork(_ dir: URL, policy: Policy, retryFailed: Bool) async throws -> Work { + if let reason = Config.unreadableReason { throw Refusal.configUnreadable(reason) } + let root = try validatedSessionRoot(for: dir) + try SessionClaim.acquire(root, stage: .finish) + defer { SessionClaim.release(root) } + 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 { + throw SummaryRegenerationError.unavailable("A finished transcript is required before post-processing.") } - defer { SessionClaim.release(dir) } let work = outstanding(dir, policy: policy, retryFailed: retryFailed) guard !work.isEmpty else { return work } guard let transcript = readTranscript(dir) else { - appendSessionLog("post-processing skipped — can't read transcript.json", to: dir) - return Work() + throw SummaryRegenerationError.unavailable("Can't read transcript.json.") } let meta = SessionState.read(dir) ?? [:] @@ -447,9 +513,12 @@ enum PostProcessor { /// cannot write each other's work away. private static func validatedSessionRoot(for dir: URL) throws -> URL { let parent = dir.deletingLastPathComponent() - guard parent.lastPathComponent == "transcripts" else { return dir } let root = parent.deletingLastPathComponent() - guard dir.resolvingSymlinksInPath().deletingLastPathComponent().path == root.resolvingSymlinksInPath().appendingPathComponent("transcripts").path, + guard parent.lastPathComponent == "transcripts", + FileManager.default.fileExists(atPath: root.appendingPathComponent("meta.json").path) + else { return dir } + guard SessionState.read(root) != nil, + dir.resolvingSymlinksInPath().deletingLastPathComponent().path == root.resolvingSymlinksInPath().appendingPathComponent("transcripts").path, TranscriptVersions.read(root).contains(where: { $0.dir.standardizedFileURL.path == dir.standardizedFileURL.path && !$0.isRequest }) else { throw SummaryRegenerationError.unavailable(localised("This transcript version is unavailable.", "Эта версия расшифровки недоступна.")) } diff --git a/Sources/verbemo/Sessions/SessionCommands.swift b/Sources/verbemo/Sessions/SessionCommands.swift index 3464c4d5..11d7b709 100644 --- a/Sources/verbemo/Sessions/SessionCommands.swift +++ b/Sources/verbemo/Sessions/SessionCommands.swift @@ -222,20 +222,11 @@ struct ProcessSession: ParsableCommand { } case .finish: - let work = try runBlocking { await PostProcessor.finish(dir) } + let result = try runBlocking { await PostProcessor.finishManually(dir) } StopHook.fireIfOwed(dir) - if work.isEmpty { - // Nothing done has two meanings and only one of them is good - // news. A session the app is naming and summarizing right now - // must not be reported as finished. - if let holder = SessionClaim.holder(dir), holder.isAlive { - print("") - print(SessionClaim.Busy(session: dir.lastPathComponent, holder: holder)) - throw ExitCode(1) - } - print("\nNothing to do — everything that can be done is done.") - return - } + print("\n" + result.description) + if !result.succeeded { throw ExitCode(1) } + } print("") diff --git a/Sources/verbemo/Sessions/SpeakerNamer.swift b/Sources/verbemo/Sessions/SpeakerNamer.swift index 6bd2cbc9..359627fa 100644 --- a/Sources/verbemo/Sessions/SpeakerNamer.swift +++ b/Sources/verbemo/Sessions/SpeakerNamer.swift @@ -144,9 +144,9 @@ enum SpeakerNamer { lastBackend = backend.name lastModel = backend.model lastReason = Analytics.reason(for: error) - log(LLMError.isUsageLimit(error) + log(LLMError.signInAdvice(error, backend: backend.name) ?? (LLMError.isUsageLimit(error) ? "\(backend.name) is out of allowance — trying the next backend" - : "naming via \(backend.name) failed: \(error)") + : "naming via \(backend.name) failed: \(error)")) } } diff --git a/Sources/verbemo/Summary/LLMBackend.swift b/Sources/verbemo/Summary/LLMBackend.swift index d67179d9..14d8582c 100644 --- a/Sources/verbemo/Summary/LLMBackend.swift +++ b/Sources/verbemo/Summary/LLMBackend.swift @@ -399,12 +399,53 @@ struct LLMBackend: Sendable { guard result.status == 0 else { throw LLMError.exit( Int(result.status), - String(decoding: result.stderr.prefix(600), as: UTF8.self) - + String(decoding: result.stdout.suffix(600), as: UTF8.self)) + failureText(stderr: result.stderr, stdout: result.stdout, input: input)) } return String(decoding: result.stdout, as: UTF8.self) } + + /// Remove the echoed request before truncation or classification, in both streams. + static func failureText(stderr: Data, stdout: Data, input: String) -> String { + let lastLine = input.split(separator: "\n").last { !$0.allSatisfy(\.isWhitespace) } ?? "" + // Word boundaries survive CLI wrapping, quoting and Markdown formatting. + let words = lastLine.components(separatedBy: .alphanumerics.inverted).filter { !$0.isEmpty } + let echoPattern = words.map(NSRegularExpression.escapedPattern(for:)).joined(separator: #"[\W_]*"#) + let echo = echoPattern.isEmpty ? nil : try? NSRegularExpression(pattern: echoPattern) + func normalized(_ text: String) -> String { text.lowercased().filter { $0.isLetter || $0.isNumber } } + let request = normalized(input) + func diagnostic(_ data: Data, limit: Int) -> String { + var text = String(decoding: data, as: UTF8.self) + if let match = echo?.matches(in: text, range: NSRange(text.startIndex..., in: text)).last, + let range = Range(match.range, in: text) { + text = "[input]" + text[range.upperBound...] + } + // A truncated echo has no final line; remove its repeated fragments too. + text = text.components(separatedBy: "\n").map { line in + let unnumbered = line.replacingOccurrences( + of: #"^\s*(?:(?:>\s*)|(?:[-*]\s+)|(?:\d+[.)|:]?\s+))*"#, + with: "", options: .regularExpression) + let fragment = normalized(unnumbered) + return !fragment.isEmpty && request.contains(fragment) ? "[input]" : line + }.joined(separator: "\n") + // Redact before cutting: truncation must not leave half a credential behind. + for (pattern, replacement) in [ + (#"\bsk-[A-Za-z0-9_-]+"#, "[redacted]"), + (#"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+"#, "Bearer [redacted]"), + (#"(?i)(\b(?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|password|secret)[\"']?\s*[:=]\s*)(?:\"(?:\\.|[^\"\\])*(?:\"|$)|'(?:\\.|[^'\\])*(?:'|$)|[^\s,\"';}]+)"#, "$1[redacted]"), + (#"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+"#, "[redacted]"), + ] { + text = text.replacingOccurrences(of: pattern, with: replacement, options: .regularExpression) + } + guard text.count > limit else { return text } + let end = text.suffix(limit) + guard let newline = end.firstIndex(of: "\n") else { return "…" + end } + return "…" + end[end.index(after: newline)...] + } + return [("stderr", diagnostic(stderr, limit: 1000)), ("stdout", diagnostic(stdout, limit: 400))] + .filter { !$0.1.isEmpty }.map { "\($0.0):\n\($0.1)" }.joined(separator: "\n") + } + } enum LLMError: Error, CustomStringConvertible { @@ -427,6 +468,7 @@ enum LLMError: Error, CustomStringConvertible { /// to the next backend is the expected, healthy path here, and reads as an /// error otherwise. var isUsageLimit: Bool { + guard !isSignedOut else { return false } let haystack: String switch self { case .http(let code, let body): @@ -440,6 +482,31 @@ enum LLMError: Error, CustomStringConvertible { return Self.usageLimitMarkers.contains { haystack.contains($0) } } + /// CLI login failures require a person; background retries cannot repair them. + var isSignedOut: Bool { + guard case .exit(_, let output) = self else { return false } + return output.components(separatedBy: "\nstdout:\n").contains { stream in + stream.split(separator: "\n").suffix(4).contains { line in + let text = line.trimmingCharacters(in: .whitespaces).lowercased() + guard !text.contains("mcp") else { return false } + return text == "not logged in" || text == "error: not logged in" + || Self.signedOutMarkers.contains { text.contains($0) } + } + } + } + + private static let signedOutMarkers = [ + "please run /login", "run codex login", "oauth session expired", + "oauth token expired", "oauth token revoked", "access token could not be refreshed", + ] + + static func signInAdvice(_ error: Error, backend: String) -> String? { + guard (error as? LLMError)?.isSignedOut == true, + ["claude-cli", "codex-cli"].contains(backend) else { return nil } + let command = backend == "claude-cli" ? "claude /login" : "codex login" + return "\(backend) is signed out — sign in again with `\(command)`; trying the next backend" + } + /// Whether the same request would plausibly succeed later: no network, a /// server that fell over, a local model that isn't running yet. /// @@ -448,6 +515,7 @@ enum LLMError: Error, CustomStringConvertible { /// a malformed answer must not be retried for ever. A spent allowance /// counts as transient: it comes back. var isTransient: Bool { + guard !isSignedOut else { return false } switch self { case .http(let code, _): return code == 429 || code >= 500 diff --git a/Sources/verbemo/Summary/Summarizer.swift b/Sources/verbemo/Summary/Summarizer.swift index 53430284..6401f1f8 100644 --- a/Sources/verbemo/Summary/Summarizer.swift +++ b/Sources/verbemo/Summary/Summarizer.swift @@ -103,9 +103,9 @@ enum Summarizer { backend: backend.name, model: backend.model)), .reason: .text(lastReason.rawValue), ]) - log(LLMError.isUsageLimit(error) + log(LLMError.signInAdvice(error, backend: backend.name) ?? (LLMError.isUsageLimit(error) ? "\(backend.name) is out of allowance — trying the next backend" - : "summary via \(backend.name) failed: \(error)") + : "summary via \(backend.name) failed: \(error)")) } } diff --git a/Sources/verbemo/UI/MeetingLibraryController.swift b/Sources/verbemo/UI/MeetingLibraryController.swift index f074885a..c2db73e5 100644 --- a/Sources/verbemo/UI/MeetingLibraryController.swift +++ b/Sources/verbemo/UI/MeetingLibraryController.swift @@ -1023,13 +1023,7 @@ final class MeetingLibraryController: NSObject, NSTextFieldDelegate { @objc private func finishClicked() { guard let item = selected else { return } if let version = selectedVersion, !version.isRequest, version.dir != item.dir { - working = true - updateButtons() - Task { - await PostProcessor.finish(version.dir, retryFailed: true) - working = false - reload() - } + finishManually(version.dir, about: item) return } switch Self.decision(for: item) { @@ -1051,14 +1045,18 @@ final class MeetingLibraryController: NSObject, NSTextFieldDelegate { reload() case .finish: - working = true - updateButtons() - Task { - let work = await PostProcessor.finish(item.dir, retryFailed: true) - working = false - reload() - if work.isEmpty { say(Self.nothingDoneLine(for: item.dir), about: item) } - } + finishManually(item.dir, about: item) + } + } + + private func finishManually(_ dir: URL, about item: SessionInventory.Item) { + working = true + updateButtons() + Task { + let result = await PostProcessor.finishManually(dir) + working = false + reload() + say(result.described, about: item) } } diff --git a/Tests/verbemoTests/CLIDiagnosticTests.swift b/Tests/verbemoTests/CLIDiagnosticTests.swift new file mode 100644 index 00000000..0539f31b --- /dev/null +++ b/Tests/verbemoTests/CLIDiagnosticTests.swift @@ -0,0 +1,122 @@ +import Foundation +import Testing + +@testable import verbemo + +struct CLIDiagnosticTests { + @Test("Failed CLI output retains the reason after a banner and removes meeting echoes", arguments: [false, true]) + func echoIsNotADiagnostic(reformatted: Bool) async throws { + let input = "Take notes.\nPrivate discussion about quota and timeout.\nWe ship the secret project on Monday." + let echo = reformatted + ? "> Take notes. Private discussion about quota and\n> timeout. We ship the secret\n> project on Monday." + : input + let output = String(repeating: "banner line\n", count: 150) + echo + "\nERROR: model is unsupported\n" + let script = "printf '%s' \"$1\" >&2; printf '%s' \"$2\"; exit 7" + do { + _ = try await LLMBackend.run(executable: "/bin/sh", arguments: ["-c", script, "test", output, echo], input: input, timeout: 5) + Issue.record("Expected failure") + } catch let error as LLMError { + guard case .exit(let code, let diagnostic) = error else { Issue.record("Wrong error"); return } + #expect(code == 7) + #expect(diagnostic.contains("model is unsupported")) + #expect(diagnostic.contains("stderr:")) + #expect(diagnostic.contains("stdout:")) + #expect(!diagnostic.contains("secret")) + #expect(!diagnostic.contains("quota")) + #expect(!error.isUsageLimit) + #expect(!error.isTransient) + #expect(diagnostic.count <= 1500) + } + } + + @Test("Streams cannot join into a service error marker") + func streamsStaySeparate() async throws { + do { + _ = try await LLMBackend.run(executable: "/bin/sh", arguments: ["-c", "printf rate >&2; printf ' limit'; exit 1"], input: "", timeout: 5) + Issue.record("Expected failure") + } catch let error as LLMError { + #expect(!error.isUsageLimit) + #expect(error.description.contains("stderr:")) + #expect(error.description.contains("stdout:")) + } + } + + @Test("Credential values in CLI diagnostics are not persisted") + func credentialsAreRedacted() async throws { + do { + _ = try await LLMBackend.run(executable: "/bin/sh", arguments: ["-c", "printf '%s' 'ERROR: token=private-test-value Authorization: Bearer fake-test-bearer sk-test-1234567890'; exit 1"], input: "", timeout: 5) + Issue.record("Expected failure") + } catch let error as LLMError { + #expect(!error.description.contains("private-test-value")) + #expect(!error.description.contains("fake-test-bearer")) + #expect(!error.description.contains("sk-test-1234567890")) + } + } + @Test("A long diagnostic keeps the complete final reason within the bound") + func keepsTail() { + let output = (1...200).map { "trace line \($0)" }.joined(separator: "\n") + "\nfatal: actual reason" + let text = LLMBackend.failureText(stderr: Data(output.utf8), stdout: Data(), input: "") + #expect(text.hasSuffix("fatal: actual reason")) + #expect(!text.contains("trace line 1\n")) + #expect(text.count <= 1010) + } + + @Test("Confirmed CLI sign-in failures require login, not a background retry", arguments: [ + "Failed to authenticate: OAuth session expired and could not be refreshed", + "API Error: 401 Invalid API key · Please run /login", + "Not logged in", "Please run codex login", + "ERROR: Your access token could not be refreshed. Please log out and sign in again.", + "OAuth token expired", "OAuth token revoked", + ]) + func signedOut(message: String) { + let error = LLMError.exit(1, message) + #expect(error.isSignedOut) + #expect(!error.isTransient) + #expect(!error.isUsageLimit) + #expect(LLMError.signInAdvice(error, backend: "codex-cli")?.contains("codex login") == true) + #expect(LLMError.signInAdvice(error, backend: "ollama") == nil) + } + + @Test("Generic authentication and earlier MCP chatter do not classify CLI login") + func unrelatedAuth() { + for message in ["mcp: calendar failed to authenticate", "mcp: Not logged in", + "Not logged in to the calendar server", "ERROR: model unsupported", + "not logged in\nstep 1\nstep 2\nstep 3\nERROR: bad model"] { + #expect(!LLMError.exit(1, message).isSignedOut) + } + #expect(!LLMError.http(401, "Please run /login").isSignedOut) + let stderr = "ERROR: Your access token could not be refreshed. Please log out and sign in again." + let text = LLMBackend.failureText(stderr: Data(stderr.utf8), stdout: Data("a\nb\nc\nd\ne".utf8), input: "") + #expect(LLMError.exit(1, text).isSignedOut, "stdout must not bury stderr's verdict") + } + + @Test("Truncated and numbered echoes cannot leak meeting text or change error classification", arguments: [false, true]) + func partialEcho(numbered: Bool) { + let input = "Take notes.\nthem: The private project exceeded quota.\nme: See you on Monday." + let output = numbered + ? "1 Take notes.\n2 them: The private project exceeded quota.\n3 me: See you\n4 on Monday.\nERROR: model unsupported" + : "Take notes.\nthem: The private project exceeded quota.\nERROR: model unsupported" + let text = LLMBackend.failureText(stderr: Data(output.utf8), stdout: Data(output.utf8), input: input) + #expect(!text.contains("private project")) + #expect(!text.contains("See you")) + #expect(!LLMError.exit(1, text).isUsageLimit) + #expect(text.contains("model unsupported")) + } + + @Test("Quoted credential values are redacted completely") + func quotedSecrets() { + let output = #"ERROR: {"password": "correct horse battery staple", "access_token": "two words"} secret='private value'"# + let text = LLMBackend.failureText(stderr: Data(output.utf8), stdout: Data(), input: "") + for word in ["correct", "horse", "battery", "staple", "two", "words", "private", "value"] { + #expect(!text.contains(word)) + } + } + + @Test("An interrupted quoted credential is still redacted", arguments: ["\"", "'"]) + func interruptedSecret(quote: String) { + let output = "ERROR: token=\(quote)private-test-value" + let text = LLMBackend.failureText(stderr: Data(output.utf8), stdout: Data(), input: "") + #expect(!text.contains("private-test-value")) + } + +} diff --git a/Tests/verbemoTests/Sessions/ManualProcessingTests.swift b/Tests/verbemoTests/Sessions/ManualProcessingTests.swift new file mode 100644 index 00000000..3b53e35f --- /dev/null +++ b/Tests/verbemoTests/Sessions/ManualProcessingTests.swift @@ -0,0 +1,217 @@ +import AppKit +import ArgumentParser +import Foundation +import Testing + +@testable import verbemo + +@Suite(.serialized) +struct ManualProcessingTests { + private func withSession(_ model: FakeModel, isolation: isolated (any Actor)? = #isolation, _ body: (URL, Home) async throws -> Void) async throws { + let home = Home.withModels([model]) + let dir = try SessionFixture.make() + defer { + try? FileManager.default.removeItem(at: home.url) + try? FileManager.default.removeItem(at: dir) + } + try home.writeConfig(["summary": ["backend": "auto"], "user_name": "Test owner"]) + try await Home.$scoped.withValue(home) { try await body(dir, home) } + } + + @Test("The actual process command retries legacy and unchanged-fingerprint failures", arguments: [false, true]) + @MainActor func cliRetries(legacy: Bool) async throws { + let model = FakeModel.working("claude-cli") + try await withSession(model) { dir, _ in + SessionState.update(dir, with: [ + SessionState.Key.summaryStatus: "failed", SessionState.Key.speakersStatus: "failed", + SessionState.Key.summaryFailedFor: legacy ? nil : MeetingEgress.fingerprint(for: .summary), + SessionState.Key.speakersFailedFor: legacy ? nil : MeetingEgress.fingerprint(for: .speakerNames), + ]) + let original = try Data(contentsOf: dir.appendingPathComponent("transcript.json")) + #expect(await PostProcessor.finish(dir).isEmpty) + let command = try ProcessSession.parse([dir.path]) + try command.run() + #expect(PostProcessor.hasCurrentSummary(dir)) + #expect(SpeakerNames.read(from: dir)?.speakers["them A"]?.name == "Фёдор") + #expect(try Data(contentsOf: dir.appendingPathComponent("transcript.json")) == original) + let calls = model.callCount + try command.run() + #expect(model.callCount == calls, "successful stages must not run again") + } + } + + @Test("The selected archive respects the root claim and preserves current results") + func archivedVersionUsesRootClaim() async throws { + let model = FakeModel.working("claude-cli") + try await withSession(model) { dir, _ in + let archive = try #require(try TranscriptVersions.archiveCurrent(dir)) + let newer = Transcript(engine: "assemblyai", model: "new", created_at: "2026-10-01T10:00:00Z", segments: SessionFixture.meeting) + try newer.write(to: dir) + try Data("current summary".utf8).write(to: dir.appendingPathComponent("summary.md")) + let current = try Data(contentsOf: dir.appendingPathComponent("transcript.json")) + try SessionClaim.acquire(dir, stage: .transcribe) + #expect(await PostProcessor.finish(archive, retryFailed: true).isEmpty) + #expect(model.callCount == 0) + SessionClaim.release(dir) + #expect(!(await PostProcessor.finish(archive, retryFailed: true)).isEmpty) + #expect(PostProcessor.hasCurrentSummary(archive)) + #expect(try Data(contentsOf: dir.appendingPathComponent("transcript.json")) == current) + #expect(try String(contentsOf: dir.appendingPathComponent("summary.md"), encoding: .utf8) == "current summary") + } + } + + @Test("Signed-out CLIs log the login remedy and fall through for names and summary") + func signedOutFallsThrough() async throws { + let failed = FakeModel("claude-cli", failing: LLMError.exit(1, "API Error: 401 Invalid API key · Please run /login")) + let next = FakeModel.working("codex-cli") + let home = Home.withModels([failed, next]) + let dir = try SessionFixture.make() + defer { try? FileManager.default.removeItem(at: dir); try? FileManager.default.removeItem(at: home.url) } + try home.writeConfig(["summary": ["backend": "auto"], "user_name": "Test owner"]) + await Home.$scoped.withValue(home) { await PostProcessor.finish(dir) } + let log = try String(contentsOf: dir.appendingPathComponent("transcribe.log"), encoding: .utf8) + #expect(log.contains("sign in again")) + #expect(log.contains("claude /login")) + #expect(PostProcessor.hasCurrentSummary(dir)) + #expect(SpeakerNames.read(from: dir)?.backend == "codex-cli") + #expect(failed.callCount == 2 && next.callCount == 2) + } + + + @Test("A repeated failure settles and the background sweep does not force it", arguments: ["failed", "deferred"]) + @MainActor func retryFailureAndSweep(outcome: String) async throws { + let model = FakeModel("claude-cli", failing: outcome == "failed" ? LLMError.exit(1, "Not logged in") : URLError(.notConnectedToInternet)) + try await withSession(model) { dir, _ in + let root = dir.deletingLastPathComponent().appendingPathComponent("sweep-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let session = root.appendingPathComponent("meeting") + try FileManager.default.moveItem(at: dir, to: session) + defer { try? FileManager.default.removeItem(at: root) } + SessionState.update(session, with: [SessionState.Key.summaryStatus: "failed", SessionState.Key.speakersStatus: "failed"]) + let command = try ProcessSession.parse([session.path]) + #expect(throws: ExitCode.self) { try command.run() } + #expect(SessionState.value(session, SessionState.Key.summaryStatus) as? String == outcome) + #expect(SessionState.value(session, SessionState.Key.speakersStatus) as? String == outcome) + let calls = model.callCount + for _ in 0..<3 { await PostProcessor.sweep(root: root) } + #expect(outcome == "failed" ? model.callCount == calls : model.callCount > calls) + } + } + + @Test("Explicit retry refuses unreadable config and claim, and unfinished diarization") + func retryGuards() async throws { + let model = FakeModel.working("claude-cli") + try await withSession(model) { dir, home in + let original = try Data(contentsOf: dir.appendingPathComponent("transcript.json")) + try home.writeConfig(text: "{") + #expect(!(await PostProcessor.finishManually(dir)).succeeded) + try home.writeConfig(["summary": ["backend": "auto"]]) + try Data("{".utf8).write(to: dir.appendingPathComponent(SessionClaim.file)) + #expect(!(await PostProcessor.finishManually(dir)).succeeded) + try FileManager.default.removeItem(at: dir.appendingPathComponent(SessionClaim.file)) + try DiarizationState(request: .init(engine: "parakeet", threshold: 0.6), status: .pending).write(to: dir) + #expect(!(await PostProcessor.finishManually(dir)).succeeded) + #expect(model.callCount == 0) + #expect(try Data(contentsOf: dir.appendingPathComponent("transcript.json")) == original) + } + } + + + @Test("A recordings folder called transcripts does not redirect the session claim") + func recordingsNamedTranscripts() async throws { + let model = FakeModel.working("claude-cli") + try await withSession(model) { dir, home in + let root = home.url.appendingPathComponent("transcripts") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let session = root.appendingPathComponent("meeting") + try FileManager.default.moveItem(at: dir, to: session) + try SessionClaim.acquire(session, stage: .transcribe) + defer { SessionClaim.release(session) } + #expect(await PostProcessor.finish(session, retryFailed: true).isEmpty) + #expect(model.callCount == 0) + } + } + + @Test("A config broken during naming is reported as paused, not as the old summary failure") + func configBreaksDuringRetry() async throws { + let home = Home.sandbox() + defer { try? FileManager.default.removeItem(at: home.url) } + let model = FakeModel("claude-cli") { _, _, _ in + try home.writeConfig(text: "{") + return SessionFixture.namesThemA + } + let scoped = Home(url: home.url, environment: [:], discoversTools: false, languageModels: { _ in [model.backend] }) + let dir = try SessionFixture.make() + defer { try? FileManager.default.removeItem(at: dir) } + try home.writeConfig(["summary": ["backend": "auto"]]) + SessionState.update(dir, with: [SessionState.Key.summaryStatus: "failed"]) + await Home.$scoped.withValue(scoped) { + let result = await PostProcessor.finishManually(dir) + #expect(!result.succeeded) + #expect(result.description.contains("config.json")) + #expect(!result.description.contains("failed again")) + } + #expect(model.callCount == 1) + #expect(SpeakerNames.read(from: dir) != nil) + #expect(!PostProcessor.hasCurrentSummary(dir)) + } + + + @Test("Completed artifacts win over a config change during the last call") + func configBreaksAfterLastCall() async throws { + let home = Home.sandbox() + defer { try? FileManager.default.removeItem(at: home.url) } + let model = FakeModel("claude-cli") { _, _, _ in + try home.writeConfig(text: "{") + return "## Summary" + } + let scoped = Home(url: home.url, environment: [:], discoversTools: false, languageModels: { _ in [model.backend] }) + let dir = try SessionFixture.make() + defer { try? FileManager.default.removeItem(at: dir) } + try home.writeConfig(["summary": ["backend": "auto"], "speaker_names": ["enabled": false]]) + await Home.$scoped.withValue(scoped) { + #expect((await PostProcessor.finishManually(dir)).succeeded) + } + #expect(PostProcessor.hasCurrentSummary(dir)) + } + + @Test("Finish processing reports the actual result in the window", arguments: ["completed", "failed", "deferred"]) + @MainActor func uiReportsOutcome(outcome: String) async throws { + let model: FakeModel = outcome == "completed" ? .working("claude-cli") : FakeModel("claude-cli", failing: + outcome == "failed" ? LLMError.exit(1, "Not logged in") : URLError(.notConnectedToInternet)) + try await withSession(model) { dir, _ in + SessionState.update(dir, with: [SessionState.Key.summaryStatus: "failed", SessionState.Key.speakersStatus: "failed"]) + let root = dir.deletingLastPathComponent().appendingPathComponent("ui-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let session = root.appendingPathComponent("meeting") + try FileManager.default.moveItem(at: dir, to: session) + defer { try? FileManager.default.removeItem(at: root) } + let app = ApplicationWindow() + let library = MeetingLibraryController(root: root, hostWindow: app.panel) + app.libraryProvider = { library } + app.navigate(.allMeetings) + app.show() + defer { + if let sheet = app.panel.attachedSheet { app.panel.endSheet(sheet) } + app.panel.orderOut(nil) + withExtendedLifetime(library) {} + } + await library.settled() + let button = try #require(library.contentView.allDescendants.compactMap { $0 as? NSButton }.first { $0.action == NSSelectorFromString("finishClicked") }) + #expect(button.isEnabled) + #expect(button.sendAction(button.action, to: button.target)) + for _ in 0..<200 where library.isProcessing || app.panel.attachedSheet == nil { + try await Task.sleep(for: .milliseconds(10)) + } + let sheet = try #require(app.panel.attachedSheet) + let text = sheet.contentView?.allDescendants.compactMap { ($0 as? NSTextField)?.stringValue }.joined(separator: " ") ?? "" + #expect(text.lowercased().contains(outcome)) + if outcome == "completed" { + #expect(PostProcessor.hasCurrentSummary(session)) + #expect(SpeakerNames.read(from: session)?.speakers["them A"]?.name == "Фёдор") + } else { + #expect(text.contains("transcribe.log")) + } + } + } +} diff --git a/docs/history/summary-retry-upstream.md b/docs/history/summary-retry-upstream.md new file mode 100644 index 00000000..41c7db54 --- /dev/null +++ b/docs/history/summary-retry-upstream.md @@ -0,0 +1,18 @@ +# Summary retry and CLI diagnostics provenance + +Verbemo issue #8 adapts the relevant behavior from +[gsamat/amanu PR #20](https://github.com/gsamat/amanu/pull/20), authored by +[shooma](https://github.com/shooma), reviewed at head +`f4f61079e547619b862033f62c59fb7ba787ff4d` on 2026-10-22. + +The upstream contribution supplied tail-first CLI diagnostics, removal of prompt +echoes, recognition of concrete Claude/Codex sign-in failures, and explicit retry +of permanently failed naming and summary stages. Its commits credit Claude Opus +5.5 as co-author. Original copyright notices and the MIT license are preserved. + +Verbemo already had `retryFailed` and UI retry eligibility. This adaptation joins +CLI and UI manual completion, preserves fingerprint-based background recovery, +protects the root session when processing an archive, and reports the actual +outcome. Diagnostic filtering covers both streams, partial/numbered echoes and +credential values. It does not import upstream analytics reporting, UI layout, +or unrelated model selection changes. diff --git a/docs/testing/2026-10-22-summary-retry.md b/docs/testing/2026-10-22-summary-retry.md new file mode 100644 index 00000000..84c29e98 --- /dev/null +++ b/docs/testing/2026-10-22-summary-retry.md @@ -0,0 +1,46 @@ +# macOS summary retry and CLI diagnostics: issue #8 + +Scope: `codex/8-summary-retry`, based on `b8b09601bb7d0b87effd775af7f24219c6dc671e`. +Upstream scope and attribution are in [the provenance note](../history/summary-retry-upstream.md). + +## Automated checks + +`VERBEMO_REQUIRE_LOCALVQE=1 swift test --no-parallel` passed: **1057 tests in 149 suites**, 144.528 seconds. The final test report is present. Twenty optional interactive/gallery tests were skipped. Local log: `/tmp/verbemo-8-full-final.log`. + +Focused coverage includes: + +- Real subprocess failures with a long banner, exact/reformatted/partial/numbered meeting echoes, separate stdout/stderr, bounded diagnostic tails, quoted/unclosed credential values, and quota/timeout words that belong to the meeting rather than the service error. +- Concrete Claude/Codex sign-in errors, unrelated MCP/authentication chatter, login advice and fallback for both names and summary. +- The actual `ProcessSession` command with unchanged-fingerprint and legacy failures; success preserves the transcript and does not repeat completed stages. Permanent failures stop background retries; deferred failures remain recoverable. Existing fingerprint-change tests also pass. +- Root session claims for archived versions, unreadable claims/configuration, pending diarization, and a recordings directory literally named `transcripts`. +- Configuration becoming unreadable during an attempt: completed artifacts survive, unfinished work reports a pause, and a completed final stage still reports success. +- The actual AppKit button action and completion/failure/deferred sheets, using isolated `Home`, `SessionFixture` and fake models. + +The initial diagnostic and manual-processing tests failed against the old behavior (20 and 12 issues respectively). Review added regressions for partial echoes, quoted secrets, archive-root detection and stale outcomes; they failed before their fixes. The first full run failed only in a new test fixture that wrote the wrong persisted diarization representation. That fixture was corrected to use `DiarizationState.write`; the final full run above passed. A second review confirmed the last two edge fixes, without a second broad review. + +## Actual CLI and window checks + +A separate ad-hoc-signed app, `.build/Verbemo-SummaryRetry.app`, uses bundle ID `name.ekho.verbemo.summaryretry8`. Its Info.plist pins `CFFIXED_USER_HOME` to `.build/summary-retry-home`; it does not replace the installed app. The profile disables automatic recording, calendar integration, transcription and live transcription. Only synthetic transcripts and local fake Claude/Codex executables are used. No real meeting, key or paid model request is needed. + +The real `process` command recovered both names and summary from a legacy failed session. Its fake CLI call log contained one naming call and one summary call. Local log: `/tmp/verbemo-8-cli-runtime.log`. + +Computer Use in the real application verified: + +1. **Completed:** Finish processing recovered names and summary, displayed “Processing completed”, showed the synthetic summary and named speakers, and removed the now-unneeded Finish processing action. +2. **Failed again:** the fake CLI returned a long banner, an echoed transcript and “ERROR: Not logged in”. The window reported failure and pointed to `transcribe.log`; the log contained login advice without the echoed transcript. +3. **Deferred:** a connection failure produced the deferred message with the log location. +4. **Selected version:** selected the older transcript in the version popup and finished it. The window stayed on that version and displayed its new summary and names. SHA-256 comparisons showed the current version's transcript, summary and names were unchanged; the archive received its own result files. + +The selected-version check used the final debug executable, SHA-256 `d66db5e01d87f93cbb56f2b773545af44e1e893b2208dc1e51a63901d3914e0c`. The three outcome checks and initial CLI check ran before the final two edge fixes (unclosed quoted credentials and config changing during the final call); those edge fixes are covered by the final suite. Native GUI checks are separate from the AppKit tests. + +Screenshot and accessibility evidence for the final selected-version check are saved locally under `/Users/ekho/.codex/visualizations/2026/10/22/01a16355-da81-7aa2-b32e-78353514e23c/summary-retry-selected-version.{png,ax.txt}`. The synthetic profile remains in this managed worktree for inspection. + +## Packaged application + +`make app -o localvqe -o nemotron` completed successfully. It rebuilt the universal arm64/x86_64 Swift application and packaged the unchanged, previously built native helpers. Strict ad-hoc signing, architecture checks, macOS 14.2 compatibility and the Nemotron relative dependency closure passed. The resulting `.build/Verbemo.app` is version 0.6.1/build 542; its executable SHA-256 is `2c11f2d59a820cead2852f10871a8877fd2772aec8f601467bc71ffe6c6e0880`. Local log: `/tmp/verbemo-8-universal.log`. + +The packaged release binary was built and verified but was not used for the GUI scenarios above; those used the isolated debug bundle. The test app was quit after validation. No Developer ID credentials or notarization were used. + +## Limits + +Real Claude/Codex authentication, live provider responses, physical audio capture and Windows were not exercised. Diagnostic filtering covers the tested echo and credential formats; future CLI output formats can require new cases. No release, notarization, merge or replacement of the user's installed app was performed.