cautpartener / client / src / core / calls.ts
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
/**
 * CallService (P4): 1:1 audio/video calls over the vendored lib call stack
 * (lib/media.ts — media-only RTCPeerConnections, perfect negotiation, sealed
 * SDP/ICE) for pair and match conversations. Group calls are OUT of scope in
 * v1 (a mesh call needs per-pair budgets and a roster protocol — honest
 * limitation, stated in-app).
 *
 * Signaling channel — the deliberate delta from chat: chat's lib runs ONE
 * libp2p Net per room, whose directed `/sueta/2/call-sig/1.0` streams carry
 * kSig-sealed frames between session PeerIds that double as room-crypto ids.
 * Our RoomHub runs ONE shared node for ALL rooms with no per-room network
 * identity and no directed-stream plumbing, so signaling rides the room's
 * GOSSIPSUB TOPIC instead: `RoomCrypto.roomTopic` — the lib's own "ephemeral
 * traffic (presence, calls)" derivation, one-way from the room secret and
 * opaque to the relay. Frames are the lib's sealed envelopes unchanged
 * (Sealer discipline):
 *
 *   {v:1, k:"ctl", f:<pid>, e:Envelope}            kMsg-sealed  (sealMsg/openMsg)
 *   {v:1, k:"sig", f:<pid>, to:<pid>, c:<callId>,
 *                  d:<env js>}                     kSig-sealed  (sealSignal — produced
 *                                                  and opened INSIDE lib/media.ts)
 *
 * Replay hygiene (relay operator can replay any frame): sealed ctl payloads
 * carry `ts` — receivers drop frames older/newer than CTL_FRESH_MS, so a
 * replayed invite cannot ghost-ring later. Sig frames carry the plaintext
 * callId `c` (a random UUID, no identity) at the ADAPTER layer — media.ts is
 * untouched — and receivers drop sigs whose `c` is not the active call's.
 * Honest residual: frames replayed WITHIN the freshness window / within the
 * same live call are indistinguishable from gossip re-delivery; ctl dedupe
 * (doneCallIds) and media.ts perfect negotiation make them no-ops at worst.
 *
 * `pid` = the per-room per-session RoomCrypto peer id; the plaintext f/to are
 * routing hints only — both AADs bind them, so a spoofed header just fails to
 * decrypt and is dropped (v1 §3 discipline). In a 1:1 room, decryptability IS
 * membership: only the two identities (all their devices) can derive the
 * room's keys. Own-device traffic is told apart by the sealed `pub` field.
 *
 * Media never touches libp2p: each call runs ONE dedicated media-only
 * RTCPeerConnection (DTLS-SRTP, own ICE/TURN via lib/turn.ts). An established
 * call keeps flowing if the relay dies — signaling is only needed to
 * (re)negotiate. Politeness = lexicographically smaller session pid
 * (media.ts: `myId < id`), deterministic and asymmetric per pair.
 *
 * Co-presence: calls are inherently synchronous — BOTH sides must be on the
 * live mesh. The service subscribes every pair/match conversation's call
 * topic whenever the mesh is up, so incoming calls ring app-wide;
 * callableNow() (subscribers of the peer's call topic > 0) gates the call
 * buttons honestly. The mailbox plays no part except the caller-appended
 * {t:"call", ts, kind:"missed"|"ended", dur?} room-log marker, which reaches
 * an offline peer through normal replay.
 */

import { APP_SALT } from "../config";
import { RoomCrypto, type Envelope } from "../lib/crypto";
import { Media, CALL_SIG_PROTOCOL } from "../lib/media";
import type { Net } from "../lib/net";
import { IceConfig } from "../lib/turn";
import { matchByConvId, matchRoomSecret } from "../public/match-service";
import type { ChatService } from "./conversations";
import type { RoomHub } from "./hub";
import { pairSecret } from "./pairwise";

export const RING_MS_DEFAULT = 45_000;
const INVITE_REPEAT_MS = 2000;
const INVITE_STALE_MS = 6500; // no invite re-send for this long ⇒ caller gone
const CONNECT_TIMEOUT_MS = 30_000;
const RECONNECT_GRACE_MS = 20_000; // active call with a dead pc — then give up
const VIDEO_KBPS = 450; // chat's cap: fits one coturn allocation either way
const MAX_FRAME_CHARS = 64 * 1024;
const CTL_FRESH_MS = 120_000; // sealed ctl frames outside |now-ts| ≤ this are replays

