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
80 changes: 80 additions & 0 deletions Sources/verbemo/Meetings/AutoRecordController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,11 @@ final class AutoRecordController {
private var currentCall: CallObservation?
private var trackedCall: CallObservation?
private var pendingCallID: String?
private weak var boundarySession: (any AutoRecordedSession)?
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
private let now: () -> Date
private var timer: Timer?
Expand Down Expand Up @@ -243,6 +248,7 @@ final class AutoRecordController {
micActiveSince = nil
startFailures = 0
if !newValue {
handoff = nil
notice = nil
if phase != .recording { phase = .watching }
lastDecision = localised("auto-record off", "автозапись выключена")
Expand All @@ -260,6 +266,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
Expand All @@ -269,6 +276,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.
Expand All @@ -292,6 +300,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
}
Expand Down Expand Up @@ -320,6 +329,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.
Expand Down Expand Up @@ -360,6 +370,76 @@ 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 }
guard let original = session.integrationCall ?? trackedCall, let originalCall = original.call else { return }
if boundarySession !== session {
boundarySession = session
roomURL = originalCall.url
roomBySource.removeAll()
if let source = original.source { roomBySource[source] = originalCall }
sawCallExit = false
}
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 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 = roomURL, let nextURL = next.url {
changed = previousURL.host?.lowercased() != nextURL.host?.lowercased()
|| previousURL.path.split(separator: "/") != nextURL.path.split(separator: "/")
} else if let previous = roomBySource[source] {
let previousID = previous.participationID ?? previous.id
let nextID = next.participationID ?? next.id
let rejoinedWithoutAddress = sawCallExit && roomURL == nil && next.url == nil
&& previous.participationID == nil && next.participationID == nil
changed = !previousID.isEmpty && !nextID.isEmpty && (previousID != nextID || rejoinedWithoutAddress)
} else {
// 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 {
roomBySource[source] = next
if let url = next.url { roomURL = url }
}
}

/// 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 {
Expand Down
6 changes: 5 additions & 1 deletion Sources/verbemo/Verbemo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
Expand Down
148 changes: 148 additions & 0 deletions Tests/verbemoTests/CallIntegrationRecordingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,154 @@ 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 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) }
let now = Date()
var settings = Config.AutoRecordSettings()
settings.calendar = false
settings.startDelay = 0
let calendar = FakeCalendar()
calendar.meetings = [FakeCalendar.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
Expand Down
Loading