Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 81 additions & 12 deletions Sources/verbemo/Sessions/PostProcessor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) ?? [:]
Expand Down Expand Up @@ -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.", "Эта версия расшифровки недоступна."))
}
Expand Down
17 changes: 4 additions & 13 deletions Sources/verbemo/Sessions/SessionCommands.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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("")
Expand Down
4 changes: 2 additions & 2 deletions Sources/verbemo/Sessions/SpeakerNamer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)"))
}
}

Expand Down
72 changes: 70 additions & 2 deletions Sources/verbemo/Summary/LLMBackend.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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):
Expand All @@ -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.
///
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions Sources/verbemo/Summary/Summarizer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)"))
}
}

Expand Down
28 changes: 13 additions & 15 deletions Sources/verbemo/UI/MeetingLibraryController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)
}
}

Expand Down
Loading
Loading