export type CallPhase = "idle" | "outgoing" | "incoming" | "connecting" | "active";

export interface CallCtl {
  kind: "call-ctl";
  op: "invite" | "cancel" | "accept" | "decline" | "hangup";
  callId: string;
  /** Sender clock — receivers drop frames outside CTL_FRESH_MS (replay guard). */
  ts: number;
  /** Caller/acceptor identity pub — own-device filtering + peer binding. */
  pub?: string;
  video?: boolean;
  busy?: boolean;
}

/** {t:"call"} room-log op — the ONLY durable trace of a call (§5d). */
export interface CallOp {
  t: "call";
  ts: number;
  kind: "missed" | "ended";
  /** Seconds, ended only. */
  dur?: number;
}

interface Channel {
  convId: string;
  peerPub: string;
  crypto: RoomCrypto;
  topic: string;
}

interface CallState {
  phase: Exclude<CallPhase, "idle">;
  dir: "out" | "in";
  convId: string;
  callId: string;
  video: boolean;
  /** The remote side's per-room session pid (learned from invite/accept). */
  peerPid: string | null;
  media: Media | null;
  local: MediaStream | null;
  remote: MediaStream | null;
  micOn: boolean;
  camOn: boolean;
  facing: "user" | "environment";
  connectedAt: number | null;
  /** Last time the media pc looked alive (reconnect watchdog). */
  lastAliveAt: number | null;
  timers: ReturnType<typeof setTimeout>[];
  intervals: ReturnType<typeof setInterval>[];
}

export type CallErrorKind = "denied" | "nodevice" | "busydevice" | "failed";

const isIOS = (): boolean =>
  /iP(hone|ad|od)/.test(navigator.userAgent) || (navigator.maxTouchPoints > 1 && /Mac/.test(navigator.userAgent));

/** getUserMedia failures are not all permission problems — say which it was. */
export function gumErrorKind(err: unknown): CallErrorKind {
  switch ((err as DOMException | undefined)?.name) {
    case "NotFoundError":
    case "OverconstrainedError":
      return "nodevice";
    case "NotReadableError":
      return "busydevice";
    default:
      return "denied";
  }
}

function videoConstraints(facing: "user" | "environment"): MediaTrackConstraints {
  return { facingMode: facing, width: { ideal: 640 }, height: { ideal: 480 }, frameRate: { ideal: 24, max: 30 } };
}

const AUDIO_CONSTRAINTS: MediaTrackConstraints = {
  echoCancellation: true,
  noiseSuppression: true,
  autoGainControl: true,
};

export class CallService {
  #hub: RoomHub;
  #chat: ChatService;
  #myPub: string;
  #seed: string;
  #ice: IceConfig;
  #channels = new Map<string, Channel>(); // convId → subscribed channel
  #building = new Set<string>(); // convId subscriptions in flight
  #ringMs = RING_MS_DEFAULT;
  #call: CallState | null = null;
  #acquiring = false; // one getUserMedia at a time (chat's orphan-stream guard)
  #wakeLock: { release(): Promise<void> } | null = null;
  #stopped = false;

  /** UI re-render hook — phase/stream/mute changes. */
  onChange: () => void = () => {};
  /** Transient outcomes the UI should toast (declined/busy/failed/denied…). */
  onNotice: (kind: "declined" | "busy" | "missed" | "ended" | "recoverfailed" | CallErrorKind) => void = () => {};

