@poolse/native 0.0.0-stage → 3.1.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 (66) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +206 -0
  3. package/README.md +116 -2
  4. package/android/build.gradle +58 -0
  5. package/android/consumer-rules.pro +11 -0
  6. package/android/src/main/AndroidManifest.xml +46 -0
  7. package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +540 -0
  8. package/android/src/main/java/dev/poolse/callcore/CallMachine.kt +492 -0
  9. package/android/src/main/java/dev/poolse/callcore/Ports.kt +132 -0
  10. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +383 -0
  11. package/android/src/main/java/dev/poolse/callcore/android/CallActionReceiver.kt +45 -0
  12. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +578 -0
  13. package/android/src/main/java/dev/poolse/callcore/android/CallForegroundService.kt +294 -0
  14. package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +207 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +161 -0
  16. package/android/src/main/java/dev/poolse/callcore/android/CallVideo.kt +36 -0
  17. package/android/src/main/java/dev/poolse/callcore/android/HandlerTimerPort.kt +42 -0
  18. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +314 -0
  19. package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +353 -0
  20. package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +103 -0
  21. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +42 -0
  22. package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +99 -0
  23. package/android/src/main/java/expo/modules/poolsecalls/CallLockscreen.kt +42 -0
  24. package/android/src/main/java/expo/modules/poolsecalls/CallPictureInPicture.kt +92 -0
  25. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallVideoView.kt +64 -0
  26. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +205 -0
  27. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +594 -0
  28. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitVideoSurface.kt +107 -0
  29. package/android/src/test/java/dev/poolse/callcore/android/CallHttpClientTest.kt +61 -0
  30. package/app.plugin.js +5 -0
  31. package/dist/index.cjs +197 -0
  32. package/dist/index.cjs.map +1 -0
  33. package/dist/index.d.cts +313 -0
  34. package/dist/index.d.ts +313 -0
  35. package/dist/index.js +161 -0
  36. package/dist/index.js.map +1 -0
  37. package/expo-module.config.json +11 -0
  38. package/ios/Core/CallCoreRuntime.swift +543 -0
  39. package/ios/Core/CallHttpClient.swift +213 -0
  40. package/ios/Core/CallMachine.swift +394 -0
  41. package/ios/Core/PORTS_READY.md +93 -0
  42. package/ios/Core/Ports.swift +238 -0
  43. package/ios/Core/SnapshotEncoding.swift +122 -0
  44. package/ios/Module/PoolseCallVideoView.swift +70 -0
  45. package/ios/Module/PoolseCallsAppDelegateSubscriber.swift +16 -0
  46. package/ios/Module/PoolseCallsModule.swift +150 -0
  47. package/ios/Platform/CallCore.swift +623 -0
  48. package/ios/Platform/CallKitController.swift +326 -0
  49. package/ios/Platform/CallPictureInPicture.swift +145 -0
  50. package/ios/Platform/LiveKitMediaPort.swift +798 -0
  51. package/ios/Platform/LiveKitVideoSurface.swift +68 -0
  52. package/ios/Platform/MessageNotifications.swift +163 -0
  53. package/ios/Platform/Ringback.swift +61 -0
  54. package/ios/Platform/VoipPush.swift +174 -0
  55. package/ios/PoolseCalls.podspec +68 -0
  56. package/package.json +52 -3
  57. package/plugin/index.js +42 -0
  58. package/plugin/package.json +1 -0
  59. package/plugin/withCallDelegate.js +35 -0
  60. package/plugin/withLockscreenCalls.js +84 -0
  61. package/plugin/withNativeCallMedia.js +19 -0
  62. package/plugin/withPictureInPicture.js +28 -0
  63. package/plugin/withRingback.js +86 -0
  64. package/src/expo-modules-core.d.ts +16 -0
  65. package/src/index.ts +564 -0
  66. package/src/react-shims.d.ts +22 -0
