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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) }
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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<pid_t>) -> 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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,38 @@ 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
}

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)
}

// shortcut: polling misses mute cycles between samples; qualify mute events before promising an instantaneous privacy interlock.
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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}
}
31 changes: 28 additions & 3 deletions Sources/verbemo/Meetings/CallIntegrationMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,33 @@ final class CallIntegrationMonitor {
private var providers: [any CallIntegration] = []
private var accepting = false

private var configuration: (enabled: Bool, space: String, accessibility: Bool)?
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()
lastConnection = 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]
}

Expand All @@ -32,7 +51,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 { lastConnection = state }
observations.removeAll { $0.integrationID == value.integrationID }
observations.append(value)
onChange?(observations)
Expand Down Expand Up @@ -67,8 +88,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)
}
}
Expand Down
65 changes: 65 additions & 0 deletions Sources/verbemo/Meetings/KTalkSetup.swift
Original file line number Diff line number Diff line change
@@ -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: @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 {
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 }
}
}
1 change: 1 addition & 0 deletions Sources/verbemo/Settings/ConfigKeys.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
14 changes: 9 additions & 5 deletions Sources/verbemo/Settings/SettingsSchema.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
Loading
Loading