  constructor(opts: { hub: RoomHub; chat: ChatService; identity: { seed: string; pub: string }; turnCredsUrl: string }) {
    this.#hub = opts.hub;
    this.#chat = opts.chat;
    this.#myPub = opts.identity.pub;
    this.#seed = opts.identity.seed;
    this.#ice = new IceConfig(opts.turnCredsUrl);
    // iOS ends tracks under screen lock — recover on wake (chat's pattern)
    document.addEventListener("visibilitychange", () => {
      if (document.visibilityState === "visible" && this.#call?.phase === "active") void this.#recoverTracks();
    });
  }

  get phase(): CallPhase {
    return this.#call?.phase ?? "idle";
  }

  get current(): {
    phase: CallPhase;
    dir: "out" | "in";
    convId: string;
    video: boolean;
    remote: MediaStream | null;
    local: MediaStream | null;
    micOn: boolean;
    camOn: boolean;
    connectedAt: number | null;
  } | null {
    const c = this.#call;
    if (!c) return null;
    return {
      phase: c.phase,
      dir: c.dir,
      convId: c.convId,
      video: c.video,
      remote: c.remote,
      local: c.local,
      micOn: c.micOn,
      camOn: c.camOn,
      connectedAt: c.connectedAt,
    };
  }

  /** Elapsed call seconds (0 before the media path connected). */
  elapsedSec(): number {
    const at = this.#call?.connectedAt;
    return at ? Math.floor((Date.now() - at) / 1000) : 0;
  }

  /** e2e/debug introspection — no secrets, no room ids. */
  debug(): { phase: CallPhase; conn: string | null; video: boolean; elapsed: number } {
    const st = this.#call?.media?.debugState() ?? [];
    return {
      phase: this.phase,
      conn: (st[0]?.conn as string | undefined) ?? null,
      video: this.#call?.video ?? false,
      elapsed: this.elapsedSec(),
    };
  }

  /** e2e hook: shorten the ring timeout (both roles read it). */
  testSetRingMs(ms: number): void {
    if (Number.isFinite(ms) && ms >= 1000) this.#ringMs = ms;
  }

  // ---- channel lifecycle (call-topic subscriptions) ------------------------

  /**
   * (Re)subscribe the call topics of every pair/match conversation. Called at
   * boot and on contact/match changes. Being callable REQUIRES the live mesh,
   * so this starts it when at least one callable conversation exists — the
   * one deliberate widening of the M3b "lazy live" policy (the hidden-suspend
   * battery valve still applies unchanged).
   */
  refresh(): void {
    if (this.#stopped) return;
    const wanted = new Map<string, { kind: "pair" | "match"; peerPub: string }>();
    for (const conv of this.#chat.conversations()) {
      if (conv.ref.kind === "pair") wanted.set(conv.ref.id, { kind: "pair", peerPub: conv.ref.id });
      else if (conv.ref.kind === "match" && conv.matchPeer) wanted.set(conv.ref.id, { kind: "match", peerPub: conv.matchPeer });
    }
    for (const [convId, ch] of [...this.#channels]) {
      if (!wanted.has(convId)) {
        this.#hub.live.leaveTopic(ch.topic);
        this.#channels.delete(convId);
      }
    }
    if (wanted.size > 0) this.#hub.ensureLive();
    for (const [convId, w] of wanted) {
      if (this.#channels.has(convId) || this.#building.has(convId)) continue;
      this.#building.add(convId);
      void this.#buildChannel(convId, w.kind, w.peerPub)
        .catch(() => {})
        .finally(() => this.#building.delete(convId));
    }
  }

  async #buildChannel(convId: string, kind: "pair" | "match", peerPub: string): Promise<void> {
    let secret: string;
    if (kind === "pair") {
      const contact = this.#chat.contactOf(convId);
      if (!contact) return;
      secret = await pairSecret({ seed: this.#seed, pub: this.#myPub }, { pub: contact.pub, xPub: contact.xPub });
    } else {
      const match = matchByConvId(convId);
      if (!match) return;
      secret = await matchRoomSecret(match);
    }
    if (this.#stopped || this.#channels.has(convId)) return;
    const crypto = await RoomCrypto.create(secret, APP_SALT);
    const ch: Channel = { convId, peerPub, crypto, topic: crypto.roomTopic };
    this.#channels.set(convId, ch);
    this.#hub.live.joinTopic(ch.topic, (data) => void this.#onTopicData(ch, data));
  }

  /** Peer devices currently subscribed to this conversation's call topic. */
  callableNow(convId: string): boolean {
    const ch = this.#channels.get(convId);
    return !!ch && this.#hub.live.subscribersOf(ch.topic) > 0;
  }

  /** Is this a conversation calls support at all (pair/match, not group)? */
  supports(convId: string): boolean {
    const ref = this.#chat.resolve(convId);
    return ref?.kind === "pair" || ref?.kind === "match";
  }

  // ---- wire ----------------------------------------------------------------

  #sendCtl(ch: Channel, ctl: Omit<CallCtl, "kind" | "ts">): void {
    void ch.crypto
      .sealMsg({ kind: "call-ctl", ts: Date.now(), ...ctl } satisfies CallCtl)
      .then((env) => {
        const frame = JSON.stringify({ v: 1, k: "ctl", f: ch.crypto.peerId, e: env });
        return this.#hub.live.publishTopic(ch.topic, new TextEncoder().encode(frame));
      })
      .catch(() => {});
  }

  async #onTopicData(ch: Channel, data: Uint8Array): Promise<void> {
    if (data.length > MAX_FRAME_CHARS) return;
    let frame: { v?: number; k?: string; f?: string; to?: string; c?: string; e?: Envelope; d?: string };
    try {
      frame = JSON.parse(new TextDecoder().decode(data)) as typeof frame;
    } catch {
      return;
    }
    if (frame.v !== 1 || typeof frame.f !== "string" || frame.f.length === 0 || frame.f.length > 128) return;
    if (frame.f === ch.crypto.peerId) return; // own frame echoed back
    if (frame.k === "ctl" && frame.e) {
      const payload = (await ch.crypto.openMsg(frame.f, frame.e)) as CallCtl | null;
      if (payload === null || payload.kind !== "call-ctl") return; // not a member — drop silently
      this.#onCtl(ch, frame.f, payload);
    } else if (frame.k === "sig" && typeof frame.d === "string") {
      // addressed sealed signaling for the media layer; AAD re-binds from/to
      if (frame.to !== ch.crypto.peerId) return;
      const call = this.#call;
      if (!call || call.convId !== ch.convId) return;
      if (call.peerPid !== null && call.peerPid !== frame.f) return; // not this call's peer
      if (frame.c !== call.callId) return; // stale/replayed sig from another call
      const bytes = new TextEncoder().encode(frame.d);
      if (call.media && this.#mediaOnFrame) {
        this.#mediaOnFrame(frame.f, bytes);
      } else if (this.#pendingSig.length < 32) {
        // the peer's first offer can outrun our accept-processing on the
        // topic — buffer, flush the moment the media pc exists (drop = deadlock)
        this.#pendingSig.push({ from: frame.f, bytes });
      }
    }
  }

  /** lib/media.ts's registered frame handler (captured by the Net adapter). */
  #mediaOnFrame: ((from: string, frame: Uint8Array) => void) | null = null;
  /** Sealed sig frames that arrived before this call's Media existed. */
  #pendingSig: { from: string; bytes: Uint8Array }[] = [];

  #flushPendingSig(call: CallState): void {
    if (!call.media || !this.#mediaOnFrame) return;
    for (const f of this.#pendingSig.splice(0)) {
      if (call.peerPid === null || call.peerPid === f.from) this.#mediaOnFrame(f.from, f.bytes);
    }
  }

  /**
   * The slice of lib Net that lib/media.ts actually uses (myId, handleFrames,
   * sendFrame), backed by the room's sealed gossipsub topic. Net is a nominal
   * class (private fields), so the adapter crosses with a cast — the same
   * pattern the hub blesses for app-plane log ops.
   */
  #netAdapter(ch: Channel, callId: string): Net {
    const adapter = {
      myId: ch.crypto.peerId,
      handleFrames: (protocol: string, onFrame: (from: string, frame: Uint8Array) => void): Promise<void> => {
        if (protocol === CALL_SIG_PROTOCOL) this.#mediaOnFrame = onFrame;
        return Promise.resolve();
      },
      sendFrame: (_protocol: string, peer: string, frame: Uint8Array): Promise<boolean> => {
        // `c` binds the sealed sig to THIS call at the adapter layer (replay
        // guard) — a random UUID, so the plaintext hint leaks no identity
        const wire = JSON.stringify({ v: 1, k: "sig", f: ch.crypto.peerId, to: peer, c: callId, d: new TextDecoder().decode(frame) });
        void this.#hub.live.publishTopic(ch.topic, new TextEncoder().encode(wire));
        return Promise.resolve(true);
      },
    };
    return adapter as unknown as Net;
  }

  #newMedia(ch: Channel, callId: string): Media {
    return new Media({
      crypto: ch.crypto,
      ice: this.#ice,
      net: this.#netAdapter(ch, callId),
      myName: () => "", // names never ride the wire — the UI shows LOCAL data
      events: {
        track: (peer, stream) => {
          const call = this.#call;
          if (!call || call.peerPid !== peer) return;
          call.remote = stream;
          this.#emit();
        },
        mediaState: (peer) => {
          // fires when the media pc reached "connected" — the truthful moment
          const call = this.#call;
          if (!call || call.peerPid !== peer) return;
          if (call.connectedAt === null) {
            call.connectedAt = Date.now();
            call.phase = "active";
            this.#emit();
          }
        },
      },
    });
  }

  // ---- outgoing ------------------------------------------------------------

  /**
   * Start a call. MUST run inside a user gesture (iOS getUserMedia rule —
   * the UI wires it directly to the button's click handler).
   */
  async start(convId: string, video: boolean): Promise<void> {
    if (this.#call || this.#acquiring || this.#stopped) return;
    const ch = this.#channels.get(convId);
    if (!ch) return;
    const local = await this.#getUserMedia(video, "user");
    if (!local) return; // onNotice already fired with the honest reason
    if (this.#call || this.#stopped) {
      // something rang (or stop()) while the permission prompt was open —
      // adopting these tracks would orphan them live
      local.getTracks().forEach((t) => t.stop());
      return;
    }
    const callId = crypto.randomUUID();
    const call = this.#newCall({ phase: "outgoing", dir: "out", convId, callId, video, local });
    call.camOn = video;
    void this.#wake();
    const invite = (): void => this.#sendCtl(ch, { op: "invite", callId, video, pub: this.#myPub });
    invite();
    call.intervals.push(setInterval(invite, INVITE_REPEAT_MS));
    call.timers.push(
      setTimeout(() => {
        // nobody answered: cancel the ring and leave the durable marker
        if (this.#call !== call || call.phase !== "outgoing") return;
        this.#sendCtl(ch, { op: "cancel", callId });
        this.#appendMarkerIfCaller(call);
        this.onNotice("missed");
        this.#teardown();
      }, this.#ringMs),
    );
    this.#emit();
  }

  /** Caller gives up while ringing (or either side hangs up in-call). */
  hangup(): void {
    const call = this.#call;
    if (!call) return;
    const ch = this.#channels.get(call.convId);
    if (call.phase === "outgoing") {
      if (ch) this.#sendCtl(ch, { op: "cancel", callId: call.callId });
      this.#appendMarkerIfCaller(call);
    } else if (call.phase === "incoming") {
      this.decline();
      return;
    } else {
      // connecting or active: never-connected logs `missed`, connected `ended`
      if (ch) this.#sendCtl(ch, { op: "hangup", callId: call.callId });
      this.#appendMarkerIfCaller(call);
    }
    this.#teardown();
  }

  // ---- incoming ------------------------------------------------------------

  #incomingStaleTimer: ReturnType<typeof setTimeout> | null = null;

  #onCtl(ch: Channel, fromPid: string, ctl: CallCtl): void {
    if (typeof ctl.callId !== "string" || ctl.callId.length === 0 || ctl.callId.length > 64) return;
    if (ctl.pub !== undefined && (typeof ctl.pub !== "string" || ctl.pub.length > 64)) return;
    // freshness: a relay operator can replay sealed frames verbatim — a stale
    // ts kills the ghost-ring (and every other late replay) at the door
    if (typeof ctl.ts !== "number" || Math.abs(Date.now() - ctl.ts) > CTL_FRESH_MS) return;
    const call = this.#call;
    switch (ctl.op) {
      case "invite": {
        if (ctl.pub === this.#myPub) return; // my own other device dialing out
        if (this.#doneCallIds.has(ctl.callId)) return; // late re-invite of a finished ring
        if (call) {
          if (call.callId === ctl.callId) {
            // ring keep-alive for the call we're showing
            if (call.phase === "incoming") this.#armIncomingStale();
            return;
          }
          // already busy with another call — auto-decline politely
          this.#sendCtl(ch, { op: "decline", callId: ctl.callId, busy: true });
          return;
        }
        const c = this.#newCall({ phase: "incoming", dir: "in", convId: ch.convId, callId: ctl.callId, video: ctl.video === true, local: null });
        c.peerPid = fromPid;
        c.timers.push(
          setTimeout(() => {
            // never answered: dismiss quietly — the CALLER appends the marker
            if (this.#call === c && c.phase === "incoming") this.#teardown();
          }, this.#ringMs),
        );
        this.#armIncomingStale();
        this.#emit();
        return;
      }
      case "cancel": {
        if (call?.callId !== ctl.callId) return;
        if (call.phase === "incoming") {
          this.#teardown();
        } else if (call.phase === "connecting" && call.dir === "in") {
          // accept-after-timeout: the caller already gave up — do NOT hold a
          // live mic/cam in "Connecting…" until the connect timeout
          this.onNotice("ended");
          this.#teardown();
        }
        return;
      }
      case "accept": {
        if (ctl.pub === this.#myPub) {
          // my own other device answered this ring — stop ringing here
          if (call?.callId === ctl.callId && call.phase === "incoming") this.#teardown();
          return;
        }
        if (!call || call.callId !== ctl.callId || call.dir !== "out" || call.phase !== "outgoing") return;
        if (ctl.pub !== ch.peerPub) return; // bound to the conversation's peer
        this.#clearRing(call);
        call.phase = "connecting";
        call.peerPid = fromPid;
        call.media = this.#newMedia(ch, call.callId);
        this.#flushPendingSig(call);
        if (call.local) call.media.attachMedia(fromPid, call.local, { maxVideoKbps: VIDEO_KBPS });
        this.#armConnectTimeout(call);
        this.#emit();
        return;
      }
      case "decline": {
        if (!call || call.callId !== ctl.callId || call.dir !== "out" || call.phase !== "outgoing") return;
        this.onNotice(ctl.busy === true ? "busy" : "declined");
        this.#teardown();
        return;
      }
      case "hangup": {
        if (!call || call.callId !== ctl.callId) return;
        if (call.phase === "connecting" || call.phase === "active") {
          this.#appendMarkerIfCaller(call);
          this.onNotice("ended");
          this.#teardown();
        }
        return;
      }
    }
  }

  /**
   * Accept the ringing call. MUST run inside a user gesture (iOS) — wired
   * straight to the overlay buttons. `withVideo` may upgrade an audio invite
   * only locally (our camera on; the caller decides their own).
   */
  async accept(withVideo: boolean): Promise<void> {
    const call = this.#call;
    if (!call || call.phase !== "incoming" || this.#acquiring) return;
    const ch = this.#channels.get(call.convId);
    if (!ch || !call.peerPid) return;
    // the user has acted — the ring/stale timers must not race the permission
    // prompt (getUserMedia can outlast any ring timeout) and tear us down
    this.#clearRing(call);
    const local = await this.#getUserMedia(withVideo, "user");
    if (!local) {
      // honest failure: stop ringing here and tell the caller
      this.#sendCtl(ch, { op: "decline", callId: call.callId });
      this.#teardown();
      return;
    }
    if (this.#call !== call || call.phase !== "incoming") {
      local.getTracks().forEach((t) => t.stop()); // caller cancelled while prompting
      return;
    }
    call.local = local;
    call.video = call.video || withVideo;
    call.camOn = withVideo;
    call.micOn = true;
    call.phase = "connecting";
    // media pc first, THEN the accept — the caller's offer finds us listening
    call.media = this.#newMedia(ch, call.callId);
    this.#flushPendingSig(call);
    call.media.attachMedia(call.peerPid, local, { maxVideoKbps: VIDEO_KBPS });
    this.#sendCtl(ch, { op: "accept", callId: call.callId, video: withVideo, pub: this.#myPub });
    this.#armConnectTimeout(call);
    void this.#wake();
    this.#emit();
  }

  /** Decline the ringing call (also the busy path's manual variant). */
  decline(): void {
    const call = this.#call;
    if (!call || call.phase !== "incoming") return;
    const ch = this.#channels.get(call.convId);
    if (ch) this.#sendCtl(ch, { op: "decline", callId: call.callId });
    this.#teardown();
  }

  // ---- in-call controls ----------------------------------------------------

  toggleMic(): void {
    const call = this.#call;
    const track = call?.local?.getAudioTracks()[0];
    if (!call || !track) return;
    call.micOn = !call.micOn;
    track.enabled = call.micOn;
    this.#emit();
  }

  /** Camera on/off. Off = stop the track (mute LED honesty); on re-acquires. */
  async toggleCam(): Promise<void> {
    const call = this.#call;
    if (!call?.local || this.#acquiring) return;
    if (call.camOn) {
      for (const t of call.local.getVideoTracks()) {
        t.stop();
        call.local.removeTrack(t);
      }
      call.camOn = false;
    } else {
      if (!(await this.#addCameraTrack(call, call.facing))) return;
      call.camOn = true;
      call.video = true;
    }
    this.#reattach(call);
    this.#emit();
  }

  /** Front/back camera flip (video calls). */
  async flipCam(): Promise<void> {
    const call = this.#call;
    if (!call?.local || !call.camOn || this.#acquiring) return;
    const next = call.facing === "user" ? "environment" : "user";
    for (const t of call.local.getVideoTracks()) {
      t.stop();
      call.local.removeTrack(t);
    }
    if (!(await this.#addCameraTrack(call, next))) {
      if (this.#call !== call) return; // died mid-flip — nothing left to patch
      call.camOn = false; // honest: the other camera failed, we are dark now
      this.#reattach(call);
      this.#emit();
      return;
    }
    call.facing = next;
    this.#reattach(call);
    this.#emit();
  }

  async #addCameraTrack(call: CallState, facing: "user" | "environment"): Promise<boolean> {
    this.#acquiring = true;
    try {
      if (isIOS()) {
        // iOS: a second getUserMedia can kill the live mic — re-acquire both
        const fresh = await navigator.mediaDevices.getUserMedia({ audio: AUDIO_CONSTRAINTS, video: videoConstraints(facing) });
        if (this.#call !== call) {
          // the call died while the prompt/acquire was in flight — adopting
          // these tracks would leave camera+mic live forever (start/accept guard)
          fresh.getTracks().forEach((t) => t.stop());
          return false;
        }
        call.local?.getTracks().forEach((t) => t.stop());
        call.local = fresh;
        const mic = fresh.getAudioTracks()[0];
        if (mic) mic.enabled = call.micOn;
      } else {
        const cam = await navigator.mediaDevices.getUserMedia({ video: videoConstraints(facing) });
        if (this.#call !== call) {
          cam.getTracks().forEach((t) => t.stop());
          return false;
        }
        call.local?.addTrack(cam.getVideoTracks()[0]);
      }
      return true;
    } catch (err) {
      if (this.#call === call) this.onNotice(gumErrorKind(err));
      return false;
    } finally {
      this.#acquiring = false;
    }
  }

  #reattach(call: CallState): void {
    if (call.media && call.peerPid && call.local) call.media.attachMedia(call.peerPid, call.local, { maxVideoKbps: VIDEO_KBPS });
  }

  // ---- internals -----------------------------------------------------------

  async #getUserMedia(video: boolean, facing: "user" | "environment"): Promise<MediaStream | null> {
    if (!navigator.mediaDevices?.getUserMedia) {
      this.onNotice("nodevice");
      return null;
    }
    this.#acquiring = true;
    try {
      return await navigator.mediaDevices.getUserMedia({
        audio: AUDIO_CONSTRAINTS,
        ...(video ? { video: videoConstraints(facing) } : {}),
      });
    } catch (err) {
      this.onNotice(gumErrorKind(err));
      return null;
    } finally {
      this.#acquiring = false;
    }
  }

  #newCall(init: Pick<CallState, "phase" | "dir" | "convId" | "callId" | "video" | "local">): CallState {
    const call: CallState = {
      ...init,
      peerPid: null,
      media: null,
      remote: null,
      micOn: true,
      camOn: false,
      facing: "user",
      connectedAt: null,
      lastAliveAt: null,
      timers: [],
      intervals: [],
    };
    this.#call = call;
    return call;
  }

  #armIncomingStale(): void {
    if (this.#incomingStaleTimer) clearTimeout(this.#incomingStaleTimer);
    this.#incomingStaleTimer = setTimeout(() => {
      this.#incomingStaleTimer = null;
      // invites stopped arriving — the caller crashed or lost the mesh
      if (this.#call?.phase === "incoming") this.#teardown();
    }, INVITE_STALE_MS);
  }

  #armConnectTimeout(call: CallState): void {
    call.timers.push(
      setTimeout(() => {
        if (this.#call !== call) return;
        if (call.phase === "connecting") {
          // never connected: honest failure — caller leaves the missed marker
          this.#appendMarkerIfCaller(call);
          this.onNotice("failed");
          this.#teardown();
        }
      }, CONNECT_TIMEOUT_MS),
    );
    // watchdog: an ACTIVE call whose pc dies and never recovers must end
    call.intervals.push(
      setInterval(() => {
        if (this.#call !== call || call.phase !== "active" || !call.media) return;
        const conn = call.media.debugState()[0]?.conn as string | undefined;
        if (conn === "connected" || conn === "connecting" || conn === "new") {
          call.lastAliveAt = Date.now();
        } else if (Date.now() - (call.lastAliveAt ?? call.connectedAt ?? Date.now()) > RECONNECT_GRACE_MS) {
          this.#appendMarkerIfCaller(call);
          this.onNotice("ended");
          this.#teardown();
        }
      }, 2000),
    );
  }

  #clearRing(call: CallState): void {
    for (const t of call.timers.splice(0)) clearTimeout(t);
    for (const i of call.intervals.splice(0)) clearInterval(i);
    if (this.#incomingStaleTimer) {
      clearTimeout(this.#incomingStaleTimer);
      this.#incomingStaleTimer = null;
    }
  }

  /** The CALLER owns the durable markers — exactly one per call. */
  #endedAppended = false;

  /**
   * §5d semantics: a call that never reached connected is `missed` no matter
   * how it died (ring timeout, caller gave up, never-connected accept —
   * including a manual hangup while still "connecting"); `ended` (+dur) is
   * reserved for calls that actually connected.
   */
  #appendMarkerIfCaller(call: CallState): void {
    if (call.dir !== "out" || this.#endedAppended) return;
    this.#endedAppended = true;
    if (call.connectedAt === null) {
      this.#appendCallOp(call.convId, { t: "call", ts: Date.now(), kind: "missed" });
      return;
    }
    const dur = Math.max(1, Math.round((Date.now() - call.connectedAt) / 1000));
    this.#appendCallOp(call.convId, { t: "call", ts: Date.now(), kind: "ended", dur });
  }

  #appendCallOp(convId: string, op: CallOp): void {
    void this.#chat
      .open(convId)
      .then((room) => room?.handle?.append(op))
      .catch(() => {});
  }

  /** Finished callIds — a late in-flight invite must not re-ring them. */
  #doneCallIds = new Set<string>();

  #teardown(): void {
    const call = this.#call;
    if (!call) return;
    this.#doneCallIds.add(call.callId);
    if (this.#doneCallIds.size > 32) {
      const oldest = this.#doneCallIds.values().next().value;
      if (oldest !== undefined) this.#doneCallIds.delete(oldest);
    }
    this.#clearRing(call);
    call.media?.close();
    this.#mediaOnFrame = null;
    this.#pendingSig = [];
    call.local?.getTracks().forEach((t) => t.stop());
    this.#call = null;
    this.#endedAppended = false;
    void this.#wakeLock?.release().catch(() => {});
    this.#wakeLock = null;
    this.#emit();
  }

  async #wake(): Promise<void> {
    try {
      const lock =
        (await (
          navigator as Navigator & { wakeLock?: { request(t: string): Promise<{ release(): Promise<void> }> } }
        ).wakeLock?.request("screen")) ?? null;
      if (!lock) return;
      if (!this.#call) {
        // teardown won the race — a lock adopted now would burn screen forever
        void lock.release().catch(() => {});
        return;
      }
      this.#wakeLock = lock;
    } catch {}
  }

  /** iOS ends tracks under screen lock — re-acquire or degrade honestly. */
  async #recoverTracks(): Promise<void> {
    const call = this.#call;
    if (!call?.local || this.#acquiring) return;
    const dead = call.local.getTracks().some((t) => t.readyState === "ended");
    if (!dead) return void this.#wake();
    this.#acquiring = true;
    try {
      const fresh = await navigator.mediaDevices.getUserMedia({
        audio: AUDIO_CONSTRAINTS,
        ...(call.camOn ? { video: videoConstraints(call.facing) } : {}),
      });
      if (this.#call !== call) {
        // call torn down while acquiring — adopting the fresh tracks would
        // keep camera/mic live on a dead call until reload (start/accept guard)
        fresh.getTracks().forEach((t) => t.stop());
        return;
      }
      call.local.getTracks().forEach((t) => t.stop());
      call.local = fresh;
      const mic = fresh.getAudioTracks()[0];
      if (mic) mic.enabled = call.micOn;
      this.#reattach(call);
    } catch {
      if (this.#call === call) {
        call.camOn = false; // degrade honestly rather than pretend
        this.onNotice("recoverfailed"); // silent mic death is a lie — say it
      }
    } finally {
      this.#acquiring = false;
    }
    if (this.#call !== call) return;
    void this.#wake();
    this.#emit();
  }

  #emit(): void {
    try {
      this.onChange();
    } catch {}
  }

  stop(): void {
    this.#stopped = true;
    this.#teardown();
    for (const ch of this.#channels.values()) this.#hub.live.leaveTopic(ch.topic);
    this.#channels.clear();
  }
}

static mirror of HEAD · about · clone: git clone https://cod-sursa.cautpartener.ro/cautpartener.git