@@ -0,0 +1,543 @@
1
+ import Foundation
2
+
3
+ /// The engine around the machine: owns the state, serializes events,
4
+ /// executes effects through the ports, runs the timers, and emits a
5
+ /// snapshot after every change. Direct port of CallCoreRuntime.kt.
6
+ ///
7
+ /// The machine decides; this class merely obeys. If behavior is wrong,
8
+ /// the fix is in CallMachine + vectors, not here.
9
+ ///
10
+ /// Threading: ONE serial queue (the main thread), no lock. Every input —
11
+ /// PushKit, CallKit actions, URLSession callbacks, SFU events, timers, JS
12
+ /// commands — is `post`ed through `executor` (default: hop to
13
+ /// DispatchQueue.main). A result produced while effects execute is QUEUED
14
+ /// behind the current dispatch, never run inside it, and each dispatch
15
+ /// emits its snapshot only after its last effect. Tests pass a direct
16
+ /// executor; the internal trampoline gives them the same ordering.
17
+ public final class CallCoreRuntime {
18
+
19
+ public static let ENDED_LINGER_MS: Int64 = 2_500
20
+ public static let RECONNECT_BUDGET_MS: Int64 = 25_000
21
+ /// CONNECTING watchdog: two HTTP attempts plus an SFU connect fit inside.
22
+ public static let CONNECT_WATCHDOG_MS: Int64 = 20_000
23
+ /// Caller-side backstop if the server's finish/no-answer never arrives.
24
+ public static let RING_OUT_BACKSTOP_MS: Int64 = 75_000
25
+ /// Device clocks drift; the deadline is server epoch.
26
+ public static let CLOCK_SLACK_MS: Int64 = 10_000
27
+ public static let RESOLVED_LRU = 32
28
+
29
+ private static let T_DEADLINE = "ring_deadline"
30
+ private static let T_LINGER = "linger"
31
+ private static let T_RECONNECT = "reconnect_budget"
32
+ private static let T_CONNECT = "connect_watchdog"
33
+ private static let T_RING_OUT = "ring_out_backstop"
34
+ private static let T_WAITING = "waiting_deadline"
35
+ private static let T_ALONE = "alone_probe"
36
+ /// Alone in a call: ask the server after a moment (the other side's own
37
+ /// reconnect gets that long); still alone this much later, leave — a
38
+ /// call with one person in it is over, whatever the server thinks.
39
+ public static let ALONE_PROBES_MS: [Int64] = [3_000, 9_000]
40
+ /// …unless someone is being rung into it: ask again this often until
41
+ /// they pick up or it rings out.
42
+ public static let ALONE_RINGING_RECHECK_MS: Int64 = 5_000
43
+
44
+ private let http: HttpPort
45
+ private let media: MediaPort
46
+ private let surface: RingSurfacePort
47
+ private let session: CallSessionPort
48
+ private let timers: TimerPort
49
+ private let sink: SnapshotSink
50
+ private let executor: (@escaping () -> Void) -> Void
51
+
52
+ private var state: MachineState = .IDLE
53
+ /// The ring being shown (its grant answers/declines it).
54
+ private var ring: RingContext?
55
+ /// Grants of rings auto-declined busy, kept until the decline fires.
56
+ private var busyRings: [String: RingContext] = [:]
57
+ /// The ring of the call waiting beside the current one (its grant
58
+ /// answers or busy-declines it).
59
+ private var waitingRingCtx: RingContext?
60
+ /// The session bundle of the current call, once the server accepted.
61
+ private var bundle: CallSessionBundle?
62
+ /// The session token place/join were called with, for one retry.
63
+ private var sessionToken: String?
64
+ /// Call generation: bumped when a call starts CONNECTING and when one ends.
65
+ private var gen = 0
66
+ /// callIds already resolved on this device; bounded LRU (insertion/refresh order).
67
+ private var resolved: [String] = []
68
+ /// The call whose media has had someone else in it (for `onRemoteCount`).
69
+ private var remoteSeenFor: String?
70
+
71
+ private var queue: [() -> Void] = []
72
+ private var draining = false
73
+
74
+ /// `executor` runs a task on the single runtime thread; must be serial.
75
+ /// Default: inline when already on the main thread, else DispatchQueue.main.async.
76
+ public init(http: HttpPort, media: MediaPort, surface: RingSurfacePort, session: CallSessionPort,
77
+ timers: TimerPort, sink: SnapshotSink,
78
+ executor: ((@escaping () -> Void) -> Void)? = nil) {
79
+ self.http = http
80
+ self.media = media
81
+ self.surface = surface
82
+ self.session = session
83
+ self.timers = timers
84
+ self.sink = sink
85
+ self.executor = executor ?? { block in
86
+ if Thread.isMainThread { block() } else { DispatchQueue.main.async(execute: block) }
87
+ }
88
+ }
89
+
90
+ // MARK: serial queue
91
+
92
+ /// Run `block` on the runtime thread, after anything already queued.
93
+ public func post(_ block: @escaping () -> Void) {
94
+ executor { [weak self] in self?.enqueue(block) }
95
+ }
96
+
97
+ private func enqueue(_ block: @escaping () -> Void) {
98
+ queue.append(block)
99
+ if draining { return } // a dispatch is executing: run after it, not inside it
100
+ draining = true
101
+ defer { draining = false }
102
+ while !queue.isEmpty {
103
+ let next = queue.removeFirst()
104
+ next()
105
+ }
106
+ }
107
+
108
+ // MARK: inputs from adapters
109
+
110
+ public func currentState() -> MachineState { state }
111
+
112
+ /// Best name for the current call: the server's bundle, else the ring's. Runtime thread only.
113
+ public var conversationName: String? { bundle?.conversationName ?? ring?.conversationName }
114
+
115
+ /// `room` or `call`, once the server's bundle says; nil before. Runtime thread only.
116
+ public var callKind: String? { bundle?.kind }
117
+
118
+ /// The current call's id and control token — what authorizes acting on
119
+ /// the call itself (ringing more people in). Nil with no session yet.
120
+ public var control: (callId: String, controlToken: String)? {
121
+ bundle.map { ($0.callId, $0.controlToken) }
122
+ }
123
+
124
+ /// The call waiting beside the current one, with its caller's names. Runtime thread only.
125
+ public var waitingRing: RingContext? { state.waiting == nil ? nil : waitingRingCtx }
126
+
127
+ /// True if `callId` was already resolved here — its ring must never surface again.
128
+ public func isResolved(_ callId: String) -> Bool { resolved.contains(callId) }
129
+
130
+ private func markResolved(_ callId: String?) {
131
+ guard let callId = callId, !callId.hasPrefix("pending:") else { return }
132
+ resolved.removeAll { $0 == callId }
133
+ resolved.append(callId)
134
+ if resolved.count > CallCoreRuntime.RESOLVED_LRU { resolved.removeFirst(resolved.count - CallCoreRuntime.RESOLVED_LRU) }
135
+ }
136
+
137
+ /// A ring arrived — push or socket, the machine treats them alike.
138
+ public func onRing(_ ctx: RingContext) {
139
+ post { [self] in
140
+ if isResolved(ctx.callId) { return }
141
+ // A late duplicate of the ring for the call we are already IN must
142
+ // not read as "another call while busy".
143
+ let s = state
144
+ if s.callId == ctx.callId && s.phase != .idle && s.phase != .ringingIn { return }
145
+ let stale = ctx.ringDeadlineEpochMs + CallCoreRuntime.CLOCK_SLACK_MS <= timers.nowMs()
146
+ if !stale { busyRings[ctx.callId] = ctx }
147
+ dispatch(.ring(callId: ctx.callId, conversationId: ctx.conversationId, media: ctx.media, stale: stale),
148
+ ringCtx: ctx)
149
+ busyRings.removeValue(forKey: ctx.callId)
150
+ }
151
+ }
152
+
153
+ public func onRingEnded(callId: String, reason: String) {
154
+ post { [self] in
155
+ dispatch(.ringEnded(callId: callId, reason: reason))
156
+ markResolved(callId)
157
+ }
158
+ }
159
+
160
+ public func onCallFinished(callId: String, reason: String? = nil) {
161
+ post { [self] in
162
+ dispatch(.callFinished(callId: callId, reason: reason))
163
+ markResolved(callId)
164
+ }
165
+ }
166
+
167
+ public func answer() { post { [self] in dispatch(.userAnswer) } }
168
+ public func decline() { post { [self] in dispatch(.userDecline) } }
169
+ public func hangUp() { post { [self] in dispatch(.userHangup) } }
170
+ /// Call waiting: end this call and answer the one waiting. With
171
+ /// `callId`, only if that is still the call waiting (a stale tap on a
172
+ /// surface for an earlier one must not answer a different call).
173
+ public func answerWaiting(callId: String? = nil) {
174
+ post { [self] in
175
+ if let id = callId, state.waiting?.callId != id { return }
176
+ dispatch(.userAnswerWaiting)
177
+ }
178
+ }
179
+ /// Call waiting: turn the waiting call away (its caller hears busy).
180
+ public func declineWaiting(callId: String? = nil) {
181
+ post { [self] in
182
+ if let id = callId, state.waiting?.callId != id { return }
183
+ dispatch(.userDeclineWaiting)
184
+ }
185
+ }
186
+
187
+ public func place(conversationId: String, media: String, sessionToken: String) {
188
+ post { [self] in
189
+ if state.phase != .idle && state.phase != .ended { return }
190
+ self.sessionToken = sessionToken
191
+ // call_id is server-minted on place; a placeholder keys the state until the bundle arrives.
192
+ dispatch(.userPlace(callId: "pending:\(conversationId)", conversationId: conversationId, media: media))
193
+ }
194
+ }
195
+
196
+ public func join(callId: String, conversationId: String?, sessionToken: String) {
197
+ post { [self] in
198
+ if state.phase != .idle && state.phase != .ended { return }
199
+ self.sessionToken = sessionToken
200
+ dispatch(.userJoin(callId: callId, conversationId: conversationId))
201
+ }
202
+ }
203
+
204
+ /// Caller-side: the bridge resolved every ring from `ring_states`.
205
+ public func allRingsResolved(_ outcome: String) { post { [self] in dispatch(.allRingsResolved(outcome: outcome)) } }
206
+
207
+ public func onMediaConnected() { post { [self] in dispatch(.mediaConnected) } }
208
+ public func onMediaFailed() { post { [self] in dispatch(.mediaFailed) } }
209
+ public func onMediaLost() { post { [self] in dispatch(.mediaLost) } }
210
+ public func onMediaReconnecting() { post { [self] in dispatch(.mediaReconnecting) } }
211
+ public func onMediaRecovered() { post { [self] in dispatch(.mediaRecovered) } }
212
+ public func onRemoteJoined() { post { [self] in dispatch(.remoteJoined) } }
213
+
214
+ /// The media's remote roster changed: `remotes` other people in it.
215
+ ///
216
+ /// Everyone else gone from a call (not a room) usually means it is over
217
+ /// — and this device may never be told: an iPhone gets no `finished`
218
+ /// push, and the conversation channel that carries the socket event can
219
+ /// have been left. So, alone, ask the server (the reconnect endpoint
220
+ /// answers 410 for a call that is over) and end here as finished if so.
221
+ /// If the server still calls it live (it never heard the other side
222
+ /// leave), leave anyway shortly after: one person is not a call —
223
+ /// unless someone is still being rung, who is worth waiting for.
224
+ /// Someone back in the room cancels the check.
225
+ public func onRemoteCount(_ remotes: Int) {
226
+ post { [self] in
227
+ guard let callId = state.callId else { return }
228
+ if remotes > 0 {
229
+ remoteSeenFor = callId
230
+ timers.cancel(key: CallCoreRuntime.T_ALONE)
231
+ return
232
+ }
233
+ guard state.phase == .active, callKind != "room", remoteSeenFor == callId else { return }
234
+ scheduleAloneProbe(callId, attempt: 0)
235
+ }
236
+ }
237
+
238
+ private func scheduleAloneProbe(_ callId: String, attempt: Int, delayMs: Int64? = nil) {
239
+ guard attempt < CallCoreRuntime.ALONE_PROBES_MS.count else { return }
240
+ let g = gen
241
+ timers.schedule(key: CallCoreRuntime.T_ALONE,
242
+ delayMs: delayMs ?? CallCoreRuntime.ALONE_PROBES_MS[attempt]) { [weak self] in
243
+ self?.post { [weak self] in
244
+ guard let self = self, g == self.gen, self.state.callId == callId else { return }
245
+ self.probeAlone(callId, attempt: attempt)
246
+ }
247
+ }
248
+ }
249
+
250
+ private func probeAlone(_ callId: String, attempt: Int) {
251
+ guard state.phase == .active, let b = bundle else { return }
252
+ let g = gen
253
+ let last = attempt == CallCoreRuntime.ALONE_PROBES_MS.count - 1
254
+ // A still-live answer carries a fresh bundle; the current one stays
255
+ // in use (its token is still good), so it is dropped.
256
+ http.reconnect(current: b) { [weak self] res in
257
+ self?.post { [weak self] in
258
+ guard let self = self, g == self.gen, self.state.callId == callId else { return }
259
+ switch res {
260
+ case .gone:
261
+ self.dispatch(.callFinished(callId: callId, reason: "finished"))
262
+ case let .ok(fresh) where fresh.ringing > 0:
263
+ self.scheduleAloneProbe(callId, attempt: 0, delayMs: CallCoreRuntime.ALONE_RINGING_RECHECK_MS)
264
+ default:
265
+ if last { self.leaveAlone(callId) } else { self.scheduleAloneProbe(callId, attempt: attempt + 1) }
266
+ }
267
+ }
268
+ }
269
+ }
270
+
271
+ private func leaveAlone(_ callId: String) {
272
+ guard state.phase == .active, let b = bundle else { return }
273
+ http.hangup(callId: b.callId, controlToken: b.controlToken)
274
+ dispatch(.callFinished(callId: callId, reason: "finished"))
275
+ }
276
+
277
+ public func setMuted(_ muted: Bool) { post { [self] in media.setMuted(muted) } }
278
+ public func setCamera(_ on: Bool) { post { [self] in media.setCamera(on) } }
279
+ public func switchCamera() { post { [self] in media.switchCamera() } }
280
+ public func setSpeaker(_ on: Bool) { post { [self] in media.setSpeaker(on) } }
281
+ public func setAudioOutput(_ id: String) { post { [self] in media.setAudioOutput(id) } }
282
+
283
+ /// Re-emit the current state (the bridge's roster/route changed).
284
+ public func reemit() { post { [self] in if state.phase != .idle { sink.emit(state: state) } } }
285
+
286
+ // MARK: dispatch
287
+
288
+ private func isTerminal(_ p: Phase) -> Bool { p == .idle || p == .ended }
289
+
290
+ private func dispatch(_ event: Event, ringCtx: RingContext? = nil) {
291
+ let before = state
292
+ let t = CallMachine.transition(before, event)
293
+ let next = t.state
294
+ state = next
295
+ // A new call attempt, or the end of one: old callbacks go stale.
296
+ if next.phase == .connecting && before.phase != .connecting { gen += 1 }
297
+ if isTerminal(next.phase) && !isTerminal(before.phase) {
298
+ gen += 1
299
+ markResolved(before.callId)
300
+ }
301
+ for effect in t.effects { execute(effect, ringCtx: ringCtx, before: before) }
302
+ // Retire the ring grant / bundle only after EVERY effect had its chance.
303
+ if isTerminal(next.phase) {
304
+ ring = nil
305
+ bundle = nil
306
+ sessionToken = nil
307
+ }
308
+ // A waiting call that went away without becoming the current one
309
+ // (declined, cancelled, timed out) is resolved: its ring never again.
310
+ if let w = before.waiting, next.waiting?.callId != w.callId, next.callId != w.callId {
311
+ markResolved(w.callId)
312
+ }
313
+ if next.waiting == nil { waitingRingCtx = nil }
314
+ runTimers(before, next)
315
+ if next != before || !t.effects.isEmpty { sink.emit(state: next) }
316
+ }
317
+
318
+ private func execute(_ effect: Effect, ringCtx: RingContext?, before: MachineState) {
319
+ let g = gen
320
+ switch effect {
321
+ case .showRing:
322
+ // A promoted waiting call rings with the ring already on file.
323
+ if let r = ringCtx { ring = r }
324
+ if let r = ring { surface.show(ring: r) }
325
+ case .dismissRing:
326
+ // The grant is NOT retired here: HTTP_DECLINE may follow in this list.
327
+ if let r = ring ?? ringCtx { surface.dismiss(callId: r.callId) }
328
+ case .ringtoneStart: surface.ringtoneStart()
329
+ case .ringtoneStop: surface.ringtoneStop()
330
+ case .ringbackStart: surface.ringbackStart()
331
+ case .ringbackStop: surface.ringbackStop()
332
+
333
+ case .httpAnswer:
334
+ if let r = ring {
335
+ http.answer(callId: r.callId, grant: r.grant) { [weak self] res in
336
+ self?.post { self?.onHttpResult(g, res) }
337
+ }
338
+ } else {
339
+ post { [weak self] in self?.onHttpResult(g, .authFailed(code: "no_grant")) }
340
+ }
341
+ case .httpJoin:
342
+ if let callId = state.callId, let token = sessionToken {
343
+ http.join(callId: callId, sessionToken: token) { [weak self] res in
344
+ self?.post { self?.onHttpResult(g, res) }
345
+ }
346
+ } else {
347
+ post { [weak self] in self?.onHttpResult(g, .authFailed(code: "no_session")) }
348
+ }
349
+ case .httpPlace:
350
+ if let conversationId = state.conversationId, let token = sessionToken {
351
+ http.place(conversationId: conversationId, media: state.media, sessionToken: token) { [weak self] res in
352
+ self?.post { self?.onHttpResult(g, res) }
353
+ }
354
+ } else {
355
+ post { [weak self] in self?.onHttpResult(g, .authFailed(code: "no_session")) }
356
+ }
357
+ case .httpDecline:
358
+ if let r = ring { http.decline(callId: r.callId, auth: r.grant, busy: false) }
359
+ case let .httpDeclineBusy(callId):
360
+ let waitingMatch = waitingRingCtx?.callId == callId ? waitingRingCtx : nil
361
+ if let r = busyRings[callId] ?? waitingMatch { http.decline(callId: r.callId, auth: r.grant, busy: true) }
362
+ markResolved(callId)
363
+ case .httpHangup:
364
+ if let b = bundle {
365
+ http.hangup(callId: b.callId, controlToken: b.controlToken)
366
+ } else if let r = ring {
367
+ // Hanging up a connecting answer with no bundle yet: resolve the ring instead.
368
+ http.decline(callId: r.callId, auth: r.grant, busy: false)
369
+ }
370
+ case .httpReconnect:
371
+ if let b = bundle {
372
+ http.reconnect(current: b) { [weak self] res in
373
+ self?.post { self?.onReconnectResult(g, res) }
374
+ }
375
+ } else {
376
+ post { [weak self] in
377
+ guard let self = self else { return }
378
+ if g == self.gen { self.dispatch(.httpGone) }
379
+ }
380
+ }
381
+
382
+ case .mediaJoin:
383
+ if let b = bundle { media.join(bundle: b) }
384
+ case .mediaLeave:
385
+ media.leave()
386
+
387
+ case .callSessionStart:
388
+ session.start(callId: state.callId ?? "", media: state.media)
389
+ case .callSessionStop:
390
+ session.stop()
391
+ bundle = nil
392
+ ring = nil
393
+ sessionToken = nil
394
+
395
+ case .showWaiting:
396
+ waitingRingCtx = ringCtx
397
+ if let r = ringCtx { surface.showWaiting(ring: r) }
398
+ case .dismissWaiting:
399
+ // The grant is NOT retired here: HTTP_DECLINE_BUSY may precede or follow.
400
+ if let id = before.waiting?.callId { surface.dismissWaiting(callId: id) }
401
+ case .promoteWaiting:
402
+ // The old call is over: nothing it started may land on this one.
403
+ markResolved(before.callId)
404
+ gen += 1
405
+ bundle = nil
406
+ sessionToken = nil
407
+ ring = waitingRingCtx
408
+ waitingRingCtx = nil
409
+ if let id = before.waiting?.callId { surface.promoteWaiting(callId: id) }
410
+ }
411
+ }
412
+
413
+ private func onHttpResult(_ requestGen: Int, _ result: HttpResult) {
414
+ if requestGen != gen {
415
+ // The call this request belonged to is over. The server may still have
416
+ // let us in: leave with the token it just gave us, and keep nothing.
417
+ if case let .ok(b) = result { http.hangup(callId: b.callId, controlToken: b.controlToken) }
418
+ return
419
+ }
420
+ switch result {
421
+ case let .ok(b):
422
+ if let existing = bundle {
423
+ // The timeout retry's twin answered too. Same call: ignore; different: leave it.
424
+ if existing.callId != b.callId { http.hangup(callId: b.callId, controlToken: b.controlToken) }
425
+ return
426
+ }
427
+ if state.phase != .connecting {
428
+ http.hangup(callId: b.callId, controlToken: b.controlToken)
429
+ return
430
+ }
431
+ bundle = b
432
+ // The server is the authority on the call's identity, conversation and media.
433
+ state.callId = b.callId
434
+ state.conversationId = b.conversationId
435
+ state.media = b.media
436
+ dispatch(.httpOk(created: b.created))
437
+ case .gone: dispatch(.httpGone)
438
+ case .timeout: dispatch(.httpTimeout)
439
+ case let .authFailed(code): dispatch(.httpFailed(code: code))
440
+ case let .failed(code): dispatch(.httpFailed(code: code))
441
+ }
442
+ }
443
+
444
+ private func onReconnectResult(_ requestGen: Int, _ result: HttpResult) {
445
+ if requestGen != gen || state.phase != .reconnecting { return }
446
+ switch result {
447
+ case let .ok(b):
448
+ // Fresh token (and possibly URL): rejoin. MEDIA_CONNECTED returns us to ACTIVE.
449
+ bundle = b
450
+ media.join(bundle: b)
451
+ case .gone: dispatch(.httpGone)
452
+ case let .authFailed(code): dispatch(.httpFailed(code: code))
453
+ case .timeout, .failed: break // transient: the reconnect budget timer is the backstop
454
+ }
455
+ }
456
+
457
+ // MARK: timers
458
+
459
+ private func schedule(_ key: String, _ delayMs: Int64, _ event: Event) {
460
+ let g = gen
461
+ timers.schedule(key: key, delayMs: delayMs) { [weak self] in
462
+ self?.post {
463
+ guard let self = self else { return }
464
+ if g == self.gen { self.dispatch(event) }
465
+ }
466
+ }
467
+ }
468
+
469
+ private func runTimers(_ before: MachineState, _ after: MachineState) {
470
+ runWaitingTimer(before, after)
471
+ // A different call in the same phase (end-and-answer while connecting)
472
+ // needs its own timers: the old ones belong to a retired generation.
473
+ if before.phase == after.phase && before.callId == after.callId { return }
474
+ switch before.phase {
475
+ case .ringingIn: timers.cancel(key: CallCoreRuntime.T_DEADLINE)
476
+ case .ended: timers.cancel(key: CallCoreRuntime.T_LINGER)
477
+ case .reconnecting: timers.cancel(key: CallCoreRuntime.T_RECONNECT)
478
+ case .connecting: timers.cancel(key: CallCoreRuntime.T_CONNECT)
479
+ case .ringingOut: timers.cancel(key: CallCoreRuntime.T_RING_OUT)
480
+ default: break
481
+ }
482
+ switch after.phase {
483
+ case .ringingIn:
484
+ guard let deadline = ring?.ringDeadlineEpochMs else { return }
485
+ // Floor at the clock slack: a non-stale ring still gets a moment on screen.
486
+ let delay = max(deadline - timers.nowMs(), CallCoreRuntime.CLOCK_SLACK_MS)
487
+ schedule(CallCoreRuntime.T_DEADLINE, delay, .ringDeadline)
488
+ case .ended:
489
+ schedule(CallCoreRuntime.T_LINGER, CallCoreRuntime.ENDED_LINGER_MS, .lingerElapsed)
490
+ case .reconnecting:
491
+ schedule(CallCoreRuntime.T_RECONNECT, CallCoreRuntime.RECONNECT_BUDGET_MS, .reconnectBudgetElapsed)
492
+ case .connecting:
493
+ schedule(CallCoreRuntime.T_CONNECT, CallCoreRuntime.CONNECT_WATCHDOG_MS, .connectTimeout)
494
+ case .ringingOut:
495
+ schedule(CallCoreRuntime.T_RING_OUT, CallCoreRuntime.RING_OUT_BACKSTOP_MS, .allRingsResolved(outcome: "no_answer"))
496
+ default: break
497
+ }
498
+ }
499
+
500
+ private func runWaitingTimer(_ before: MachineState, _ after: MachineState) {
501
+ let was = before.waiting?.callId
502
+ let now = after.waiting?.callId
503
+ if was == now { return }
504
+ if was != nil { timers.cancel(key: CallCoreRuntime.T_WAITING) }
505
+ guard let id = now, let deadline = waitingRingCtx?.ringDeadlineEpochMs else { return }
506
+ let delay = max(deadline - timers.nowMs(), CallCoreRuntime.CLOCK_SLACK_MS)
507
+ // Keyed to the waiting call, not the generation: the current call may
508
+ // move on (connect, reconnect) while this one keeps waiting.
509
+ timers.schedule(key: CallCoreRuntime.T_WAITING, delayMs: delay) { [weak self] in
510
+ self?.post {
511
+ guard let self = self, self.state.waiting?.callId == id else { return }
512
+ self.dispatch(.waitingDeadline)
513
+ }
514
+ }
515
+ }
516
+ }
517
+
518
+ /// The real TimerPort: DispatchQueue.main work items keyed by token.
519
+ /// `nowMs` is wall-clock epoch (compared against the server's ring_deadline);
520
+ /// the delay itself counts down monotonically.
521
+ public final class MainQueueTimerPort: TimerPort {
522
+ private var pending: [String: DispatchWorkItem] = [:]
523
+ private let queue: DispatchQueue
524
+
525
+ public init(queue: DispatchQueue = .main) { self.queue = queue }
526
+
527
+ public func nowMs() -> Int64 { Int64((Date().timeIntervalSince1970 * 1000).rounded()) }
528
+
529
+ public func schedule(key: String, delayMs: Int64, fire: @escaping () -> Void) {
530
+ cancel(key: key)
531
+ var item: DispatchWorkItem!
532
+ item = DispatchWorkItem { [weak self] in
533
+ if let self = self, self.pending[key] === item { self.pending.removeValue(forKey: key) }
534
+ fire()
535
+ }
536
+ pending[key] = item
537
+ queue.asyncAfter(deadline: .now() + .milliseconds(Int(max(0, delayMs))), execute: item)
538
+ }
539
+
540
+ public func cancel(key: String) {
541
+ pending.removeValue(forKey: key)?.cancel()
542
+ }
543
+ }