From 62810ae3884b59801d830e346ec08f71a7a2d650 Mon Sep 17 00:00:00 2001 From: Boris Gorbylev Date: Mon, 30 Nov 2026 13:20:49 +0300 Subject: [PATCH 1/3] fix: split automatic recordings when KTalk changes rooms Co-authored-by: OpenAI Codex --- .../Meetings/AutoRecordController.swift | 74 ++++++++++ Sources/verbemo/Verbemo.swift | 6 +- .../CallIntegrationRecordingTests.swift | 130 ++++++++++++++++++ 3 files changed, 209 insertions(+), 1 deletion(-) diff --git a/Sources/verbemo/Meetings/AutoRecordController.swift b/Sources/verbemo/Meetings/AutoRecordController.swift index 76e501d..26c8b0c 100644 --- a/Sources/verbemo/Meetings/AutoRecordController.swift +++ b/Sources/verbemo/Meetings/AutoRecordController.swift @@ -127,6 +127,10 @@ final class AutoRecordController { private var currentCall: CallObservation? private var trackedCall: CallObservation? private var pendingCallID: String? + private weak var boundarySession: (any AutoRecordedSession)? + private var boundaryCall: CallObservation? + private var sawCallExit = false + private var handoff: (integration: String, previousEvent: CalendarWatcher.Meeting?)? private var callUnknown = false private let now: () -> Date private var timer: Timer? @@ -243,6 +247,7 @@ final class AutoRecordController { micActiveSince = nil startFailures = 0 if !newValue { + handoff = nil notice = nil if phase != .recording { phase = .watching } lastDecision = localised("auto-record off", "автозапись выключена") @@ -260,6 +265,7 @@ final class AutoRecordController { /// The user started a recording by hand — don't treat it as ours. func noteManualStart() { + handoff = nil currentEvent = calendar?.bestMatch(for: now()) trackedCall = nil phase = .watching @@ -269,6 +275,7 @@ final class AutoRecordController { /// don't want it recorded; stay out of the way until that call actually /// ends, and consider the current calendar event dealt with. func noteManualStop() { + handoff = nil if let recorded = currentSession?()?.integrationCall ?? trackedCall { let stoppedAt = now() // The user may press Stop after already joining the next meeting. @@ -292,6 +299,7 @@ final class AutoRecordController { /// from before would otherwise read the sleep as the mic being held, and /// start a recording on the first tick after wake. func noteSystemSleep() { + handoff = nil micActiveSince = nil micIdleSince = nil } @@ -320,6 +328,7 @@ final class AutoRecordController { return } + guard handoff == nil else { return } let observations = callObservations() var micSettings = settings // Unavailable integration data must leave ordinary call detection usable. @@ -360,6 +369,71 @@ final class AutoRecordController { } } + /// Called before the session consumes the same observation. A replacement + /// room must never update the old recording's title or participants. + func observeCallBoundary(_ observations: [CallObservation]) { + guard enabled, handoff == nil, let session = currentSession?(), session.trigger != .manual else { return } + if boundarySession !== session { + boundarySession = session + boundaryCall = nil + sawCallExit = false + } + guard let original = boundaryCall ?? session.integrationCall ?? trackedCall, + let value = observations.first(where: { $0.integrationID == original.integrationID }), + (0...5).contains(now().timeIntervalSince(value.observedAt)) else { return } + if value.participation == .idle { + sawCallExit = true + return + } + guard value.participation == .inCall, let previous = original.call, let next = value.call else { return } + + // Prefer the room address: AX can reuse a window across rooms and + // the application can replace its conference or window ID on rejoin. + let changed: Bool + if let previousURL = previous.url, let nextURL = next.url { + changed = previousURL.host?.lowercased() != nextURL.host?.lowercased() + || previousURL.path.split(separator: "/") != nextURL.path.split(separator: "/") + } else if original.source == value.source, value.source != nil { + let previousID = previous.participationID ?? previous.id + let nextID = next.participationID ?? next.id + let rejoinedWithoutAddress = sawCallExit && previous.url == nil && next.url == nil + && previous.participationID == nil && next.participationID == nil + changed = !previousID.isEmpty && !nextID.isEmpty && (previousID != nextID || rejoinedWithoutAddress) + } else { + return + } + sawCallExit = false + if changed { + handoff = (value.integrationID, currentEvent) + stop("call-changed") + } else if next.url != nil || previous.url == nil { + boundaryCall = value + } + } + + /// The audio devices are free now. Read the latest observation again in + /// case the user left the new room while the previous capture drained. + func resumeAfterCallChange() { + guard let handoff else { return } + self.handoff = nil + let settings = loadSettings() + let time = now() + guard settings.enabled, currentSession?() == nil, canStartRecording() else { return } + let signal = CallIntegrationBridge.signal(microphone: .init(active: false, names: [], families: [], allHolders: []), + observations: callObservations(), settings: settings, now: time) + guard let joined = signal.observation, joined.integrationID == handoff.integration else { return } + var event = calendar?.bestMatch(for: time) + if let previous = handoff.previousEvent, let match = event, + Self.occurrenceKey(previous) == Self.occurrenceKey(match) { event = nil } + guard settings.micActivity || (settings.calendar && event != nil) else { return } + var context = MeetingContext(meeting: event, app: joined.application.name, appFamilies: [joined.application.bundleID]) + context.applyCall(joined) + if attemptStart(settings.micActivity ? .micActivity : .calendar, context, now: time) { + currentEvent = event + if let event { markHandled(event) } + } + } + private func observe(_ session: AutoRecordedSession, mic: MicActivityMonitor.Result) { let id = ObjectIdentifier(session) if observedSession != id { diff --git a/Sources/verbemo/Verbemo.swift b/Sources/verbemo/Verbemo.swift index e02c4a8..6b3195a 100644 --- a/Sources/verbemo/Verbemo.swift +++ b/Sources/verbemo/Verbemo.swift @@ -481,7 +481,10 @@ final class AppController { if Config.showWindowAtLaunch(), !SetupState.isPending { window.show() } autoRecord.currentSession = { [weak self] in self?.session } - callIntegrations.onChange = { [weak self] in self?.session?.updateCallObservation($0) } + callIntegrations.onChange = { [weak self] observations in + self?.autoRecord.observeCallBoundary(observations) + self?.session?.updateCallObservation(observations) + } autoRecord.startRecording = { [weak self] trigger, context in self?.startSession(trigger: trigger, context: context) ?? false } @@ -1091,6 +1094,7 @@ final class AppController { let cleanup = Task { [weak self] in await session.finishCapture() self?.recordingCleanup = nil + if reason == "call-changed", let self, !isStopping { autoRecord.resumeAfterCallChange() } } recordingCleanup = cleanup let duration = Date().timeIntervalSince(session.startedAt) diff --git a/Tests/verbemoTests/CallIntegrationRecordingTests.swift b/Tests/verbemoTests/CallIntegrationRecordingTests.swift index 44b0ad5..ec6baa7 100644 --- a/Tests/verbemoTests/CallIntegrationRecordingTests.swift +++ b/Tests/verbemoTests/CallIntegrationRecordingTests.swift @@ -110,6 +110,136 @@ struct CallIntegrationRecordingTests { #expect(controller.notice == nil) } + @Test(arguments: [true, false]) + func activeRecordingMovesToTheNextRoom(reusedWindow: Bool) { + let now = Date() + var settings = Config.AutoRecordSettings() + settings.calendar = false + var reading = observation(date: now, id: "window-A") + reading.source = .accessibility + if reusedWindow { reading.call?.url = URL(string: "https://example.ktalk.ru/a") } + var session: FakeAutoSession? = FakeAutoSession(startedAt: now, trigger: .micActivity) + session?.integrationCall = reading + let controller = AutoRecordController(settings: settings, calendar: nil, loadSettings: { settings }, + now: { now }, callObservations: { [reading] }) + controller.currentSession = { session } + var stops: [String] = [] + var starts: [CallObservation?] = [] + controller.stopRecording = { stops.append($0); session = nil } + controller.startRecording = { _, context in starts.append(context.callObservation); return true } + + controller.observeCallBoundary([reading]) + var unknown = reading + unknown.participation = .unknown + controller.observeCallBoundary([unknown]) + controller.observeCallBoundary([reading]) + #expect(stops.isEmpty) + + if reusedWindow { + reading.call?.url = URL(string: "https://example.ktalk.ru/b") + } else { + var idle = reading + idle.participation = .idle + controller.observeCallBoundary([idle]) + } + controller.observeCallBoundary([reading]) + controller.observeCallBoundary([reading]) + #expect(stops == ["call-changed"]) + #expect(starts.isEmpty) + controller.resumeAfterCallChange() + controller.resumeAfterCallChange() + #expect(starts == [reading]) + } + + @Test func reconnectAndSourceChangesKeepRecordingUntilAnotherRoomIsConfirmed() { + let now = Date() + let settings = Config.AutoRecordSettings() + var reading = observation(date: now, id: "conference") + reading.call?.url = URL(string: "https://example.ktalk.ru/a") + let session = FakeAutoSession(startedAt: now, trigger: .micActivity) + session.integrationCall = reading + let controller = AutoRecordController(settings: settings, calendar: nil, loadSettings: { settings }, + now: { now }, callObservations: { [reading] }) + controller.currentSession = { session } + var stops: [String] = [] + controller.stopRecording = { stops.append($0) } + controller.observeCallBoundary([reading]) + reading.participation = .idle + controller.observeCallBoundary([reading]) + reading.participation = .inCall + reading.source = .accessibility + reading.call?.id = "replacement-window" + reading.call?.url = nil + controller.observeCallBoundary([reading]) + reading.call?.url = URL(string: "ktalk://example.ktalk.ru/a") + controller.observeCallBoundary([reading]) + reading.call?.url = URL(string: "ktalk://example.ktalk.ru/b") + reading.observedAt = now.addingTimeInterval(-10) + controller.observeCallBoundary([reading]) + #expect(stops.isEmpty) + reading.observedAt = now + controller.observeCallBoundary([reading]) + #expect(stops == ["call-changed"]) + } + + @Test func roomSwitchWritesTwoRecordingsWithTheirOwnMeetingContext() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let now = Date() + var settings = Config.AutoRecordSettings() + settings.calendar = false + settings.startDelay = 0 + let calendar = FakeCalendar() + calendar.meetings = [.meeting(id: "scheduled-first-room", start: now)] + var reading = observation(date: now, id: "first") + var active: RecordingSession? + var sessions: [RecordingSession] = [] + let controller = AutoRecordController(settings: settings, calendar: calendar, loadSettings: { settings }, + checkMic: { _ in .init(active: false, names: [], families: [], allHolders: []) }, + now: { now }, callObservations: { [reading] }) + controller.currentSession = { active } + controller.startRecording = { trigger, context in + do { + let session = try RecordingSession(root: root, context: context, trigger: trigger, + mic: FakeMicRecorder(), system: FakeSystemRecorder()) + try session.start(systemAudioScope: "all") + sessions.append(session) + active = session + return true + } catch { + Issue.record(error) + return false + } + } + controller.stopRecording = { reason in + #expect(active?.stop(reason: reason) == true) + active = nil + } + controller.tick() + let first = try #require(active) + reading = observation(date: now, id: "second") + reading.call?.title = "Second room" + controller.observeCallBoundary([reading]) + active?.updateCallObservation([reading]) + await first.finishCapture() + controller.resumeAfterCallChange() + let second = try #require(active) + #expect(second.stop()) + await second.finishCapture() + #expect(sessions.count == 2) + #expect(first.dir != second.dir) + func metadata(_ session: RecordingSession) throws -> [String: Any] { + let bytes = try Data(contentsOf: session.dir.appendingPathComponent("meta.json")) + return try #require(try JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + } + let firstMeta = try metadata(first) + let secondMeta = try metadata(second) + #expect(firstMeta["title"] as? String == "Weekly") + #expect(firstMeta["stop_reason"] as? String == "call-changed") + #expect(secondMeta["title"] as? String == "Second room") + #expect(secondMeta["calendar"] == nil) + } + @Test func asynchronousCaptureFailureUsesTheAutomaticStartBackoff() { let h = AutoRecordHarness() h.micActive = true From 9cfa89f7b96ef7dfd348a9c7d810e87e8f510760 Mon Sep 17 00:00:00 2001 From: Boris Gorbylev Date: Mon, 30 Nov 2026 13:22:33 +0300 Subject: [PATCH 2/3] fix: track comparable room IDs across KTalk observation sources Co-authored-by: OpenAI Codex --- .../Meetings/AutoRecordController.swift | 28 +++++++++++-------- .../CallIntegrationRecordingTests.swift | 18 ++++++++++++ 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/Sources/verbemo/Meetings/AutoRecordController.swift b/Sources/verbemo/Meetings/AutoRecordController.swift index 26c8b0c..178e1b9 100644 --- a/Sources/verbemo/Meetings/AutoRecordController.swift +++ b/Sources/verbemo/Meetings/AutoRecordController.swift @@ -128,7 +128,8 @@ final class AutoRecordController { private var trackedCall: CallObservation? private var pendingCallID: String? private weak var boundarySession: (any AutoRecordedSession)? - private var boundaryCall: CallObservation? + private var roomURL: URL? + private var roomBySource: [CallObservationSource: CallInfo] = [:] private var sawCallExit = false private var handoff: (integration: String, previousEvent: CalendarWatcher.Meeting?)? private var callUnknown = false @@ -373,41 +374,46 @@ final class AutoRecordController { /// room must never update the old recording's title or participants. func observeCallBoundary(_ observations: [CallObservation]) { guard enabled, handoff == nil, let session = currentSession?(), session.trigger != .manual else { return } + guard let original = session.integrationCall ?? trackedCall, let originalCall = original.call else { return } if boundarySession !== session { boundarySession = session - boundaryCall = nil + roomURL = originalCall.url + roomBySource.removeAll() + if let source = original.source { roomBySource[source] = originalCall } sawCallExit = false } - guard let original = boundaryCall ?? session.integrationCall ?? trackedCall, - let value = observations.first(where: { $0.integrationID == original.integrationID }), + guard let value = observations.first(where: { $0.integrationID == original.integrationID }), (0...5).contains(now().timeIntervalSince(value.observedAt)) else { return } if value.participation == .idle { sawCallExit = true return } - guard value.participation == .inCall, let previous = original.call, let next = value.call else { return } + guard value.participation == .inCall, let source = value.source, let next = value.call else { return } // Prefer the room address: AX can reuse a window across rooms and // the application can replace its conference or window ID on rejoin. let changed: Bool - if let previousURL = previous.url, let nextURL = next.url { + if let previousURL = roomURL, let nextURL = next.url { changed = previousURL.host?.lowercased() != nextURL.host?.lowercased() || previousURL.path.split(separator: "/") != nextURL.path.split(separator: "/") - } else if original.source == value.source, value.source != nil { + } else if let previous = roomBySource[source] { let previousID = previous.participationID ?? previous.id let nextID = next.participationID ?? next.id - let rejoinedWithoutAddress = sawCallExit && previous.url == nil && next.url == nil + let rejoinedWithoutAddress = sawCallExit && roomURL == nil && next.url == nil && previous.participationID == nil && next.participationID == nil changed = !previousID.isEmpty && !nextID.isEmpty && (previousID != nextID || rejoinedWithoutAddress) } else { - return + // No comparable identity on the first sample from this source. + // Remember it so a subsequent change within that source is visible. + changed = false } sawCallExit = false if changed { handoff = (value.integrationID, currentEvent) stop("call-changed") - } else if next.url != nil || previous.url == nil { - boundaryCall = value + } else { + roomBySource[source] = next + if let url = next.url { roomURL = url } } } diff --git a/Tests/verbemoTests/CallIntegrationRecordingTests.swift b/Tests/verbemoTests/CallIntegrationRecordingTests.swift index ec6baa7..7f452b8 100644 --- a/Tests/verbemoTests/CallIntegrationRecordingTests.swift +++ b/Tests/verbemoTests/CallIntegrationRecordingTests.swift @@ -182,6 +182,24 @@ struct CallIntegrationRecordingTests { #expect(stops == ["call-changed"]) } + @Test func switchingObservationSourcesKeepsDetectingRoomChangesWithoutAddresses() { + let now = Date() + var reading = observation(date: now, id: "conference") + let session = FakeAutoSession(startedAt: now, trigger: .micActivity) + session.integrationCall = reading + let controller = AutoRecordController(settings: .init(), calendar: nil, now: { now }) + controller.currentSession = { session } + var stops: [String] = [] + controller.stopRecording = { stops.append($0) } + reading.source = .accessibility + reading.call?.id = "window-A" + controller.observeCallBoundary([reading]) + #expect(stops.isEmpty) + reading.call?.id = "window-B" + controller.observeCallBoundary([reading]) + #expect(stops == ["call-changed"]) + } + @Test func roomSwitchWritesTwoRecordingsWithTheirOwnMeetingContext() async throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: root) } From 7aac11e2cdff815c8c6936c5001eddc482fefa7f Mon Sep 17 00:00:00 2001 From: Boris Gorbylev Date: Mon, 30 Nov 2026 13:25:25 +0300 Subject: [PATCH 3/3] test: use the calendar fixture for recording handoff Co-authored-by: OpenAI Codex --- Tests/verbemoTests/CallIntegrationRecordingTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/verbemoTests/CallIntegrationRecordingTests.swift b/Tests/verbemoTests/CallIntegrationRecordingTests.swift index 7f452b8..0fe00fc 100644 --- a/Tests/verbemoTests/CallIntegrationRecordingTests.swift +++ b/Tests/verbemoTests/CallIntegrationRecordingTests.swift @@ -208,7 +208,7 @@ struct CallIntegrationRecordingTests { settings.calendar = false settings.startDelay = 0 let calendar = FakeCalendar() - calendar.meetings = [.meeting(id: "scheduled-first-room", start: now)] + calendar.meetings = [FakeCalendar.meeting(id: "scheduled-first-room", start: now)] var reading = observation(date: now, id: "first") var active: RecordingSession? var sessions: [RecordingSession] = []