From ab62b6d11eb343367466f2c9bc6e5e55021a4bec Mon Sep 17 00:00:00 2001 From: Boris Gorbylev Date: Mon, 30 Nov 2026 15:26:33 +0300 Subject: [PATCH 1/2] feat: manage KTalk startup and show verified connection status Co-authored-by: OpenAI Codex --- .../Sources/KTalkIntegration/KTalkCDP.swift | 5 ++ .../KTalkIntegration/KTalkConnection.swift | 59 +++++++++++++ .../KTalkIntegration/KTalkIntegration.swift | 19 ++++- .../KTalkConnectionTests.swift | 16 ++++ .../Meetings/CallIntegrationMonitor.swift | 24 +++++- Sources/verbemo/Meetings/KTalkSetup.swift | 65 +++++++++++++++ Sources/verbemo/Settings/ConfigKeys.swift | 1 + Sources/verbemo/Settings/SettingsSchema.swift | 14 ++-- Sources/verbemo/UI/ActivityStatusBar.swift | 22 ++++- Sources/verbemo/UI/MenuBarController.swift | 14 +++- Sources/verbemo/UI/SettingsController.swift | 82 ++++++++++++++++++- Sources/verbemo/Verbemo.swift | 56 ++++++++++++- Tests/verbemoTests/KTalkSettingsTests.swift | 74 ++++++++++++++++- docs/call-integrations.md | 14 ++-- docs/configuration.md | 6 +- 15 files changed, 440 insertions(+), 31 deletions(-) create mode 100644 Packages/CallIntegrations/Sources/KTalkIntegration/KTalkConnection.swift create mode 100644 Packages/CallIntegrations/Tests/CallIntegrationTests/KTalkConnectionTests.swift create mode 100644 Sources/verbemo/Meetings/KTalkSetup.swift diff --git a/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkCDP.swift b/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkCDP.swift index a2dcfc8..43b35d9 100644 --- a/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkCDP.swift +++ b/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkCDP.swift @@ -15,6 +15,7 @@ actor KTalkCDP { && page.user == nil && page.password == nil } } + private(set) var connection = KTalkConnection.checking private let space: URL? private let port: Int private let session: URLSession @@ -74,6 +75,9 @@ actor KTalkCDP { readings.append(reading) } guard !stopped else { return .init(participation: .unknown) } + if targets.isEmpty { connection = .waitingForSpace } + else if readings.allSatisfy({ $0.participation == .unknown && !$0.emptyWindow }) { connection = .unsupported } + else { connection = .connected } let active = readings.filter { $0.participation == .inCall } if !active.isEmpty { idleTargets = nil } if active.count > 1 { return .init(participation: .unknown) } @@ -86,6 +90,7 @@ actor KTalkCDP { idleTargets = nil return .init(participation: .unknown) } catch { + connection = .unavailable for socket in sockets.values { socket.cancel(with: .goingAway, reason: nil) } sockets.removeAll() return .init(participation: .unknown) diff --git a/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkConnection.swift b/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkConnection.swift new file mode 100644 index 0000000..3d21a8c --- /dev/null +++ b/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkConnection.swift @@ -0,0 +1,59 @@ +import AppKit +import Foundation + +public enum KTalkConnection: Error, Equatable, Sendable { + case checking, missingSpace, notInstalled, notRunning, portClosed, portConflict, inspectionFailed + case unavailable, waitingForSpace, unsupported, connected +} + +/// Inspect the listener before contacting it. The diagnostic CLI uses a synthetic +/// transport in tests; the product always supplies this check. +public actor KTalkListener { + public init() {} + private var cached: (ContinuousClock.Instant, KTalkConnection)? + public func inspect(beforeLaunch: Bool = false) async -> KTalkConnection { + if !beforeLaunch, let cached, cached.0.duration(to: .now) < .seconds(3) { return cached.1 } + let (installed, pids) = await MainActor.run { + (NSWorkspace.shared.urlForApplication(withBundleIdentifier: "kontur.talk") != nil, + Set(NSRunningApplication.runningApplications(withBundleIdentifier: "kontur.talk").map(\.processIdentifier))) + } + if !beforeLaunch && pids.isEmpty { + let result: KTalkConnection = installed ? .notRunning : .notInstalled + cached = (.now, result) + return result + } + let process = Process() + let pipe = Pipe() + process.executableURL = URL(fileURLWithPath: "/usr/sbin/lsof") + process.arguments = ["-nP", "-a", "-iTCP:9333", "-sTCP:LISTEN", "-Fpn"] + process.standardOutput = pipe + process.standardError = FileHandle.nullDevice + do { try process.run() } catch { return .inspectionFailed } + let bytes = pipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + let result = Self.classify(output: String(decoding: bytes, as: UTF8.self), exit: process.terminationStatus, + installed: installed, pids: pids) + cached = (.now, result) + return result + } + + static func classify(output: String, exit: Int32, installed: Bool, pids: Set) -> KTalkConnection { + if exit == 1 && output.isEmpty { + if pids.isEmpty { return installed ? .notRunning : .notInstalled } + return .portClosed + } + guard exit == 0 else { return .inspectionFailed } + var owner: pid_t? + var found = false + for line in output.split(separator: "\n") { + switch line.first { + case "p": owner = pid_t(line.dropFirst()) + case "n": + guard let owner, pids.contains(owner), line == "n127.0.0.1:9333" else { return .portConflict } + found = true + default: break + } + } + return found ? .connected : .inspectionFailed + } +} diff --git a/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkIntegration.swift b/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkIntegration.swift index 0ad96f9..f100e29 100644 --- a/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkIntegration.swift +++ b/Packages/CallIntegrations/Sources/KTalkIntegration/KTalkIntegration.swift @@ -9,10 +9,13 @@ public actor KTalkIntegration: CallAudioIntegration { private let accessibilityEnabled: Bool private var stopped = false private let spaceURL: URL? + public private(set) var connection = KTalkConnection.checking + private let listener: KTalkListener? private let port: Int - public init(spaceURL: URL? = nil, port: Int = 9333, accessibilityEnabled: Bool = true) throws { + public init(spaceURL: URL? = nil, port: Int = 9333, accessibilityEnabled: Bool = true, listener: KTalkListener? = nil) throws { guard (1024...65535).contains(port), spaceURL.map(KTalkModel.validSpace) ?? true else { throw ConfigurationError.invalidEndpoint } + self.listener = listener cdp = KTalkCDP(space: spaceURL, port: port) self.spaceURL = spaceURL; self.port = port self.accessibilityEnabled = accessibilityEnabled @@ -20,8 +23,8 @@ public actor KTalkIntegration: CallAudioIntegration { public enum ConfigurationError: Error { case invalidEndpoint } - public func makeAudioCapture(for callID: String) throws -> any CallAudioCapture { - guard !stopped, let spaceURL else { throw CallAudioFailure.unavailable } + public func makeAudioCapture(for callID: String) async throws -> any CallAudioCapture { + guard !stopped, let spaceURL, (await listener?.inspect() ?? .connected) == .connected else { throw CallAudioFailure.unavailable } return try KTalkAudioCapture(space: spaceURL, port: port, callID: callID) } @@ -29,7 +32,15 @@ public actor KTalkIntegration: CallAudioIntegration { public func observe() async -> CallObservation { let began = Date() guard !stopped else { return observation(.init(participation: .unknown), source: nil, at: began) } - let direct = await cdp.read() + let ownership = spaceURL == nil ? .missingSpace : await listener?.inspect() ?? .connected + let direct: KTalkReading + if ownership == .connected, spaceURL != nil { + direct = await cdp.read() + connection = await cdp.connection + } else { + direct = .init(participation: .unknown) + connection = ownership + } let fallback = direct.participation == .unknown && accessibilityEnabled ? await accessibility.read() : KTalkReading(participation: .unknown) guard !stopped else { return observation(.init(participation: .unknown), source: nil, at: began) } let (reading, source) = KTalkResolver.resolve(cdp: direct, accessibility: fallback) diff --git a/Packages/CallIntegrations/Tests/CallIntegrationTests/KTalkConnectionTests.swift b/Packages/CallIntegrations/Tests/CallIntegrationTests/KTalkConnectionTests.swift new file mode 100644 index 0000000..e321717 --- /dev/null +++ b/Packages/CallIntegrations/Tests/CallIntegrationTests/KTalkConnectionTests.swift @@ -0,0 +1,16 @@ +import Testing +@testable import KTalkIntegration + +struct KTalkConnectionTests { + @Test func listenerMustBelongExclusivelyToKTalkOnLoopback() { + func check(_ output: String, _ exit: Int32 = 0) -> KTalkConnection { + KTalkListener.classify(output: output, exit: exit, installed: true, pids: [42]) + } + #expect(check("p42\nn127.0.0.1:9333\n") == .connected) + #expect(check("p42\nn*:9333\n") == .portConflict) + #expect(check("p42\nn127.0.0.1:9333\np88\nn127.0.0.1:9333\n") == .portConflict) + #expect(check("", 1) == .portClosed) + #expect(check("", 2) == .inspectionFailed) + #expect(KTalkListener.classify(output: "", exit: 1, installed: true, pids: []) == .notRunning) + } +} diff --git a/Sources/verbemo/Meetings/CallIntegrationMonitor.swift b/Sources/verbemo/Meetings/CallIntegrationMonitor.swift index 4539f90..adef9b1 100644 --- a/Sources/verbemo/Meetings/CallIntegrationMonitor.swift +++ b/Sources/verbemo/Meetings/CallIntegrationMonitor.swift @@ -11,14 +11,26 @@ final class CallIntegrationMonitor { private var providers: [any CallIntegration] = [] private var accepting = false + private var configuration: (enabled: Bool, space: String, accessibility: Bool)? + private(set) var connection: KTalkConnection? + func reloadConfiguration() { + let next = Config.ktalkIntegration() + if let configuration, configuration == next { return } + configuration = next + stopAdmission() + tasks.removeAll() + connection = next.enabled ? .checking : nil + start(providers: Self.configuredProviders()) + } + static func configuredProviders() -> [any CallIntegration] { let settings = Config.ktalkIntegration() guard settings.enabled else { return [] } let text = settings.space let url = text.isEmpty ? nil : URL(string: text) let provider = (text.isEmpty || url != nil ? try? KTalkIntegration(spaceURL: url, - accessibilityEnabled: settings.accessibility) : nil) - ?? (try! KTalkIntegration(accessibilityEnabled: settings.accessibility)) + accessibilityEnabled: settings.accessibility, listener: KTalkListener()) : nil) + ?? (try! KTalkIntegration(accessibilityEnabled: settings.accessibility, listener: KTalkListener())) return [provider] } @@ -32,7 +44,9 @@ final class CallIntegrationMonitor { tasks.append(Task { [weak self] in while !Task.isCancelled { let value = await provider.observe() + let state = await (provider as? KTalkIntegration)?.connection guard !Task.isCancelled, let self, accepting else { break } + if let state { connection = state } observations.removeAll { $0.integrationID == value.integrationID } observations.append(value) onChange?(observations) @@ -67,8 +81,12 @@ final class CallIntegrationMonitor { let candidate = Self.directCandidate(in: observations) let id = candidate?.integrationID == observation.integrationID && candidate?.call?.id == observation.call?.id ? candidate?.call?.id : nil + let unavailable = connection return { - guard let id else { throw CallAudioFailure.unavailable } + guard let id else { + if let unavailable, unavailable != .connected { throw unavailable } + throw CallAudioFailure.unavailable + } return try await provider.makeAudioCapture(for: id) } } diff --git a/Sources/verbemo/Meetings/KTalkSetup.swift b/Sources/verbemo/Meetings/KTalkSetup.swift new file mode 100644 index 0000000..1801a20 --- /dev/null +++ b/Sources/verbemo/Meetings/KTalkSetup.swift @@ -0,0 +1,65 @@ +import AppKit +import KTalkIntegration + +extension KTalkConnection { + var detail: String { + switch self { + case .checking: localised("Checking KTalk…", "Проверяем связь с Толком…") + case .missingSpace: localised("Enter a valid KTalk space URL.", "Укажите корректный адрес пространства Толка.") + case .notInstalled: localised("KTalk is not installed.", "Толк не установлен.") + case .notRunning: localised("KTalk is closed.", "Толк закрыт.") + case .portClosed: localised("KTalk port 9333 is closed. Recording will use microphone and system audio.", "Порт Толка 9333 закрыт. Запись пойдёт с микрофона и системного звука.") + case .portConflict: localised("Port 9333 has a different owner or is exposed outside loopback.", "Порт 9333 занят другим процессом или доступен за пределами этого компьютера.") + case .inspectionFailed: localised("Could not verify the KTalk listener.", "Не удалось проверить владельца порта Толка.") + case .unavailable: localised("KTalk is not answering the direct connection.", "Толк не отвечает на запрос прямого подключения.") + case .waitingForSpace: localised("Port available. Open your configured KTalk space.", "Порт доступен. Откройте настроенное пространство Толка.") + case .unsupported: localised("KTalk replied with unsupported call data.", "Толк вернул неподдерживаемые данные звонка.") + case .connected: localised("KTalk connected. Verbemo can read the call data.", "Толк подключён. Verbemo получает данные через порт.") + } + } +} + +@MainActor +enum KTalkSetup { + static let bundleID = "kontur.talk" + + static func launch(restart: Bool, allowed: @escaping @MainActor () -> Bool, + inspect: () async -> KTalkConnection = { await KTalkListener().inspect(beforeLaunch: true) }, + quit: () async throws -> Void = quitKTalk, + open: () async throws -> Void = openKTalk) async throws { + let state = await inspect() + guard allowed() else { throw CancellationError() } + if state == .portClosed && restart { + try await quit() + } else if state != .notRunning { + throw SetupError(state.detail) + } + guard allowed(), await inspect() == .notRunning, allowed() else { + throw SetupError(localised("KTalk launch conditions changed. Check again.", "Условия запуска Толка изменились. Повторите проверку.")) + } + try await open() + } + + private static func quitKTalk() async throws { + let running = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID) + guard running.count == 1, let app = running.first, app.terminate() else { + throw SetupError(localised("Quit KTalk and try again.", "Завершите Толк и повторите попытку.")) + } + for _ in 0..<50 where !app.isTerminated { try await Task.sleep(for: .milliseconds(200)) } + guard app.isTerminated else { throw SetupError(localised("KTalk is still running.", "Толк ещё работает.")) } + } + + private static func openKTalk() async throws { + guard let url = NSWorkspace.shared.urlForApplication(withBundleIdentifier: bundleID) else { + throw SetupError(KTalkConnection.notInstalled.detail) + } + let configuration = NSWorkspace.OpenConfiguration() + configuration.arguments = ["--remote-debugging-address=127.0.0.1", "--remote-debugging-port=9333"] + _ = try await NSWorkspace.shared.openApplication(at: url, configuration: configuration) + } + + struct SetupError: LocalizedError { + let errorDescription: String? + init(_ description: String) { errorDescription = description } + } +} diff --git a/Sources/verbemo/Settings/ConfigKeys.swift b/Sources/verbemo/Settings/ConfigKeys.swift index 0628714..9ce9bbc 100644 --- a/Sources/verbemo/Settings/ConfigKeys.swift +++ b/Sources/verbemo/Settings/ConfigKeys.swift @@ -21,6 +21,7 @@ extension Config { case mcpEnabled = "mcp.enabled" case mcpPort = "mcp.port" case ktalkEnabled = "call_integrations.ktalk.enabled" + case ktalkLaunch = "call_integrations.ktalk.launch_on_start" case ktalkSpace = "call_integrations.ktalk.space_url" case ktalkAccessibility = "call_integrations.ktalk.accessibility" case onStop = "on_stop" diff --git a/Sources/verbemo/Settings/SettingsSchema.swift b/Sources/verbemo/Settings/SettingsSchema.swift index d8c7846..340c78e 100644 --- a/Sources/verbemo/Settings/SettingsSchema.swift +++ b/Sources/verbemo/Settings/SettingsSchema.swift @@ -223,15 +223,19 @@ enum SettingsSchema { Entry(["call_integrations", "ktalk", "enabled"], localised("Enable KTalk integration", "Включить интеграцию с KTalk"), localised("Detect calls and transcribe separate participant tracks, including your own. Direct recording follows mute in KTalk.", "Обнаруживать звонки и расшифровывать отдельные дорожки участников, включая вашу. Прямая запись учитывает mute в KTalk."), - .toggle, default: false, needsRestart: true), + .toggle, default: false), Entry(["call_integrations", "ktalk", "space_url"], localised("KTalk space URL", "Адрес пространства KTalk"), - localised("https://SPACE.ktalk.ru. Direct audio needs KTalk's local diagnostic port 9333. Enable it explicitly; Verbemo does not restart KTalk or open the port.", - "https://SPACE.ktalk.ru. Для прямого звука нужен локальный порт диагностики KTalk 9333. Его нужно включить явно: Verbemo не перезапускает KTalk и не открывает порт."), - .text, describedAs: localised("Without direct audio", "Без прямого звука"), needsRestart: true), + localised("Enter your KTalk space, for example https://SPACE.ktalk.ru.", + "Введите адрес своего пространства, например https://SPACE.ktalk.ru."), + .text, describedAs: localised("Without direct audio", "Без прямого звука")), Entry(["call_integrations", "ktalk", "accessibility"], localised("Detect calls with Accessibility", "Обнаруживать звонки через Универсальный доступ"), localised("Uses an existing permission when direct call data is unavailable. This detects calls but cannot provide separate audio tracks.", "Использует уже выданное разрешение, когда прямые данные недоступны. Позволяет обнаружить звонок, но не получить отдельные аудиодорожки."), - .toggle, default: true, needsRestart: true), + .toggle, default: true), + Entry(Config.Key.ktalkLaunch.path, localised("Start KTalk with Verbemo", "Запускать Толк вместе с Verbemo"), + localised("Opens KTalk with local direct audio when Verbemo starts. Turn off KTalk’s own automatic launch in its Other settings.", + "При запуске Verbemo открывает Толк с прямым звуком. Отключите собственный автозапуск Толка в его настройках → Прочие."), + .toggle, default: false), ]), Section(title: localised("Local MCP access", "Локальный доступ MCP"), entries: [ Entry(["mcp", "enabled"], localised("Local MCP access", "Локальный доступ MCP"), diff --git a/Sources/verbemo/UI/ActivityStatusBar.swift b/Sources/verbemo/UI/ActivityStatusBar.swift index fe4cec7..2e4da43 100644 --- a/Sources/verbemo/UI/ActivityStatusBar.swift +++ b/Sources/verbemo/UI/ActivityStatusBar.swift @@ -1,4 +1,5 @@ import AppKit +import KTalkIntegration struct ActivityWork { let jobs: [ProcessingOperations.Snapshot] @@ -38,6 +39,8 @@ struct ActivityAccess { var hasSelectedCalendar = true var directCallReady = false var accessibility: SetupPermissions.State? = nil + var ktalk: KTalkConnection? = nil + var ktalkCapture: String? = nil var denied: Bool { if microphone == .denied || calendar == .denied { return true } @@ -90,6 +93,7 @@ final class ActivityStatusBar: NSStackView { private let systemAccess = NSButton() private let calendarAccess = NSButton() private let accessibilityAccess = NSButton() + private let ktalkConnection = NSButton() private let messages = NSButton() private let messagePopover = NSPopover() private var serviceViews: [NSView] = [] @@ -135,6 +139,7 @@ final class ActivityStatusBar: NSStackView { (microphoneAccess, "activity.microphone-access", #selector(microphoneClicked)), (systemAccess, "activity.system-access", #selector(systemClicked)), (calendarAccess, "activity.calendar-access", #selector(calendarSettings)), + (ktalkConnection, "activity.ktalk-connection", #selector(ktalkSettings)), (accessibilityAccess, "activity.accessibility-access", #selector(ktalkSettings)), (messages, "activity.messages", #selector(showMessages)), (recording, "activity.recording", #selector(recordingClicked)), @@ -166,7 +171,7 @@ final class ActivityStatusBar: NSStackView { automatic.menu = menu automatic.target = self automatic.action = #selector(automaticClicked) - levels.setViews([microphoneAccess, mic, systemAccess, system, calendarAccess, accessibilityAccess], in: .center) + levels.setViews([microphoneAccess, mic, systemAccess, system, calendarAccess, accessibilityAccess, ktalkConnection], in: .center) levels.spacing = 4 levels.setHuggingPriority(.required, for: .horizontal) for meter in [mic, system] { meter.widthAnchor.constraint(equalToConstant: 32).isActive = true } @@ -280,13 +285,22 @@ final class ActivityStatusBar: NSStackView { func updateAccess(_ state: ActivityAccess) { let changed = accessState.microphone != state.microphone || accessState.systemAudio != state.systemAudio || accessState.calendar != state.calendar || accessState.directCallReady != state.directCallReady - || accessState.accessibility != state.accessibility + || accessState.accessibility != state.accessibility || accessState.ktalk != state.ktalk || accessState.ktalkCapture != state.ktalkCapture accessState = state automaticDestination = state.automaticDestination if changed || microphoneAccess.image == nil { refreshSources() } } private func refreshSources() { + ktalkConnection.isHidden = accessState.ktalk == nil + if let state = accessState.ktalk { + let detail = [state.detail, accessState.ktalkCapture].compactMap { $0 }.joined(separator: "\n") + source(ktalkConnection, symbol: state == .connected ? "checkmark.circle.fill" : "exclamationmark.circle", + detail: detail, caution: state != .connected) + ktalkConnection.title = "KTalk" + ktalkConnection.imagePosition = .imageLeading + if state == .connected { ktalkConnection.contentTintColor = .systemGreen } + } accessibilityAccess.isHidden = accessState.accessibility == nil if let accessibility = accessState.accessibility { source(accessibilityAccess, symbol: "accessibility", @@ -310,8 +324,8 @@ final class ActivityStatusBar: NSStackView { : systemLost ? localised("System audio signal unavailable", "Сигнал звука системы недоступен") : parts[1], caution: SetupPermissions.needsSystemAudioTest(accessState.systemAudio) || systemLost) if accessState.directCallReady { - source(microphoneAccess, symbol: "person.wave.2", detail: localised("Your audio comes from KTalk; device access is only needed for fallback.", "Ваш звук поступает из KTalk; доступ к устройству нужен только для резерва."), caution: false) - source(systemAccess, symbol: "person.2.wave.2", detail: localised("Participant audio comes from KTalk; system capture is only needed for fallback.", "Звук участников поступает из KTalk; системный захват нужен только для резерва."), caution: false) + source(microphoneAccess, symbol: "person.wave.2", detail: accessState.ktalkCapture == nil ? localised("KTalk call detected. Direct microphone audio will be checked when recording starts.", "Обнаружен звонок Толка. Прямой звук микрофона будет проверен при записи.") : localised("Your audio comes from KTalk; device access is only needed for fallback.", "Ваш звук поступает из KTalk; доступ к устройству нужен только для резерва."), caution: false) + source(systemAccess, symbol: "person.2.wave.2", detail: accessState.ktalkCapture == nil ? localised("KTalk call detected. Participant tracks will be checked when recording starts.", "Обнаружен звонок Толка. Дорожки участников будут проверены при записи.") : localised("Participant audio comes from KTalk; system capture is only needed for fallback.", "Звук участников поступает из KTalk; системный захват нужен только для резерва."), caution: false) } calendarAccess.isHidden = accessState.calendar == nil if let calendar = accessState.calendar { diff --git a/Sources/verbemo/UI/MenuBarController.swift b/Sources/verbemo/UI/MenuBarController.swift index 3ee875c..43e7a14 100644 --- a/Sources/verbemo/UI/MenuBarController.swift +++ b/Sources/verbemo/UI/MenuBarController.swift @@ -36,6 +36,7 @@ final class MenuBarController { private let pauseItem: NSMenuItem private let autoRecordItem: NSMenuItem private let autoRecordStatus: NSMenuItem + private let ktalkStatus = NSMenuItem() private let setupItem: NSMenuItem var onToggle: (() -> Void)? @@ -44,6 +45,7 @@ final class MenuBarController { var onShowMeetings: (() -> Void)? var onShowRecording: (() -> Void)? var onImport: (() -> Void)? + var onShowKTalk: (() -> Void)? var onShowSettings: (() -> Void)? var onShowSetup: (() -> Void)? var onQuit: (() -> Void)? @@ -88,6 +90,9 @@ final class MenuBarController { let settings = NSMenuItem(title: localised("Settings…", "Настройки…"), action: #selector(showSettingsClicked), keyEquivalent: ",") + ktalkStatus.isHidden = true + ktalkStatus.action = #selector(showKTalk) + menu.addItem(ktalkStatus) menu.addItem(settings) configProblemItem = NSMenuItem(title: "", action: #selector(showSettingsClicked), keyEquivalent: "") configProblemItem.isHidden = true @@ -101,7 +106,7 @@ final class MenuBarController { menu.addItem(quit) for item in [stateLabel, toggleItem, pauseItem, autoRecordItem, - autoRecordStatus, importItem, settings, configProblemItem, setupItem, meetings, quit] { + autoRecordStatus, ktalkStatus, importItem, settings, configProblemItem, setupItem, meetings, quit] { item.target = self } recordingRow.onOpen = { [weak self] in self?.statusClicked() } @@ -240,6 +245,13 @@ final class MenuBarController { } /// Keep routine detection status quiet; show only exceptions. + func updateKTalk(_ detail: String?) { + ktalkStatus.isHidden = detail == nil + if let detail { ktalkStatus.title = detail } + } + + @objc private func showKTalk() { onShowKTalk?() } + func updateAutoRecord(enabled: Bool, notice: AutoRecordController.Notice?) { autoRecordItem.state = enabled ? .on : .off autoRecordStatus.title = notice?.title ?? "" diff --git a/Sources/verbemo/UI/SettingsController.swift b/Sources/verbemo/UI/SettingsController.swift index c466c1d..eaec356 100644 --- a/Sources/verbemo/UI/SettingsController.swift +++ b/Sources/verbemo/UI/SettingsController.swift @@ -1,4 +1,5 @@ import AppKit +import KTalkIntegration /// Settings pages hosted by the application's Journal window. @MainActor @@ -15,7 +16,45 @@ final class SettingsController: NSObject, NSTextFieldDelegate { didSet { mcpSettings.controller = mcp } } private let ktalkStatus = NSTextField(wrappingLabelWithString: localised("Waiting for call information", "Ожидание сведений о звонке")) - func updateKTalkStatus(_ text: String) { ktalkStatus.stringValue = text } + private let ktalkAction = NSButton() + private var connection: KTalkConnection? + var onKTalkEnabledWithLaunchConsent: (() -> Void)? + var onKTalkLaunch: ((_ restart: Bool) -> Void)? + func updateKTalkStatus(_ text: String, connection: KTalkConnection? = nil, busy: Bool = false, blocked: Bool = false) { + self.connection = connection + ktalkStatus.stringValue = text + ktalkStatus.setAccessibilityLabel(text) + ktalkAction.isHidden = connection != .portClosed && connection != .notRunning + ktalkAction.isEnabled = !busy && !blocked + ktalkAction.title = connection == .portClosed + ? localised("Restart KTalk with direct audio…", "Перезапустить Толк с прямым звуком…") + : localised("Open KTalk with direct audio…", "Открыть Толк с прямым звуком…") + } + + private func confirmKTalk(_ title: String, detail: String) -> Bool { + let alert = NSAlert() + alert.messageText = title + alert.informativeText = detail + alert.addButton(withTitle: localised("Continue", "Продолжить")) + alert.addButton(withTitle: localised("Cancel", "Отмена")) + return alert.runModal() == .alertFirstButtonReturn + } + + private var diagnosticNotice: String { + localised("While KTalk runs, other processes on this Mac can access its session through local port 9333.", + "Пока Толк работает, другие процессы на этом Mac смогут обращаться к его сессии через локальный порт 9333.") + } + + @objc private func launchKTalk() { + let restart = connection == .portClosed + var detail = diagnosticNotice + if restart { + detail += "\n" + localised("A call might be active even if Verbemo cannot detect it. Continue only after leaving the meeting.", + "Толк может быть на встрече, даже если Verbemo её не распознал. Продолжайте только после выхода из встречи.") + } + guard confirmKTalk(ktalkAction.title, detail: detail) else { return } + onKTalkLaunch?(restart) + } var requestAccessibility: () -> Void = { SetupPermissions.requestAccessibility() } private let accessibilityAccess = AccessRow( title: localised("Accessibility", "Универсальный доступ"), @@ -223,7 +262,11 @@ final class SettingsController: NSObject, NSTextFieldDelegate { fallback.font = SetupLayout.detailFont fallback.textColor = StudioStyle.muted fallback.maximumNumberOfLines = 0 - let help = SetupLayout.box([SetupLayout.row(title: ktalkStatus), SetupLayout.row(title: fallback)]) + ktalkAction.target = self + ktalkAction.action = #selector(launchKTalk) + ktalkAction.identifier = .init("ktalk.launch") + ktalkAction.isHidden = true + let help = SetupLayout.box([SetupLayout.row(title: ktalkStatus), ktalkAction, SetupLayout.row(title: fallback)]) for view in [ktalkStatus, fallback] { view.widthAnchor.constraint(equalTo: help.widthAnchor, constant: -38).isActive = true } form.addArrangedSubview(help) help.widthAnchor.constraint(equalTo: form.widthAnchor, constant: -48).isActive = true @@ -857,6 +900,35 @@ final class SettingsController: NSObject, NSTextFieldDelegate { } } if entry.path.first == "cleanup" { operationNotice = "" } + var launchWhenClosed = false + if entry.path == Config.Key.ktalkEnabled.path, case .set(let value) = resolution, value as? Bool == true { + let alert = NSAlert() + alert.messageText = localised("Set up KTalk direct audio?", "Настроить прямой звук Толка?") + alert.informativeText = diagnosticNotice + "\n" + localised( + "Verbemo will open KTalk if it is closed. An open KTalk requires a separate restart confirmation.", + "Verbemo откроет Толк, если он закрыт. Для перезапуска открытого Толка потребуется отдельное подтверждение.") + alert.addButton(withTitle: localised("Set up direct audio", "Настроить прямой звук")) + alert.addButton(withTitle: localised("Enable detection only", "Включить без запуска")) + alert.addButton(withTitle: localised("Cancel", "Отмена")) + switch alert.runModal() { + case .alertFirstButtonReturn: launchWhenClosed = true + case .alertSecondButtonReturn: break + default: refresh(); return + } + } + if entry.path == Config.Key.ktalkLaunch.path, case .set(let value) = resolution, value as? Bool == true { + guard Config.ktalkIntegration().enabled else { + operationNotice = localised("Enable KTalk integration first.", "Сначала включите интеграцию с Толком.") + refresh(); return + } + guard confirmKTalk(localised("Start KTalk with Verbemo at login?", "Запускать Толк вместе с Verbemo при входе?"), detail: diagnosticNotice + "\n" + localised("This also enables Verbemo’s login item. You can change it under General.", "Будет включён и автозапуск Verbemo. Его можно изменить в основных настройках.")) else { refresh(); return } + do { + let status = LoginItem.status() == .notRegistered ? try LoginItem.register() : LoginItem.status() + if status == .needsApproval { LoginItem.openSettings() } + if status == .unavailable { throw KTalkSetup.SetupError(localised("Install Verbemo in Applications first.", "Сначала установите Verbemo в Программы.")) } + operationNotice = "" + } catch { operationNotice = error.localizedDescription; refresh(); return } + } switch resolution { @@ -865,6 +937,12 @@ final class SettingsController: NSObject, NSTextFieldDelegate { case .invalid: return } + if launchWhenClosed && Config.ktalkIntegration().enabled { onKTalkEnabledWithLaunchConsent?() } + if entry.path == Config.Key.ktalkEnabled.path, !Config.ktalkIntegration().enabled { + Config.update(path: Config.Key.ktalkLaunch.path, value: nil) + operationNotice = localised("Quit KTalk to close an open diagnostic port.", "Чтобы закрыть открытый диагностический порт, завершите Толк.") + } + if entry.needsRestart { restartNotice = localised( "“\(entry.label)” applies the next time verbemo starts.", diff --git a/Sources/verbemo/Verbemo.swift b/Sources/verbemo/Verbemo.swift index 6b3195a..fd55911 100644 --- a/Sources/verbemo/Verbemo.swift +++ b/Sources/verbemo/Verbemo.swift @@ -295,6 +295,10 @@ final class AppController { private let calendar: CalendarWatcher private let autoRecord: AutoRecordController private let callIntegrations = CallIntegrationMonitor() + private var ktalkLaunchTask: Task? + private var ktalkLaunchError: String? + private enum KTalkLaunchRequest { case enable, startup } + private var pendingKTalkLaunch: KTalkLaunchRequest? private var session: RecordingSession? private var recordingCleanup: Task? /// Whether a meeting is being recorded. The session itself stays private — @@ -432,6 +436,10 @@ final class AppController { self.window.bringToFront() } menuBar.onImport = { [weak self] in self?.chooseMediaToImport() } + menuBar.onShowKTalk = { [weak self] in + self?.window.navigate(.ktalk) + self?.window.bringToFront() + } menuBar.onShowSettings = { [weak self] in self?.showSettings() } menuBar.onShowSetup = { [weak self] in self?.showSetup() } window.onCheckForUpdates = { [weak self] in self?.checkForUpdates() } @@ -480,6 +488,8 @@ final class AppController { window.updateLivePreference(enabled: Config.liveTranscriptionEnabled()) if Config.showWindowAtLaunch(), !SetupState.isPending { window.show() } + window.settings.onKTalkEnabledWithLaunchConsent = { [weak self] in self?.pendingKTalkLaunch = .enable } + window.settings.onKTalkLaunch = { [weak self] restart in self?.launchKTalk(restart: restart) } autoRecord.currentSession = { [weak self] in self?.session } callIntegrations.onChange = { [weak self] observations in self?.autoRecord.observeCallBoundary(observations) @@ -531,6 +541,7 @@ final class AppController { self?.showConfigProblems() // auto_record.enabled is written by Settings, the setup form, // the menu and the status window alike, and obeyed from here. + self?.callIntegrations.reloadConfiguration() self?.autoRecord.reloadSettings() self?.showAutoRecord() self?.mcp.refresh() @@ -569,7 +580,8 @@ final class AppController { // permission sent an existing installation back to setup. Watching a // call must not wait for that window or for a calendar permission // prompt. The watcher itself waits for an already-granted microphone. - callIntegrations.start(providers: CallIntegrationMonitor.configuredProviders()) + pendingKTalkLaunch = Config.ktalkIntegration().enabled && Config.flag(.ktalkLaunch, in: Config.raw()) ? .startup : nil + callIntegrations.reloadConfiguration() autoRecord.start() showAutoRecord() if SetupState.isPending { @@ -792,6 +804,7 @@ final class AppController { mcp.stopAdmission() ticker?.invalidate(); ticker = nil autoRecord.stop() + ktalkLaunchTask?.cancel() callIntegrations.stopAdmission() network?.stop(); network = nil settingsApplier = nil @@ -861,9 +874,40 @@ final class AppController { showAutoRecord() } + private var ktalkLaunchAllowed: Bool { + !isStopping && session == nil && !callIntegrations.observations.contains { $0.participation == .inCall } + && Config.ktalkIntegration().enabled + } + + private func launchKTalk(restart: Bool) { + guard ktalkLaunchTask == nil, ktalkLaunchAllowed else { return } + ktalkLaunchError = nil + ktalkLaunchTask = Task { [weak self] in + guard let self else { return } + defer { ktalkLaunchTask = nil; if !isStopping { showAutoRecord() } } + do { + try await KTalkSetup.launch(restart: restart) { !Task.isCancelled && self.ktalkLaunchAllowed } + } catch is CancellationError { + return + } catch { ktalkLaunchError = error.localizedDescription } + } + } + private func showAutoRecord() { let automatic = Config.autoRecord() let ktalk = Config.ktalkIntegration() + let connection = ktalk.enabled ? callIntegrations.connection : nil + if !ktalk.enabled { + pendingKTalkLaunch = nil + ktalkLaunchError = nil + ktalkLaunchTask?.cancel() + } else if pendingKTalkLaunch == .startup && !Config.flag(.ktalkLaunch, in: Config.raw()) { + pendingKTalkLaunch = nil + } + if pendingKTalkLaunch != nil, let connection, connection != .checking, connection != .missingSpace { + pendingKTalkLaunch = nil + if connection == .notRunning { launchKTalk(restart: false) } + } let accessibility = SetupPermissions.accessibility() let calendarPermission = SetupPermissions.calendar() let access = ActivityAccess( @@ -874,8 +918,14 @@ final class AppController { micActivity: automatic.micActivity, autoCalendar: automatic.calendar, hasSelectedCalendar: !automatic.calendar || automatic.micActivity || !calendar.selectedCalendars().isEmpty, directCallReady: session.map { $0.captureSource == .direct } ?? callIntegrations.directCallReady, - accessibility: ktalk.enabled && ktalk.accessibility ? accessibility : nil) - window.settings.updateKTalkStatus(session?.captureSource.title ?? callIntegrations.statusText) + accessibility: ktalk.enabled && ktalk.accessibility ? accessibility : nil, + ktalk: connection, ktalkCapture: session?.captureSource.title) + let restartBlocked = connection == .portClosed && !ktalkLaunchAllowed + let status = [connection?.detail ?? callIntegrations.statusText, session?.captureSource.title, + restartBlocked ? localised("Restart is available after the call and recording end.", "Перезапуск доступен после окончания встречи и записи.") : nil, + connection == .connected ? nil : ktalkLaunchError].compactMap { $0 }.joined(separator: "\n") + menuBar.updateKTalk(connection?.detail) + window.settings.updateKTalkStatus(status, connection: connection, busy: ktalkLaunchTask != nil, blocked: !ktalkLaunchAllowed) window.settings.updateAccessibility(accessibility) let decision = autoRecord.enabled ? access.automaticBlockReason ?? autoRecord.notice?.title ?? autoRecord.lastDecision : nil menuBar.updateAutoRecord(enabled: autoRecord.enabled, notice: autoRecord.notice) diff --git a/Tests/verbemoTests/KTalkSettingsTests.swift b/Tests/verbemoTests/KTalkSettingsTests.swift index b138166..d700293 100644 --- a/Tests/verbemoTests/KTalkSettingsTests.swift +++ b/Tests/verbemoTests/KTalkSettingsTests.swift @@ -1,5 +1,6 @@ import AppKit import Testing +import KTalkIntegration @testable import verbemo @Suite(.serialized) @MainActor @@ -23,7 +24,7 @@ struct KTalkSettingsTests { let content = app.settings.content(for: destination) for entry in SettingsSchema.sections.flatMap(\.entries) where entry.path.first == "call_integrations" { #expect(SettingsPage.destination(for: entry.path) == destination) - #expect(entry.needsRestart) + #expect(!entry.needsRestart) let key = entry.path.joined(separator: ".") let control = try #require(content.allDescendants.first { $0.identifier?.rawValue == key }) #expect(!control.isHiddenOrHasHiddenAncestor) @@ -33,6 +34,77 @@ struct KTalkSettingsTests { #expect(Config.ktalkIntegration().space == "https://synthetic.ktalk.ru") } + @Test(.freshHome, .speaking(.russian)) func connectionStatusIsVisibleAndActionableBeforeACall() throws { + let app = ApplicationWindow() + defer { _ = app.stopForTermination() } + let page = app.settings.content(for: .ktalk) + let label = try #require(page.allDescendants.first { $0.identifier?.rawValue == "ktalk.status" } as? NSTextField) + let launch = try #require(page.allDescendants.first { $0.identifier?.rawValue == "ktalk.launch" } as? NSButton) + app.navigate(.ktalk) + let bar = try #require(app.panel.contentView?.allDescendants.first { $0 is ActivityStatusBar } as? ActivityStatusBar) + app.panel.orderFront(nil) + defer { app.panel.orderOut(nil) } + let badge = try #require(bar.allDescendants.first { $0.identifier?.rawValue == "activity.ktalk-connection" } as? NSButton) + var destination: ApplicationNavigationState.Destination? + bar.onAccess = { destination = $0 } + for state in [KTalkConnection.portClosed, .waitingForSpace, .connected, .portConflict] { + app.settings.updateKTalkStatus(state.detail, connection: state) + bar.updateAccess(.init(microphone: .denied, systemAudio: nil, calendar: nil, ktalk: state)) + for appearance in [NSAppearance.Name.aqua, .darkAqua] { + app.panel.appearance = NSAppearance(named: appearance) + app.panel.setContentSize(.init(width: 760, height: 640)) + app.panel.contentView?.layoutSubtreeIfNeeded() + let frame = badge.convert(badge.bounds, to: bar) + #expect(frame.width > 0 && frame.minX >= 0 && frame.maxX <= bar.bounds.width) + #expect(badge.acceptsFirstResponder) + } + #expect(label.stringValue == state.detail) + #expect(!badge.isHidden && badge.accessibilityLabel() == state.detail) + #expect(badge.title == "KTalk") + #expect(launch.isHidden == (state != .portClosed)) + #expect(badge.contentTintColor == (state == .connected ? .systemGreen : .systemOrange)) + } + #expect(badge.sendAction(badge.action, to: badge.target)) + #expect(destination == .ktalk) + app.settings.updateKTalkStatus(KTalkConnection.portClosed.detail, connection: .portClosed, blocked: true) + #expect(!launch.isEnabled) + bar.updateAccess(.init(microphone: .denied, systemAudio: nil, calendar: nil)) + #expect(badge.isHidden) + } + + @Test func managedLaunchRechecksTheListenerAndNeverRestartsOnItsOwn() async { + for (state, restart, finalState, busy, expected) in [ + (KTalkConnection.portClosed, false, KTalkConnection.notRunning, false, [String]()), + (.portClosed, true, .notRunning, false, ["quit", "open"]), + (.portClosed, true, .notRunning, true, []), + (.portConflict, true, .portConflict, false, []), + (.portClosed, true, .portConflict, false, ["quit"]), + (.notRunning, false, .notRunning, false, ["open"]) + ] { + var actions: [String] = [] + var results = [state, finalState] + do { + try await KTalkSetup.launch(restart: restart, allowed: { !busy }, + inspect: { results.removeFirst() }, quit: { actions.append("quit") }, open: { actions.append("open") }) + #expect(expected.last == "open") + } catch { #expect(expected.last != "open") } + #expect(actions == expected) + } + } + + @Test(.freshHome) func monitorAppliesChangesWithoutRestart() async { + let monitor = CallIntegrationMonitor() + monitor.reloadConfiguration() + #expect(monitor.connection == nil) + Config.update(path: Config.Key.ktalkEnabled.path, value: true) + monitor.reloadConfiguration() + #expect(monitor.connection == .checking) + Config.update(path: Config.Key.ktalkEnabled.path, value: nil) + monitor.reloadConfiguration() + #expect(monitor.connection == nil && monitor.observations.isEmpty) + await monitor.stop() + } + @Test(.freshHome) func directReadinessDoesNotWarnAboutUnusedDevices() throws { let bar = ActivityStatusBar() bar.updateAccess(.init(microphone: .denied, systemAudio: nil, calendar: nil, directCallReady: true)) diff --git a/docs/call-integrations.md b/docs/call-integrations.md index 6ac392a..8d5e743 100644 --- a/docs/call-integrations.md +++ b/docs/call-integrations.md @@ -18,7 +18,7 @@ Providers own their transport lifecycle and must return unknown on failure. Set `call_integrations.ktalk.enabled` to true and, for CDP, set `space_url` to an exact HTTPS space origin. Settings have their own **KTalk integration** / -**Интеграция с KTalk** page and require restarting Verbemo. Accessibility +**Интеграция с KTalk** page and take effect immediately. Accessibility permission is optional. Its permission row shows the current macOS grant and provides an **Allow…** action that requests access and opens the appropriate System Settings pane. Grant the permission there; Verbemo refreshes the state @@ -27,10 +27,14 @@ when returning to the app and during its regular status updates. When KTalk integration and Accessibility detection are enabled, the status bar also shows an Accessibility icon. Missing access is highlighted; clicking it opens KTalk settings. Checking or displaying the state never requests access. -The adapter never opens a debug port, changes installed KTalk files, reads session -tokens, joins a call, or requests system permission automatically. To use CDP, -fully quit KTalk and explicitly start it with the diagnostic flags used in the -research: +The connection indicator in Settings and the status bar follows the configured +space. It confirms a KTalk-owned loopback listener and a successful call-data +query. Recording source is shown separately. Open or restart KTalk from Settings +after leaving any meeting. The launch confirmation explains the local session +access. Optional startup uses Verbemo’s existing macOS login item. Turn off +KTalk’s own automatic launch in its Other settings to avoid a startup race. +Disabling integration stops observation; quit KTalk to close its listener. +The equivalent manual launch after quitting KTalk is: ```sh open -a '/Applications/Толк.app' --args --remote-debugging-address=127.0.0.1 --remote-debugging-port=9333 diff --git a/docs/configuration.md b/docs/configuration.md index 7069ea2..365d592 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -352,10 +352,10 @@ existing `call_integrations.ktalk.enabled` flag (default `false`). It enables ca detection and separate audio tracks for each participant, including your own outgoing track. `call_integrations.ktalk.space_url` (default empty) is the exact `https://SPACE.ktalk.ru` origin. Direct audio requires an explicitly enabled -loopback diagnostic (CDP) port **9333**. Verbemo does not open the port or restart -KTalk. `call_integrations.ktalk.accessibility` (default `true`) permits call +loopback diagnostic (CDP) port **9333**. Launch or restart KTalk from integration settings after leaving any meeting. +Enable `call_integrations.ktalk.launch_on_start` to launch a closed KTalk with Verbemo. `call_integrations.ktalk.accessibility` (default `true`) permits call observation through existing Accessibility permission; it cannot supply audio. -These three settings take effect after restarting Verbemo. +Observation settings apply immediately. The startup option applies when Verbemo launches. Direct mode captures KTalk's existing tracks without starting Verbemo's microphone or system-audio capture. Your track follows mute in KTalk; mute means silence, From 7ab24038ecce5456488159eb619de8b0432abd48 Mon Sep 17 00:00:00 2001 From: Boris Gorbylev Date: Mon, 30 Nov 2026 15:31:42 +0300 Subject: [PATCH 2/2] fix: expire stale KTalk readiness and isolate setup callbacks Co-authored-by: OpenAI Codex --- .../verbemo/Meetings/CallIntegrationMonitor.swift | 13 ++++++++++--- Sources/verbemo/Meetings/KTalkSetup.swift | 6 +++--- Sources/verbemo/UI/SettingsController.swift | 2 +- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/Sources/verbemo/Meetings/CallIntegrationMonitor.swift b/Sources/verbemo/Meetings/CallIntegrationMonitor.swift index adef9b1..0087103 100644 --- a/Sources/verbemo/Meetings/CallIntegrationMonitor.swift +++ b/Sources/verbemo/Meetings/CallIntegrationMonitor.swift @@ -12,14 +12,21 @@ final class CallIntegrationMonitor { private var accepting = false private var configuration: (enabled: Bool, space: String, accessibility: Bool)? - private(set) var connection: KTalkConnection? + private var lastConnection: KTalkConnection? + var connection: KTalkConnection? { + if lastConnection == .connected, + !observations.contains(where: { $0.integrationID == "ktalk" && (0...5).contains(Date().timeIntervalSince($0.observedAt)) }) { + return .unavailable + } + return lastConnection + } func reloadConfiguration() { let next = Config.ktalkIntegration() if let configuration, configuration == next { return } configuration = next stopAdmission() tasks.removeAll() - connection = next.enabled ? .checking : nil + lastConnection = next.enabled ? .checking : nil start(providers: Self.configuredProviders()) } @@ -46,7 +53,7 @@ final class CallIntegrationMonitor { let value = await provider.observe() let state = await (provider as? KTalkIntegration)?.connection guard !Task.isCancelled, let self, accepting else { break } - if let state { connection = state } + if let state { lastConnection = state } observations.removeAll { $0.integrationID == value.integrationID } observations.append(value) onChange?(observations) diff --git a/Sources/verbemo/Meetings/KTalkSetup.swift b/Sources/verbemo/Meetings/KTalkSetup.swift index 1801a20..bd90ac5 100644 --- a/Sources/verbemo/Meetings/KTalkSetup.swift +++ b/Sources/verbemo/Meetings/KTalkSetup.swift @@ -24,9 +24,9 @@ enum KTalkSetup { static let bundleID = "kontur.talk" static func launch(restart: Bool, allowed: @escaping @MainActor () -> Bool, - inspect: () async -> KTalkConnection = { await KTalkListener().inspect(beforeLaunch: true) }, - quit: () async throws -> Void = quitKTalk, - open: () async throws -> Void = openKTalk) async throws { + inspect: @MainActor () async -> KTalkConnection = { await KTalkListener().inspect(beforeLaunch: true) }, + quit: @MainActor () async throws -> Void = quitKTalk, + open: @MainActor () async throws -> Void = openKTalk) async throws { let state = await inspect() guard allowed() else { throw CancellationError() } if state == .portClosed && restart { diff --git a/Sources/verbemo/UI/SettingsController.swift b/Sources/verbemo/UI/SettingsController.swift index eaec356..8ae945a 100644 --- a/Sources/verbemo/UI/SettingsController.swift +++ b/Sources/verbemo/UI/SettingsController.swift @@ -908,7 +908,7 @@ final class SettingsController: NSObject, NSTextFieldDelegate { "Verbemo will open KTalk if it is closed. An open KTalk requires a separate restart confirmation.", "Verbemo откроет Толк, если он закрыт. Для перезапуска открытого Толка потребуется отдельное подтверждение.") alert.addButton(withTitle: localised("Set up direct audio", "Настроить прямой звук")) - alert.addButton(withTitle: localised("Enable detection only", "Включить без запуска")) + alert.addButton(withTitle: localised("Enable without launching KTalk", "Включить без запуска")) alert.addButton(withTitle: localised("Cancel", "Отмена")) switch alert.runModal() { case .alertFirstButtonReturn: launchWhenClosed = true