@poolse/native 3.7.1 → 3.9.0

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 (41) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +94 -1
  3. package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +8 -0
  4. package/android/src/main/java/dev/poolse/callcore/CallServers.kt +72 -0
  5. package/android/src/main/java/dev/poolse/callcore/Ports.kt +34 -0
  6. package/android/src/main/java/dev/poolse/callcore/RoutedHttpPort.kt +74 -0
  7. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +3 -3
  8. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +131 -14
  9. package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +3 -0
  10. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +4 -0
  11. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +1 -1
  12. package/android/src/main/java/dev/poolse/callcore/android/MessageActionWorker.kt +35 -12
  13. package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +142 -48
  14. package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +8 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/PoolseIncomingCall.kt +16 -0
  16. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +6 -0
  17. package/android/src/main/java/dev/poolse/callcore/android/ServerRegistry.kt +107 -0
  18. package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +23 -0
  19. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +58 -7
  20. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +96 -9
  21. package/dist/index.cjs +83 -24
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +156 -9
  24. package/dist/index.d.ts +156 -9
  25. package/dist/index.js +77 -25
  26. package/dist/index.js.map +1 -1
  27. package/ios/Core/CallCoreRuntime.swift +8 -0
  28. package/ios/Core/CallHttpClient.swift +11 -1
  29. package/ios/Core/CallServers.swift +89 -0
  30. package/ios/Core/Ports.swift +35 -2
  31. package/ios/Core/RoutedHttpPort.swift +83 -0
  32. package/ios/Core/SnapshotEncoding.swift +17 -1
  33. package/ios/Module/PoolseCallsModule.swift +50 -8
  34. package/ios/Platform/CallCore.swift +132 -12
  35. package/ios/Platform/CallKitController.swift +4 -1
  36. package/ios/Platform/LiveKitMediaPort.swift +103 -14
  37. package/ios/Platform/MessageNotifications.swift +76 -23
  38. package/ios/Platform/ServerRegistry.swift +90 -0
  39. package/ios/Platform/VoipPush.swift +5 -1
  40. package/package.json +1 -1
  41. package/src/index.ts +265 -31
@@ -11,6 +11,8 @@ import UIKit
11
11
  /// The host-supplied configuration, persisted so a PushKit cold wake
12
12
  /// (no JS, no configure call) rebuilds the same core from disk.
