@poolse/native 3.9.0 → 3.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +129 -9
  3. package/android/src/main/AndroidManifest.xml +4 -0
  4. package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +83 -6
  5. package/android/src/main/java/dev/poolse/callcore/Ports.kt +28 -1
  6. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +3 -3
  7. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +155 -10
  8. package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +7 -1
  9. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +21 -1
  10. package/android/src/main/java/dev/poolse/callcore/android/CallVideo.kt +32 -0
  11. package/android/src/main/java/dev/poolse/callcore/android/EscalationNotification.kt +475 -0
  12. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +9 -4
  13. package/android/src/main/java/dev/poolse/callcore/android/MeetingNotification.kt +127 -0
  14. package/android/src/main/java/dev/poolse/callcore/android/PoolseIncomingCall.kt +9 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +9 -0
  16. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +48 -2
  17. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +121 -6
  18. package/android/src/test/java/dev/poolse/callcore/android/CallHttpClientTest.kt +15 -0
  19. package/dist/index.cjs +108 -0
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +241 -23
  22. package/dist/index.d.ts +241 -23
  23. package/dist/index.js +98 -1
  24. package/dist/index.js.map +1 -1
  25. package/ios/Core/CallCoreRuntime.swift +79 -5
  26. package/ios/Core/CallHttpClient.swift +9 -2
  27. package/ios/Core/Ports.swift +31 -2
  28. package/ios/Core/SnapshotEncoding.swift +22 -3
  29. package/ios/Module/PoolseCallsModule.swift +48 -1
  30. package/ios/Platform/CallCore.swift +100 -1
  31. package/ios/Platform/CallKitController.swift +1 -1
  32. package/ios/Platform/EscalationNotifications.swift +195 -0
  33. package/ios/Platform/LiveKitMediaPort.swift +127 -3
  34. package/ios/Platform/MessageNotifications.swift +60 -1
  35. package/ios/Platform/VoipPush.swift +11 -2
  36. package/package.json +1 -1
  37. package/src/index.ts +354 -23
@@ -9,7 +9,7 @@ public class PoolseCallsModule: Module {
9
9
  public func definition() -> ModuleDefinition {
10
10
  Name("PoolseCalls")
11
11
 
12
- Events("onCallState", "onVoipToken", "onPictureInPicture", "onNotificationAction")
12
+ Events("onCallState", "onVoipToken", "onPictureInPicture", "onNotificationAction", "onCallAction", "onCallData")
13
13
 
14
14
  // Normally done at launch by PoolseCallsAppDelegateSubscriber; this is
15
15
  // the backstop for a host whose AppDelegate does not forward to Expo.
@@ -31,9 +31,15 @@ public class PoolseCallsModule: Module {
31
31
  CallPictureInPicture.listener = { [weak self] active in
32
32
  self?.sendEvent("onPictureInPicture", ["active": active])
33
33
  }
34
+ MessageNotifications.callActionListener = { [weak self] event in
35
+ self?.sendEvent("onCallAction", event)
36
+ }
34
37
  MessageNotifications.actionListener = { [weak self] event in
35
38
  self?.sendEvent("onNotificationAction", event)
36
39
  }
40
+ CallCore.dataListener = { [weak self] message in
41
+ self?.sendEvent("onCallData", message)
42
+ }
37
43
  }
38
44
  }
39
45
 
@@ -43,6 +49,8 @@ public class PoolseCallsModule: Module {
43
49
  VoipPush.tokenListener = nil
44
50
  CallPictureInPicture.listener = nil
45
51
  MessageNotifications.actionListener = nil
52
+ MessageNotifications.callActionListener = nil
53
+ CallCore.dataListener = nil
46
54
  }
47
55
  }
48
56
 
@@ -125,11 +133,43 @@ public class PoolseCallsModule: Module {
125
133
  return true
126
134
  }
127
135
  Function("stopScreenShare") { onCore { $0.setScreenShare(false) } }
136
+ // Capture processing (CL7). Noise suppression is Apple's voice
137
+ // processing; blur is Vision person segmentation (iOS 15+).
138
+ Function("noiseSuppressionSupported") { () -> Bool in true }
139
+ Function("setNoiseSuppression") { (on: Bool) -> Bool in
140
+ guard CallCore.getOrNull() != nil else { return false }
141
+ onCore { $0.setNoiseSuppression(on) }
142
+ return true
143
+ }
144
+ Function("backgroundBlurSupported") { () -> Bool in true }
145
+ Function("setBackgroundBlur") { (on: Bool) -> Bool in
146
+ guard CallCore.getOrNull() != nil else { return false }
147
+ onCore { $0.setBackgroundBlur(on) }
148
+ return true
149
+ }
128
150
  Function("setSpeaker") { (on: Bool) in onCore { $0.setSpeaker(on) } }
129
151
  Function("setAudioOutput") { (id: String) in onCore { $0.setAudioOutput(id) } }
