From e2ed165fb500ca1f4054b1408b7cc5e063fcae67 Mon Sep 17 00:00:00 2001 From: Boris Gorbylev Date: Thu, 22 Oct 2026 14:52:05 +0300 Subject: [PATCH 1/3] feat(summary): choose a provider for one regeneration Refs #28. Freeze per-job routes and prompts, validate access, preserve previous summaries, and require explicit retries for one-run destinations. Co-Authored-By: OpenAI Codex --- Sources/verbemo/Config.swift | 10 +- Sources/verbemo/SessionState.swift | 1 + Sources/verbemo/Sessions/PostProcessor.swift | 16 +- .../verbemo/Sessions/TranscriptVersions.swift | 1 + Sources/verbemo/Setup/Credentials.swift | 6 +- Sources/verbemo/Summary/LLMBackend.swift | 71 +++++-- Sources/verbemo/Summary/MeetingEgress.swift | 12 +- Sources/verbemo/Summary/Summarizer.swift | 16 +- Sources/verbemo/Summary/SummaryRequest.swift | 65 ++++++ Sources/verbemo/UI/MeetingActionState.swift | 1 - .../verbemo/UI/MeetingLibraryController.swift | 45 ++--- .../verbemo/UI/SummaryRegenerationSheet.swift | 117 +++++++++++ .../MeetingActionStateTests.swift | 2 +- .../SummaryCLIConfigurationTests.swift | 21 ++ .../SummaryProviderSheetTests.swift | 45 +++++ Tests/verbemoTests/SummaryRequestTests.swift | 191 ++++++++++++++++++ docs/testing/2026-10-22-summary-provider.md | 62 ++++++ 17 files changed, 610 insertions(+), 72 deletions(-) create mode 100644 Sources/verbemo/Summary/SummaryRequest.swift create mode 100644 Sources/verbemo/UI/SummaryRegenerationSheet.swift create mode 100644 Tests/verbemoTests/SummaryCLIConfigurationTests.swift create mode 100644 Tests/verbemoTests/SummaryProviderSheetTests.swift create mode 100644 Tests/verbemoTests/SummaryRequestTests.swift create mode 100644 docs/testing/2026-10-22-summary-provider.md diff --git a/Sources/verbemo/Config.swift b/Sources/verbemo/Config.swift index 4f1375a3..1bf7cc6c 100644 --- a/Sources/verbemo/Config.swift +++ b/Sources/verbemo/Config.swift @@ -480,7 +480,7 @@ enum Config { /// Post-transcript summarization. `backend: auto` walks the chain in /// LLMBackend: the local `claude` CLI, the Anthropic API, the `codex` CLI, /// the OpenAI API, then ollama — subscriptions before metered keys. - struct SummarySettings { + struct SummarySettings: Sendable { var enabled = Config.defaultFlag(.summaryEnabled) var backend = Config.defaultString(.summaryBackend) /// Summarizing is where a cheap model quietly costs you something: @@ -547,12 +547,12 @@ enum Config { /// named by `transcription.openai.api_key_path` (or, in a config written /// before that setting, `summary.openai_api_key_path` — see /// `openAIKeyFile`), verbemo's own key file, then the shared one. - static func openAIKey() -> String? { + static func openAIKey(in config: [String: Any]? = Config.raw()) -> String? { if let env = Home.current.variable("OPENAI_API_KEY"), !env.trimmed.isEmpty { return env.trimmed } - if let configured = openAIKeyFile(in: load()) { return secret(at: configured) } + if let configured = openAIKeyFile(in: config) { return secret(at: configured) } return secret(at: openAIKeyPath) ?? secret(atAnyOf: openAISharedKeyPaths) } @@ -579,12 +579,12 @@ enum Config { /// Anthropic key, in order: ANTHROPIC_API_KEY, a token file named by /// `summary.api_key_path`, verbemo's own key file, then the shared one. - static func anthropicKey() -> String? { + static func anthropicKey(in config: [String: Any]? = Config.raw()) -> String? { if let env = Home.current.variable("ANTHROPIC_API_KEY"), !env.trimmed.isEmpty { return env.trimmed } - if let configured = summary().apiKeyPath { return secret(at: configured) } + if let configured = summary(in: config).apiKeyPath { return secret(at: configured) } return secret(at: anthropicKeyPath) ?? secret(atAnyOf: anthropicSharedKeyPaths) } diff --git a/Sources/verbemo/SessionState.swift b/Sources/verbemo/SessionState.swift index 865680fd..a05df796 100644 --- a/Sources/verbemo/SessionState.swift +++ b/Sources/verbemo/SessionState.swift @@ -19,6 +19,7 @@ enum SessionState { /// network, spent allowance): retry later. `failed: ` — it /// won't work on a retry. Absent — nothing to do, either because the /// summary exists or because summarizing is off. + static let summaryManual = "summary_manual" static let summaryStatus = "summary_status" /// The same three states for putting names to the speaker labels. /// `deferred` — no model could be reached: retry later. `failed` — it diff --git a/Sources/verbemo/Sessions/PostProcessor.swift b/Sources/verbemo/Sessions/PostProcessor.swift index 48e148f8..3dd94977 100644 --- a/Sources/verbemo/Sessions/PostProcessor.swift +++ b/Sources/verbemo/Sessions/PostProcessor.swift @@ -74,6 +74,7 @@ enum PostProcessor { && (retryFailed || !gaveUp(SessionState.Key.speakersStatus, SessionState.Key.speakersFailedFor, .speakerNames)) work.summary = policy.summary + && meta[SessionState.Key.summaryManual] as? Bool != true && !hasCurrentSummary(dir, meta: meta) && (retryFailed || !gaveUp(SessionState.Key.summaryStatus, SessionState.Key.summaryFailedFor, .summary)) @@ -98,13 +99,13 @@ enum PostProcessor { } /// Regenerate just this version's summary; keep the previous bytes on failure. - static func regenerateSummary(_ dir: URL, policy: Policy = .configured) async throws { + static func regenerateSummary(_ dir: URL, policy: Policy = .configured, request: SummaryRequest? = nil) async throws { let root = try validatedSessionRoot(for: dir) func validate() throws -> Transcript { - if let reason = Config.unreadableReason { + if request == nil, let reason = Config.unreadableReason { throw Refusal.configUnreadable(reason) } - guard policy.summary else { + guard request != nil || policy.summary else { throw SummaryRegenerationError.unavailable(localised("Summary generation is off.", "Создание сводки выключено.")) } guard !FileManager.default.fileExists(atPath: root.appendingPathComponent(".recording.json").path), @@ -118,6 +119,13 @@ enum PostProcessor { try SessionClaim.acquire(root, stage: .finish) defer { SessionClaim.release(root) } let transcript = try validate() + try Task.checkCancellation() + if request != nil { + // A one-run destination must never become a configured background retry. + try SessionState.amend(dir, with: [SessionState.Key.summaryManual: true]) + } + try await request?.checkAccess() + try Task.checkCancellation() let meta = SessionState.read(root) ?? [:] let calendar = meta["calendar"] as? [String: Any] let title = (meta["title"] as? String) ?? (calendar?["title"] as? String) ?? root.lastPathComponent @@ -127,7 +135,7 @@ enum PostProcessor { context.append("Participants: " + attendees.joined(separator: ", ")) } let names = SpeakerNames.read(from: dir) - guard await Summarizer.summarize(transcript: transcript.named(with: names), context: context, into: dir) != nil else { + guard await Summarizer.summarize(transcript: transcript.named(with: names), context: context, into: dir, request: request) != nil else { throw SummaryRegenerationError.unavailable(localised( "The summary could not be regenerated. The previous summary is preserved; see the session log.", "Не удалось перегенерировать сводку. Предыдущая сводка сохранена; подробности в журнале встречи.")) diff --git a/Sources/verbemo/Sessions/TranscriptVersions.swift b/Sources/verbemo/Sessions/TranscriptVersions.swift index d31c6365..def68e99 100644 --- a/Sources/verbemo/Sessions/TranscriptVersions.swift +++ b/Sources/verbemo/Sessions/TranscriptVersions.swift @@ -186,6 +186,7 @@ enum TranscriptVersions { let reset: [String: Any?] = [ SessionState.Key.summaryStale: archive != nil && fm.fileExists(atPath: dir.appendingPathComponent("summary.md").path) ? true : nil, SessionState.Key.speakersStatus: nil, SessionState.Key.summaryStatus: nil, + SessionState.Key.summaryManual: nil, SessionState.Key.speakersFailedFor: nil, SessionState.Key.summaryFailedFor: nil, SessionState.Key.speakersDeferrals: nil, SessionState.Key.summaryDeferrals: nil, SessionState.Key.transcriptionFailed: nil, SessionState.Key.transcriptionAttempts: nil, diff --git a/Sources/verbemo/Setup/Credentials.swift b/Sources/verbemo/Setup/Credentials.swift index 7e21c8fc..b4afab78 100644 --- a/Sources/verbemo/Setup/Credentials.swift +++ b/Sources/verbemo/Setup/Credentials.swift @@ -123,12 +123,12 @@ enum Credentials { // transcription. if Home.current.variable("OPENAI_API_KEY")? .trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false { - return Config.openAIKey() + return Config.openAIKey(in: config) } if let named = pathSetting(.summaryOpenAIKeyPath, in: config) { return Config.secret(at: named) } - return Config.openAIKey() + return Config.openAIKey(in: config) } if let named = pathSetting(.summaryOpenAICompatibleKeyPath, in: config) { return Config.secret(at: named) @@ -136,7 +136,7 @@ enum Credentials { if let pasted = Config.secret(at: openAICompatibleKeyPath) { return pasted } let host = URL(string: baseURL.trimmingCharacters(in: .whitespacesAndNewlines))? .host?.lowercased() ?? "" - return OpenAICompatible.isLoopback(host) ? Config.openAIKey() : nil + return OpenAICompatible.isLoopback(host) ? Config.openAIKey(in: config) : nil } private static func pathSetting(_ key: Config.Key, in config: [String: Any]?) -> URL? { diff --git a/Sources/verbemo/Summary/LLMBackend.swift b/Sources/verbemo/Summary/LLMBackend.swift index d67179d9..ae7a387b 100644 --- a/Sources/verbemo/Summary/LLMBackend.swift +++ b/Sources/verbemo/Summary/LLMBackend.swift @@ -32,6 +32,7 @@ struct LLMBackend: Sendable { /// option — and the whole transcript went back to every backend in the /// chain at every launch and every change of network, for ever. var isUnchosenFallback = false + var checkAccess: @Sendable () async throws -> Void = {} /// (system prompt, user prompt) → completion text. let call: @Sendable (String, String) async throws -> String @@ -59,27 +60,29 @@ struct LLMBackend: Sendable { static func available( preference: String = "auto", anthropicModel: String? = nil, - openAIModel overriddenOpenAIModel: String? = nil + openAIModel overriddenOpenAIModel: String? = nil, + config: [String: Any]? = Config.raw(), + freezeConfiguration: Bool = false ) -> [LLMBackend] { // Whatever the home says instead — nothing at all, in a test that has // not brought a fake of its own. if let supplied = Home.current.languageModels { return supplied(preference) } - let settings = Config.summary() + let settings = Config.summary(in: config) let openAIModelID = overriddenOpenAIModel ?? settings.openAIModel var candidates: [LLMBackend] = [] if let claude = cliPath("claude") { candidates.append(claudeCLI(path: claude, model: anthropicModel)) } - if let key = Config.anthropicKey() { + if let key = Config.anthropicKey(in: config) { candidates.append(anthropic(key: key, model: anthropicModel ?? settings.model)) } if let codex = cliPath("codex") { - candidates.append(codexCLI(path: codex)) + candidates.append(codexCLI(path: codex, freezeConfiguration: freezeConfiguration)) } // Not simply the OpenAI key: an OpenAI-compatible endpoint has a key // of its own — see `Credentials.summaryOpenAIKey`. - if let key = Credentials.summaryOpenAIKey() { + if let key = Credentials.summaryOpenAIKey(in: config) { candidates.append(openAI(key: key, model: openAIModelID, baseURL: settings.openAIBaseURL)) } var local = ollama(model: settings.ollamaModel, baseURL: settings.ollamaBaseURL) @@ -109,10 +112,21 @@ struct LLMBackend: Sendable { } } + private static func checkKey(_ check: Credentials.Check) async throws { + switch await check.ask() { + case .works: return + case .refused: throw LLMError.http(401, "Authentication refused") + case .unreachable: throw URLError(.cannotConnectToHost) + case .unexpected(let status): throw LLMError.http(status, "Access check failed") + } + } + // MARK: - Anthropic private static func claudeCLI(path: String, model: String?) -> LLMBackend { - LLMBackend(name: "claude-cli", model: model) { system, prompt in + LLMBackend(name: "claude-cli", model: model, checkAccess: { + _ = try await run(executable: path, arguments: ["auth", "status"], input: "", timeout: 20) + }) { system, prompt in try await run( executable: path, arguments: claudeArguments(system: system, model: model), @@ -163,7 +177,9 @@ struct LLMBackend: Sendable { } private static func anthropic(key: String, model: String) -> LLMBackend { - LLMBackend(name: "anthropic-api", model: model) { system, prompt in + LLMBackend(name: "anthropic-api", model: model, checkAccess: { + try await checkKey(.init(service: .anthropic, key: key)) + }) { system, prompt in var request = URLRequest(url: URL(string: "https://api.anthropic.com/v1/messages")!) request.httpMethod = "POST" request.timeoutInterval = 600 @@ -197,17 +213,31 @@ struct LLMBackend: Sendable { /// `codex exec` prints a running trace to stdout, so the answer is read /// from the file it writes with `--output-last-message` rather than /// scraped out of the log. - private static func codexCLI(path: String) -> LLMBackend { + static func codexCLI(path: String, freezeConfiguration: Bool = false) -> LLMBackend { + let configURL = codexConfigURL + let config = try? Data(contentsOf: configURL) + let servers = config.flatMap { String(data: $0, encoding: .utf8) }.map(mcpServerNames(inTOML:)) ?? [] + let checkConfig: @Sendable () throws -> Void = { + guard !freezeConfiguration || (try? Data(contentsOf: configURL)) == config else { + throw PostProcessor.SummaryRegenerationError.unavailable(localised( + "Codex configuration changed. Choose the provider again before sending the transcript.", + "Настройки Codex изменились. Выберите способ заново перед отправкой текста.")) + } + } // The CLI resolves its model from its own config or default. We do // not know that model here and must not report the API's model as it. - LLMBackend(name: "codex-cli", model: nil) { system, prompt in + return LLMBackend(name: "codex-cli", model: nil, checkAccess: { + try checkConfig() + _ = try await run(executable: path, arguments: ["login", "status"], input: "", timeout: 20) + }) { system, prompt in + try checkConfig() let output = FileManager.default.temporaryDirectory .appendingPathComponent("verbemo-codex-\(UUID().uuidString).txt") defer { try? FileManager.default.removeItem(at: output) } _ = try await run( executable: path, - arguments: codexArguments(output: output), + arguments: codexArguments(output: output, mcpServers: freezeConfiguration ? servers : codexMCPServers()), input: "\(system)\n\n\(prompt)", timeout: 1800 ) @@ -265,11 +295,15 @@ struct LLMBackend: Sendable { /// The MCP servers the person's codex config defines, read from /// `$CODEX_HOME/config.toml` or `~/.codex/config.toml`. - static func codexMCPServers() -> [String]? { + private static var codexConfigURL: URL { let home = Home.current.variable("CODEX_HOME").map { Home.current.expanding($0) } ?? Home.current.url.appendingPathComponent(".codex", isDirectory: true) + return home.appendingPathComponent("config.toml") + } + + static func codexMCPServers() -> [String]? { guard let text = try? String( - contentsOf: home.appendingPathComponent("config.toml"), encoding: .utf8) + contentsOf: codexConfigURL, encoding: .utf8) else { return [] } return mcpServerNames(inTOML: text) } @@ -328,7 +362,10 @@ struct LLMBackend: Sendable { } private static func openAI(key: String, model: String, baseURL: String) -> LLMBackend { - LLMBackend(name: "openai-api", model: model) { system, prompt in + LLMBackend(name: "openai-api", model: model, checkAccess: { + _ = try OpenAICompatible.url(baseURL: baseURL, path: "models") + try await checkKey(.init(service: .openAI(baseURL: baseURL), key: key)) + }) { system, prompt in let url = try OpenAICompatible.url(baseURL: baseURL, path: "chat/completions") var request = URLRequest(url: url) request.httpMethod = "POST" @@ -363,7 +400,13 @@ struct LLMBackend: Sendable { // MARK: - local private static func ollama(model: String, baseURL: String) -> LLMBackend { - LLMBackend(name: "ollama", model: model, promptLimit: OllamaClient.promptLimit) { + LLMBackend(name: "ollama", model: model, promptLimit: OllamaClient.promptLimit, checkAccess: { + let models = try await OllamaClient.listModels(baseURL: baseURL) + guard SetupSelection.ollamaModel(named: model, in: models) != nil else { + throw PostProcessor.SummaryRegenerationError.unavailable(localised( + "The selected Ollama model is unavailable.", "Выбранная модель Ollama недоступна.")) + } + }) { system, prompt in try await OllamaClient.chat( baseURL: baseURL, model: model, system: system, prompt: prompt) diff --git a/Sources/verbemo/Summary/MeetingEgress.swift b/Sources/verbemo/Summary/MeetingEgress.swift index 63cb2c84..40e3f66e 100644 --- a/Sources/verbemo/Summary/MeetingEgress.swift +++ b/Sources/verbemo/Summary/MeetingEgress.swift @@ -91,13 +91,15 @@ enum MeetingEgress { /// of all of it is ever written down. static func fingerprint(for purpose: Purpose) -> String? { guard let route = route(for: purpose) else { return nil } - let summary = Config.summary() + return fingerprint(for: purpose, route: route, summary: Config.summary(), backends: backends(for: purpose)) + } + + static func fingerprint(for purpose: Purpose, route: Route, summary: Config.SummarySettings, + backends: [LLMBackend], config: [String: Any]? = Config.raw()) -> String { var parts = [purpose.rawValue, route.preference, route.anthropicModel ?? "-"] - parts += LLMBackend.available( - preference: route.preference, anthropicModel: route.anthropicModel - ).map { "\($0.name)=\($0.model ?? "-")" } + parts += backends.map { "\($0.name)=\($0.model ?? "-")" } parts += [summary.openAIBaseURL, summary.ollamaBaseURL] - parts += [Config.anthropicKey(), Credentials.summaryOpenAIKey()].map { key in + parts += [Config.anthropicKey(in: config), Credentials.summaryOpenAIKey(in: config)].map { key in key.map { digest($0) } ?? "-" } if purpose == .summary { diff --git a/Sources/verbemo/Summary/Summarizer.swift b/Sources/verbemo/Summary/Summarizer.swift index 53430284..bd34625e 100644 --- a/Sources/verbemo/Summary/Summarizer.swift +++ b/Sources/verbemo/Summary/Summarizer.swift @@ -21,7 +21,8 @@ enum Summarizer { static func summarize( transcript: Transcript, context: [String], - into dir: URL + into dir: URL, + request: SummaryRequest? = nil ) async -> String? { func log(_ message: String) { appendSessionLog(message, to: dir) } @@ -29,12 +30,12 @@ enum Summarizer { // minutes, and the route below is read from the file as it is now. // Nothing is recorded, so the summary is still owed once the file // reads again. - if let reason = Config.unreadableReason { + if request == nil, let reason = Config.unreadableReason { log("summary waits — config.json can't be read (\(reason))") return nil } - let settings = Config.summary() - guard MeetingEgress.route(for: .summary) != nil else { return nil } + let settings = request?.settings ?? Config.summary() + guard request != nil || MeetingEgress.route(for: .summary) != nil else { return nil } let body = plainText(transcript) guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { @@ -42,7 +43,7 @@ enum Summarizer { return nil } - let backends = MeetingEgress.backends(for: .summary) + let backends = request?.backends ?? MeetingEgress.backends(for: .summary) guard !backends.isEmpty else { log("summary skipped — no backend available") Analytics.track(.summaryFailed, [ @@ -68,6 +69,8 @@ enum Summarizer { for backend in backends { guard !Task.isCancelled else { return nil } do { + if request != nil { try await backend.checkAccess() } + try Task.checkCancellation() log("summarizing with \(backend.name)") let markdown = try await produce( body: body, header: header, settings: settings, backend: backend @@ -92,6 +95,7 @@ enum Summarizer { ]) return backend.name } catch { + if error is CancellationError || Task.isCancelled { return nil } // Falling through is the expected path when a subscription is // spent, so say which kind of failure this was — otherwise a // healthy hand-off reads like something broke. @@ -118,7 +122,7 @@ enum Summarizer { statusKey: SessionState.Key.summaryStatus, fingerprintKey: SessionState.Key.summaryFailedFor, countKey: SessionState.Key.summaryDeferrals, - fingerprint: MeetingEgress.fingerprint(for: .summary))) + fingerprint: request?.fingerprint ?? MeetingEgress.fingerprint(for: .summary))) let deferred: Bool switch verdict { case .deferred: diff --git a/Sources/verbemo/Summary/SummaryRequest.swift b/Sources/verbemo/Summary/SummaryRequest.swift new file mode 100644 index 00000000..2fdf4978 --- /dev/null +++ b/Sources/verbemo/Summary/SummaryRequest.swift @@ -0,0 +1,65 @@ +import Foundation + +/// Immutable parameters and backend closures for one user-approved summary attempt. +/// Keys stay inside closures in memory; nothing here is written to configuration. +struct SummaryRequest: Sendable { + let settings: Config.SummarySettings + let backends: [LLMBackend] + let fingerprint: String? + + static func capture(backend: String? = nil) throws -> SummaryRequest { + if let reason = Config.unreadableReason { throw PostProcessor.Refusal.configUnreadable(reason) } + let config = Config.raw() + var settings = Config.summary(in: config) + if let backend { + guard LLMBackend.names.contains(backend) else { throw unavailable() } + settings.backend = backend + settings.enabled = true + } + guard settings.enabled, settings.backend != "none" else { throw unavailable() } + let backends = LLMBackend.available(preference: settings.backend, + anthropicModel: settings.configuredModel, config: config, freezeConfiguration: true) + guard !backends.isEmpty else { throw unavailable() } + return SummaryRequest(settings: settings, backends: backends, + fingerprint: MeetingEgress.fingerprint(for: .summary, + route: .init(preference: settings.backend, anthropicModel: settings.configuredModel), + summary: settings, backends: backends, config: config)) + } + + func checkAccess() async throws { + var failure: (any Error)? + for backend in backends { + try Task.checkCancellation() + do { try await backend.checkAccess(); return } + catch { failure = error } + } + throw failure ?? Self.unavailable() + } + + static func unavailable() -> PostProcessor.SummaryRegenerationError { + .unavailable(localised("This provider is unavailable. Check Summary settings.", + "Способ недоступен. Проверьте настройки сводки.")) + } + + var disclosure: String { + let destinations = backends.map { backend in + switch backend.name { + case "codex-cli": return localised("Codex (service configured in Codex)", "Codex (сервис из настроек Codex)") + case "claude-cli": return "Claude Code / Anthropic" + case "anthropic-api": return "Anthropic API" + case "openai-api": return "API · " + Self.host(settings.openAIBaseURL) + case "ollama": return "Ollama · " + Self.host(settings.ollamaBaseURL) + + localised(" (cloud models may forward text)", " (облачная модель может отправить текст дальше)") + default: return backend.name + } + }.joined(separator: " → ") + return localised("Transcript destination: ", "Куда отправится текст: ") + destinations + + localised(". Only for this summary; global settings stay unchanged.", + ". Только для этой сводки; общие настройки не меняются.") + } + + private static func host(_ address: String) -> String { + guard let url = URL(string: address), let host = url.host else { return localised("invalid address", "неверный адрес") } + return host + (url.port.map { ":\($0)" } ?? "") + } +} diff --git a/Sources/verbemo/UI/MeetingActionState.swift b/Sources/verbemo/UI/MeetingActionState.swift index f376d5cf..315fc72c 100644 --- a/Sources/verbemo/UI/MeetingActionState.swift +++ b/Sources/verbemo/UI/MeetingActionState.swift @@ -31,7 +31,6 @@ struct MeetingActionState { if !configReadable { return localised("Fix config.json before processing.", "Сначала исправьте config.json.") } if action == .regenerateSummary { if !transcriptReady || hasPendingTranscript { return localised("A finished transcript is required.", "Сначала нужна готовая расшифровка.") } - if !summaryEnabled { return localised("Enable summary generation in settings.", "Включите создание сводки в настройках.") } } else { if !hasAudio { return localised("The source audio was not kept.", "Исходное аудио не сохранено.") } if !transcriptionEnabled { return localised("Enable transcription in settings.", "Включите расшифровку в настройках.") } diff --git a/Sources/verbemo/UI/MeetingLibraryController.swift b/Sources/verbemo/UI/MeetingLibraryController.swift index f074885a..9ab167e8 100644 --- a/Sources/verbemo/UI/MeetingLibraryController.swift +++ b/Sources/verbemo/UI/MeetingLibraryController.swift @@ -115,6 +115,7 @@ final class MeetingLibraryController: NSObject, NSTextFieldDelegate { private var undoDeletionID: UUID? var isProcessing: Bool { working || deletion.hasWork } func cancelPendingDeletion() { deletion.cancelAll(); onActivityChange?() } + private var summarySheet: SummaryRegenerationSheet? private var working = false { didSet { onActivityChange?() } } init(root: URL, pasteboard: NSPasteboard = .general, hostWindow: NSWindow) { @@ -433,40 +434,18 @@ final class MeetingLibraryController: NSObject, NSTextFieldDelegate { @objc private func regenerateClicked() { regenerateSummary() } private func regenerateSummary() { guard currentActions.reason(for: .regenerateSummary) == nil, let dir = artifactDirectory, panel.attachedSheet == nil else { updateButtons(); return } - let alert = NSAlert() - alert.messageText = localised("Create a new summary", "Создать новую сводку") - alert.informativeText = localised( - "Uses the selected transcript version and your configured provider. The previous summary is kept if this attempt fails.", - "Используется выбранная версия расшифровки и способ из настроек. Если попытка не удастся, предыдущая сводка сохранится.") - let method = NSTextField(wrappingLabelWithString: localised("Configured provider: ", "Способ из настроек: ") + Self.summaryMethodName(Config.summary().backend)) - let placeholder = JournalUnavailableView(.summaryProvider, title: localised("Choose a provider for this run", "Выбрать способ только для этой сводки")) - let accessory = NSStackView(views: [method, placeholder]) - accessory.orientation = .vertical - accessory.alignment = .leading - accessory.spacing = 16 - accessory.frame = NSRect(x: 0, y: 0, width: 380, height: 126) - for view in accessory.arrangedSubviews { view.widthAnchor.constraint(equalTo: accessory.widthAnchor).isActive = true } - alert.accessoryView = accessory - alert.addButton(withTitle: localised("Create summary", "Создать сводку")) - alert.addButton(withTitle: localised("Cancel", "Отмена")) - alert.addButton(withTitle: localised("Summary settings", "Настройки сводки")) - alert.beginSheetModal(for: panel) { [weak self] response in + working = true + updateButtons() + let sheet = SummaryRegenerationSheet(onSettings: { [weak self] in self?.onNavigateSettings?(.summary) }, run: { request in + try await PostProcessor.regenerateSummary(dir, request: request) + }, completion: { [weak self] in guard let self else { return } - if response == .alertThirdButtonReturn { self.onNavigateSettings?(.summary); return } - guard response == .alertFirstButtonReturn, - self.artifactDirectory == dir, self.currentActions.reason(for: .regenerateSummary) == nil else { return } - self.working = true - self.updateButtons() - self.updateInspector() - self.table.reloadData() - Task { [weak self] in - guard let self else { return } - do { try await PostProcessor.regenerateSummary(dir) } - catch { await NSAlert(error: error).beginSheetModal(for: panel) } - working = false - reload() - } - } + summarySheet = nil + working = false + reload() + }) + summarySheet = sheet + panel.beginSheet(sheet.window) } func beginRenamingMeeting() { guard let item = selected else { return } diff --git a/Sources/verbemo/UI/SummaryRegenerationSheet.swift b/Sources/verbemo/UI/SummaryRegenerationSheet.swift new file mode 100644 index 00000000..6270c999 --- /dev/null +++ b/Sources/verbemo/UI/SummaryRegenerationSheet.swift @@ -0,0 +1,117 @@ +import AppKit + +/// The request is captured when a choice is displayed, and retained for an explicit retry. +@MainActor +final class SummaryRegenerationSheet { + let window = NSPanel(contentRect: NSRect(x: 0, y: 0, width: 500, height: 340), + styleMask: [.titled], backing: .buffered, defer: false) + let picker = NSPopUpButton() + let disclosure = NSTextField(wrappingLabelWithString: "") + let status = NSTextField(wrappingLabelWithString: "") + let create = NSButton() + private let cancel = NSButton() + private let onSettings: (() -> Void)? + private let run: (SummaryRequest) async throws -> Void + private let completion: () -> Void + private var request: SummaryRequest? + private var finished = false + private(set) var task: Task? + private static let choices: [String?] = [nil, "codex-cli", "claude-cli", "openai-api", "anthropic-api", "ollama"] + + init(onSettings: (() -> Void)? = nil, run: @escaping (SummaryRequest) async throws -> Void, completion: @escaping () -> Void) { + self.run = run; self.completion = completion; self.onSettings = onSettings + window.title = localised("Create a new summary", "Создать новую сводку") + window.isReleasedWhenClosed = false + let heading = NSTextField(labelWithString: window.title) + heading.font = .systemFont(ofSize: 18, weight: .semibold) + let note = NSTextField(wrappingLabelWithString: localised( + "Uses the selected transcript version. The previous summary is kept on failure or cancellation.", + "Используется выбранная версия расшифровки. При ошибке или отмене предыдущая сводка сохранится.")) + note.textColor = .secondaryLabelColor + picker.addItems(withTitles: [localised("From settings", "Из настроек"), "Codex", "Claude Code", "OpenAI API", "Anthropic API", "Ollama"]) + picker.identifier = .init("summary.provider") + picker.setAccessibilityLabel(localised("Provider for this summary", "Способ для этой сводки")) + picker.target = self; picker.action = #selector(selectionChanged) + disclosure.identifier = .init("summary.destination") + disclosure.font = .systemFont(ofSize: 12) + status.identifier = .init("summary.status") + status.textColor = .secondaryLabelColor + create.bezelStyle = .rounded; create.keyEquivalent = "\r" + create.identifier = .init("summary.create") + create.target = self; create.action = #selector(start) + cancel.title = localised("Cancel", "Отмена") + cancel.bezelStyle = .rounded; cancel.keyEquivalent = "\u{1b}" + cancel.target = self; cancel.action = #selector(cancelClicked) + let buttons = NSStackView(views: [SetupLayout.spacer(), cancel, create]) + let content = NSStackView(views: [heading, note, picker, disclosure, status, buttons]) + content.orientation = .vertical; content.alignment = .leading; content.spacing = 16 + content.edgeInsets = NSEdgeInsets(top: 24, left: 24, bottom: 24, right: 24) + if onSettings != nil { + let settings = NSButton(title: localised("Summary settings…", "Настройки сводки…"), target: self, action: #selector(settingsClicked)) + settings.isBordered = false + content.insertArrangedSubview(settings, at: 5) + } + window.contentView = content + content.widthAnchor.constraint(equalToConstant: 500).isActive = true + for view in content.arrangedSubviews { + view.widthAnchor.constraint(equalTo: content.widthAnchor, constant: -48).isActive = true + } + selectionChanged() + } + + @objc func selectionChanged() { + guard task == nil else { return } + status.stringValue = "" + create.title = localised("Check and create", "Проверить и создать") + do { + request = try SummaryRequest.capture(backend: Self.choices[picker.indexOfSelectedItem]) + disclosure.stringValue = request?.disclosure ?? "" + create.isEnabled = true + } catch { + request = nil; disclosure.stringValue = error.localizedDescription + create.isEnabled = false + } + } + + @objc func start() { + guard task == nil, let request else { return } + picker.isEnabled = false; create.isEnabled = false + status.stringValue = localised("Checking access and creating the summary…", "Проверка доступа и создание сводки…") + task = Task { [self] in + do { + try await run(request) + task = nil + close() + } catch { + let cancelled = Task.isCancelled || error is CancellationError + task = nil + if cancelled { close(); return } + status.stringValue = error.localizedDescription + picker.isEnabled = true; create.isEnabled = true + create.title = localised("Retry same choice", "Повторить с тем же выбором") + } + } + } + + @objc private func cancelClicked() { + if let task { + task.cancel() + status.stringValue = localised("Cancelling…", "Отмена…") + cancel.isEnabled = false + } else { close() } + } + + @objc private func settingsClicked() { + guard task == nil else { return } + close() + onSettings?() + } + + private func close() { + guard !finished else { return } + finished = true + window.sheetParent?.endSheet(window) + window.orderOut(nil) + completion() + } +} diff --git a/Tests/verbemoTests/MeetingActionStateTests.swift b/Tests/verbemoTests/MeetingActionStateTests.swift index 265d9ce1..b3153af6 100644 --- a/Tests/verbemoTests/MeetingActionStateTests.swift +++ b/Tests/verbemoTests/MeetingActionStateTests.swift @@ -25,7 +25,7 @@ struct MeetingActionStateTests { #expect(state.reason(for: .copySummary) == nil) state.isBusy = false state.summaryEnabled = false - #expect(state.reason(for: .regenerateSummary) != nil) + #expect(state.reason(for: .regenerateSummary) == nil) state.summaryEnabled = true state.configReadable = false #expect(state.reason(for: .regenerateSummary) != nil) diff --git a/Tests/verbemoTests/SummaryCLIConfigurationTests.swift b/Tests/verbemoTests/SummaryCLIConfigurationTests.swift new file mode 100644 index 00000000..3d256603 --- /dev/null +++ b/Tests/verbemoTests/SummaryCLIConfigurationTests.swift @@ -0,0 +1,21 @@ +import Foundation +import Testing +@testable import verbemo + +struct SummaryCLIConfigurationTests { + @Test func codexRefusesChangedConfigurationBeforeProbeOrTranscript() async throws { + let home = Home.sandbox() + defer { try? FileManager.default.removeItem(at: home.url) } + let folder = home.url.appendingPathComponent(".codex") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + let config = folder.appendingPathComponent("config.toml") + try Data("model = \"original\"".utf8).write(to: config) + try await Home.$scoped.withValue(home) { + let backend = LLMBackend.codexCLI(path: "/usr/bin/true", freezeConfiguration: true) + try await backend.checkAccess() + try Data("model = \"changed\"".utf8).write(to: config) + await #expect(throws: PostProcessor.SummaryRegenerationError.self) { try await backend.checkAccess() } + await #expect(throws: PostProcessor.SummaryRegenerationError.self) { _ = try await backend.call("system", "private transcript") } + } + } +} diff --git a/Tests/verbemoTests/SummaryProviderSheetTests.swift b/Tests/verbemoTests/SummaryProviderSheetTests.swift new file mode 100644 index 00000000..a0499afd --- /dev/null +++ b/Tests/verbemoTests/SummaryProviderSheetTests.swift @@ -0,0 +1,45 @@ +import AppKit +import Foundation +import Testing +@testable import verbemo + +@Suite(.serialized) +@MainActor +struct SummaryProviderSheetTests { + @Test func pickerKeepsSelectionForExplicitRetry() async throws { + let chosen = FakeModel("codex-cli") { call, _, _ in + if call == 0 { throw LLMError.exit(1, "Not logged in") } + return "retried" + } + let other = FakeModel("claude-cli", answer: "wrong provider") + let home = Home.withModels([other, chosen]) + let dir = try SessionFixture.make() + defer { for url in [home.url, dir] { try? FileManager.default.removeItem(at: url) } } + try home.writeConfig(["summary": ["backend": "claude-cli"]]) + try Data("old".utf8).write(to: dir.appendingPathComponent("summary.md")) + try await Home.$scoped.withValue(home) { + let sheet = SummaryRegenerationSheet(run: { request in + try await PostProcessor.regenerateSummary(dir, request: request) + }, completion: {}) + sheet.picker.selectItem(at: 1) + sheet.selectionChanged() + #expect(sheet.disclosure.stringValue.contains("Codex")) + sheet.start() + await sheet.task?.value + #expect(sheet.picker.indexOfSelectedItem == 1) + #expect(sheet.create.isEnabled) + #expect(try String(contentsOf: dir.appendingPathComponent("summary.md"), encoding: .utf8) == "old") + try home.writeConfig(["summary": ["backend": "claude-cli", "enabled": false]]) + sheet.start() + await sheet.task?.value + #expect(try String(contentsOf: dir.appendingPathComponent("summary.md"), encoding: .utf8) == "retried\n") + #expect(other.callCount == 0) + } + } + + @Test func oneRunChoiceIsAvailableWithAutomaticSummaryDisabled() { + let state = MeetingActionState(transcriptReady: true, summaryReady: false, hasAudio: false, + isRecording: false, isBusy: false, configReadable: true, transcriptionEnabled: false, summaryEnabled: false) + #expect(state.reason(for: .regenerateSummary) == nil) + } +} diff --git a/Tests/verbemoTests/SummaryRequestTests.swift b/Tests/verbemoTests/SummaryRequestTests.swift new file mode 100644 index 00000000..42b755d8 --- /dev/null +++ b/Tests/verbemoTests/SummaryRequestTests.swift @@ -0,0 +1,191 @@ +import Foundation +import Testing +@testable import verbemo + +struct SummaryRequestTests { + @Test func selectedProviderIsFrozenAndDoesNotChangeOtherMeetings() async throws { + let chosen = FakeModel("codex-cli") { _, system, prompt in + #expect(system.contains("English")) + #expect(prompt.contains("Original template")) + return "chosen" + } + let configured = FakeModel("claude-cli", answer: "configured") + let home = Home.withModels([configured, chosen]) + let first = try SessionFixture.make() + let second = try SessionFixture.make() + defer { for url in [home.url, first, second] { try? FileManager.default.removeItem(at: url) } } + try home.writeConfig(["summary": ["backend": "claude-cli", "language": "English", "template": "Original template"]]) + try await Home.$scoped.withValue(home) { + let request = try SummaryRequest.capture(backend: "codex-cli") + let before = try Data(contentsOf: Config.path) + try await PostProcessor.regenerateSummary(first, request: request) + #expect(try Data(contentsOf: Config.path) == before) + try await PostProcessor.regenerateSummary(second) + #expect(try String(contentsOf: first.appendingPathComponent("summary.md"), encoding: .utf8) == "chosen\n") + #expect(try String(contentsOf: second.appendingPathComponent("summary.md"), encoding: .utf8) == "configured\n") + try home.writeConfig(["summary": ["enabled": false, "backend": "none", "language": "Russian"]]) + try await PostProcessor.regenerateSummary(first, request: request) + #expect(chosen.callCount == 2 && configured.callCount == 1) + #expect(request.settings.language == "English") + } + } + + @Test(arguments: [true, false]) func selectedFailureCannotFallBackOrBecomeBackgroundWork(explicit: Bool) async throws { + let chosen = FakeModel("codex-cli", failing: LLMError.exit(1, "Not logged in")) + let other = FakeModel("claude-cli", answer: "must not receive transcript") + let home = Home.withModels([other, chosen]) + let dir = try SessionFixture.make() + defer { for url in [home.url, dir] { try? FileManager.default.removeItem(at: url) } } + try home.writeConfig(["summary": ["backend": "codex-cli"], "speaker_names": ["enabled": false]]) + try await Home.$scoped.withValue(home) { + let request = try SummaryRequest.capture(backend: explicit ? "codex-cli" : nil) + await #expect(throws: (any Error).self) { try await PostProcessor.regenerateSummary(dir, request: request) } + try home.writeConfig(["summary": ["backend": "claude-cli"], "speaker_names": ["enabled": false]]) + for _ in 0..<8 { #expect(await PostProcessor.finish(dir).isEmpty) } + #expect(chosen.callCount == 1 && other.callCount == 0) + #expect(SessionState.value(dir, SessionState.Key.summaryFailedFor) as? String == request.fingerprint) + await #expect(throws: (any Error).self) { try await PostProcessor.regenerateSummary(dir, request: request) } + #expect(chosen.callCount == 2 && other.callCount == 0) + } + } + + @Test func accessFailureNeverSendsTranscriptOrChangesOldSummary() async throws { + let backend = LLMBackend(name: "codex-cli", model: nil, checkAccess: { throw LLMError.exit(1, "Not logged in") }) { _, _ in + Issue.record("Unavailable backend received the transcript") + return "wrong" + } + let home = Home.sandbox(languageModels: { _ in [backend] }) + let dir = try SessionFixture.make() + defer { for url in [home.url, dir] { try? FileManager.default.removeItem(at: url) } } + try Data("old".utf8).write(to: dir.appendingPathComponent("summary.md")) + try await Home.$scoped.withValue(home) { + let request = try SummaryRequest.capture(backend: "codex-cli") + await #expect(throws: (any Error).self) { try await PostProcessor.regenerateSummary(dir, request: request) } + #expect(try String(contentsOf: dir.appendingPathComponent("summary.md"), encoding: .utf8) == "old") + #expect(!SessionClaim.isHeld(dir)) + } + } + + @Test func cancelledReplacementKeepsOldSummary() async throws { + let model = FakeModel("codex-cli", failing: CancellationError()) + let home = Home.withModels([model]) + let dir = try SessionFixture.make() + defer { for url in [home.url, dir] { try? FileManager.default.removeItem(at: url) } } + try Data("old".utf8).write(to: dir.appendingPathComponent("summary.md")) + try await Home.$scoped.withValue(home) { + let request = try SummaryRequest.capture(backend: "codex-cli") + await #expect(throws: (any Error).self) { try await PostProcessor.regenerateSummary(dir, request: request) } + #expect(try String(contentsOf: dir.appendingPathComponent("summary.md"), encoding: .utf8) == "old") + #expect(!SessionClaim.isHeld(dir)) + } + } + @Test func unwritableMetadataStopsBeforeSendingText() async throws { + let model = FakeModel("codex-cli", answer: "must not send") + let home = Home.withModels([model]) + let dir = try SessionFixture.make() + defer { for url in [home.url, dir] { try? FileManager.default.removeItem(at: url) } } + let meta = dir.appendingPathComponent("meta.json") + try FileManager.default.setAttributes([.immutable: true], ofItemAtPath: meta.path) + defer { try? FileManager.default.setAttributes([.immutable: false], ofItemAtPath: meta.path) } + try await Home.$scoped.withValue(home) { + let request = try SummaryRequest.capture(backend: "codex-cli") + await #expect(throws: (any Error).self) { try await PostProcessor.regenerateSummary(dir, request: request) } + #expect(model.callCount == 0) + } + } + + @Test func selectedArchiveUsesRootClaimAndDoesNotReplaceCurrentSummary() async throws { + let model = FakeModel("codex-cli", answer: "archive replacement") + let home = Home.withModels([model]) + let dir = try SessionFixture.make() + defer { for url in [home.url, dir] { try? FileManager.default.removeItem(at: url) } } + try Data("old archive".utf8).write(to: dir.appendingPathComponent("summary.md")) + let archive = try #require(try TranscriptVersions.archiveCurrent(dir)) + try Transcript(engine: "assemblyai", model: "newer", created_at: "2026-10-22T11:00:00Z", + segments: [.init(speaker: "me", start_ms: 0, end_ms: 1000, text: "New transcript only")]).write(to: dir) + try Data("current summary".utf8).write(to: dir.appendingPathComponent("summary.md")) + try await Home.$scoped.withValue(home) { + let request = try SummaryRequest.capture(backend: "codex-cli") + try SessionClaim.acquire(dir, stage: .transcribe) + await #expect(throws: (any Error).self) { try await PostProcessor.regenerateSummary(archive, request: request) } + SessionClaim.release(dir) + #expect(model.callCount == 0) + try await PostProcessor.regenerateSummary(archive, request: request) + #expect(try String(contentsOf: archive.appendingPathComponent("summary.md"), encoding: .utf8) == "archive replacement\n") + #expect(try String(contentsOf: dir.appendingPathComponent("summary.md"), encoding: .utf8) == "current summary") + #expect(SessionState.value(dir, SessionState.Key.summaryManual) == nil) + #expect(model.prompts.first?.contains("Фёдор") == true) + #expect(model.prompts.first?.contains("New transcript only") == false) + } + } + + @Test func cancellationInFlightCannotPublishEvenIfBackendIgnoresIt() async throws { + let gate = Gate() + let entered = Gate() + let backend = LLMBackend(name: "codex-cli", model: nil) { _, _ in + entered.open() + await gate.pass() + return "late replacement" + } + let home = Home.sandbox(languageModels: { _ in [backend] }) + let dir = try SessionFixture.make() + defer { for url in [home.url, dir] { try? FileManager.default.removeItem(at: url) } } + try Data("old".utf8).write(to: dir.appendingPathComponent("summary.md")) + try await Home.$scoped.withValue(home) { + let request = try SummaryRequest.capture(backend: "codex-cli") + let task = Task { try await PostProcessor.regenerateSummary(dir, request: request) } + await entered.pass() + task.cancel() + gate.open() + await #expect(throws: (any Error).self) { try await task.value } + #expect(try String(contentsOf: dir.appendingPathComponent("summary.md"), encoding: .utf8) == "old") + #expect(!SessionClaim.isHeld(dir)) + } + } + + @Test func parallelRequestsKeepIndependentRoutesAndPrompts() async throws { + let entered = Gate(), release = Gate() + let codex = LLMBackend(name: "codex-cli", model: nil) { system, _ in + entered.open() + await release.pass() + #expect(system.contains("English")) + return "first" + } + let ollama = LLMBackend(name: "ollama", model: "local") { system, _ in + #expect(system.contains("Russian")) + return "second" + } + let home = Home.sandbox(languageModels: { LLMBackend.chain(preference: $0, from: [codex, ollama]) }) + let first = try SessionFixture.make(), second = try SessionFixture.make() + defer { for url in [home.url, first, second] { try? FileManager.default.removeItem(at: url) } } + try home.writeConfig(["summary": ["language": "English"]]) + try await Home.$scoped.withValue(home) { + let request = try SummaryRequest.capture(backend: "codex-cli") + let task = Task { try await PostProcessor.regenerateSummary(first, request: request) } + await entered.pass() + try home.writeConfig(["summary": ["language": "Russian", "backend": "ollama"]]) + let next = try SummaryRequest.capture(backend: "ollama") + do { try await PostProcessor.regenerateSummary(second, request: next) } + catch { release.open(); throw error } + release.open() + try await task.value + #expect(try String(contentsOf: first.appendingPathComponent("summary.md"), encoding: .utf8) == "first\n") + #expect(try String(contentsOf: second.appendingPathComponent("summary.md"), encoding: .utf8) == "second\n") + } + } + + @Test func keyResolutionUsesTheSameConfigurationSnapshotAsEndpoint() throws { + let home = Home.sandbox() + defer { try? FileManager.default.removeItem(at: home.url) } + try Home.$scoped.withValue(home) { + let old = home.url.appendingPathComponent("old-key") + let new = home.url.appendingPathComponent("new-key") + try Data("old synthetic key".utf8).write(to: old) + try Data("new synthetic key".utf8).write(to: new) + let snapshot: [String: Any] = ["transcription": ["openai": ["api_key_path": old.path]]] + try home.writeConfig(["transcription": ["openai": ["api_key_path": new.path]]]) + #expect(Credentials.summaryOpenAIKey(in: snapshot) == "old synthetic key") + } + } + +} diff --git a/docs/testing/2026-10-22-summary-provider.md b/docs/testing/2026-10-22-summary-provider.md new file mode 100644 index 00000000..b8872590 --- /dev/null +++ b/docs/testing/2026-10-22-summary-provider.md @@ -0,0 +1,62 @@ +# One-run summary provider (#28) + +Scope: macOS Journal summary regeneration only. Existing provider integrations, +credential storage, speaker naming, Windows behavior and signed release policy +remain outside this feature. The final branch must include the completed #8 +CLI-diagnostics/manual-processing change before merge and preview publication. + +## Behavior + +The sheet offers the configured chain, Codex, Claude Code, OpenAI-compatible API, +Anthropic API and Ollama. A choice captures settings and backend closures before +launch, including endpoint/key pairing, models, template and language. A change +to Codex's own config stops a one-run request until the user makes a fresh choice. +The disclosure lists the possible destinations. Explicit service choices never +fall back. Global settings and other meetings are not changed by the job. + +Access checks use CLI authentication status, existing API model-list probes and +the selected Ollama model list. These checks do not include the transcript or +generate paid text. They cannot guarantee that a later generation will succeed. +Generation rechecks access before each candidate receives text. + +All sheet requests persist `summary_manual` under the selected version's metadata +before contacting a service. This write is required. Background and generic +finish-processing attempts cannot pick these jobs up with different settings; +repeat through the summary sheet instead. The open sheet retains its request for +an explicit retry. Retranscription clears the marker for the new transcript. +No credentials or request payloads are persisted by this feature. + +The selected archive shares the root session claim. Summary output is replaced +atomically only after a successful completion and cancellation check. Previous +summary bytes survive errors and cancelled or late replies. + +## Development verification + +- Baseline: 15 existing summary/egress tests passed. +- Independent implementation: full Swift run passed 1045 tests in 149 suites; + subsequent review added regressions and fixes, so this is not final combined + branch evidence. +- Focused regressions cover immutable prompts/routes, parallel jobs, failed access, + explicit retries, no configured/background fallback, selected archive/root claim, + required metadata write, and cancellation of a backend that ignores cancellation. +- Review reproduced a configured-choice background reroute and a key-resolution + mismatch. The fixes block all sheet jobs from background pickup and derive the + endpoint and key file from the same configuration snapshot. + +## Native development check + +A separate `name.ekho.verbemo.summary28` ad-hoc debug bundle uses a pinned +`CFFIXED_USER_HOME` at `/tmp/verbemo28-native/home`. It contains two fictional +meetings, a loopback fake Ollama and executable fake Codex/Claude tools. Actual +provider keys, personal meetings and paid requests are not used. + +Observed in the real window: provider menu and destination disclosure; one-run +Ollama generation with automatic summary disabled; refusal by fake Codex before +any transcript call; explicit retry through the same Codex choice; cancellation +of an in-flight Ollama reply with the prior summary still displayed. The other +meeting remained unchanged. The initial native check exposed a generic LLMError +message; final integration must replace it using #8's diagnosis. + +Final combined revision, checks and release evidence will be recorded after #8 +is ready. Windows runtime, real cloud authentication and VoiceOver speech are not +established by these macOS synthetic checks. From fc0b8f0ac514ce80678331e7a463e4d771dd602a Mon Sep 17 00:00:00 2001 From: Boris Gorbylev Date: Thu, 22 Oct 2026 14:52:17 +0300 Subject: [PATCH 2/3] fix(macos): retry failed post-processing and clarify CLI errors Adapt the summary retry and CLI diagnostic behavior from upstream PR #20; share manual completion between the command and journal while preserving session claims and background failure fingerprints. Co-Authored-By: shooma Co-Authored-By: OpenAI Codex --- Sources/verbemo/Sessions/PostProcessor.swift | 93 +++++++- .../verbemo/Sessions/SessionCommands.swift | 17 +- Sources/verbemo/Sessions/SpeakerNamer.swift | 4 +- Sources/verbemo/Summary/LLMBackend.swift | 72 +++++- Sources/verbemo/Summary/Summarizer.swift | 4 +- .../verbemo/UI/MeetingLibraryController.swift | 28 ++- Tests/verbemoTests/CLIDiagnosticTests.swift | 122 ++++++++++ .../Sessions/ManualProcessingTests.swift | 217 ++++++++++++++++++ docs/history/summary-retry-upstream.md | 18 ++ docs/testing/2026-10-22-summary-retry.md | 46 ++++ 10 files changed, 575 insertions(+), 46 deletions(-) create mode 100644 Tests/verbemoTests/CLIDiagnosticTests.swift create mode 100644 Tests/verbemoTests/Sessions/ManualProcessingTests.swift create mode 100644 docs/history/summary-retry-upstream.md create mode 100644 docs/testing/2026-10-22-summary-retry.md 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. From 60798e2ca9a1a9e1cf39c9749cf394125885dabc Mon Sep 17 00:00:00 2001 From: Boris Gorbylev Date: Thu, 22 Oct 2026 15:11:34 +0300 Subject: [PATCH 3/3] fix(summary): reconcile one-run choices with manual retries Integrate completed #8 diagnostics and retry semantics without rerouting per-run summary jobs. Keep safe login advice and truthful outcomes in the sheet, journal and CLI. Co-Authored-By: OpenAI Codex --- Sources/verbemo/Sessions/PostProcessor.swift | 10 +++ Sources/verbemo/Sessions/SpeakerNamer.swift | 7 +- Sources/verbemo/Summary/LLMBackend.swift | 5 +- Sources/verbemo/Summary/Summarizer.swift | 13 ++-- Sources/verbemo/Summary/SummaryRequest.swift | 15 ++++- .../verbemo/UI/MeetingLibraryController.swift | 6 +- .../SummaryIntegrationTests.swift | 66 +++++++++++++++++++ docs/testing/2026-10-22-summary-provider.md | 53 +++++++++++---- 8 files changed, 148 insertions(+), 27 deletions(-) create mode 100644 Tests/verbemoTests/SummaryIntegrationTests.swift diff --git a/Sources/verbemo/Sessions/PostProcessor.swift b/Sources/verbemo/Sessions/PostProcessor.swift index f4b33ce8..7d833c55 100644 --- a/Sources/verbemo/Sessions/PostProcessor.swift +++ b/Sources/verbemo/Sessions/PostProcessor.swift @@ -195,10 +195,20 @@ enum PostProcessor { } } + static func manualSummaryRefusal(_ dir: URL) -> Completion? { + let meta = SessionState.read(dir) ?? [:] + guard meta[SessionState.Key.summaryManual] as? Bool == true, + !hasCurrentSummary(dir, meta: meta) else { return nil } + let english = "This summary needs an explicit provider choice. Use Create a new summary to retry." + return .refused(english, localised(english, + "Для этой сводки нужно выбрать способ создания. Нажмите «Создать новую сводку», чтобы повторить попытку.")) + } + /// 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 { let work = try await finishWork(dir, policy: policy, retryFailed: true) + if let refusal = manualSummaryRefusal(dir) { return refusal } guard !work.isEmpty else { return .nothingToDo } let meta = SessionState.read(dir) ?? [:] let missingNames = work.names && !FileManager.default.fileExists(atPath: dir.appendingPathComponent(SpeakerNames.file).path) diff --git a/Sources/verbemo/Sessions/SpeakerNamer.swift b/Sources/verbemo/Sessions/SpeakerNamer.swift index 359627fa..0dfe850e 100644 --- a/Sources/verbemo/Sessions/SpeakerNamer.swift +++ b/Sources/verbemo/Sessions/SpeakerNamer.swift @@ -102,7 +102,7 @@ enum SpeakerNamer { var lastModel: String? var lastReason = Analytics.Reason.unknown - for backend in backends { + for (index, backend) in backends.enumerated() { do { log("naming speakers with \(backend.name)") let answer = try await backend.call( @@ -144,8 +144,9 @@ enum SpeakerNamer { lastBackend = backend.name lastModel = backend.model lastReason = Analytics.reason(for: error) - log(LLMError.signInAdvice(error, backend: backend.name) ?? (LLMError.isUsageLimit(error) - ? "\(backend.name) is out of allowance — trying the next backend" + let hasNext = index + 1 < backends.count + log(LLMError.signInAdvice(error, backend: backend.name, hasNextBackend: hasNext) ?? (LLMError.isUsageLimit(error) + ? "\(backend.name) is out of allowance" + (hasNext ? " — trying the next backend" : "") : "naming via \(backend.name) failed: \(error)")) } } diff --git a/Sources/verbemo/Summary/LLMBackend.swift b/Sources/verbemo/Summary/LLMBackend.swift index 6f916cdf..75d960df 100644 --- a/Sources/verbemo/Summary/LLMBackend.swift +++ b/Sources/verbemo/Summary/LLMBackend.swift @@ -543,11 +543,12 @@ enum LLMError: Error, CustomStringConvertible { "oauth token expired", "oauth token revoked", "access token could not be refreshed", ] - static func signInAdvice(_ error: Error, backend: String) -> String? { + static func signInAdvice(_ error: Error, backend: String, hasNextBackend: Bool = true) -> 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" + return "\(backend) is signed out — sign in again with `\(command)`" + + (hasNextBackend ? "; trying the next backend" : "") } /// Whether the same request would plausibly succeed later: no network, a diff --git a/Sources/verbemo/Summary/Summarizer.swift b/Sources/verbemo/Summary/Summarizer.swift index 9b687538..7ba6b997 100644 --- a/Sources/verbemo/Summary/Summarizer.swift +++ b/Sources/verbemo/Summary/Summarizer.swift @@ -66,7 +66,7 @@ enum Summarizer { // particular: given a participant list, the summarizer writes "Anna // will send the contract" instead of "them will send the contract". let header = context.isEmpty ? "" : context.joined(separator: "\n") + "\n" - for backend in backends { + for (index, backend) in backends.enumerated() { guard !Task.isCancelled else { return nil } do { if request != nil { try await backend.checkAccess() } @@ -107,8 +107,9 @@ enum Summarizer { backend: backend.name, model: backend.model)), .reason: .text(lastReason.rawValue), ]) - log(LLMError.signInAdvice(error, backend: backend.name) ?? (LLMError.isUsageLimit(error) - ? "\(backend.name) is out of allowance — trying the next backend" + let hasNext = index + 1 < backends.count + log(LLMError.signInAdvice(error, backend: backend.name, hasNextBackend: hasNext) ?? (LLMError.isUsageLimit(error) + ? "\(backend.name) is out of allowance" + (hasNext ? " — trying the next backend" : "") : "summary via \(backend.name) failed: \(error)")) } } @@ -128,15 +129,15 @@ enum Summarizer { case .deferred: deferred = true log("no backend answered, and at least one could not be reached — summary deferred, " - + "will be retried later") + + (request == nil ? "will be retried later" : "use Create a new summary to retry this choice")) case .gaveUp(let deferrals?): deferred = false log("no backend has answered in \(deferrals) tries — giving up on the summary until " - + "the summary settings, keys or backends change") + + (request == nil ? "the summary settings, keys or backends change" : "you use Create a new summary to retry")) case .gaveUp(nil): deferred = false log("every backend failed for good — giving up on the summary until the " - + "summary settings, keys or backends change") + + (request == nil ? "summary settings, keys or backends change" : "next explicit attempt with Create a new summary")) } Analytics.track(.summaryFailed, [ .backend: .text(settings.backend), diff --git a/Sources/verbemo/Summary/SummaryRequest.swift b/Sources/verbemo/Summary/SummaryRequest.swift index 2fdf4978..b796bace 100644 --- a/Sources/verbemo/Summary/SummaryRequest.swift +++ b/Sources/verbemo/Summary/SummaryRequest.swift @@ -31,7 +31,20 @@ struct SummaryRequest: Sendable { for backend in backends { try Task.checkCancellation() do { try await backend.checkAccess(); return } - catch { failure = error } + catch { + if error is CancellationError || Task.isCancelled { throw CancellationError() } + if let advice = LLMError.signInAdvice(error, backend: backend.name, hasNextBackend: false) { + let command = backend.name == "claude-cli" ? "claude /login" : "codex login" + failure = PostProcessor.SummaryRegenerationError.unavailable(localised(advice, + "Нет входа в \(backend.name). Выполните \(command) и повторите попытку.")) + } else if error is PostProcessor.SummaryRegenerationError { + failure = error + } else { + failure = PostProcessor.SummaryRegenerationError.unavailable(localised( + "Could not verify access to \(backend.name). Check its connection and Summary settings, then retry.", + "Не удалось проверить доступ к \(backend.name). Проверьте подключение и настройки сводки, затем повторите попытку.")) + } + } } throw failure ?? Self.unavailable() } diff --git a/Sources/verbemo/UI/MeetingLibraryController.swift b/Sources/verbemo/UI/MeetingLibraryController.swift index 843732f7..dfed788d 100644 --- a/Sources/verbemo/UI/MeetingLibraryController.swift +++ b/Sources/verbemo/UI/MeetingLibraryController.swift @@ -983,9 +983,9 @@ final class MeetingLibraryController: NSObject, NSTextFieldDelegate { case .transcribe(let clearingFirst): return .transcribe(clearingFirst: clearingFirst) case .finish: - return PostProcessor.outstanding(item.dir, policy: policy, retryFailed: true).isEmpty - ? .nothingOwed - : .finish + if !PostProcessor.outstanding(item.dir, policy: policy, retryFailed: true).isEmpty { return .finish } + if let refusal = PostProcessor.manualSummaryRefusal(item.dir) { return .refuse(refusal.described) } + return .nothingOwed } } diff --git a/Tests/verbemoTests/SummaryIntegrationTests.swift b/Tests/verbemoTests/SummaryIntegrationTests.swift new file mode 100644 index 00000000..fa76c5c4 --- /dev/null +++ b/Tests/verbemoTests/SummaryIntegrationTests.swift @@ -0,0 +1,66 @@ +import AppKit +import ArgumentParser +import Foundation +import Testing +@testable import verbemo + +@Suite(.serialized) +struct SummaryIntegrationTests { + @Test @MainActor func manualFinishCannotRerouteAOneRunFailure() async throws { + let failed = FakeModel("codex-cli", failing: LLMError.exit(1, "Not logged in")) + let other = FakeModel("claude-cli", answer: "must not run") + let home = Home.withModels([other, failed]) + let dir = try SessionFixture.make() + defer { for url in [home.url, dir] { try? FileManager.default.removeItem(at: url) } } + try home.writeConfig(["summary": ["backend": "claude-cli"], "speaker_names": ["enabled": false]]) + try await Home.$scoped.withValue(home) { + let request = try SummaryRequest.capture(backend: "codex-cli") + await #expect(throws: (any Error).self) { try await PostProcessor.regenerateSummary(dir, request: request) } + let result = await PostProcessor.finishManually(dir) + #expect(!result.succeeded) + #expect(result.description.contains("Create a new summary")) + let command = try ProcessSession.parse([dir.path]) + #expect(throws: ExitCode.self) { try command.run() } + let item = try #require(SessionInventory.item(for: dir)) + if case .refuse = MeetingLibraryController.decision(for: item) {} else { Issue.record("Must explain how to retry") } + #expect(other.callCount == 0 && failed.callCount == 1) + let log = try String(contentsOf: dir.appendingPathComponent("transcribe.log"), encoding: .utf8) + #expect(log.contains("codex login")) + #expect(!log.contains("trying the next backend")) + } + } + + @Test func singleNamingProviderDoesNotPromiseFallback() async throws { + let failed = FakeModel("codex-cli", failing: LLMError.exit(1, "Not logged in")) + let home = Home.withModels([failed]) + let dir = try SessionFixture.make() + defer { for url in [home.url, dir] { try? FileManager.default.removeItem(at: url) } } + try home.writeConfig(["summary": ["backend": "codex-cli"], "speaker_names": ["enabled": true]]) + await Home.$scoped.withValue(home) { + await SpeakerNamer.name(transcript: SessionFixture.transcript, title: nil, attendees: [], app: nil, into: dir) + } + let log = try String(contentsOf: dir.appendingPathComponent("transcribe.log"), encoding: .utf8) + #expect(log.contains("codex login")) + #expect(!log.contains("trying the next backend")) + } + + @Test @MainActor func preflightLoginErrorKeepsChoiceAndGivesAction() async throws { + let backend = LLMBackend(name: "codex-cli", model: nil, checkAccess: { + throw LLMError.exit(1, "Not logged in\nPlease run codex login\ntoken=synthetic-secret") + }) { _, _ in Issue.record("Must not send text"); return "wrong" } + let home = Home.sandbox(languageModels: { _ in [backend] }) + let dir = try SessionFixture.make() + defer { for url in [home.url, dir] { try? FileManager.default.removeItem(at: url) } } + await Home.$scoped.withValue(home) { + let sheet = SummaryRegenerationSheet(run: { request in + try await PostProcessor.regenerateSummary(dir, request: request) + }, completion: {}) + sheet.picker.selectItem(at: 1); sheet.selectionChanged() + sheet.start(); await sheet.task?.value + #expect(sheet.status.stringValue.contains("codex login")) + #expect(!sheet.status.stringValue.contains("synthetic-secret")) + #expect(!sheet.status.stringValue.contains("LLMError")) + #expect(sheet.picker.indexOfSelectedItem == 1 && sheet.create.isEnabled) + } + } +} diff --git a/docs/testing/2026-10-22-summary-provider.md b/docs/testing/2026-10-22-summary-provider.md index b8872590..23e0ccc8 100644 --- a/docs/testing/2026-10-22-summary-provider.md +++ b/docs/testing/2026-10-22-summary-provider.md @@ -2,8 +2,9 @@ Scope: macOS Journal summary regeneration only. Existing provider integrations, credential storage, speaker naming, Windows behavior and signed release policy -remain outside this feature. The final branch must include the completed #8 -CLI-diagnostics/manual-processing change before merge and preview publication. +remain outside this feature. The branch incorporates completed #8 / PR #37 at +`fc0b8f0ac514ce80678331e7a463e4d771dd602a` through a merge commit, preserving its +history and upstream attribution. Base: `d7b82fe174d82f70630ecb3918ca6bd07dde7cd6`. ## Behavior @@ -30,12 +31,29 @@ The selected archive shares the root session claim. Summary output is replaced atomically only after a successful completion and cancellation check. Previous summary bytes survive errors and cancelled or late replies. -## Development verification +## Integration with #8 -- Baseline: 15 existing summary/egress tests passed. -- Independent implementation: full Swift run passed 1045 tests in 149 suites; - subsequent review added regressions and fixes, so this is not final combined - branch evidence. +Ordinary failed summary/naming work still supports explicit retry through the +Journal action and `verbemo process`. A one-run summary with no current output +instead reports an actionable refusal directing the user back to the provider +sheet. It cannot report successful completion or silently adopt the configured +chain. Other unfinished work can still complete. + +The sheet uses #8's signed-out classification for a safe, localized login hint. +Raw CLI output is not displayed there. Summary and naming logs only promise a +next backend when one actually exists; one-run jobs never promise a background +retry. + +## Verification + +- Combined branch: `VERBEMO_REQUIRE_LOCALVQE=1 swift test --no-parallel` passed + **1072 tests in 153 suites** (147.199 seconds). This includes the integration + fixes below, before a final naming-log wording change and its added regression. +- After that final wording change, focused diagnostics/manual-processing/naming/ + integration checks passed **31 tests in 4 suites** (15.279 seconds). +- Independent review found no blocking issues in the combined change. Its last + small finding (a single naming backend still promising fallback) was reproduced + by a failing test and fixed; that regression now passes. - Focused regressions cover immutable prompts/routes, parallel jobs, failed access, explicit retries, no configured/background fallback, selected archive/root claim, required metadata write, and cancellation of a backend that ignores cancellation. @@ -54,9 +72,20 @@ Observed in the real window: provider menu and destination disclosure; one-run Ollama generation with automatic summary disabled; refusal by fake Codex before any transcript call; explicit retry through the same Codex choice; cancellation of an in-flight Ollama reply with the prior summary still displayed. The other -meeting remained unchanged. The initial native check exposed a generic LLMError -message; final integration must replace it using #8's diagnosis. +meeting remained unchanged. + +The integrated debug bundle repeated the signed-out check: it showed a readable +Russian `codex login` instruction and retained Codex. The fake CLI generation +count stayed at 1 during failed preflight, then reached 2 after explicit retry. +Cancelling a delayed loopback response left the previous summary in place even +after the late reply, with no remaining session claim. The second meeting still +contained its original summary. + +Separate real CLI processes against another isolated home verified `process`: +legacy failed summary -> exit 0 and a generated summary; one-run pending summary +-> exit 1 with “Create a new summary”, no generated output and no route fallback. -Final combined revision, checks and release evidence will be recorded after #8 -is ready. Windows runtime, real cloud authentication and VoiceOver speech are not -established by these macOS synthetic checks. +PR #36 records exact final CI and published-preview evidence after merge. These +local checks do not establish Windows runtime, real cloud authentication or +VoiceOver speech. UI screenshot suites are opt-in and were skipped in the full +Swift run; the native checks above were performed separately.