13
13
  struct CallCoreConfig {
14
+ /// The default server's origin ("" when the app only uses `addServer`);
15
+ /// every server, this one included, lives in ServerRegistry.
14
16
  var apiBaseUrl: String
15
17
  var ringback: String?
16
18
  /// `production` | `sandbox` — the APNs environment the VoIP token
@@ -44,9 +46,20 @@ final class CallCore {
44
46
  static var listener: (([String: Any]?) -> Void)?
45
47
 
46
48
  /// Configure and PERSIST (see CallCore.kt). Re-configuring swaps in place:
47
- /// HTTP and the ringback read the config per use.
49
+ /// HTTP and the ringback read the config per use. A non-empty
50
+ /// `apiBaseUrl` is the `default` server; "" sets the options only and
51
+ /// keeps whatever default server there is.
48
52
  static func configure(apiBaseUrl: String, ringback: String?, apnsEnvironment: String?) {
49
- let trimmed = apiBaseUrl.hasSuffix("/") ? String(apiBaseUrl.dropLast()) : apiBaseUrl
53
+ var trimmed = apiBaseUrl
54
+ while trimmed.hasSuffix("/") { trimmed.removeLast() }
55
+ if trimmed.isEmpty {
56
+ trimmed = ServerRegistry.shared.servers.get(CallServers.defaultId)?.apiBaseUrl ?? ""
57
+ } else {
58
+ var server = ServerRegistry.shared.servers.get(CallServers.defaultId)
59
+ ?? CallServer(id: CallServers.defaultId, apiBaseUrl: trimmed)
60
+ server.apiBaseUrl = trimmed
61
+ ServerRegistry.shared.upsert(server)
62
+ }
50
63
  defaults.set(trimmed, forKey: "apiBaseUrl")
51
64
  defaults.set(ringback, forKey: "ringback")
52
65
  defaults.set(apnsEnvironment, forKey: "apnsEnvironment")
@@ -56,6 +69,22 @@ final class CallCore {
56
69
  configLock.unlock()
57
70
  }
58
71
 
72
+ /// `addServer` before any `configure`: the core still has to exist
73
+ /// (it carries the rings), with the default options.
74
+ static func ensureConfigured() {
75
+ restoreConfig()
76
+ if config == nil { configure(apiBaseUrl: "", ringback: nil, apnsEnvironment: nil) }
77
+ }
78
+
79
+ /// A single-server build's persisted origin, for the registry's
80
+ /// one-time migration. Reads the stores directly: the registry is not
81
+ /// loaded yet. Any thread.
82
+ static func persistedLegacyApiBaseUrl() -> String? {
83
+ if let url = defaults.string(forKey: "apiBaseUrl"), !url.isEmpty { return url }
84
+ if let url = readConfigFile()?.apiBaseUrl, !url.isEmpty { return url }
85
+ return nil
86
+ }
87
+
59
88
  /// The APNs environment last configured (persisted), if any.
60
89
  static var apnsEnvironment: String? {
61
90
  config?.apnsEnvironment ?? defaults.string(forKey: "apnsEnvironment") ?? readConfigFile()?.apnsEnvironment
@@ -119,7 +148,7 @@ final class CallCore {
119
148
  private static func readConfigFile() -> CallCoreConfig? {
120
149
  guard let url = configFileURL, let data = try? Data(contentsOf: url),
121
150
  let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
122
- let api = obj["apiBaseUrl"] as? String, !api.isEmpty else { return nil }
151
+ let api = obj["apiBaseUrl"] as? String else { return nil }
123
152
  return CallCoreConfig(apiBaseUrl: api, ringback: obj["ringback"] as? String,
124
153
  apnsEnvironment: obj["apnsEnvironment"] as? String)
125
154
  }
@@ -140,6 +169,7 @@ final class CallCore {
140
169
  // MARK: parts
141
170
 
142
171
  private let callKit = CallKitController.shared
172
+ private var router: RoutedHttpPort!
143
173
  private var mediaPort: LiveKitMediaPort!
144
174
  private var runtime: CallCoreRuntime!
145
175
  private var ringback: Ringback!
@@ -161,6 +191,8 @@ final class CallCore {
161
191
  private var audioOutputId: String?
162
192
  private var connectionQuality = "unknown"
163
193
  private var videoPaused = false
194
+ /// False while the server holds our media back (recording consent).
195
+ private var canPublish = true
164
196
 
165
197
  /// ring_ended reasons seen per call — the CallKit end reason.
166
198
  private var ringEndReasons: [String: String] = [:]
@@ -169,14 +201,29 @@ final class CallCore {
169
201
 
170
202
  private let snapshotLock = NSLock()
171
203
  private var lastSnapshot: [String: Any]?
204
+ /// The push's `workspace_name` per ringing call (under snapshotLock).
205
+ private var ringWorkspaces: [String: String] = [:]
206
+
207
+ private func ringWorkspaceName(_ callId: String?) -> String? {
208
+ guard let id = callId else { return nil }
209
+ snapshotLock.lock(); defer { snapshotLock.unlock() }
210
+ return ringWorkspaces[id]
211
+ }
172
212
 
173
213
  private init() {
174
214
  ringback = Ringback(resourceName: { CallCore.config?.ringback })
175
215
  eventsAdapter = EventsAdapter()
176
216
  mediaPort = LiveKitMediaPort(events: eventsAdapter)
177
217
  surfaceAdapter = SurfaceAdapter()
218
+ // One HTTP client per server, each reading its URL per request (a
219
+ // re-added server's new address applies at once); the router picks
220
+ // the one the call belongs to.
221
+ let session = CallHttpClient.defaultSession()
222
+ router = RoutedHttpPort { serverId in
223
+ CallHttpClient(baseUrl: { ServerRegistry.shared.baseUrl(serverId) }, session: session)
224
+ }
178
225
  runtime = CallCoreRuntime(
179
- http: CallHttpClient(baseUrl: { CallCore.config?.apiBaseUrl ?? "" }),
226
+ http: router,
180
227
  media: mediaPort,
181
228
  surface: surfaceAdapter,
182
229
  session: surfaceAdapter,
@@ -199,7 +246,18 @@ final class CallCore {
199
246
 
200
247
  // MARK: - native entry points
201
248
 
202
- func onRing(_ ring: RingContext) { runtime.onRing(ring) }
249
+ /// Bound to its server before the runtime sees it: a busy-decline runs
250
+ /// inside the ring's own dispatch.
251
+ func onRing(_ ring: RingContext) {
252
+ router.bindCall(ring.callId, serverId: ring.serverId)
253
+ if let name = ring.workspaceName {
254
+ snapshotLock.lock()
255
+ ringWorkspaces[ring.callId] = name
256
+ if ringWorkspaces.count > 16 { ringWorkspaces = [ring.callId: name] }
257
+ snapshotLock.unlock()
258
+ }
259
+ runtime.onRing(ring)
260
+ }
203
261
 
204
262
  func onRingEnded(callId: String, reason: String) {
205
263
  onMain { [self] in
@@ -263,20 +321,39 @@ final class CallCore {
263
321
  /// True while `callId` is the call waiting beside the current one. Main thread.
264
322
  func isWaiting(_ callId: String) -> Bool { runtime.currentState().waiting?.callId == callId }
265
323
 
266
- func place(conversationId: String, media: String, sessionToken: String) {
324
+ /// `serverId`: the server the session token is for (nil = the default).
325
+ func place(conversationId: String, media: String, sessionToken: String, serverId: String? = nil) {
267
326
  onMain { [self] in
327
+ // Busy: the runtime ignores it, so the binding must not move either.
328
+ let p = runtime.currentState().phase
329
+ guard p == .idle || p == .ended else { return }
268
330
  localEnd = false
331
+ router.bindPlace(conversationId, serverId: serverId)
269
332
  runtime.place(conversationId: conversationId, media: media, sessionToken: sessionToken)
270
333
  }
271
334
  }
272
335
 
273
- func join(callId: String, conversationId: String?, sessionToken: String) {
336
+ func join(callId: String, conversationId: String?, sessionToken: String, serverId: String? = nil) {
274
337
  onMain { [self] in
338
+ let p = runtime.currentState().phase
339
+ guard p == .idle || p == .ended else { return }
275
340
  localEnd = false
341
+ router.bindCall(callId, serverId: serverId)
276
342
  runtime.join(callId: callId, conversationId: conversationId, sessionToken: sessionToken)
277
343
  }
278
344
  }
279
345
 
346
+ /// The server `callId` runs on: its binding, else the default (when there is one).
347
+ private func server(of callId: String?) -> String? {
348
+ guard let id = callId else { return nil }
349
+ if let bound = router.serverFor(id) { return bound }
350
+ let servers = ServerRegistry.shared.servers
351
+ return servers.get(CallServers.defaultId)?.id ?? (servers.all.count == 1 ? servers.all[0].id : nil)
352
+ }
353
+
354
+ /// The server of the current call (nil = the default). Main thread.
355
+ var currentServerId: String? { server(of: runtime.currentState().callId) }
356
+
280
357
  func setMuted(_ muted: Bool) {
281
358
  onMain { [self] in
282
359
  applyMuted(muted)
@@ -309,6 +386,10 @@ final class CallCore {
309
386
  /// Not optimistic: the adapter reports the route once iOS has moved it.
310
387
  func setAudioOutput(_ id: String) { runtime.setAudioOutput(id) }
311
388
 
389
+ /// Consent given: publish the mic and camera again as the user last had
390
+ /// them. Also happens by itself once the server lets us publish.
391
+ func republish() { runtime.republish() }
392
+
312
393
  /// The current call's id and control token (main thread).
313
394
  var control: (callId: String, controlToken: String)? { runtime.control }
314
395
 
@@ -370,12 +451,43 @@ final class CallCore {
370
451
  waiting: runtime.waitingRing,
371
452
  connectionQuality: connectionQuality,
372
453
  videoPaused: videoPaused,
373
- screenSharing: screenSharing
454
+ screenSharing: screenSharing,
455
+ canPublish: canPublish,
456
+ recording: runtime.capture.recording,
457
+ transcription: runtime.capture.transcription
374
458
  )
375
- snapshotLock.lock(); lastSnapshot = snap; snapshotLock.unlock()
459
+ let snapWithServer = snap.map { withServers($0, state: state) }
460
+ snapshotLock.lock(); lastSnapshot = snapWithServer; snapshotLock.unlock()
376
461
  reconcileCallKit(state)
377
462
  reconcileDevice(state)
378
- CallCore.listener?(snap)
463
+ CallCore.listener?(snapWithServer)
464
+ }
465
+
466
+ /// The workspace each call belongs to: `serverId` and `workspaceName`
467
+ /// on the snapshot and on its waiting call.
468
+ private func withServers(_ snap: [String: Any], state: MachineState) -> [String: Any] {
469
+ var out = snap
470
+ let servers = ServerRegistry.shared.servers
471
+ let serverId = server(of: state.callId)
472
+ let ringName = ringWorkspaceName(state.callId)
473
+ out["serverId"] = serverId ?? NSNull()
474
+ out["workspaceName"] = (ringName ?? servers.get(serverId)?.name) ?? NSNull()
475
+ if var waiting = out["waiting"] as? [String: Any], let w = runtime.waitingRing {
476
+ waiting["serverId"] = (w.serverId ?? server(of: w.callId)) ?? NSNull()
477
+ waiting["workspaceName"] = (w.workspaceName ?? servers.get(w.serverId)?.name) ?? NSNull()
478
+ out["waiting"] = waiting
479
+ }
480
+ return out
481
+ }
482
+
483
+ /// "Ana · Acme" for the system call UI — the workspace only with several
484
+ /// signed in. Nil without a name: there is nothing to retitle with.
485
+ private func callTitle(_ base: String?, callId: String?) -> String? {
486
+ guard base != nil else { return nil }
487
+ let serverId = server(of: callId)
488
+ let label = ServerRegistry.shared.servers.workspaceLabel(serverId: serverId,
489
+ pushName: ringWorkspaceName(callId))
490
+ return CallServers.title(base, workspace: label)
379
491
  }
380
492
 
381
493
  private func resetExtras(_ callId: String?, _ media: String?) {
@@ -393,6 +505,7 @@ final class CallCore {
393
505
  audioOutputId = nil
394
506
  connectionQuality = "unknown"
395
507
  videoPaused = false
508
+ canPublish = true
396
509
  }
397
510
 
398
511
  /// CallKit follows the FINAL state of each dispatch.
@@ -415,7 +528,8 @@ final class CallCore {
415
528
  // Answered from the app's own UI: tell CallKit (audio follows).
416
529
  if !t.outgoing && !t.answered && state.direction == .incoming { callKit.requestAnswer(callId: t.callId) }
417
530
  if t.outgoing && state.phase == .active { callKit.reportConnected(callId: t.callId) }
418
- callKit.updateTitle(callId: t.callId, title: conversationName, video: state.media == "video")
531
+ callKit.updateTitle(callId: t.callId, title: callTitle(conversationName, callId: t.callId),
532
+ video: state.media == "video")
419
533
  default:
420
534
  break
421
535
  }
@@ -463,7 +577,8 @@ final class CallCore {
463
577
  fileprivate func sessionStart(callId: String, media: String) {
464
578
  guard callKit.tracked(callId: callId) == nil else { return } // an answered incoming call
465
579
  let state = runtime.currentState()
466
- callKit.startOutgoing(callId: callId, handle: state.conversationId ?? callId, title: runtime.conversationName,
580
+ callKit.startOutgoing(callId: callId, handle: state.conversationId ?? callId,
581
+ title: callTitle(runtime.conversationName, callId: callId),
467
582
  video: media == "video") { [weak self] in
468
583
  // CallKit refused: the call goes on without the system UI.
469
584
  self?.mediaPort.activateAudioWithoutCallKit(media: media)
@@ -516,6 +631,10 @@ final class CallCore {
516
631
  runtime.post { [weak self] in self?.screenSharing = on }
517
632
  runtime.reemit()
518
633
  }
634
+ fileprivate func publishAllowed(_ allowed: Bool) {
635
+ runtime.post { [weak self] in self?.canPublish = allowed }
636
+ runtime.reemit()
637
+ }
519
638
  }
520
639
 
521
640
  // MARK: - CallKit actions
@@ -616,6 +735,7 @@ private final class EventsAdapter: MediaEvents {
616
735
  func onLocalScreen(_ on: Bool) { core?.localScreen(on) }
617
736
  func onAudioOutputs(_ outputs: [AudioOutput], selectedId: String?) { core?.outputs(outputs, selected: selectedId) }
618
737
  func onNetwork(quality: String, videoPaused: Bool) { core?.network(quality: quality, videoPaused: videoPaused) }
738
+ func onCanPublish(_ allowed: Bool) { core?.publishAllowed(allowed) }
619
739
  }
620
740
 
621
741
  /// Host-facing entry points.
@@ -127,7 +127,10 @@ final class CallKitController: NSObject, CXProviderDelegate {
127
127
 
128
128
  func reportIncoming(ring: RingContext) {
129
129
  let hasVideo = ring.media == "video"
130
- let title = ring.conversationName ?? ring.callerName
130
+ let title = CallServers.title(
131
+ ring.conversationName ?? ring.callerName,
132
+ workspace: ServerRegistry.shared.servers.workspaceLabel(serverId: ring.serverId, pushName: ring.workspaceName)
133
+ )
131
134
  if let existing = calls.values.first(where: { $0.callId == ring.callId && !$0.ended }) {
132
135
  provider.reportNewIncomingCall(with: existing.uuid, update: update(title: title, handle: ring.conversationId, video: hasVideo)) { _ in }
133
136
  return
@@ -32,6 +32,9 @@ protocol MediaEvents: AnyObject {
32
32
  /// Our own link to the SFU (`good` | `poor` | `lost` | `unknown`), and
33
33
  /// whether incoming video is paused to keep the audio going.
34
34
  func onNetwork(quality: String, videoPaused: Bool)
35
+ /// Whether the server lets us publish (false: recording consent not
36
+ /// given yet, docs/RECORDING.md §5). Sent on every change.
37
+ func onCanPublish(_ allowed: Bool)
35
38
  }
36
39
 
37
40
  /// Step-by-step trace of the audio path, in the device log as
@@ -93,6 +96,11 @@ final class LiveKitMediaPort: NSObject, MediaPort {
93
96
  private var mutedWanted = false
94
97
  private var cameraWanted: Bool?
95
98
  private var joinedCallId: String?
99
+ /// The server lets us publish. False while it holds our media back for
100
+ /// consent: the mic/camera choices above are kept, nothing is published
101
+ /// (LiveKit unpublished what was live), and they come back as they were
102
+ /// once permission returns.
103
+ private var canPublish = true
96
104
 
97
105
  /// Our own link to the SFU, as last reported.
98
106
  private var localQuality = "unknown"
@@ -267,9 +275,14 @@ final class LiveKitMediaPort: NSObject, MediaPort {
267
275
  }
268
276
  let muted = await MainActor.run { self.mutedWanted }
269
277
  let activeNow = await MainActor.run { self.audioActive }
270
- pcTrace("connected; publishing mic muted=\(muted) audioActive=\(activeNow)")
271
- do { try await r.localParticipant.setMicrophone(enabled: !muted) } catch {
272
- NSLog("[PoolseCalls] microphone publish failed: %@", "\(error)")
278
+ // The token may say listen-only (consent required, not yet given):
279
+ // publish nothing then — the permission update brings it back.
280
+ let allowed = await MainActor.run { self.updateCanPublish(r) }
281
+ pcTrace("connected; publishing mic muted=\(muted) audioActive=\(activeNow) canPublish=\(allowed)")
282
+ if allowed {
283
+ do { try await r.localParticipant.setMicrophone(enabled: !muted) } catch {
284
+ NSLog("[PoolseCalls] microphone publish failed: %@", "\(error)")
285
+ }
273
286
  }
274
287
  // Connected and publishing: make sure nothing changed the session
275
288
  pcTrace("mic published enabled=\(r.localParticipant.isMicrophoneEnabled()) \(pcSessionDescription())")
@@ -280,7 +293,7 @@ final class LiveKitMediaPort: NSObject, MediaPort {
280
293
  self.ensureAudioActivated(r, attempt: 0)
281
294
  }
282
295
  let camera = await MainActor.run { self.cameraWanted ?? wantsVideo }
283
- if camera { await self.enableCamera(r, true) }
296
+ if camera && allowed { await self.enableCamera(r, true) }
284
297
  await MainActor.run {
285
298
  self.reportLocalCamera(r)
286
299
  self.refreshVideo()
@@ -294,7 +307,7 @@ final class LiveKitMediaPort: NSObject, MediaPort {
294
307
  connectedRoom = ObjectIdentifier(r)
295
308
  if outputWanted != nil { applyRoute() }
296
309
  events?.onConnected()
297
- if !r.remoteParticipants.isEmpty { events?.onRemoteJoined() }
310
+ if !people(r).isEmpty { events?.onRemoteJoined() }
298
311
  emit(r)
299
312
  refreshVideo()
300
313
  }
@@ -326,6 +339,7 @@ final class LiveKitMediaPort: NSObject, MediaPort {
326
339
  private func resetWanted() {
327
340
  mutedWanted = false
328
341
  cameraWanted = nil
342
+ canPublish = true
329
343
  outputWanted = nil
330
344
  pauseWork?.cancel()
331
345
  resumeWork?.cancel()
@@ -369,7 +383,7 @@ final class LiveKitMediaPort: NSObject, MediaPort {
369
383
  /// broadcast ends, from here or from the status bar), so the snapshot
370
384
  /// follows the real state rather than the request.
371
385
  func setScreenShare(_ on: Bool) {
372
- guard let r = room, connectedRoom == ObjectIdentifier(r) else { return }
386
+ guard let r = room, connectedRoom == ObjectIdentifier(r), canPublish || !on else { return }
373
387
  if !on, BroadcastManager.shared.isBroadcasting { BroadcastManager.shared.requestStop() }
374
388
  Task { [weak self] in
375
389
  do { _ = try await r.localParticipant.setScreenShare(enabled: on) } catch {
@@ -389,13 +403,14 @@ final class LiveKitMediaPort: NSObject, MediaPort {
389
403
 
390
404
  func setMuted(_ muted: Bool) {
391
405
  mutedWanted = muted
392
- guard let r = room, connectedRoom == ObjectIdentifier(r) else { return }
406
+ // Not allowed to publish: only remembered, applied on republish.
407
+ guard let r = room, connectedRoom == ObjectIdentifier(r), canPublish else { return }
393
408
  Task { _ = try? await r.localParticipant.setMicrophone(enabled: !muted) }
394
409
  }
395
410
 
396
411
  func setCamera(_ on: Bool) {
397
412
  cameraWanted = on
398
- guard let r = room, connectedRoom == ObjectIdentifier(r) else { return }
413
+ guard let r = room, connectedRoom == ObjectIdentifier(r), canPublish else { return }
399
414
  Task { [weak self] in
400
415
  await self?.enableCamera(r, on)
401
416
  await MainActor.run {
@@ -406,6 +421,55 @@ final class LiveKitMediaPort: NSObject, MediaPort {
406
421
  }
407
422
  }
408
423
 
424
+ // MARK: - publish permission (recording consent)
425
+
426
+ /// Reads the local participant's permission; reports a change. Returns it.
427
+ @discardableResult
428
+ private func updateCanPublish(_ r: Room) -> Bool {
429
+ guard room === r else { return canPublish }
430
+ let now = r.localParticipant.permissions.canPublish
431
+ if now != canPublish {
432
+ canPublish = now
433
+ pcTrace("canPublish=\(now)")
434
+ events?.onCanPublish(now)
435
+ }
436
+ return now
437
+ }
438
+
439
+ /// The server changed what we may do. Revoked: LiveKit has unpublished
440
+ /// our tracks itself — nothing to do but say so. Back: publish the mic
441
+ /// and camera the way the user last had them.
442
+ fileprivate func permissionsChanged(_ r: Room) {
443
+ guard room === r, connectedRoom == ObjectIdentifier(r) else { return }
444
+ let was = canPublish
445
+ if updateCanPublish(r) && !was { republish() }
446
+ }
447
+
448
+ /// Mic and camera as the user last had them — after consent (the app
449
+ /// calls this from its consent prompt; the permission update does it
450
+ /// too). A no-op while the server still says listen-only.
451
+ func republish() {
452
+ guard let r = room, connectedRoom == ObjectIdentifier(r), updateCanPublish(r) else { return }
453
+ let muted = mutedWanted
454
+ let camera = cameraWanted ?? (media == "video")
455
+ pcTrace("republish muted=\(muted) camera=\(camera)")
456
+ Task { [weak self] in
457
+ if r.localParticipant.isMicrophoneEnabled() != !muted {
458
+ do { try await r.localParticipant.setMicrophone(enabled: !muted) } catch {
459
+ NSLog("[PoolseCalls] microphone republish failed: %@", "\(error)")
460
+ }
461
+ }
462
+ guard let self = self else { return }
463
+ let cameraLive = await MainActor.run { self.room === r && self.localCameraTrack(r) != nil }
464
+ if camera && !cameraLive { await self.enableCamera(r, true) }
465
+ await MainActor.run {
466
+ guard self.room === r else { return }
467
+ self.reportLocalCamera(r)
468
+ self.refreshVideo()
469
+ }
470
+ }
471
+ }
472
+
409
473
  func switchCamera() {
410
474
  guard let r = room, let track = localCameraTrack(r), let capturer = track.capturer as? CameraCapturer else { return }
411
475
  Task { [weak self] in
@@ -640,7 +704,7 @@ final class LiveKitMediaPort: NSObject, MediaPort {
640
704
  guard let r = room else { return nil }
641
705
  if local { return localCameraTrack(r) }
642
706
  guard let id = participantId,
643
- let p = r.remoteParticipants.values.first(where: { $0.identity?.stringValue == id }) else { return nil }
707
+ let p = people(r).first(where: { $0.identity?.stringValue == id }) else { return nil }
644
708
  return remoteCamera(p)
645
709
  }
646
710
 
@@ -662,7 +726,7 @@ final class LiveKitMediaPort: NSObject, MediaPort {
662
726
  return pub.track as? VideoTrack
663
727
  }
664
728
  guard let id = participantId,
665
- let p = r.remoteParticipants.values.first(where: { $0.identity?.stringValue == id }) else { return nil }
729
+ let p = people(r).first(where: { $0.identity?.stringValue == id }) else { return nil }
666
730
  return remoteScreen(p)
667
731
  }
668
732
 
@@ -698,7 +762,8 @@ final class LiveKitMediaPort: NSObject, MediaPort {
698
762
  case .disconnected:
699
763
  events?.onLost()
700
764
  case .participantJoined:
701
- events?.onRemoteJoined()
765
+ // The transcript assistant or the recorder joining is nobody answering.
766
+ if !people(r).isEmpty { events?.onRemoteJoined() }
702
767
  emit(r)
703
768
  refreshVideo()
704
769
  case .tracksChanged:
@@ -712,6 +777,8 @@ final class LiveKitMediaPort: NSObject, MediaPort {
712
777
  case .quality:
713
778
  qualityChanged(r)
714
779
  emit(r)
780
+ case .permissions:
781
+ permissionsChanged(r)
715
782
  }
716
783
  }
717
784
 
@@ -765,7 +832,7 @@ final class LiveKitMediaPort: NSObject, MediaPort {
765
832
  }
766
833
 
767
834
  private func hasRemoteVideo(_ r: Room) -> Bool {
768
- r.remoteParticipants.values.contains { p in p.trackPublications.values.contains { $0.source == .camera } }
835
+ people(r).contains { p in p.trackPublications.values.contains { $0.source == .camera } }
769
836
  }
770
837
 
771
838
  private func setVideoPaused(_ r: Room, _ paused: Bool) {
@@ -793,9 +860,27 @@ final class LiveKitMediaPort: NSObject, MediaPort {
793
860
  events?.onNetwork(quality: localQuality, videoPaused: videoPaused)
794
861
  }
795
862
 
863
+ /// The remote PEOPLE: poolse's transcript assistant and LiveKit Egress's
864
+ /// recorder are in the room but are not someone in the call — never in
865
+ /// the roster, the count that ends a call left alone, or a video tile.
866
+ /// Phone (SIP) participants are people.
867
+ private func people(_ r: Room) -> [RemoteParticipant] {
868
+ r.remoteParticipants.values.filter { p in
869
+ !ServiceParticipants.isService(identity: p.identity?.stringValue ?? "", kind: Self.kindName(p.kind))
870
+ }
871
+ }
872
+
873
+ /// The kinds `ServiceParticipants` tells apart; nil for the rest.
874
+ static func kindName(_ k: Participant.Kind) -> String? {
875
+ if k == .agent { return "agent" }
876
+ if k == .egress { return "egress" }
877
+ if k == .sip { return "sip" }
878
+ return nil
879
+ }
880
+
796
881
  /// The REMOTE roster — the local participant is never included.
797
882
  private func emit(_ r: Room) {
798
- let roster = r.remoteParticipants.values.map { p -> SnapshotParticipant in
883
+ let roster = people(r).map { p -> SnapshotParticipant in
799
884
  let identity = p.identity?.stringValue ?? ""
800
885
  return SnapshotParticipant(
801
886
  userId: identity,
@@ -822,7 +907,7 @@ final class LiveKitMediaPort: NSObject, MediaPort {
822
907
 
823
908
  /// LiveKit's delegate → main-thread room events for the port.
824
909
  final class RoomObserver: NSObject, RoomDelegate, @unchecked Sendable {
825
- enum Kind { case connected, reconnecting, reconnected, disconnected, participantJoined, tracksChanged, rosterChanged, quality }
910
+ enum Kind { case connected, reconnecting, reconnected, disconnected, participantJoined, tracksChanged, rosterChanged, quality, permissions }
826
911
 
827
912
  private weak var port: LiveKitMediaPort?
828
913
  private weak var room: Room?
@@ -855,4 +940,8 @@ final class RoomObserver: NSObject, RoomDelegate, @unchecked Sendable {
855
940
  func room(_ room: Room, participant: Participant, didUpdateMetadata metadata: String?) { send(room, .rosterChanged) }
856
941
  func room(_ room: Room, participant: Participant, didUpdateAttributes attributes: [String: String]) { send(room, .rosterChanged) }
857
942
  func room(_ room: Room, participant: Participant, didUpdateConnectionQuality quality: ConnectionQuality) { send(room, .quality) }
943
+ // Only ever the local participant's (LiveKit's own LocalParticipant sends it).
944
+ func room(_ room: Room, participant: Participant, didUpdatePermissions permissions: ParticipantPermissions) {
945
+ if participant is LocalParticipant { send(room, .permissions) }
946
+ }
858
947
  }