130
152
  // Recording consent accepted: mic and camera back as they were.
131
153
  Function("republish") { onCore { $0.republish() } }
132
154
 
155
+ // The call's data channel (CL4, CL6): `data` is UTF-8 text, or bytes
156
+ // as base64 with `options.base64`. Resolves false when not connected,
157
+ // over 14 000 bytes, or refused.
158
+ AsyncFunction("publishData") { (topic: String, data: String, options: [String: Any]?, promise: Promise) in
159
+ let bytes = (options?["base64"] as? Bool == true) ? Data(base64Encoded: data) : data.data(using: .utf8)
160
+ guard let bytes = bytes, let core = CallCore.getOrNull() else { return promise.resolve(false) }
161
+ core.publishData(topic: topic, data: bytes, reliable: options?["reliable"] as? Bool ?? true,
162
+ to: options?["to"] as? [String] ?? []) { ok in promise.resolve(ok) }
163
+ }.runOnQueue(.main)
164
+
165
+ // Breakout rooms (MEETINGS.md §5): the live call's media to another
166
+ // room of the same call, keeping the CallKit call. `session` is the
167
+ // JSON of POST /breakouts/:room/join or /calls/:id/breakouts/return.
168
+ AsyncFunction("moveToRoom") { (session: String, promise: Promise) in
169
+ guard let core = CallCore.getOrNull() else { return promise.resolve(false) }
170
+ core.moveToRoom(payload: session) { ok in promise.resolve(ok) }
171
+ }.runOnQueue(.main)
172
+
133
173
  // Picture-in-picture: armed while a video call shows someone; the
134
174
  // <CallVideoView pictureInPicture> on screen is what it grows out of.
