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 3c0e3372..7d833c55 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.", "Не удалось перегенерировать сводку. Предыдущая сводка сохранена; подробности в журнале встречи.")) @@ -187,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/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 14d8582c..75d960df 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) @@ -500,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/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 6401f1f8..7ba6b997 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, [ @@ -65,9 +66,11 @@ 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() } + 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. @@ -103,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)")) } } @@ -118,21 +123,21 @@ 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: 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 new file mode 100644 index 00000000..b796bace --- /dev/null +++ b/Sources/verbemo/Summary/SummaryRequest.swift @@ -0,0 +1,78 @@ +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 { + 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() + } + + 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 c2db73e5..dfed788d 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 } @@ -1004,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/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/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/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..23e0ccc8 --- /dev/null +++ b/docs/testing/2026-10-22-summary-provider.md @@ -0,0 +1,91 @@ +# 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 branch incorporates completed #8 / PR #37 at +`fc0b8f0ac514ce80678331e7a463e4d771dd602a` through a merge commit, preserving its +history and upstream attribution. Base: `d7b82fe174d82f70630ecb3918ca6bd07dde7cd6`. + +## 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. + +## Integration with #8 + +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. +- 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 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. + +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.