@decentnetwork/beagle 0.1.131 → 0.1.138

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.
@@ -291,9 +291,10 @@ var PeerWebRTC = (() => {
291
291
  const signal = { type: obj.type, callId: obj.callId };
292
292
  if (typeof obj.sdp === "string")
293
293
  signal.sdp = obj.sdp;
294
- if (Array.isArray(obj.candidates)) {
295
- signal.candidates = obj.candidates.filter((c) => c && typeof c.sdp === "string").map((c) => ({
296
- sdp: c.sdp,
294
+ const rawCandidates = Array.isArray(obj.candidates) ? obj.candidates : obj.candidate && typeof obj.candidate === "object" ? [obj.candidate] : void 0;
295
+ if (rawCandidates) {
296
+ signal.candidates = rawCandidates.map((x) => x && typeof x === "object" ? x : void 0).map((c) => ({ c, line: candidateLine(c) })).filter((e) => e.line !== void 0).map(({ c, line }) => ({
297
+ sdp: line,
297
298
  sdpMLineIndex: typeof c.sdpMLineIndex === "number" ? c.sdpMLineIndex : 0,
298
299
  sdpMid: typeof c.sdpMid === "string" ? c.sdpMid : null
299
300
  }));
@@ -309,6 +310,15 @@ var PeerWebRTC = (() => {
309
310
  signal.event = obj.event;
310
311
  return signal;
311
312
  }
313
+ function candidateLine(c) {
314
+ if (!c)
315
+ return void 0;
316
+ if (typeof c.sdp === "string")
317
+ return c.sdp;
318
+ if (typeof c.candidate === "string")
319
+ return c.candidate;
320
+ return void 0;
321
+ }
312
322
  function looksLikeSignal(input) {
313
323
  const text = (typeof input === "string" ? input : new TextDecoder().decode(input)).replace(/\0+$/u, "").trimStart();
314
324
  return text.startsWith("{") && text.includes('"callId"') && text.includes('"type"');
@@ -324,7 +334,7 @@ var PeerWebRTC = (() => {
324
334
  var ICE_FAILED_GRACE_MS = 12e4;
325
335
  var DEFAULT_RING_TIMEOUT_MS = 6e4;
326
336
  var ENDED_CALL_MEMORY_MS = 12e4;
327
- var _opts, _iceServers, _sessions, _restartOffersEnabled, _endedCalls, _placeCall, placeCall_fn, _startRingTimer, startRingTimer_fn, _clearRingTimer, clearRingTimer_fn, _setOutgoingVideoTrack, setOutgoingVideoTrack_fn, _renegotiate, renegotiate_fn, _createOffer, createOffer_fn, _createAnswer, createAnswer_fn, _cleanOutbound, cleanOutbound_fn, _cleanInbound, cleanInbound_fn, _preferLeanVideoCodecs, preferLeanVideoCodecs_fn, _restartIce, restartIce_fn, _handleSignal, handleSignal_fn, _onOffer, onOffer_fn, _answerRenegotiation, answerRenegotiation_fn, _negotiationFailed, negotiationFailed_fn, _onAnswer, onAnswer_fn, _onCandidate, onCandidate_fn, _onBye, onBye_fn, _onAuxiliary, onAuxiliary_fn, _createSession, createSession_fn, _wirePeerConnection, wirePeerConnection_fn, _ensureRemoteStream, ensureRemoteStream_fn, _attachLocalMedia, attachLocalMedia_fn, _flushLocalCandidates, flushLocalCandidates_fn, _drainRemoteCandidates, drainRemoteCandidates_fn, _send, send_fn, _sendByeSafe, sendByeSafe_fn, _cleanup, cleanup_fn, _rememberEnded, rememberEnded_fn, _recentlyEnded, recentlyEnded_fn, _setState, setState_fn, _normId, normId_fn, _toInfo, _newCallId, newCallId_fn, _log, log_fn;
337
+ var _opts, _iceServers, _sessions, _restartOffersEnabled, _endedCalls, _placeCall, placeCall_fn, _startRingTimer, startRingTimer_fn, _clearRingTimer, clearRingTimer_fn, _setOutgoingVideoTrack, setOutgoingVideoTrack_fn, _renegotiate, renegotiate_fn, _sendRenegotiationOffer, sendRenegotiationOffer_fn, _createOffer, createOffer_fn, _createAnswer, createAnswer_fn, _cleanOutbound, cleanOutbound_fn, _cleanInbound, cleanInbound_fn, _preferLeanVideoCodecs, preferLeanVideoCodecs_fn, _restartIce, restartIce_fn, _handleSignal, handleSignal_fn, _onOffer, onOffer_fn, _answerRenegotiation, answerRenegotiation_fn, _negotiationFailed, negotiationFailed_fn, _onAnswer, onAnswer_fn, _onCandidate, onCandidate_fn, _onBye, onBye_fn, _onAuxiliary, onAuxiliary_fn, _createSession, createSession_fn, _wirePeerConnection, wirePeerConnection_fn, _ensureRemoteStream, ensureRemoteStream_fn, _attachLocalMedia, attachLocalMedia_fn, _canTrickle, canTrickle_fn, _localSdpSent, localSdpSent_fn, _flushLocalCandidates, flushLocalCandidates_fn, _drainRemoteCandidates, drainRemoteCandidates_fn, _send, send_fn, _sendByeSafe, sendByeSafe_fn, _cleanup, cleanup_fn, _rememberEnded, rememberEnded_fn, _recentlyEnded, recentlyEnded_fn, _setState, setState_fn, _normId, normId_fn, _toInfo, _newCallId, newCallId_fn, _log, log_fn;
328
338
  var CallEngine = class extends Emitter {
329
339
  constructor(opts) {
330
340
  var _a, _b;
@@ -340,6 +350,7 @@ var PeerWebRTC = (() => {
340
350
  /** Create + send a fresh offer to renegotiate media (e.g. after adding a
341
351
  * screen-share track). The peer applies it via #onOffer's renegotiation path. */
342
352
  __privateAdd(this, _renegotiate);
353
+ __privateAdd(this, _sendRenegotiationOffer);
343
354
  /** createOffer with the lean codec set applied (see #preferLeanVideoCodecs)
344
355
  * and the result sanitized (see #cleanOutbound). Every offer — initial,
345
356
  * screen-share re-offer, ICE restart — goes through here. */
@@ -396,6 +407,17 @@ var PeerWebRTC = (() => {
396
407
  __privateAdd(this, _wirePeerConnection);
397
408
  __privateAdd(this, _ensureRemoteStream);
398
409
  __privateAdd(this, _attachLocalMedia);
410
+ /** May a local candidate go out now? Only once
411
+ * - the remote SDP is applied (iOS parity: the native SDK's hasReceivedSdp —
412
+ * the peer has a matching call), and
413
+ * - every local offer/answer we applied has been SENT: a candidate must
414
+ * never overtake the description it belongs to. */
415
+ __privateAdd(this, _canTrickle);
416
+ /** An offer/answer went out (or failed to): release the candidates held for it. */
417
+ __privateAdd(this, _localSdpSent);
418
+ /** Send queued local candidates, oldest first, one signal each (as before).
419
+ * One flush at a time; a candidate gathered meanwhile joins the queue and
420
+ * goes out in turn. A failed send is logged and the rest still go. */
399
421
  __privateAdd(this, _flushLocalCandidates);
400
422
  __privateAdd(this, _drainRemoteCandidates);
401
423
  __privateAdd(this, _send);
@@ -492,11 +514,16 @@ var PeerWebRTC = (() => {
492
514
  session.pendingOffer = void 0;
493
515
  await __privateMethod(this, _drainRemoteCandidates, drainRemoteCandidates_fn).call(this, session);
494
516
  const answer = await __privateMethod(this, _createAnswer, createAnswer_fn).call(this, session);
495
- await session.pc.setLocalDescription(answer);
496
- await __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "answer", sdp: answer.sdp, callId });
517
+ session.localSdpUnsent++;
497
518
  try {
498
- await __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "action", action: "accept", callId });
499
- } catch {
519
+ await session.pc.setLocalDescription(answer);
520
+ await __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "answer", sdp: answer.sdp, callId });
521
+ try {
522
+ await __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "action", action: "accept", callId });
523
+ } catch {
524
+ }
525
+ } finally {
526
+ __privateMethod(this, _localSdpSent, localSdpSent_fn).call(this, session);
500
527
  }
501
528
  __privateMethod(this, _setState, setState_fn).call(this, session, "connecting");
502
529
  await __privateMethod(this, _flushLocalCandidates, flushLocalCandidates_fn).call(this, session);
@@ -632,7 +659,6 @@ var PeerWebRTC = (() => {
632
659
  }
633
660
  }
634
661
  const offer = await __privateMethod(this, _createOffer, createOffer_fn).call(this, session);
635
- await session.pc.setLocalDescription(offer);
636
662
  const options = [];
637
663
  if (audio)
638
664
  options.push("audio");
@@ -640,18 +666,24 @@ var PeerWebRTC = (() => {
640
666
  options.push("video");
641
667
  if (data)
642
668
  options.push("data");
669
+ session.localSdpUnsent++;
643
670
  try {
644
- await __privateMethod(this, _send, send_fn).call(this, peerId, {
645
- type: "offer",
646
- sdp: offer.sdp,
647
- options,
648
- callId,
649
- event: void 0
650
- });
651
- } catch (err) {
652
- const e = err instanceof Error ? err : new Error(String(err));
653
- e.sendFailed = true;
654
- throw e;
671
+ await session.pc.setLocalDescription(offer);
672
+ try {
673
+ await __privateMethod(this, _send, send_fn).call(this, peerId, {
674
+ type: "offer",
675
+ sdp: offer.sdp,
676
+ options,
677
+ callId,
678
+ event: void 0
679
+ });
680
+ } catch (err) {
681
+ const e = err instanceof Error ? err : new Error(String(err));
682
+ e.sendFailed = true;
683
+ throw e;
684
+ }
685
+ } finally {
686
+ __privateMethod(this, _localSdpSent, localSdpSent_fn).call(this, session);
655
687
  }
656
688
  if (session.closed)
657
689
  return;
@@ -729,9 +761,18 @@ var PeerWebRTC = (() => {
729
761
  };
730
762
  _renegotiate = new WeakSet();
731
763
  renegotiate_fn = async function(session) {
732
- var _a, _b;
733
764
  const offer = await __privateMethod(this, _createOffer, createOffer_fn).call(this, session);
734
- await session.pc.setLocalDescription(offer);
765
+ session.localSdpUnsent++;
766
+ try {
767
+ await session.pc.setLocalDescription(offer);
768
+ await __privateMethod(this, _sendRenegotiationOffer, sendRenegotiationOffer_fn).call(this, session, offer);
769
+ } finally {
770
+ __privateMethod(this, _localSdpSent, localSdpSent_fn).call(this, session);
771
+ }
772
+ };
773
+ _sendRenegotiationOffer = new WeakSet();
774
+ sendRenegotiationOffer_fn = async function(session, offer) {
775
+ var _a, _b;
735
776
  const options = [];
736
777
  if (session.audio)
737
778
  options.push("audio");
@@ -801,13 +842,18 @@ var PeerWebRTC = (() => {
801
842
  __privateMethod(this, _log, log_fn).call(this, `ICE restart ${session.restartAttempts}/${ICE_RESTART_MAX} for call ${session.callId}`);
802
843
  try {
803
844
  const offer = await __privateMethod(this, _createOffer, createOffer_fn).call(this, session, { iceRestart: true });
804
- await session.pc.setLocalDescription(offer);
805
- const options = [];
806
- if (session.audio)
807
- options.push("audio");
808
- if (session.video || session.screenStream)
809
- options.push("video");
810
- await __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "offer", sdp: offer.sdp, options, callId: session.callId });
845
+ session.localSdpUnsent++;
846
+ try {
847
+ await session.pc.setLocalDescription(offer);
848
+ const options = [];
849
+ if (session.audio)
850
+ options.push("audio");
851
+ if (session.video || session.screenStream)
852
+ options.push("video");
853
+ await __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "offer", sdp: offer.sdp, options, callId: session.callId });
854
+ } finally {
855
+ __privateMethod(this, _localSdpSent, localSdpSent_fn).call(this, session);
856
+ }
811
857
  } catch (err) {
812
858
  __privateMethod(this, _log, log_fn).call(this, `ICE restart failed: ${err.message}`);
813
859
  }
@@ -870,8 +916,13 @@ var PeerWebRTC = (() => {
870
916
  try {
871
917
  await session.pc.setRemoteDescription({ type: "offer", sdp: __privateMethod(this, _cleanInbound, cleanInbound_fn).call(this, sdp, "offer") });
872
918
  const answer = await __privateMethod(this, _createAnswer, createAnswer_fn).call(this, session);
873
- await session.pc.setLocalDescription(answer);
874
- await __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "answer", sdp: answer.sdp, callId: session.callId });
919
+ session.localSdpUnsent++;
920
+ try {
921
+ await session.pc.setLocalDescription(answer);
922
+ await __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "answer", sdp: answer.sdp, callId: session.callId });
923
+ } finally {
924
+ __privateMethod(this, _localSdpSent, localSdpSent_fn).call(this, session);
925
+ }
875
926
  } catch (err) {
876
927
  __privateMethod(this, _negotiationFailed, negotiationFailed_fn).call(this, session, "re-offer", err);
877
928
  }
@@ -972,6 +1023,7 @@ var PeerWebRTC = (() => {
972
1023
  state: "connecting",
973
1024
  hasReceivedSdp: false,
974
1025
  localCandidateQueue: [],
1026
+ localSdpUnsent: 0,
975
1027
  remoteCandidateQueue: [],
976
1028
  restartAttempts: 0,
977
1029
  closed: false
@@ -992,11 +1044,9 @@ var PeerWebRTC = (() => {
992
1044
  sdpMLineIndex: (_a = ev.candidate.sdpMLineIndex) != null ? _a : 0,
993
1045
  sdpMid: (_b = ev.candidate.sdpMid) != null ? _b : null
994
1046
  };
995
- if (session.hasReceivedSdp) {
996
- void __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "candidate", candidates: [sig], callId: session.callId });
997
- } else {
998
- session.localCandidateQueue.push(sig);
999
- }
1047
+ session.localCandidateQueue.push(sig);
1048
+ if (__privateMethod(this, _canTrickle, canTrickle_fn).call(this, session))
1049
+ void __privateMethod(this, _flushLocalCandidates, flushLocalCandidates_fn).call(this, session);
1000
1050
  };
1001
1051
  pc.ontrack = (ev) => {
1002
1052
  __privateMethod(this, _ensureRemoteStream, ensureRemoteStream_fn).call(this, session, ev.track);
@@ -1105,13 +1155,31 @@ var PeerWebRTC = (() => {
1105
1155
  }
1106
1156
  this.emit("localStream", session.callId, stream);
1107
1157
  };
1158
+ _canTrickle = new WeakSet();
1159
+ canTrickle_fn = function(session) {
1160
+ return session.hasReceivedSdp && session.localSdpUnsent === 0 && !session.closed;
1161
+ };
1162
+ _localSdpSent = new WeakSet();
1163
+ localSdpSent_fn = function(session) {
1164
+ session.localSdpUnsent--;
1165
+ if (__privateMethod(this, _canTrickle, canTrickle_fn).call(this, session))
1166
+ void __privateMethod(this, _flushLocalCandidates, flushLocalCandidates_fn).call(this, session);
1167
+ };
1108
1168
  _flushLocalCandidates = new WeakSet();
1109
1169
  flushLocalCandidates_fn = async function(session) {
1110
- if (!session.hasReceivedSdp || session.localCandidateQueue.length === 0)
1170
+ if (session.flushingLocal)
1111
1171
  return;
1112
- const queued = session.localCandidateQueue.splice(0);
1113
- for (const sig of queued) {
1114
- await __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "candidate", candidates: [sig], callId: session.callId });
1172
+ session.flushingLocal = true;
1173
+ try {
1174
+ while (__privateMethod(this, _canTrickle, canTrickle_fn).call(this, session) && session.localCandidateQueue.length > 0) {
1175
+ const sig = session.localCandidateQueue.shift();
1176
+ try {
1177
+ await __privateMethod(this, _send, send_fn).call(this, session.peerId, { type: "candidate", candidates: [sig], callId: session.callId });
1178
+ } catch {
1179
+ }
1180
+ }
1181
+ } finally {
1182
+ session.flushingLocal = false;
1115
1183
  }
1116
1184
  };
1117
1185
  _drainRemoteCandidates = new WeakSet();
@@ -1454,50 +1522,63 @@ var PeerWebRTC = (() => {
1454
1522
  "https://www.callpass.cn/push-api/push-message",
1455
1523
  "https://tokyo.fi.chat:3004/push-api/push-message"
1456
1524
  ];
1457
- var _appKey, _appName, _endpoints, _fetch;
1525
+ var _appKey, _appName, _endpoints, _fetch, _gateway, _env, _sendDirect, sendDirect_fn;
1458
1526
  var BeaglePushClient = class {
1459
1527
  constructor(opts) {
1528
+ __privateAdd(this, _sendDirect);
1460
1529
  __privateAdd(this, _appKey, void 0);
1461
1530
  __privateAdd(this, _appName, void 0);
1462
1531
  __privateAdd(this, _endpoints, void 0);
1463
1532
  __privateAdd(this, _fetch, void 0);
1464
- var _a, _b;
1465
- __privateSet(this, _appKey, opts.appKey);
1533
+ __privateAdd(this, _gateway, void 0);
1534
+ __privateAdd(this, _env, void 0);
1535
+ var _a, _b, _c;
1536
+ if (!opts.appKey && !opts.gateway)
1537
+ throw new Error("BeaglePushClient: pass a gateway, an appKey, or both");
1538
+ __privateSet(this, _appKey, opts.appKey || void 0);
1466
1539
  __privateSet(this, _appName, opts.appName);
1467
1540
  __privateSet(this, _endpoints, ((_a = opts.endpoints) == null ? void 0 : _a.length) ? opts.endpoints : DEFAULT_ENDPOINTS);
1468
- const f = (_b = opts.fetch) != null ? _b : globalThis.fetch;
1469
- if (!f)
1541
+ __privateSet(this, _gateway, opts.gateway);
1542
+ __privateSet(this, _env, (_b = opts.env) != null ? _b : "prod");
1543
+ const f = (_c = opts.fetch) != null ? _c : globalThis.fetch;
1544
+ if (!f && __privateGet(this, _appKey))
1470
1545
  throw new Error("BeaglePushClient: no fetch available \u2014 pass opts.fetch");
1471
1546
  __privateSet(this, _fetch, f);
1472
1547
  }
1473
1548
  /**
1474
1549
  * Ring an offline peer. `calleeUserId` is the destination (their Carrier user
1475
- * id); the payload describes the call. Tries each endpoint until one accepts.
1476
- * Resolves `true` on success, `false` if every endpoint failed.
1550
+ * id); the payload describes the call. Resolves `true` on success.
1477
1551
  */
1478
1552
  async sendCallPush(calleeUserId, payload) {
1553
+ return (await this.sendCall(calleeUserId, payload)).ok;
1554
+ }
1555
+ /**
1556
+ * {@link sendCallPush} with the route it took. Through the gateway first when
1557
+ * there is one: an answer from it is final (ok or not); only "not answered"
1558
+ * (connect error, timeout, 502/503/504) falls back to the direct call, and
1559
+ * only when this client has an appKey.
1560
+ */
1561
+ async sendCall(calleeUserId, payload) {
1479
1562
  var _a;
1480
- const params = new URLSearchParams({
1481
- account: calleeUserId,
1482
- payload: JSON.stringify(payload),
1483
- appKey: __privateGet(this, _appKey),
1484
- appName: __privateGet(this, _appName)
1485
- }).toString();
1486
- for (const endpoint of __privateGet(this, _endpoints)) {
1563
+ let gateway;
1564
+ if (__privateGet(this, _gateway)) {
1487
1565
  try {
1488
- const url = endpoint + (endpoint.includes("?") ? "&" : "?") + params;
1489
- const res = await __privateGet(this, _fetch).call(this, url, { method: "POST" });
1490
- if (!res.ok)
1491
- continue;
1492
- const json = await res.json().catch(() => ({}));
1493
- const code = json.code;
1494
- const ok = code === void 0 || code === 0 || code === "0" || ((_a = json.data) == null ? void 0 : _a.success) === true;
1495
- if (ok)
1496
- return true;
1497
- } catch {
1566
+ gateway = await __privateGet(this, _gateway).send("call", [
1567
+ ["env", __privateGet(this, _env)],
1568
+ ["account", calleeUserId],
1569
+ ["payload", JSON.stringify(payload)],
1570
+ ["appName", __privateGet(this, _appName)]
1571
+ ]);
1572
+ } catch (err) {
1573
+ gateway = { answered: false, reason: (_a = err == null ? void 0 : err.message) != null ? _a : String(err) };
1498
1574
  }
1575
+ if (gateway.answered)
1576
+ return { ok: gateway.ok, via: "gateway", gateway };
1499
1577
  }
1500
- return false;
1578
+ if (!__privateGet(this, _appKey))
1579
+ return { ok: false, via: "none", ...gateway ? { gateway } : {} };
1580
+ const ok = await __privateMethod(this, _sendDirect, sendDirect_fn).call(this, calleeUserId, payload, __privateGet(this, _appKey));
1581
+ return { ok, via: ok ? "direct" : "none", ...gateway ? { gateway } : {} };
1501
1582
  }
1502
1583
  /** Convenience: ring `calleeUserId` for a call over `channel`. */
1503
1584
  ring(calleeUserId, args) {
@@ -1528,5 +1609,35 @@ var PeerWebRTC = (() => {
1528
1609
  _appName = new WeakMap();
1529
1610
  _endpoints = new WeakMap();
1530
1611
  _fetch = new WeakMap();
1612
+ _gateway = new WeakMap();
1613
+ _env = new WeakMap();
1614
+ _sendDirect = new WeakSet();
1615
+ sendDirect_fn = async function(calleeUserId, payload, appKey) {
1616
+ var _a;
1617
+ const fetchFn = __privateGet(this, _fetch);
1618
+ if (!fetchFn)
1619
+ return false;
1620
+ const params = new URLSearchParams({
1621
+ account: calleeUserId,
1622
+ payload: JSON.stringify(payload),
1623
+ appKey,
1624
+ appName: __privateGet(this, _appName)
1625
+ }).toString();
1626
+ for (const endpoint of __privateGet(this, _endpoints)) {
1627
+ try {
1628
+ const url = endpoint + (endpoint.includes("?") ? "&" : "?") + params;
1629
+ const res = await fetchFn(url, { method: "POST" });
1630
+ if (!res.ok)
1631
+ continue;
1632
+ const json = await res.json().catch(() => ({}));
1633
+ const code = json.code;
1634
+ const ok = code === void 0 || code === 0 || code === "0" || ((_a = json.data) == null ? void 0 : _a.success) === true;
1635
+ if (ok)
1636
+ return true;
1637
+ } catch {
1638
+ }
1639
+ }
1640
+ return false;
1641
+ };
1531
1642
  return __toCommonJS(dist_exports);
1532
1643
  })();
@@ -15,7 +15,7 @@ import { mkdir, readFile, writeFile, unlink } from "node:fs/promises";
15
15
  import { basename, resolve } from "node:path";
16
16
  import { CarrierNode } from "./carrier-node.js";
17
17
  import { MessageStore } from "./message-store.js";
18
- import { parseGroupFile, withoutFileData } from "./group-file.js";
18
+ import { parseGroupFile, storedGroupFiles, withoutFileData } from "./group-file.js";
19
19
  import { FriendMetaStore } from "./friend-meta.js";
20
20
  import { Logger } from "./logger.js";
21
21
  import { acquireIdentityLock } from "./identity-lock.js";
@@ -129,6 +129,7 @@ export class EmbeddedHost {
129
129
  // checks this same file, so holding it is what stops `agentnet up` from
130
130
  // starting a second peer on our keypair while we are live.
131
131
  this.#releaseIdentity = acquireIdentityLock(this.#opts.dataDir);
132
+ void this.#migrateStoredGroupFiles();
132
133
  try {
133
134
  await this.#startPeer();
134
135
  }
@@ -328,17 +329,7 @@ export class EmbeddedHost {
328
329
  try {
329
330
  if (f.sha256 && this.#messages.hasFileSha(pubkey, f.sha256))
330
331
  return;
331
- await mkdir(this.downloadsDir, { recursive: true });
332
- const safe = sanitizeFileName(f.name);
333
- const dot = safe.lastIndexOf(".");
334
- let name = safe;
335
- for (let i = 2; i < 1000; i++) {
336
- const existing = await readFile(resolve(this.downloadsDir, name)).catch(() => undefined);
337
- if (!existing || existing.equals(f.data))
338
- break;
339
- name = dot > 0 ? `${safe.slice(0, dot)}-${i}${safe.slice(dot)}` : `${safe}-${i}`;
340
- }
341
- await writeFile(resolve(this.downloadsDir, name), f.data);
332
+ const name = await this.#writeGroupDownload(f);
342
333
  this.#messages.appendFile(pubkey, "in", { name, size: f.data.length, sha256: f.sha256 }, Date.now(), { origin: { userid: f.origin.userid, nickname: f.origin.nickname }, via });
343
334
  this.#logger.info(`saved group file "${name}" (${f.data.length}B) from ${f.origin.nickname || "member"} in ${pubkey.slice(0, 8)}`);
344
335
  }
@@ -349,6 +340,52 @@ export class EmbeddedHost {
349
340
  this.#meta.ensure(pubkey);
350
341
  this.#events.emit("event", { type: "chat", userid: pubkey, dir: "in" });
351
342
  }
343
+ /** downloads/<name> ← a group file's bytes; a different file of the same
344
+ * name gets "-2", "-3"… Returns the name used. */
345
+ async #writeGroupDownload(f) {
346
+ await mkdir(this.downloadsDir, { recursive: true });
347
+ const safe = sanitizeFileName(f.name);
348
+ const dot = safe.lastIndexOf(".");
349
+ let name = safe;
350
+ for (let i = 2; i < 1000; i++) {
351
+ const existing = await readFile(resolve(this.downloadsDir, name)).catch(() => undefined);
352
+ if (!existing || existing.equals(f.data))
353
+ break;
354
+ name = dot > 0 ? `${safe.slice(0, dot)}-${i}${safe.slice(dot)}` : `${safe}-${i}`;
355
+ }
356
+ await writeFile(resolve(this.downloadsDir, name), f.data);
357
+ return name;
358
+ }
359
+ /** On start: group files a host older than beagle 0.1.131 stored as CGP1
360
+ * text with their bytes inside become playable files in place (and
361
+ * messages.json loses the base64); a copy of bytes already saved is
362
+ * dropped. A no-op once nothing is left. */
363
+ async #migrateStoredGroupFiles() {
364
+ let saved = 0;
365
+ let dropped = 0;
366
+ for (const peer of [...this.#messages.lastMessages().keys()]) {
367
+ const todo = storedGroupFiles(this.#messages.thread(peer));
368
+ for (const p of todo) {
369
+ try {
370
+ if (p.duplicate) {
371
+ this.#messages.deleteMessages(peer, [p.id]);
372
+ dropped++;
373
+ continue;
374
+ }
375
+ const name = await this.#writeGroupDownload(p.file);
376
+ this.#messages.convertToFile(peer, p.id, { name, size: p.file.data.length, sha256: p.file.sha256 }, { userid: p.file.origin.userid, nickname: p.file.origin.nickname });
377
+ saved++;
378
+ }
379
+ catch (e) {
380
+ this.#logger.warn(`stored group file "${p.file.name}" not converted: ${e.message}`);
381
+ }
382
+ }
383
+ if (todo.length)
384
+ this.#events.emit("event", { type: "chat", userid: peer, dir: "in" });
385
+ }
386
+ if (saved || dropped)
387
+ this.#logger.info(`stored group files: ${saved} saved as files, ${dropped} duplicates dropped`);
388
+ }
352
389
  /** Persist a received file under downloads/ and log it in the thread. */
353
390
  async #saveIncoming(pubkey, name, data) {
354
391
  const safe = sanitizeFileName(name);
@@ -44,3 +44,21 @@ export declare function withoutFileData(text: string): string;
44
44
  * name, same post time)? Used to replace the "not delivered" card when the
45
45
  * bytes arrive later for the same message. */
46
46
  export declare function sameGroupFile(storedText: string, f: GroupFile): boolean;
47
+ /** Stored messages that still hold a group file's bytes as CGP1 text: those a
48
+ * daemon older than 0.1.315 received after the group service began sending
49
+ * data_base64 (2026-11-05 17:53 PST). They show as "not delivered" although
50
+ * the bytes are in messages.json. Each one is to be saved as a file in place,
51
+ * or dropped when the thread already holds the same bytes (`duplicate`).
52
+ * Pure: the caller does the writing. */
53
+ export declare function storedGroupFiles(thread: readonly {
54
+ id: string;
55
+ dir: string;
56
+ text: string;
57
+ file?: {
58
+ sha256?: string;
59
+ };
60
+ }[]): Array<{
61
+ id: string;
62
+ file: GroupFile;
63
+ duplicate: boolean;
64
+ }>;
@@ -90,3 +90,23 @@ export function sameGroupFile(storedText, f) {
90
90
  return d.timestampUs === f.timestampUs;
91
91
  return d.size === f.size;
92
92
  }
93
+ /** Stored messages that still hold a group file's bytes as CGP1 text: those a
94
+ * daemon older than 0.1.315 received after the group service began sending
95
+ * data_base64 (2026-11-05 17:53 PST). They show as "not delivered" although
96
+ * the bytes are in messages.json. Each one is to be saved as a file in place,
97
+ * or dropped when the thread already holds the same bytes (`duplicate`).
98
+ * Pure: the caller does the writing. */
99
+ export function storedGroupFiles(thread) {
100
+ const have = new Set(thread.map((m) => m.file?.sha256).filter((s) => !!s));
101
+ const out = [];
102
+ for (const m of thread) {
103
+ if (m.dir !== "in" || m.file || !m.text || !m.text.includes("data_base64"))
104
+ continue;
105
+ const f = parseGroupFile(m.text);
106
+ if (!f?.data || !f.sha256)
107
+ continue;
108
+ out.push({ id: m.id, file: f, duplicate: have.has(f.sha256) });
109
+ have.add(f.sha256);
110
+ }
111
+ return out;
112
+ }
@@ -102,6 +102,15 @@ export declare class MessageStore {
102
102
  origin?: ChatMessage["origin"];
103
103
  via?: "online" | "offline";
104
104
  }): ChatMessage;
105
+ /** Turn an existing message into a file message in place (same id, same
106
+ * position): a stored group file's CGP1 text becomes the playable file. */
107
+ convertToFile(peer: string, id: string, file: {
108
+ name: string;
109
+ size: number;
110
+ sha256?: string;
111
+ }, origin?: ChatMessage["origin"]): ChatMessage | undefined;
112
+ /** Every message in a peer's thread (oldest first). Read-only use. */
113
+ thread(peer: string): readonly ChatMessage[];
105
114
  /** True when this peer's thread already holds a file with these bytes. */
106
115
  hasFileSha(peer: string, sha256: string): boolean;
107
116
  /** Patch an existing file message's transfer fields (status / sent bytes).
@@ -128,6 +128,23 @@ export class MessageStore {
128
128
  msg.via = extra.via;
129
129
  return this.push(peer, msg);
130
130
  }
131
+ /** Turn an existing message into a file message in place (same id, same
132
+ * position): a stored group file's CGP1 text becomes the playable file. */
133
+ convertToFile(peer, id, file, origin) {
134
+ const msg = this.byPeer.get(peer)?.find((m) => m.id === id);
135
+ if (!msg)
136
+ return undefined;
137
+ msg.text = "";
138
+ msg.file = file;
139
+ if (origin)
140
+ msg.origin = origin;
141
+ this.scheduleSave();
142
+ return msg;
143
+ }
144
+ /** Every message in a peer's thread (oldest first). Read-only use. */
145
+ thread(peer) {
146
+ return this.byPeer.get(peer) ?? [];
147
+ }
131
148
  /** True when this peer's thread already holds a file with these bytes. */
132
149
  hasFileSha(peer, sha256) {
133
150
  return (this.history(peer)[peer] ?? []).some((m) => m.file?.sha256 === sha256);
package/dist/server.js CHANGED
@@ -28,6 +28,7 @@ import { historyStats } from "./assistant-stats.js";
28
28
  import { readFriendStore, pickPunk } from "./friend-store.js";
29
29
  import { desktopRequestRow, findPending } from "./pending-requests.js";
30
30
  import { GreetingStore, mergeGreetings } from "./friend-greetings.js";
31
+ import { CallRegistry, pageOf } from "./call-claims.js";
31
32
  import { createDiscoverFetch } from "./discover-cache.js";
32
33
  import { applyWalletBind } from "@decentnetwork/beagle-ui/wallet-proof";
33
34
  import { settleUpload } from "./upload-settle.js";
@@ -969,6 +970,9 @@ export function startBeagleServer(opts) {
969
970
  const port = opts.listenPort ?? 8765;
970
971
  const log = opts.log ?? ((s) => console.log(s));
971
972
  const greetings = opts.greetingsPath ? new GreetingStore(opts.greetingsPath) : null;
973
+ // Who has each recent incoming call — see call-claims.ts. Every page polls
974
+ // through here, so this is where "answered elsewhere" is decided.
975
+ const calls = new CallRegistry();
972
976
  // Exit reachability with memory (see exit-probe.ts). One per server, state
973
977
  // kept next to routes.yaml so a restart does not re-probe dead exits.
974
978
  const exitProber = new ExitProber({
@@ -2600,11 +2604,31 @@ export function startBeagleServer(opts) {
2600
2604
  // RtcSignals here and long-polls call-poll for inbound ones; the daemon
2601
2605
  // relays both over the Carrier "carrier" invite extension.
2602
2606
  if (req.method === "POST" && url === "/api/call-signal") {
2603
- const { userid, data } = await readBody(req);
2607
+ const { userid, data, page } = await readBody(req);
2608
+ // First claim wins: another page's answer / accept / decline for a
2609
+ // call already claimed never reaches the caller.
2610
+ const gate = calls.observeOutbound(pageOf(page), userid, data);
2611
+ if (!gate.allow) {
2612
+ sendJson(res, 409, { ok: false, error: "answered elsewhere", answeredElsewhere: true, call: gate.record });
2613
+ return;
2614
+ }
2604
2615
  const r = await opts.call({ op: "call-signal", userid, data });
2605
2616
  sendJson(res, r.ok ? 200 : 400, r);
2606
2617
  return;
2607
2618
  }
2619
+ // A page answers or declines an incoming call: claim it before sending
2620
+ // anything to the caller. `won: false` = another page or client has it;
2621
+ // stop ringing and send nothing.
2622
+ if (req.method === "POST" && url === "/api/call-claim") {
2623
+ const { callId, peerId, action, page } = await readBody(req);
2624
+ if (typeof callId !== "string" || !callId) {
2625
+ sendJson(res, 400, { ok: false, error: "callId required" });
2626
+ return;
2627
+ }
2628
+ const r = calls.claim(callId, String(peerId ?? ""), pageOf(page), action === "rejected" ? "rejected" : "accepted");
2629
+ sendJson(res, 200, { ok: true, won: r.won, call: r.record, callsVersion: calls.version });
2630
+ return;
2631
+ }
2608
2632
  // Carrier bootstrap TURN for browser RTCPeerConnection — same scheme as
2609
2633
  // Android WebrtcClient.getIceServers() / carrier_get_turn_server().
2610
2634
  if (req.method === "GET" && url === "/api/call-ice-servers") {
@@ -2630,18 +2654,39 @@ export function startBeagleServer(opts) {
2630
2654
  // `since` is the caller's broadcast cursor: signal delivery is
2631
2655
  // per-subscriber, so two open tabs BOTH ring on an incoming call.
2632
2656
  // Without it (older UI) the backend serves only future signals.
2633
- const sinceRaw = new URL(req.url || "/", "http://x").searchParams.get("since");
2657
+ const qs = new URL(req.url || "/", "http://x").searchParams;
2658
+ const sinceRaw = qs.get("since");
2634
2659
  const since = sinceRaw !== null && sinceRaw !== "" ? Number(sinceRaw) : undefined;
2635
- try {
2636
- const r = await opts.call({
2637
- op: "call-poll",
2638
- ...(Number.isFinite(since) ? { since } : {}),
2639
- });
2640
- sendJson(res, 200, r.ok ? r.data ?? { signals: [] } : { signals: [] });
2660
+ // `cv`: the calls-table version this page holds (call-claims.ts). A
2661
+ // claim or an end must reach every page within about a second, but
2662
+ // the backend may hold this poll ~20 s, so a change to the table
2663
+ // answers the poll at once — with the page's own cursor, so the
2664
+ // signals the backend is still holding are read on the next poll
2665
+ // (the log is broadcast; reading never consumes).
2666
+ const cvRaw = qs.get("cv");
2667
+ const cv = cvRaw !== null && cvRaw !== "" ? Number(cvRaw) : undefined;
2668
+ const backendP = opts
2669
+ .call({ op: "call-poll", ...(Number.isFinite(since) ? { since } : {}) })
2670
+ .catch(() => null);
2671
+ let r;
2672
+ if (Number.isFinite(since) && Number.isFinite(cv)) {
2673
+ const w = calls.wait(cv, 25_000);
2674
+ const CHANGED = Symbol("calls changed");
2675
+ const onChange = w.promise.then((changed) => changed ? CHANGED : backendP);
2676
+ const first = await Promise.race([backendP, onChange]);
2677
+ w.cancel();
2678
+ r = first === CHANGED ? null : first;
2641
2679
  }
2642
- catch {
2643
- sendJson(res, 200, { signals: [] });
2680
+ else {
2681
+ r = await backendP;
2644
2682
  }
2683
+ const data = r === null ? { signals: [], cursor: since } : r.ok ? { signals: [], ...(r.data ?? {}) } : { signals: [] };
2684
+ for (const sig of data.signals ?? []) {
2685
+ calls.observeInbound(String(sig.userid ?? ""), sig.data);
2686
+ }
2687
+ data.calls = calls.snapshot();
2688
+ data.callsVersion = calls.version;
2689
+ sendJson(res, 200, data);
2645
2690
  return;
2646
2691
  }
2647
2692
  if (req.method === "POST" && url === "/api/friend-remove") {