135
175
  Function("setPictureInPictureEnabled") { (on: Bool) in
@@ -161,6 +201,13 @@ public class PoolseCallsModule: Module {
161
201
 
162
202
  // Reply / Mark as read done from a notification while JS was not
163
203
  // listening (usually: the app was not running). Oldest first, once.
204
+ // A meeting notice's tap / Join that launched the app (cold start), once.
205
+ Function("takeCallAction") { () -> [String: Any]? in
206
+ var out: [String: Any]?
207
+ let take = { out = MessageNotifications.pendingCallAction; MessageNotifications.pendingCallAction = nil }
208
+ if Thread.isMainThread { take() } else { DispatchQueue.main.sync(execute: take) }
209
+ return out
210
+ }
164
211
  Function("takeNotificationActions") { () -> [[String: Any]] in
165
212
  MessageNotifications.takePending()
166
213
  }
@@ -45,6 +45,10 @@ final class CallCore {
45
45
  /// The bridge's snapshot subscriber; process-level so JS may subscribe before configure.
46
46
  static var listener: (([String: Any]?) -> Void)?
47
47
 
48
+ /// The bridge's data-channel subscriber (CL4, CL6): `{topic, payload
49
+ /// (base64), text (UTF-8 or nil), fromIdentity, fromName}`. Main thread.
50
+ static var dataListener: (([String: Any]) -> Void)?
51
+
48
52
  /// Configure and PERSIST (see CallCore.kt). Re-configuring swaps in place:
49
53
  /// HTTP and the ringback read the config per use. A non-empty
50
54
  /// `apiBaseUrl` is the `default` server; "" sets the options only and
@@ -193,6 +197,9 @@ final class CallCore {
193
197
  private var videoPaused = false
194
198
  /// False while the server holds our media back (recording consent).
195
199
  private var canPublish = true
200
+ /// Taken over by the same user on another device (CL11): the end that
201
+ /// follows reads `reason: 'moved'`.
202
+ private var movedElsewhere = false
196
203
 
197
204
  /// ring_ended reasons seen per call — the CallKit end reason.
198
205
  private var ringEndReasons: [String: String] = [:]
@@ -203,6 +210,16 @@ final class CallCore {
203
210
  private var lastSnapshot: [String: Any]?
204
211
  /// The push's `workspace_name` per ringing call (under snapshotLock).
205
212
  private var ringWorkspaces: [String: String] = [:]
213
+ /// Meeting rings (CA4) per call: the meeting's title, "" when it has
214
+ /// none (under snapshotLock). Absent: a person calling.
215
+ private var ringMeetings: [String: String] = [:]
216
+
217
+ private func ringMeetingTitle(_ callId: String?) -> String?? {
218
+ guard let id = callId else { return nil }
219
+ snapshotLock.lock(); defer { snapshotLock.unlock() }
220
+ guard let title = ringMeetings[id] else { return nil }
221
+ return .some(title.isEmpty ? nil : title)
222
+ }
206
223
 
207
224
  private func ringWorkspaceName(_ callId: String?) -> String? {
208
225
  guard let id = callId else { return nil }
@@ -256,6 +273,12 @@ final class CallCore {
256
273
  if ringWorkspaces.count > 16 { ringWorkspaces = [ring.callId: name] }
257
274
  snapshotLock.unlock()
258
275
  }
276
+ if ring.isMeeting {
277
+ snapshotLock.lock()
278
+ if ringMeetings.count > 16 { ringMeetings = [:] }
279
+ ringMeetings[ring.callId] = ring.meetingTitle ?? ""
280
+ snapshotLock.unlock()
281
+ }
259
282
  runtime.onRing(ring)
260
283
  }
261
284
 
@@ -375,6 +398,16 @@ final class CallCore {
375
398
  /// Not optimistic: screenSharing flips when the screen is published.
376
399
  func setScreenShare(_ on: Bool) { onMain { [self] in mediaPort.setScreenShare(on) } }
377
400
 
401
+ /// Noise suppression (CL7), on by default; see LiveKitMediaPort.
402
+ func setNoiseSuppression(_ on: Bool) {
403
+ onMain { [self] in mediaPort.setNoiseSuppression(on); runtime.reemit() }
404
+ }
405
+
406
+ /// Background blur on the camera (CL7).
407
+ func setBackgroundBlur(_ on: Bool) {
408
+ onMain { [self] in mediaPort.setBackgroundBlur(on); runtime.reemit() }
409
+ }
410
+
378
411
  func setSpeaker(_ on: Bool) {
379
412
  onMain { [self] in
380
413
  audioRoute = on ? "speaker" : "earpiece" // optimistic; the adapter reports the real one
@@ -393,6 +426,31 @@ final class CallCore {
393
426
  /// The current call's id and control token (main thread).
394
427
  var control: (callId: String, controlToken: String)? { runtime.control }
395
428
 
429
+ /// Breakout rooms (MEETINGS.md §5): the call's media to the room of
430
+ /// `payload` — the JSON of `POST /breakouts/:room/join` (or of `POST
431
+ /// /calls/:id/breakouts/return`). CallKit keeps the call; see
432
+ /// CallCoreRuntime.moveToRoom. `done(false)`: unparseable, no live
433
+ /// call, or another call's session.
434
+ func moveToRoom(payload: String, done: @escaping (Bool) -> Void) {
435
+ onMain { [self] in
436
+ guard let current = runtime.currentBundle,
437
+ let next = try? CallHttpClient.parseBundle(payload, current: current) else {
438
+ done(false)
439
+ return
440
+ }
441
+ runtime.moveToRoom(next) { [weak self] ok in
442
+ // The last room's people are not in this one.
443
+ if ok { self?.roster = [] }
444
+ done(ok)
445
+ }
446
+ }
447
+ }
448
+
449
+ /// A data-channel message to the call's room (CL4, CL6); see LiveKitMediaPort.publishData.
450
+ func publishData(topic: String, data: Data, reliable: Bool, to: [String], done: @escaping (Bool) -> Void) {
451
+ onMain { [self] in mediaPort.publishData(topic: topic, data: data, reliable: reliable, to: to, done: done) }
452
+ }
453
+
396
454
  /// A video slot for the native view. Main thread.
397
455
  func createVideoSurface(renderMode: VideoView.RenderMode = .auto) -> LiveKitVideoSurface {
398
456
  mediaPort.createVideoSurface(renderMode: renderMode)
@@ -472,9 +530,32 @@ final class CallCore {
472
530
  let ringName = ringWorkspaceName(state.callId)
473
531
  out["serverId"] = serverId ?? NSNull()
474
532
  out["workspaceName"] = (ringName ?? servers.get(serverId)?.name) ?? NSNull()
533
+ out["noiseSuppression"] = mediaPort.noiseSuppression
534
+ out["backgroundBlur"] = mediaPort.backgroundBlur
535
+ out["movedElsewhere"] = movedElsewhere
536
+ // Breakout rooms (MEETINGS.md §5): the room the media is in, nil in the main room.
537
+ if let b = runtime.breakout {
538
+ out["breakout"] = ["roomId": b.roomId, "name": b.name ?? NSNull()] as [String: Any]
539
+ } else {
540
+ out["breakout"] = NSNull()
541
+ }
542
+ out["selfIdentity"] = mediaPort.localIdentity ?? NSNull()
543
+ // Taken over by another of this user's devices: the machine ends it
544
+ // as `left` (CALL_CONTRACT.md §9); the app is told why.
545
+ if movedElsewhere && state.phase == .ended { out["reason"] = "moved" }
546
+ // A scheduled meeting that rang this device (CA4).
547
+ if let meeting = ringMeetingTitle(state.callId) {
548
+ out["ringType"] = "meeting"
549
+ out["meetingTitle"] = meeting ?? NSNull()
550
+ } else {
551
+ out["ringType"] = "call"
552
+ out["meetingTitle"] = NSNull()
553
+ }
475
554
  if var waiting = out["waiting"] as? [String: Any], let w = runtime.waitingRing {
476
555
  waiting["serverId"] = (w.serverId ?? server(of: w.callId)) ?? NSNull()
477
556
  waiting["workspaceName"] = (w.workspaceName ?? servers.get(w.serverId)?.name) ?? NSNull()
557
+ waiting["ringType"] = w.isMeeting ? "meeting" : "call"
558
+ waiting["meetingTitle"] = w.meetingTitle ?? NSNull()
478
559
  out["waiting"] = waiting
479
560
  }
480
561
  return out
@@ -506,6 +587,7 @@ final class CallCore {
506
587
  connectionQuality = "unknown"
507
588
  videoPaused = false
508
589
  canPublish = true
590
+ movedElsewhere = false
509
591
  }
510
592
 
511
593
  /// CallKit follows the FINAL state of each dispatch.
@@ -608,7 +690,8 @@ final class CallCore {
608
690
  fileprivate func remoteJoined() { runtime.onRemoteJoined() }
609
691
  fileprivate func participants(_ p: [SnapshotParticipant]) {
610
692
  runtime.post { [weak self] in self?.roster = p }
611
- runtime.onRemoteCount(p.count)
693
+ // An agent keeps nobody company: a call left with only agents is over.
694
+ runtime.onRemoteCount(p.filter { !$0.isAgent }.count)
612
695
  runtime.reemit()
613
696
  }
614
697
  fileprivate func route(_ r: String) {
@@ -635,6 +718,18 @@ final class CallCore {
635
718
  runtime.post { [weak self] in self?.canPublish = allowed }
636
719
  runtime.reemit()
637
720
  }
721
+ fileprivate func movedAway() {
722
+ runtime.post { [weak self] in self?.movedElsewhere = true }
723
+ }
724
+ fileprivate func data(topic: String, payload: Data, from: String?, name: String?) {
725
+ CallCore.dataListener?([
726
+ "topic": topic,
727
+ "payload": payload.base64EncodedString(),
728
+ "text": String(data: payload, encoding: .utf8) ?? NSNull(),
729
+ "fromIdentity": from ?? NSNull(),
730
+ "fromName": name ?? NSNull(),
731
+ ])
732
+ }
638
733
  }
639
734
 
640
735
  // MARK: - CallKit actions
@@ -736,6 +831,10 @@ private final class EventsAdapter: MediaEvents {
736
831
  func onAudioOutputs(_ outputs: [AudioOutput], selectedId: String?) { core?.outputs(outputs, selected: selectedId) }
737
832
  func onNetwork(quality: String, videoPaused: Bool) { core?.network(quality: quality, videoPaused: videoPaused) }
738
833
  func onCanPublish(_ allowed: Bool) { core?.publishAllowed(allowed) }
834
+ func onMovedElsewhere() { core?.movedAway() }
835
+ func onData(topic: String, payload: Data, fromIdentity: String?, fromName: String?) {
836
+ core?.data(topic: topic, payload: payload, from: fromIdentity, name: fromName)
837
+ }
739
838
  }
740
839
 
741
840
  /// Host-facing entry points.
@@ -128,7 +128,7 @@ final class CallKitController: NSObject, CXProviderDelegate {
128
128
  func reportIncoming(ring: RingContext) {
129
129
  let hasVideo = ring.media == "video"
130
130
  let title = CallServers.title(
131
- ring.conversationName ?? ring.callerName,
131
+ ring.displayTitle,
132
132
  workspace: ServerRegistry.shared.servers.workspaceLabel(serverId: ring.serverId, pushName: ring.workspaceName)
133
133
  )
134
134
  if let existing = calls.values.first(where: { $0.callId == ring.callId && !$0.ended }) {
@@ -0,0 +1,195 @@
1
+ import Foundation
2
+ import UIKit
3
+ import UserNotifications
4
+
5
+ /// An agent attending a meeting for the user asks them something its brief
6
+ /// doesn't cover (server docs/AGENTS_IN_CALLS.md §5). The server sends an
7
+ /// alert push with category `poolse_agent_escalation`; iOS shows it, and
8
+ /// this answers its actions natively — Approve, Decline, and Answer (an
9
+ /// inline text field) — from the lock screen with the app killed.
10
+ ///
11
+ /// The reply is `POST /v1/agent-escalations/:id/reply` with the push's
12
+ /// `reply_token` in the body and no Authorization header: the token names
13
+ /// that escalation and person only, works once, until `expires_at`. It
14
+ /// goes to the push's own server (its `tenant_id`), the push's
15
+ /// `reply_url` only when that server isn't configured here.
16
+ ///
17
+ /// A failure posts "Couldn't send your answer" with the same actions
18
+ /// (while trying again can still work). Results reach JS as
19
+ /// `onNotificationAction` with `action: "escalation"`.
20
+ ///
21
+ /// `PoolseMessageReplyRequiresUnlock` (the config plugin's
22
+ /// `messageReplyRequiresUnlock`) makes these actions ask for Face ID / the
23
+ /// passcode first too.
24
+ enum EscalationNotifications {
25
+ static let category = "poolse_agent_escalation"
26
+ static let approveAction = "poolse_escalation_approve"
27
+ static let declineAction = "poolse_escalation_decline"
28
+ static let answerAction = "poolse_escalation_answer"
29
+
30
+ /// The category, registered with the message one (MessageNotifications).
31
+ static func makeCategory(requireUnlock: Bool) -> UNNotificationCategory {
32
+ let options: UNNotificationActionOptions = requireUnlock ? [.authenticationRequired] : []
33
+ let approve = UNNotificationAction(identifier: approveAction, title: "Approve", options: options)
34
+ let decline = UNNotificationAction(identifier: declineAction, title: "Decline", options: options)
35
+ let answer = UNTextInputNotificationAction(
36
+ identifier: answerAction,
37
+ title: "Answer",
38
+ options: options,
39
+ textInputButtonTitle: "Send",
40
+ textInputPlaceholder: "Your answer"
41
+ )
42
+ return UNNotificationCategory(
43
+ identifier: category,
44
+ actions: [approve, decline, answer],
45
+ intentIdentifiers: [],
46
+ hiddenPreviewsBodyPlaceholder: "Your agent has a question",
47
+ options: []
48
+ )
49
+ }
50
+
51
+ /// An action on an escalation notification. False for a plain tap (the
52
+ /// host opens the conversation) or a dismissal.
53
+ static func didReceive(_ response: UNNotificationResponse) -> Bool {
54
+ let decision: String
55
+ switch response.actionIdentifier {
56
+ case approveAction: decision = "approve"
57
+ case declineAction: decision = "decline"
58
+ case answerAction: decision = "answer"
59
+ default: return false
60
+ }
61
+ let content = response.notification.request.content
62
+ let info = content.userInfo
63
+ func str(_ key: String) -> String? { (info[key] as? String).flatMap { $0.isEmpty ? nil : $0 } }
64
+ guard let id = str("escalation_id") else { return true }
65
+ let server = ServerRegistry.shared.servers.resolve(tenantId: str("tenant_id"))
66
+ var event: [String: Any] = [
67
+ "action": "escalation",
68
+ "escalationId": id,
69
+ "decision": decision,
70
+ "conversationId": str("conversation_id") ?? "",
71
+ "callId": str("call_id") ?? NSNull(),
72
+ ]
73
+ if let sid = server?.id { event["serverId"] = sid }
74
+
75
+ var body: [String: Any] = [:]
76
+ if decision == "answer" {
77
+ let text = String(((response as? UNTextInputNotificationResponse)?.userText ?? "")
78
+ .trimmingCharacters(in: .whitespacesAndNewlines).prefix(1000))
79
+ guard !text.isEmpty else { return true }
80
+ body["answer"] = text
81
+ event["text"] = text
82
+ } else {
83
+ body["decision"] = decision
84
+ }
85
+
86
+ guard let token = str("reply_token") else {
87
+ event["ok"] = false
88
+ event["error"] = "no_token"
89
+ MessageNotifications.report(event)
90
+ postFailure(content, reason: "Open the app to answer.", retry: false)
91
+ return true
92
+ }
93
+ body["token"] = token
94
+
95
+ var origin = server?.apiBaseUrl ?? ServerRegistry.shared.baseUrl(nil)
96
+ if origin.isEmpty { origin = CallCore.persistedApiBaseUrl() ?? "" }
97
+ let encodedId = id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? id
98
+ let url = !origin.isEmpty
99
+ ? URL(string: "\(origin)/v1/agent-escalations/\(encodedId)/reply")
100
+ : str("reply_url").flatMap(URL.init(string:))
101
+ guard let url = url else {
102
+ event["ok"] = false
103
+ event["error"] = "not_configured"
104
+ MessageNotifications.report(event)
105
+ postFailure(content, reason: "Open the app to answer.", retry: false)
106
+ return true
107
+ }
108
+
109
+ // Started before anything async: iOS may suspend a background-launched
110
+ // app right after the delegate returns.
111
+ let background = BackgroundTask(name: "poolse-escalation-\(decision)")
112
+ send(url: url, body: body, background: background) { status, code in
113
+ let ok = (200..<300).contains(status)
114
+ event["ok"] = ok
115
+ if !ok {
116
+ event["error"] = code ?? (status == 0 ? "network" : "http_\(status)")
117
+ if status != 0 { event["status"] = status }
118
+ let retry = ![401, 404, 409, 410].contains(status)
119
+ postFailure(content, reason: reason(status), retry: retry)
120
+ }
121
+ MessageNotifications.report(event)
122
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { background.end() }
123
+ }
124
+ return true
125
+ }
126
+
127
+ /// "Couldn't send your answer" — with the same actions and token while
128
+ /// trying again can still work.
129
+ private static func postFailure(_ original: UNNotificationContent, reason: String, retry: Bool) {
130
+ let content = UNMutableNotificationContent()
131
+ content.title = "Couldn't send your answer"
132
+ content.body = "\(original.body)\n\(reason)"
133
+ content.threadIdentifier = original.threadIdentifier
134
+ content.sound = .default
135
+ var info = original.userInfo
136
+ info["poolse_escalation_failed"] = "1"
137
+ if !retry { info.removeValue(forKey: "reply_token") }
138
+ content.userInfo = info
139
+ if retry { content.categoryIdentifier = category }
140
+ let id = (original.userInfo["escalation_id"] as? String) ?? UUID().uuidString
141
+ let request = UNNotificationRequest(identifier: "poolse-escalation-failed-\(id)", content: content, trigger: nil)
142
+ UNUserNotificationCenter.current().add(request) { error in
143
+ if let error = error { pcTrace("escalation failure notification refused: \(error)") }
144
+ }
145
+ }
146
+
147
+ private static func reason(_ status: Int) -> String {
148
+ switch status {
149
+ case 0: return "No connection. Try again."
150
+ case 401: return "This notification expired. Open the app to answer."
151
+ case 404: return "This question is gone."
152
+ case 409: return "It was already answered."
153
+ case 410: return "Too late — the question expired."
154
+ case 422: return "The answer couldn't be sent (1 to 1000 characters)."
155
+ case 429: return "Too many tries. Wait a moment."
156
+ default: return "Something went wrong. Try again."
157
+ }
158
+ }
159
+
160
+ private static let session: URLSession = {
161
+ let config = URLSessionConfiguration.ephemeral
162
+ config.timeoutIntervalForRequest = 15
163
+ config.waitsForConnectivity = false
164
+ return URLSession(configuration: config)
165
+ }()
166
+
167
+ /// The POST, retried once after a second only when nothing came back
168
+ /// (the token works once: an answered request is never sent again).
169
+ private static func send(url: URL, body: [String: Any], background: BackgroundTask, attempt: Int = 1,
170
+ done: @escaping (Int, String?) -> Void) {
171
+ var request = URLRequest(url: url)
172
+ request.httpMethod = "POST"
173
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
174
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
175
+ request.httpBody = try? JSONSerialization.data(withJSONObject: body)
176
+ session.dataTask(with: request) { data, response, error in
177
+ let status = error == nil ? ((response as? HTTPURLResponse)?.statusCode ?? 0) : 0
178
+ let json = data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any]
179
+ let code = (json?["error"] as? [String: Any])?["code"] as? String
180
+ if status == 0 && attempt < 2 {
181
+ DispatchQueue.main.async {
182
+ guard background.remaining > 20 else { return done(status, code) }
183
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
184
+ send(url: url, body: body, background: background, attempt: attempt + 1, done: done)
185
+ }
186
+ }
187
+ return
188
+ }
189
+ if !(200..<300).contains(status) {
190
+ pcTrace("escalation reply failed status=\(status) code=\(code ?? "-") error=\(String(describing: error))")
191
+ }
192
+ done(status, code)
193
+ }.resume()
194
+ }
195
+ }
@@ -35,6 +35,12 @@ protocol MediaEvents: AnyObject {
35
35
  /// Whether the server lets us publish (false: recording consent not
36
36
  /// given yet, docs/RECORDING.md §5). Sent on every change.
37
37
  func onCanPublish(_ allowed: Bool)
38
+ /// The SFU replaced us with the same user joining from another device
39
+ /// ("move call to this device", CALL_CONTRACT.md §9). Sent just before `onLost`.
40
+ func onMovedElsewhere()
41
+ /// A data-channel message from someone in the room (CL4, CL6): its
42
+ /// topic, the bytes, and who sent it (nil identity: the server).
43
+ func onData(topic: String, payload: Data, fromIdentity: String?, fromName: String?)
38
44
  }
39
45
 
40
46
  /// Step-by-step trace of the audio path, in the device log as
@@ -113,6 +119,12 @@ final class LiveKitMediaPort: NSObject, MediaPort {
113
119
  private static let pauseVideoAfter: TimeInterval = 6
114
120
  private static let resumeVideoAfter: TimeInterval = 10
115
121
 
122
+ /// Capture processing (CL7); per process, not per call.
123
+ private(set) var noiseSuppression = true
124
+ private(set) var backgroundBlur = false
125
+ /// The capturer holds its processor weakly: this keeps it alive.
126
+ private var blurProcessor: BackgroundBlurVideoProcessor?
127
+
116
128
  private let surfaces = NSHashTable<LiveKitVideoSurface>.weakObjects()
117
129
  private var audioPrepared = false
118
130
  private var audioActive = false
@@ -370,6 +382,45 @@ final class LiveKitMediaPort: NSObject, MediaPort {
370
382
  events?.onLocalScreen(false)
371
383
  }
372
384
 
385
+ // MARK: - data channel (CL4, CL6)
386
+
387
+ /// The most one message may carry — the web CallRoom's
388
+ /// CALL_DATA_MAX_BYTES, under LiveKit's ~15 KiB packet.
389
+ static let dataMaxBytes = 14_000
390
+
391
+ /// Our LiveKit identity (the poolse user id) while connected.
392
+ var localIdentity: String? {
393
+ guard let r = room, connectedRoom == ObjectIdentifier(r) else { return nil }
394
+ return r.localParticipant.identity?.stringValue
395
+ }
396
+
397
+ /// Send `data` under `topic` to everyone in the room, or to `to` (LiveKit
398
+ /// identities). `reliable: false` for what is stale a moment later (a
399
+ /// moving pointer). `done(false)`: not connected, over the cap, or LiveKit refused.
400
+ func publishData(topic: String, data: Data, reliable: Bool, to: [String], done: @escaping (Bool) -> Void) {
401
+ guard let r = room, connectedRoom == ObjectIdentifier(r), !topic.isEmpty,
402
+ data.count <= Self.dataMaxBytes else {
403
+ done(false)
404
+ return
405
+ }
406
+ let options = DataPublishOptions(destinationIdentities: to.map { Participant.Identity(from: $0) },
407
+ topic: topic, reliable: reliable)
408
+ Task {
409
+ do {
410
+ try await r.localParticipant.publish(data: data, options: options)
411
+ await MainActor.run { done(true) }
412
+ } catch {
413
+ NSLog("[PoolseCalls] data publish on %@ failed: %@", topic, "\(error)")
414
+ await MainActor.run { done(false) }
415
+ }
416
+ }
417
+ }
418
+
419
+ fileprivate func dataReceived(_ r: Room, topic: String, data: Data, from: String?, name: String?) {
420
+ guard room === r, !topic.isEmpty, data.count <= Self.dataMaxBytes else { return }
421
+ events?.onData(topic: topic, payload: data, fromIdentity: from, fromName: name)
422
+ }
423
+
373
424
  // MARK: - screen sharing
374
425
 
375
426
  /// Sharing the screen needs the app's broadcast upload extension (the
@@ -742,8 +793,37 @@ final class LiveKitMediaPort: NSObject, MediaPort {
742
793
  return (track.capturer as? CameraCapturer)?.position == .back ? "back" : "front"
743
794
  }
744
795
 
796
+ // MARK: - capture processing (CL7)
797
+
798
+ /// Apple's voice processing (VPIO) does echo cancellation, gain control
799
+ /// and noise suppression as one unit, so "off" bypasses all of it —
800
+ /// meant for headphones (music, an instrument). Valid mid-call.
801
+ func setNoiseSuppression(_ on: Bool) {
802
+ noiseSuppression = on
803
+ AudioManager.shared.isVoiceProcessingBypassed = !on
804
+ }
805
+
806
+ /// Blur behind the person on the published camera (Vision person
807
+ /// segmentation, LiveKit's BackgroundBlurVideoProcessor). Survives a
808
+ /// camera flip and republish: re-applied whenever the camera is reported.
809
+ func setBackgroundBlur(_ on: Bool) {
810
+ backgroundBlur = on
811
+ if let r = room { applyBlur(r) }
812
+ }
813
+
814
+ private func applyBlur(_ r: Room) {
815
+ guard let track = localCameraTrack(r) else { return }
816
+ if backgroundBlur {
817
+ if blurProcessor == nil { blurProcessor = BackgroundBlurVideoProcessor() }
818
+ if track.capturer.processor !== blurProcessor { track.capturer.processor = blurProcessor }
819
+ } else if track.capturer.processor != nil {
820
+ track.capturer.processor = nil
821
+ }
822
+ }
823
+
745
824
  private func reportLocalCamera(_ r: Room) {
746
825
  guard room === r else { return }
826
+ applyBlur(r)
747
827
  let on = localCameraTrack(r) != nil
748
828
  events?.onLocalCamera(on: on, facing: on ? cameraFacing() : nil)
749
829
  }
@@ -760,6 +840,10 @@ final class LiveKitMediaPort: NSObject, MediaPort {
760
840
  case .reconnected:
761
841
  events?.onRecovered()
762
842
  case .disconnected:
843
+ // The same user joined from another device: LiveKit replaces the
844
+ // older participant (one identity per user). The reconnect that
845
+ // follows is refused, and the call ends as moved.
846
+ if r.disconnectError?.type == .duplicateIdentity { events?.onMovedElsewhere() }
763
847
  events?.onLost()
764
848
  case .participantJoined:
765
849
  // The transcript assistant or the recorder joining is nobody answering.
@@ -863,10 +947,11 @@ final class LiveKitMediaPort: NSObject, MediaPort {
863
947
  /// The remote PEOPLE: poolse's transcript assistant and LiveKit Egress's
864
948
  /// recorder are in the room but are not someone in the call — never in
865
949
  /// the roster, the count that ends a call left alone, or a video tile.
866
- /// Phone (SIP) participants are people.
950
+ /// Agents are listed separately (`agents`). Phone (SIP) participants are people.
867
951
  private func people(_ r: Room) -> [RemoteParticipant] {
868
952
  r.remoteParticipants.values.filter { p in
869
- !ServiceParticipants.isService(identity: p.identity?.stringValue ?? "", kind: Self.kindName(p.kind))
953
+ !ServiceParticipants.isService(identity: p.identity?.stringValue ?? "", kind: Self.kindName(p.kind)) &&
954
+ Self.metadata(p)?["agent"] as? Bool != true
870
955
  }
871
956
  }
872
957
 
@@ -878,8 +963,39 @@ final class LiveKitMediaPort: NSObject, MediaPort {
878
963
  return nil
879
964
  }
880
965
 
966
+ /// Agents invited into the call (AGENTS_IN_CALLS.md §1): kind AGENT like
967
+ /// poolse's room assistant, but marked `agent: true` in their token
968
+ /// metadata — listed (with the badge), unlike the assistant and recorder.
969
+ private func agents(_ r: Room) -> [(RemoteParticipant, [String: Any])] {
970
+ r.remoteParticipants.values.compactMap { p -> (RemoteParticipant, [String: Any])? in
971
+ guard let m = Self.metadata(p), m["agent"] as? Bool == true else { return nil }
972
+ return (p, m)
973
+ }
974
+ }
975
+
976
+ static func metadata(_ p: Participant) -> [String: Any]? {
977
+ guard let m = p.metadata, let d = m.data(using: .utf8) else { return nil }
978
+ return (try? JSONSerialization.jsonObject(with: d)) as? [String: Any]
979
+ }
980
+
881
981
  /// The REMOTE roster — the local participant is never included.
882
982
  private func emit(_ r: Room) {
983
+ let agentRows = agents(r).map { entry -> SnapshotParticipant in
984
+ let (p, m) = entry
985
+ let identity = p.identity?.stringValue ?? ""
986
+ return SnapshotParticipant(
987
+ userId: identity,
988
+ externalId: externalId(p) ?? identity,
989
+ speaking: p.isSpeaking,
990
+ muted: !p.isMicrophoneEnabled(),
991
+ cameraOn: false,
992
+ connectionQuality: Self.wire(p.connectionQuality),
993
+ screenSharing: false,
994
+ isAgent: true,
995
+ agentLabel: (m["label"] as? String).flatMap { $0.isEmpty ? nil : $0 } ?? p.name,
996
+ agentMode: m["mode"] as? String
997
+ )
998
+ }
883
999
  let roster = people(r).map { p -> SnapshotParticipant in
884
1000
  let identity = p.identity?.stringValue ?? ""
885
1001
  return SnapshotParticipant(
@@ -892,7 +1008,7 @@ final class LiveKitMediaPort: NSObject, MediaPort {
892
1008
  screenSharing: remoteScreen(p) != nil
893
1009
  )
894
1010
  }
895
- events?.onParticipants(roster)
1011
+ events?.onParticipants(roster + agentRows)
896
1012
  }
897
1013
 
898
1014
  /// The host's own user id, if the server put it in attributes/metadata.
@@ -940,6 +1056,14 @@ final class RoomObserver: NSObject, RoomDelegate, @unchecked Sendable {
940
1056
  func room(_ room: Room, participant: Participant, didUpdateMetadata metadata: String?) { send(room, .rosterChanged) }
941
1057
  func room(_ room: Room, participant: Participant, didUpdateAttributes attributes: [String: String]) { send(room, .rosterChanged) }
942
1058
  func room(_ room: Room, participant: Participant, didUpdateConnectionQuality quality: ConnectionQuality) { send(room, .quality) }
1059
+ func room(_ room: Room, participant: RemoteParticipant?, didReceiveData data: Data, forTopic topic: String,
1060
+ encryptionType: EncryptionType) {
1061
+ let from = participant?.identity?.stringValue
1062
+ let name = participant?.name
1063
+ DispatchQueue.main.async { [weak self] in
1064
+ self?.port?.dataReceived(room, topic: topic, data: data, from: from, name: name)
1065
+ }
1066
+ }
943
1067
  // Only ever the local participant's (LiveKit's own LocalParticipant sends it).
944
1068
  func room(_ room: Room, participant: Participant, didUpdatePermissions permissions: ParticipantPermissions) {
945
1069
  if participant is LocalParticipant { send(room, .permissions) }