@coasys/ad4m 0.13.1-staging.1 → 0.13.1-staging.2

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 (222) hide show
  1. package/lib/index.cjs +3789 -1192
  2. package/lib/index.js +3783 -1193
  3. package/lib/src/generated/api/AgentsByDidsRequest.d.ts +3 -0
  4. package/lib/src/generated/api/CallSessionInfo.d.ts +23 -0
  5. package/lib/src/generated/api/DiscardBatchRequest.d.ts +3 -0
  6. package/lib/src/generated/api/Events.d.ts +13 -3
  7. package/lib/src/generated/api/Events.js +1 -0
  8. package/lib/src/generated/api/FlowStateChangedEvent.d.ts +38 -0
  9. package/lib/src/generated/api/FlowStateEntry.d.ts +18 -0
  10. package/lib/src/generated/api/FlowStateEntry.js +2 -0
  11. package/lib/src/generated/api/IceServer.d.ts +18 -0
  12. package/lib/src/generated/api/IceServer.js +2 -0
  13. package/lib/src/generated/api/OnlineAgent.d.ts +4 -0
  14. package/lib/src/generated/api/PerspectiveDiscardBatchParams.d.ts +4 -0
  15. package/lib/src/generated/api/PerspectiveDiscardBatchParams.js +2 -0
  16. package/lib/src/generated/api/PerspectiveFlowFiredParams.d.ts +8 -0
  17. package/lib/src/generated/api/PerspectiveFlowFiredParams.js +2 -0
  18. package/lib/src/generated/api/PerspectiveFlowStatesParams.d.ts +11 -0
  19. package/lib/src/generated/api/PerspectiveFlowStatesParams.js +2 -0
  20. package/lib/src/generated/api/PerspectiveGetAllShaclParams.d.ts +7 -0
  21. package/lib/src/generated/api/PerspectiveGetAllShaclParams.js +2 -0
  22. package/lib/src/generated/api/PerspectiveModelQueryParams.d.ts +6 -1
  23. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.d.ts +6 -0
  24. package/lib/src/generated/api/PerspectiveRemoveSubjectParams.js +2 -0
  25. package/lib/src/generated/api/PerspectiveResynced.d.ts +8 -0
  26. package/lib/src/generated/api/PerspectiveResynced.js +2 -0
  27. package/lib/src/generated/api/PerspectiveSubscribed.d.ts +10 -0
  28. package/lib/src/generated/api/PerspectiveSubscribed.js +2 -0
  29. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.d.ts +10 -0
  30. package/lib/src/generated/api/PerspectiveUpdateSubjectParams.js +2 -0
  31. package/lib/src/generated/api/QuerySubscriptionUpdate.d.ts +19 -0
  32. package/lib/src/generated/api/QuerySubscriptionUpdate.js +2 -0
  33. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.d.ts +7 -0
  34. package/lib/src/generated/api/QuerySubscriptionUpdateEvent.js +1 -0
  35. package/lib/src/generated/api/QueryUpdatesLagged.d.ts +7 -0
  36. package/lib/src/generated/api/QueryUpdatesLagged.js +2 -0
  37. package/lib/src/generated/api/RemoveSubjectRequest.d.ts +9 -0
  38. package/lib/src/generated/api/RemoveSubjectRequest.js +2 -0
  39. package/lib/src/generated/api/ResyncSubscriptionRequest.d.ts +3 -0
  40. package/lib/src/generated/api/ResyncSubscriptionRequest.js +2 -0
  41. package/lib/src/generated/api/RpcMethods.d.ts +134 -14
  42. package/lib/src/generated/api/RpcMethods.js +12 -0
  43. package/lib/src/generated/api/SfuAddIceCandidateParams.d.ts +8 -0
  44. package/lib/src/generated/api/SfuAddIceCandidateParams.js +2 -0
  45. package/lib/src/generated/api/SfuAnswerServerOfferParams.d.ts +8 -0
  46. package/lib/src/generated/api/SfuAnswerServerOfferParams.js +2 -0
  47. package/lib/src/generated/api/SfuCallJoinParams.d.ts +14 -0
  48. package/lib/src/generated/api/SfuCallJoinParams.js +2 -0
  49. package/lib/src/generated/api/SfuCallRenegotiationOffer.d.ts +30 -0
  50. package/lib/src/generated/api/SfuCallRenegotiationOffer.js +1 -0
  51. package/lib/src/generated/api/SfuCascadePipe.d.ts +4 -0
  52. package/lib/src/generated/api/SfuCascadePipe.js +2 -0
  53. package/lib/src/generated/api/SfuCascadeStatus.d.ts +8 -0
  54. package/lib/src/generated/api/SfuCascadeStatus.js +1 -0
  55. package/lib/src/generated/api/SfuConfig.d.ts +52 -0
  56. package/lib/src/generated/api/SfuConfig.js +1 -0
  57. package/lib/src/generated/api/SfuDataMessage.d.ts +24 -0
  58. package/lib/src/generated/api/SfuDataMessage.js +2 -0
  59. package/lib/src/generated/api/SfuEnsureMembershipParams.d.ts +4 -0
  60. package/lib/src/generated/api/SfuEnsureMembershipParams.js +2 -0
  61. package/lib/src/generated/api/SfuMigrateEvent.d.ts +21 -0
  62. package/lib/src/generated/api/SfuMigrateEvent.js +2 -0
  63. package/lib/src/generated/api/SfuNeighbourhoodParams.d.ts +3 -0
  64. package/lib/src/generated/api/SfuNeighbourhoodParams.js +2 -0
  65. package/lib/src/generated/api/SfuParticipantQualityPreference.d.ts +7 -0
  66. package/lib/src/generated/api/SfuParticipantQualityPreference.js +2 -0
  67. package/lib/src/generated/api/SfuPerspectiveParams.d.ts +6 -0
  68. package/lib/src/generated/api/SfuPerspectiveParams.js +2 -0
  69. package/lib/src/generated/api/SfuQualityPreferenceParams.d.ts +8 -0
  70. package/lib/src/generated/api/SfuQualityPreferenceParams.js +2 -0
  71. package/lib/src/generated/api/SfuRoomInfo.d.ts +11 -0
  72. package/lib/src/generated/api/SfuRoomInfo.js +1 -0
  73. package/lib/src/generated/api/SfuRoomParams.d.ts +4 -0
  74. package/lib/src/generated/api/SfuRoomParams.js +2 -0
  75. package/lib/src/generated/api/SfuRoomParticipantInfo.d.ts +11 -0
  76. package/lib/src/generated/api/SfuRoomParticipantInfo.js +2 -0
  77. package/lib/src/generated/api/SfuRoomRoster.d.ts +13 -0
  78. package/lib/src/generated/api/SfuRoomRoster.js +2 -0
  79. package/lib/src/generated/api/SfuSendDataParams.d.ts +10 -0
  80. package/lib/src/generated/api/SfuSendDataParams.js +2 -0
  81. package/lib/src/generated/api/SfuSetConfigParams.d.ts +5 -0
  82. package/lib/src/generated/api/SfuSetConfigParams.js +1 -0
  83. package/lib/src/generated/api/SfuStatus.d.ts +24 -0
  84. package/lib/src/generated/api/SfuStatus.js +2 -0
  85. package/lib/src/generated/api/TrackMapEntry.d.ts +17 -0
  86. package/lib/src/generated/api/TrackMapEntry.js +2 -0
  87. package/lib/src/generated/api/UpdateSubjectRequest.d.ts +12 -0
  88. package/lib/src/generated/api/UpdateSubjectRequest.js +2 -0
  89. package/lib/src/generated/api/index.d.ts +3 -0
  90. package/lib/src/index.d.ts +7 -0
  91. package/lib/src/index.js +4 -0
  92. package/lib/src/model/Ad4mModel.d.ts +84 -0
  93. package/lib/src/model/Ad4mModel.js +234 -4
  94. package/lib/src/model/ModelQueryBuilder.d.ts +16 -35
  95. package/lib/src/model/ModelQueryBuilder.js +88 -270
  96. package/lib/src/model/decorators.d.ts +32 -0
  97. package/lib/src/model/decorators.js +40 -1
  98. package/lib/src/model/shacl-gen.d.ts +3 -1
  99. package/lib/src/model/shacl-gen.js +13 -1
  100. package/lib/src/model/types.d.ts +7 -0
  101. package/lib/src/neighbourhood/MeshManager.d.ts +384 -0
  102. package/lib/src/neighbourhood/MeshManager.js +1144 -0
  103. package/lib/src/neighbourhood/NeighbourhoodClient.d.ts +91 -0
  104. package/lib/src/neighbourhood/NeighbourhoodClient.js +196 -0
  105. package/lib/src/neighbourhood/NeighbourhoodProxy.d.ts +55 -1
  106. package/lib/src/neighbourhood/NeighbourhoodProxy.js +170 -3
  107. package/lib/src/neighbourhood/Session.d.ts +105 -0
  108. package/lib/src/neighbourhood/Session.js +412 -0
  109. package/lib/src/neighbourhood/SfuManager.d.ts +174 -0
  110. package/lib/src/neighbourhood/SfuManager.js +619 -0
  111. package/lib/src/neighbourhood/SfuTypes.d.ts +35 -0
  112. package/lib/src/neighbourhood/SfuTypes.js +8 -0
  113. package/lib/src/perspectives/FlowInstance.d.ts +63 -24
  114. package/lib/src/perspectives/FlowInstance.js +74 -31
  115. package/lib/src/perspectives/FlowModels.d.ts +0 -16
  116. package/lib/src/perspectives/FlowModels.js +8 -16
  117. package/lib/src/perspectives/LiveQuery.d.ts +49 -0
  118. package/lib/src/perspectives/LiveQuery.js +169 -0
  119. package/lib/src/perspectives/PerspectiveClient.d.ts +24 -15
  120. package/lib/src/perspectives/PerspectiveClient.js +33 -36
  121. package/lib/src/perspectives/PerspectiveProxy.d.ts +67 -167
  122. package/lib/src/perspectives/PerspectiveProxy.js +121 -475
  123. package/lib/src/perspectives/TextContent.d.ts +31 -0
  124. package/lib/src/perspectives/TextContent.js +52 -0
  125. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +23 -0
  126. package/lib/src/perspectives/WakerSubscriptionManager.js +58 -17
  127. package/lib/src/shacl/SHACLFlow.d.ts +7 -4
  128. package/lib/src/shacl/SHACLFlow.js +7 -4
  129. package/lib/src/shacl/SHACLShape.d.ts +9 -0
  130. package/lib/src/shacl/SHACLShape.js +37 -0
  131. package/package.json +2 -2
  132. package/pnpm-workspace.yaml +4 -1
  133. package/src/Ad4mClient.test.ts +89 -17
  134. package/src/generated/api/AgentsByDidsRequest.ts +3 -0
  135. package/src/generated/api/CallSessionInfo.ts +20 -0
  136. package/src/generated/api/DiscardBatchRequest.ts +3 -0
  137. package/src/generated/api/Events.ts +14 -3
  138. package/src/generated/api/FlowStateChangedEvent.ts +36 -0
  139. package/src/generated/api/FlowStateEntry.ts +18 -0
  140. package/src/generated/api/IceServer.ts +19 -0
  141. package/src/generated/api/OnlineAgent.ts +6 -1
  142. package/src/generated/api/PerspectiveDiscardBatchParams.ts +3 -0
  143. package/src/generated/api/PerspectiveFlowFiredParams.ts +7 -0
  144. package/src/generated/api/PerspectiveFlowStatesParams.ts +11 -0
  145. package/src/generated/api/PerspectiveGetAllShaclParams.ts +6 -0
  146. package/src/generated/api/PerspectiveModelQueryParams.ts +5 -1
  147. package/src/generated/api/PerspectiveRemoveSubjectParams.ts +3 -0
  148. package/src/generated/api/PerspectiveResynced.ts +7 -0
  149. package/src/generated/api/PerspectiveSubscribed.ts +8 -0
  150. package/src/generated/api/PerspectiveUpdateSubjectParams.ts +7 -0
  151. package/src/generated/api/QuerySubscriptionUpdate.ts +10 -0
  152. package/src/generated/api/QuerySubscriptionUpdateEvent.ts +9 -0
  153. package/src/generated/api/QueryUpdatesLagged.ts +7 -0
  154. package/src/generated/api/RemoveSubjectRequest.ts +7 -0
  155. package/src/generated/api/ResyncSubscriptionRequest.ts +3 -0
  156. package/src/generated/api/RpcMethods.ts +68 -8
  157. package/src/generated/api/SfuAddIceCandidateParams.ts +7 -0
  158. package/src/generated/api/SfuAnswerServerOfferParams.ts +7 -0
  159. package/src/generated/api/SfuCallJoinParams.ts +13 -0
  160. package/src/generated/api/SfuCallRenegotiationOffer.ts +29 -0
  161. package/src/generated/api/SfuCascadePipe.ts +3 -0
  162. package/src/generated/api/SfuCascadeStatus.ts +7 -0
  163. package/src/generated/api/SfuConfig.ts +53 -0
  164. package/src/generated/api/SfuDataMessage.ts +23 -0
  165. package/src/generated/api/SfuEnsureMembershipParams.ts +3 -0
  166. package/src/generated/api/SfuMigrateEvent.ts +20 -0
  167. package/src/generated/api/{KeepAliveQueryRequest.ts → SfuNeighbourhoodParams.ts} +1 -1
  168. package/src/generated/api/SfuParticipantQualityPreference.ts +6 -0
  169. package/src/generated/api/{PerspectiveSubscribeQueryResult.ts → SfuPerspectiveParams.ts} +4 -1
  170. package/src/generated/api/SfuQualityPreferenceParams.ts +7 -0
  171. package/src/generated/api/SfuRoomInfo.ts +7 -0
  172. package/src/generated/api/SfuRoomParams.ts +3 -0
  173. package/src/generated/api/SfuRoomParticipantInfo.ts +8 -0
  174. package/src/generated/api/SfuRoomRoster.ts +12 -0
  175. package/src/generated/api/SfuSendDataParams.ts +7 -0
  176. package/src/generated/api/SfuSetConfigParams.ts +4 -0
  177. package/src/generated/api/SfuStatus.ts +24 -0
  178. package/src/generated/api/TrackMapEntry.ts +18 -0
  179. package/src/generated/api/UpdateSubjectRequest.ts +10 -0
  180. package/src/generated/api/index.ts +3 -0
  181. package/src/index.ts +7 -0
  182. package/src/model/Ad4mModel.test.ts +255 -231
  183. package/src/model/Ad4mModel.ts +271 -4
  184. package/src/model/ModelQueryBuilder.ts +103 -310
  185. package/src/model/abstract-classes.test.ts +225 -0
  186. package/src/model/decorators.ts +81 -0
  187. package/src/model/shacl-gen.ts +13 -0
  188. package/src/model/types.ts +7 -0
  189. package/src/neighbourhood/MeshManager.test.ts +2640 -0
  190. package/src/neighbourhood/MeshManager.ts +1350 -0
  191. package/src/neighbourhood/NeighbourhoodClient.ts +271 -0
  192. package/src/neighbourhood/NeighbourhoodProxy.test.ts +23 -0
  193. package/src/neighbourhood/NeighbourhoodProxy.ts +247 -1
  194. package/src/neighbourhood/Session.test.ts +800 -0
  195. package/src/neighbourhood/Session.ts +525 -0
  196. package/src/neighbourhood/SfuManager.test.ts +677 -0
  197. package/src/neighbourhood/SfuManager.ts +803 -0
  198. package/src/neighbourhood/SfuTypes.ts +40 -0
  199. package/src/perspectives/FlowInstance.ts +108 -31
  200. package/src/perspectives/FlowModels.ts +8 -18
  201. package/src/perspectives/LiveQuery.test.ts +197 -0
  202. package/src/perspectives/LiveQuery.ts +189 -0
  203. package/src/perspectives/PerspectiveClient.ts +51 -51
  204. package/src/perspectives/PerspectiveProxy.test.ts +85 -401
  205. package/src/perspectives/PerspectiveProxy.ts +126 -536
  206. package/src/perspectives/TextContent.test.ts +123 -0
  207. package/src/perspectives/TextContent.ts +36 -0
  208. package/src/perspectives/WakerSubscriptionManager.test.ts +88 -6
  209. package/src/perspectives/WakerSubscriptionManager.ts +69 -18
  210. package/src/shacl/SHACLFlow.ts +7 -4
  211. package/src/shacl/SHACLShape.test.ts +2 -1
  212. package/src/shacl/SHACLShape.ts +49 -0
  213. package/lib/src/generated/api/KeepAliveQueryRequest.d.ts +0 -3
  214. package/lib/src/generated/api/PerspectiveModelSubscribeResult.d.ts +0 -7
  215. package/lib/src/generated/api/PerspectiveQuerySubscriptionFilter.d.ts +0 -6
  216. package/lib/src/generated/api/PerspectiveSubscribeQueryResult.d.ts +0 -4
  217. package/src/generated/api/PerspectiveModelSubscribeResult.ts +0 -6
  218. package/src/generated/api/PerspectiveQuerySubscriptionFilter.ts +0 -3
  219. /package/lib/src/generated/api/{KeepAliveQueryRequest.js → AgentsByDidsRequest.js} +0 -0
  220. /package/lib/src/generated/api/{PerspectiveModelSubscribeResult.js → CallSessionInfo.js} +0 -0
  221. /package/lib/src/generated/api/{PerspectiveQuerySubscriptionFilter.js → DiscardBatchRequest.js} +0 -0
  222. /package/lib/src/generated/api/{PerspectiveSubscribeQueryResult.js → FlowStateChangedEvent.js} +0 -0
@@ -0,0 +1,2640 @@
1
+ /**
2
+ * MeshManager unit tests: two or more agents negotiating in one process.
3
+ *
4
+ * Ported from WE Framework's `packages/module-system/call/src/mesh.test.ts`,
5
+ * which tests the same algorithm behind a function API. The mesh is the part
6
+ * that cannot be checked by reading it: perfect negotiation is a protocol
7
+ * between two peers whose bugs (glare, a lost candidate, a connection that
8
+ * never tears down) only appear when both sides run.
9
+ *
10
+ * The `RTCPeerConnection` fake is deliberately thin: it models signalling
11
+ * state and the callbacks the mesh drives, and nothing about media. What is
12
+ * under test is the negotiation, not the browser. Nothing sleeps: a hand-moved
13
+ * clock and `mesh.tick()` stand in for the sweep timer (`sweepMs: 0`).
14
+ */
15
+
16
+ // ── Browser shims for Node/Jest ─────────────────────────────────────
17
+
18
+ /**
19
+ * The mesh groups its outbound tracks into one stream and collects each
20
+ * peer's inbound tracks into another, so it constructs `MediaStream` even
21
+ * when no media exists. Node has no such global.
22
+ */
23
+ class FakeMediaStream {
24
+ #tracks: unknown[]
25
+ constructor(tracks: unknown[] = []) {
26
+ this.#tracks = [...tracks]
27
+ }
28
+ getTracks() {
29
+ return [...this.#tracks]
30
+ }
31
+ getVideoTracks() {
32
+ return this.#tracks.filter((track) => (track as { kind?: string }).kind === "video")
33
+ }
34
+ getAudioTracks() {
35
+ return this.#tracks.filter((track) => (track as { kind?: string }).kind === "audio")
36
+ }
37
+ addTrack(track: unknown) {
38
+ if (!this.#tracks.includes(track)) this.#tracks.push(track)
39
+ }
40
+ removeTrack(track: unknown) {
41
+ const i = this.#tracks.indexOf(track)
42
+ if (i !== -1) this.#tracks.splice(i, 1)
43
+ }
44
+ }
45
+ ;(globalThis as { MediaStream?: unknown }).MediaStream = FakeMediaStream
46
+
47
+ /** A track that can go quiet, come back and end, as a remote track does. */
48
+ class FakeTrack {
49
+ readyState: MediaStreamTrackState = "live"
50
+ muted = false
51
+ private listeners = new Map<string, Set<() => void>>()
52
+
53
+ constructor(readonly kind: "audio" | "video") {}
54
+
55
+ addEventListener(name: string, cb: () => void) {
56
+ if (!this.listeners.has(name)) this.listeners.set(name, new Set())
57
+ this.listeners.get(name)!.add(cb)
58
+ }
59
+
60
+ removeEventListener(name: string, cb: () => void) {
61
+ this.listeners.get(name)?.delete(cb)
62
+ }
63
+
64
+ listening(name: string) {
65
+ return (this.listeners.get(name)?.size ?? 0) > 0
66
+ }
67
+
68
+ /** Change the state the event describes, then fire it. */
69
+ fire(name: "mute" | "unmute" | "ended") {
70
+ if (name === "mute") this.muted = true
71
+ if (name === "unmute") this.muted = false
72
+ if (name === "ended") this.readyState = "ended"
73
+ for (const cb of [...(this.listeners.get(name) ?? [])]) cb()
74
+ }
75
+ }
76
+
77
+ const track = (kind: "audio" | "video") => new FakeTrack(kind) as unknown as MediaStreamTrack
78
+ const stream = (...tracks: MediaStreamTrack[]) => new FakeMediaStream(tracks) as unknown as MediaStream
79
+
80
+ import {
81
+ MeshManager,
82
+ parseCallMessage,
83
+ createTelepresenceChannel,
84
+ CALL_PROTOCOL_VERSION,
85
+ DEFAULT_ICE_SERVERS,
86
+ DISCONNECT_GRACE_MS,
87
+ HANDSHAKE_GRACE_MS,
88
+ MAX_RECOVERY_ATTEMPTS,
89
+ RECOVERY_INTERVAL_MS,
90
+ REPAIR_SPACING_MS,
91
+ type CallMessage,
92
+ type MeshParticipant,
93
+ type RecoveryRung,
94
+ type SignallingChannel,
95
+ type TelepresenceProxy,
96
+ } from "./MeshManager"
97
+ import type { PerspectiveExpression } from "../perspectives/Perspective"
98
+
99
+ // ── A fake RTCPeerConnection ────────────────────────────────────────
100
+
101
+ let nextConnection = 0
102
+
103
+ class FakePeerConnection {
104
+ /** Which connection this is, written into every description it makes — see `setRemoteDescription`. */
105
+ readonly id = `pc${(nextConnection += 1)}`
106
+ /** The connection the remote descriptions applied so far came from. */
107
+ private remoteOrigin: string | null = null
108
+
109
+ signalingState: RTCSignalingState = "stable"
110
+ connectionState: RTCPeerConnectionState = "new"
111
+ localDescription: RTCSessionDescriptionInit | null = null
112
+ remoteDescription: RTCSessionDescriptionInit | null = null
113
+
114
+ onnegotiationneeded: (() => void) | null = null
115
+ onicecandidate: ((e: { candidate: { toJSON(): RTCIceCandidateInit } | null }) => void) | null = null
116
+ ontrack: ((e: { track: unknown }) => void) | null = null
117
+ onconnectionstatechange: (() => void) | null = null
118
+
119
+ senders: { track: MediaStreamTrack | null; replaceTrack(t: MediaStreamTrack | null): Promise<void> }[] = []
120
+ addedTracks: unknown[] = []
121
+ /** The m-sections this connection has negotiated. */
122
+ transceivers: { kind: string; direction: string }[] = []
123
+ candidates: RTCIceCandidateInit[] = []
124
+ closed = false
125
+
126
+ /**
127
+ * Fire `negotiationneeded` once per task, as a browser does: declaring an
128
+ * audio and a video section together produces one negotiation.
129
+ */
130
+ private negotiationNeeded = false
131
+ private negotiationQueued = false
132
+ private queueNegotiation() {
133
+ this.negotiationNeeded = true
134
+ if (this.negotiationQueued) return
135
+ this.negotiationQueued = true
136
+ queueMicrotask(() => {
137
+ this.negotiationQueued = false
138
+ // Cleared by `setLocalDescription`: a peer that has just answered
139
+ // an offer describing these sections does not then offer them again.
140
+ if (!this.negotiationNeeded) return
141
+ // And never mid-handshake: the spec aborts the event unless stable.
142
+ if (this.signalingState !== "stable") return
143
+ this.onnegotiationneeded?.()
144
+ })
145
+ }
146
+
147
+ private makeSender(track: MediaStreamTrack | null) {
148
+ const sender = {
149
+ track,
150
+ async replaceTrack(next: MediaStreamTrack | null) {
151
+ sender.track = next
152
+ },
153
+ }
154
+ this.senders.push(sender)
155
+ return sender
156
+ }
157
+
158
+ addTransceiver(kind: string, init?: { direction?: string; streams?: MediaStream[] }) {
159
+ this.transceivers.push({ kind, direction: init?.direction ?? "sendrecv" })
160
+ this.queueNegotiation()
161
+ return { sender: this.makeSender(null) }
162
+ }
163
+
164
+ addTrack(track: MediaStreamTrack, _stream?: MediaStream) {
165
+ this.addedTracks.push(track)
166
+ this.queueNegotiation()
167
+ return this.makeSender(track)
168
+ }
169
+
170
+ getSenders() {
171
+ return this.senders
172
+ }
173
+
174
+ private offersMade = 0
175
+ private remoteOfferSeq = 0
176
+
177
+ async setLocalDescription(description?: RTCSessionDescriptionInit) {
178
+ this.negotiationNeeded = false
179
+ // With no argument the browser picks offer or answer from the signaling state.
180
+ const type = description?.type ?? (this.signalingState === "have-remote-offer" ? "answer" : "offer")
181
+ // As a browser does: an offer only from stable, an answer only to an offer.
182
+ if ((type === "offer") !== (this.signalingState !== "have-remote-offer")) {
183
+ throw new Error(`InvalidStateError: cannot set a local ${type} in state ${this.signalingState}`)
184
+ }
185
+ // An offer is `offer-sdp@pc1#2` (pc1's second offer); an answer names
186
+ // the offer it answers: `answer-sdp@pc2>pc1#2`.
187
+ const sdp =
188
+ type === "offer"
189
+ ? `offer-sdp@${this.id}#${(this.offersMade += 1)}`
190
+ : `answer-sdp@${this.id}>${this.remoteDescription?.sdp?.split("@")[1] ?? ""}`
191
+ this.localDescription = { type: type as RTCSdpType, sdp }
192
+ this.signalingState = type === "offer" ? "have-local-offer" : "stable"
193
+ }
194
+
195
+ /**
196
+ * Refuses a description from a different connection than the one it has
197
+ * been talking to — the browser's "The order of m-lines in subsequent
198
+ * offer doesn't match order from previous offer/answer" — and an answer
199
+ * to another offer than the one out — "The order of m-lines in answer
200
+ * doesn't match order in offer". Modelled by origin rather than by
201
+ * m-lines; a hand-written description with no origin is accepted.
202
+ */
203
+ async setRemoteDescription(description: RTCSessionDescriptionInit) {
204
+ const [, tail] = description.sdp?.split("@") ?? []
205
+ const origin = tail?.split(/[#>]/)[0] ?? null
206
+ if (origin && this.remoteOrigin && origin !== this.remoteOrigin) {
207
+ throw new Error(
208
+ "InvalidAccessError: Failed to set remote offer sdp: The order of m-lines in subsequent offer doesn't match order from previous offer/answer.",
209
+ )
210
+ }
211
+ // An offer older than one applied describes m-lines the connection has moved past.
212
+ const offerSeq = Number(tail?.split(">")[0].split("#")[1])
213
+ if (description.type === "offer" && offerSeq < this.remoteOfferSeq) {
214
+ throw new Error(
215
+ "InvalidAccessError: Failed to set remote offer sdp: The order of m-lines in subsequent offer doesn't match order from previous offer/answer.",
216
+ )
217
+ }
218
+ if (description.type === "offer" && offerSeq) this.remoteOfferSeq = offerSeq
219
+ const answers = tail?.split(">")[1]
220
+ if (description.type === "answer" && answers && answers !== this.localDescription?.sdp?.split("@")[1]) {
221
+ throw new Error(
222
+ "InvalidAccessError: Failed to set remote answer sdp: The order of m-lines in answer doesn't match order in offer. Rejecting answer.",
223
+ )
224
+ }
225
+ if (origin) this.remoteOrigin = origin
226
+ this.remoteDescription = description
227
+ this.signalingState = description.type === "offer" ? "have-remote-offer" : "stable"
228
+ }
229
+
230
+ async addIceCandidate(candidate: RTCIceCandidateInit) {
231
+ if (this.signalingState === "stable" && !this.remoteDescription) {
232
+ throw new Error("no remote description")
233
+ }
234
+ this.candidates.push(candidate)
235
+ }
236
+
237
+ /** How many ICE restarts this connection was asked for — the cheapest rung of the ladder. */
238
+ restartIceCalls = 0
239
+ restartIce() {
240
+ this.restartIceCalls += 1
241
+ // A real restart re-gathers and renegotiates.
242
+ this.queueNegotiation()
243
+ }
244
+
245
+ /** What `transportOf` reads. Empty unless a test says otherwise. */
246
+ stats: Record<string, unknown>[] = []
247
+ async getStats() {
248
+ return new Map(this.stats.map((report) => [report.id as string, report]))
249
+ }
250
+
251
+ close() {
252
+ this.closed = true
253
+ }
254
+
255
+ /** Test helper: pretend ICE produced a candidate. */
256
+ emitCandidate(candidate: RTCIceCandidateInit) {
257
+ this.onicecandidate?.({ candidate: { toJSON: () => candidate } })
258
+ }
259
+
260
+ /** Test helper: drive the connection state the recovery ladder reads. */
261
+ setConnectionState(state: RTCPeerConnectionState) {
262
+ this.connectionState = state
263
+ this.onconnectionstatechange?.()
264
+ }
265
+ }
266
+
267
+ // ── In-memory signalling ────────────────────────────────────────────
268
+
269
+ type Listener = (from: string, payload: unknown) => void
270
+ type PublishResult = { ok: boolean; ms: number }
271
+
272
+ interface ChannelOptions {
273
+ /**
274
+ * Swallow an outgoing message instead of delivering it — a lossy
275
+ * transport, which is what telepresence is. Read on every publish, so a
276
+ * test can lose the opening handshake and then let the repair through.
277
+ * A dropped message is still reported `ok`: the executor accepted it and
278
+ * no peer received it, which is the failure being modelled.
279
+ */
280
+ drop?: (payload: unknown) => boolean
281
+ /** Hold publish results until `results.release()`, so sends stay outstanding. */
282
+ holdResults?: boolean
283
+ }
284
+
285
+ /**
286
+ * Every subscriber hears every publish but its own, and the sender id comes
287
+ * from the transport, never from the payload. Delivery is synchronous; a
288
+ * test that wants a message late or out of order drops it and hands it to
289
+ * {@link InMemoryBus.deliver} itself.
290
+ */
291
+ class InMemoryBus {
292
+ private subscribers = new Map<string, Set<Listener>>()
293
+
294
+ channel(selfId: string, options: ChannelOptions = {}) {
295
+ const watchers = new Set<(result: PublishResult) => void>()
296
+ const sent: unknown[] = []
297
+ const report = (result: PublishResult) => {
298
+ for (const cb of [...watchers]) cb(result)
299
+ }
300
+ const results = {
301
+ holding: !!options.holdResults,
302
+ held: 0,
303
+ /** Report every held publish, oldest first. */
304
+ release(result: PublishResult = { ok: true, ms: 18_000 }) {
305
+ const n = results.held
306
+ results.held = 0
307
+ for (let i = 0; i < n; i += 1) report(result)
308
+ },
309
+ }
310
+
311
+ const channel: SignallingChannel = {
312
+ publish: (payload) => {
313
+ sent.push(payload)
314
+ if (!options.drop?.(payload)) this.deliver(selfId, payload)
315
+ if (results.holding) results.held += 1
316
+ else report({ ok: true, ms: 0 })
317
+ },
318
+ onMessage: (cb) => {
319
+ if (!this.subscribers.has(selfId)) this.subscribers.set(selfId, new Set())
320
+ this.subscribers.get(selfId)!.add(cb)
321
+ return () => { this.subscribers.get(selfId)?.delete(cb) }
322
+ },
323
+ onPublishResult: (cb) => {
324
+ watchers.add(cb)
325
+ return () => { watchers.delete(cb) }
326
+ },
327
+ }
328
+
329
+ return { channel, sent, results }
330
+ }
331
+
332
+ /** Hand a message to one subscriber, whoever it claims to be from — even itself. */
333
+ deliverTo(to: string, from: string, payload: unknown) {
334
+ for (const cb of [...(this.subscribers.get(to) ?? [])]) cb(from, payload)
335
+ }
336
+
337
+ /** Deliver as though `from` had published it: to every subscriber but `from`. */
338
+ deliver(from: string, payload: unknown) {
339
+ for (const [id, listeners] of this.subscribers) {
340
+ if (id === from) continue
341
+ for (const cb of [...listeners]) cb(from, payload)
342
+ }
343
+ }
344
+ }
345
+
346
+ // ── Helpers ─────────────────────────────────────────────────────────
347
+
348
+ /**
349
+ * A clock the tests move by hand. The recovery ladder is defined in seconds;
350
+ * `advance` moves the clock and `mesh.tick()` is the sweep.
351
+ */
352
+ function makeClock() {
353
+ let at = 1_000
354
+ return { now: () => at, advance: (ms: number) => (at += ms) }
355
+ }
356
+
357
+ interface MeshOptions extends ChannelOptions {
358
+ iceServers?: RTCIceServer[]
359
+ now?: () => number
360
+ /** What `join` is handed. An empty stream unless a test says otherwise. */
361
+ localStream?: MediaStream
362
+ }
363
+
364
+ /** Every mesh a test made, so each is left afterwards and no timer or listener outlives its test. */
365
+ const meshes: MeshManager[] = []
366
+
367
+ async function makeMesh(bus: InMemoryBus, selfId: string, callId: string, options: MeshOptions = {}) {
368
+ const { channel, sent, results } = bus.channel(selfId, options)
369
+
370
+ const connections: FakePeerConnection[] = []
371
+ const configs: RTCConfiguration[] = []
372
+ const errors: Error[] = []
373
+ const recoveries: { peerId: string; rung: RecoveryRung; attempts: number }[] = []
374
+ const joins: string[] = []
375
+ const leaves: string[] = []
376
+ const updates: MeshParticipant[] = []
377
+ const states: [string, RTCPeerConnectionState][] = []
378
+
379
+ const mesh = new MeshManager({
380
+ channel,
381
+ callId,
382
+ selfId,
383
+ iceServers: options.iceServers,
384
+ now: options.now,
385
+ // No timer: every test drives `tick()` itself, so a sweep never fires
386
+ // between an act and its assertion. The interval has its own test.
387
+ sweepMs: 0,
388
+ createPeerConnection: (configuration) => {
389
+ configs.push(configuration)
390
+ const pc = new FakePeerConnection()
391
+ connections.push(pc)
392
+ return pc as unknown as RTCPeerConnection
393
+ },
394
+ })
395
+ meshes.push(mesh)
396
+
397
+ mesh.on("error", (error: Error) => errors.push(error))
398
+ mesh.on("peer-recovery", (peerId: string, attempt: { rung: RecoveryRung; attempts: number }) =>
399
+ recoveries.push({ peerId, ...attempt }))
400
+ mesh.on("participant-joined", (p: MeshParticipant) => joins.push(p.did))
401
+ mesh.on("participant-left", (p: MeshParticipant) => leaves.push(p.did))
402
+ mesh.on("participant-updated", (p: MeshParticipant) => updates.push(p))
403
+ mesh.on("peer-state", (peerId: string, state: RTCPeerConnectionState) => states.push([peerId, state]))
404
+
405
+ await mesh.join(options.localStream ?? stream())
406
+
407
+ /** The connection currently serving a pair — the last one built, after any rebuilds. */
408
+ const live = () => connections[connections.length - 1]
409
+
410
+ return { mesh, connections, configs, errors, recoveries, joins, leaves, updates, states, sent, results, live }
411
+ }
412
+
413
+ /** Every message kind the mesh published, in order. The warm-up message has none. */
414
+ const kinds = (sent: unknown[]) => sent.map((payload) => (payload as { kind?: string }).kind)
415
+
416
+ /** Let queued microtasks and promise chains settle. */
417
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 0))
418
+
419
+ const settleAll = async () => {
420
+ for (let n = 0; n < 6; n += 1) await settle()
421
+ }
422
+
423
+ afterEach(async () => {
424
+ for (const mesh of meshes.splice(0)) await mesh.destroy()
425
+ })
426
+
427
+ const CALL_ID = "call:rec-abc"
428
+
429
+ // ── Protocol ────────────────────────────────────────────────────────
430
+
431
+ describe("parseCallMessage", () => {
432
+ const good: CallMessage = {
433
+ v: CALL_PROTOCOL_VERSION,
434
+ call: "room:x",
435
+ kind: "description",
436
+ description: { type: "offer", sdp: "v=0" },
437
+ }
438
+
439
+ it("accepts a well-formed description", () => {
440
+ expect(parseCallMessage(good)).toEqual(good)
441
+ })
442
+
443
+ it("accepts an offer with no sdp", () => {
444
+ const noSdp = { ...good, description: { type: "offer" } }
445
+ expect(parseCallMessage(noSdp)).toEqual({
446
+ ...good,
447
+ description: { type: "offer", sdp: undefined },
448
+ })
449
+ })
450
+
451
+ it("accepts an answer", () => {
452
+ const answer = { ...good, description: { type: "answer", sdp: "a=0" } }
453
+ expect(parseCallMessage(answer)).toEqual(answer)
454
+ })
455
+
456
+ it("accepts an ICE candidate", () => {
457
+ const ice = {
458
+ v: CALL_PROTOCOL_VERSION,
459
+ call: "room:x",
460
+ kind: "ice" as const,
461
+ candidate: { candidate: "a=candidate:1 ..." },
462
+ }
463
+ expect(parseCallMessage(ice)).toEqual(ice)
464
+ })
465
+
466
+ it("accepts a data message", () => {
467
+ const data = {
468
+ v: CALL_PROTOCOL_VERSION,
469
+ call: "room:x",
470
+ kind: "data" as const,
471
+ label: "chat",
472
+ data: "hello",
473
+ binary: false,
474
+ }
475
+ expect(parseCallMessage(data)).toEqual(data)
476
+ })
477
+
478
+ it("coerces missing binary flag to false", () => {
479
+ const raw = {
480
+ v: CALL_PROTOCOL_VERSION,
481
+ call: "room:x",
482
+ kind: "data",
483
+ label: "chat",
484
+ data: "hello",
485
+ }
486
+ const parsed = parseCallMessage(raw)
487
+ expect(parsed).not.toBeNull()
488
+ expect((parsed as { binary: boolean }).binary).toBe(false)
489
+ })
490
+
491
+ it.each([
492
+ ["mismatched version", { ...good, v: 99 }],
493
+ ["missing call id", { ...good, call: undefined }],
494
+ ["empty call id", { ...good, call: "" }],
495
+ ["unknown kind", { ...good, kind: "chat" }],
496
+ ["non-object description", { ...good, description: "offer" }],
497
+ ["invalid sdp type", { ...good, description: { type: "nonsense", sdp: "x" } }],
498
+ ["null payload", null],
499
+ ["string payload", "offer"],
500
+ ["number payload", 42],
501
+ ["null description", { ...good, description: null }],
502
+ ["non-string data label", { v: CALL_PROTOCOL_VERSION, call: "x", kind: "data", label: 123, data: "y" }],
503
+ ["non-string data payload", { v: CALL_PROTOCOL_VERSION, call: "x", kind: "data", label: "x", data: 123 }],
504
+ ["null ice candidate", { v: CALL_PROTOCOL_VERSION, call: "x", kind: "ice", candidate: null }],
505
+ ])("rejects %s", (_label, payload) => {
506
+ expect(parseCallMessage(payload)).toBeNull()
507
+ })
508
+
509
+ it("carries which connections a message is between, and only as strings", () => {
510
+ expect(parseCallMessage({ ...good, gen: "g1", peerGen: "g2" })).toEqual({ ...good, gen: "g1", peerGen: "g2" })
511
+ // A malformed generation is dropped rather than failing the message:
512
+ // without one, it is read the way a peer predating generations is read.
513
+ expect(parseCallMessage({ ...good, gen: 7, peerGen: { x: 1 } })).toEqual(good)
514
+ expect(parseCallMessage({ v: CALL_PROTOCOL_VERSION, call: "room:x", kind: "reset", gen: "g1" })).toEqual({
515
+ v: CALL_PROTOCOL_VERSION,
516
+ call: "room:x",
517
+ kind: "reset",
518
+ gen: "g1",
519
+ })
520
+ })
521
+
522
+ it("stays at protocol version 1, the version WE speaks", () => {
523
+ // A bump would make SDK and WE peers in one call drop every message
524
+ // from each other. New kinds and fields go in without one.
525
+ expect(CALL_PROTOCOL_VERSION).toBe(1)
526
+ })
527
+
528
+ it("reads WE's current wire format, generations and reset included", () => {
529
+ // Exactly what WE's mesh publishes: `to` in the payload, both
530
+ // generations, and the `reset` kind. `to` is addressing and is not
531
+ // part of the parsed message.
532
+ const call = "space:rec-abc"
533
+ const offer = {
534
+ v: 1, call, to: "did:alice", kind: "description",
535
+ description: { type: "offer", sdp: "v=0\r\n" }, gen: "k3j2a9x1", peerGen: "p0q9r8s7",
536
+ }
537
+ const candidate = {
538
+ v: 1, call, to: "did:alice", kind: "ice",
539
+ candidate: { candidate: "candidate:1 1 udp 2122260223 10.0.0.2 5000 typ host", sdpMid: "0", sdpMLineIndex: 0 },
540
+ gen: "k3j2a9x1",
541
+ }
542
+ const reset = { v: 1, call, to: "did:alice", kind: "reset", gen: "k3j2a9x1", peerGen: "p0q9r8s7" }
543
+ const warm = { v: 1, call, warm: true }
544
+
545
+ expect(parseCallMessage(offer)).toEqual({
546
+ v: 1, call, kind: "description",
547
+ description: { type: "offer", sdp: "v=0\r\n" }, gen: "k3j2a9x1", peerGen: "p0q9r8s7",
548
+ })
549
+ expect(parseCallMessage(candidate)).toEqual({
550
+ v: 1, call, kind: "ice", candidate: candidate.candidate, gen: "k3j2a9x1",
551
+ })
552
+ expect(parseCallMessage(reset)).toEqual({ v: 1, call, kind: "reset", gen: "k3j2a9x1", peerGen: "p0q9r8s7" })
553
+ // The warm-up message has no kind and parses to nothing, on both sides.
554
+ expect(parseCallMessage(warm)).toBeNull()
555
+ })
556
+ })
557
+
558
+ // ── Negotiation and roster ──────────────────────────────────────────
559
+
560
+ describe("call mesh", () => {
561
+ let bus: InMemoryBus
562
+
563
+ beforeEach(() => {
564
+ bus = new InMemoryBus()
565
+ })
566
+
567
+ it("connects two peers, with exactly one surviving offer", async () => {
568
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
569
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
570
+
571
+ // Presence says both are in the call. Neither sent a join message.
572
+ alice.mesh.setRoster(["did:alice", "did:bob"])
573
+ bob.mesh.setRoster(["did:alice", "did:bob"])
574
+ await settle()
575
+
576
+ expect(alice.connections).toHaveLength(1)
577
+ expect(bob.connections).toHaveLength(1)
578
+
579
+ // Negotiation begins with the connection, not with the first track.
580
+ await settle()
581
+ await settle()
582
+
583
+ expect(alice.connections[0].signalingState).toBe("stable")
584
+ expect(bob.connections[0].signalingState).toBe("stable")
585
+ const answered = [alice, bob].filter((peer) => peer.connections[0].localDescription?.type === "answer")
586
+ expect(answered).toHaveLength(1)
587
+
588
+ // And a track needs no further handshake — it attaches to a section that already exists.
589
+ await alice.mesh.replaceTrack("audio", track("audio"))
590
+ await settle()
591
+
592
+ expect(alice.connections[0].addedTracks).toEqual([])
593
+ expect(alice.errors).toEqual([])
594
+ expect(bob.errors).toEqual([])
595
+ })
596
+
597
+ it("publishes one warm-up message on join, which no peer acts on", async () => {
598
+ // The first broadcast on a fresh neighbourhood is the slow one; it
599
+ // should not be the first SDP offer.
600
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
601
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
602
+
603
+ expect(alice.sent).toEqual([{ v: CALL_PROTOCOL_VERSION, call: CALL_ID, warm: true }])
604
+ bob.mesh.setRoster(["did:alice", "did:bob"])
605
+ await settle()
606
+
607
+ expect(bob.errors).toEqual([])
608
+ expect(bob.connections[0].remoteDescription).toBeNull()
609
+ })
610
+
611
+ it("negotiates a video section even when this agent has no camera", async () => {
612
+ // A connection carries only the kinds it negotiated a section for, so
613
+ // an agent sending no video left the other agent's camera nowhere to land.
614
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
615
+ alice.mesh.setRoster(["did:alice", "did:bob"])
616
+ await settle()
617
+
618
+ await alice.mesh.replaceTrack("audio", track("audio"))
619
+ await settle()
620
+
621
+ expect(alice.connections[0].transceivers.map((t) => t.kind).sort()).toEqual(["audio", "video"])
622
+ expect(alice.connections[0].transceivers.every((t) => t.direction === "sendrecv")).toBe(true)
623
+ })
624
+
625
+ it("survives glare: both peers offering at once still converges", async () => {
626
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
627
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
628
+
629
+ alice.mesh.setRoster(["did:alice", "did:bob"])
630
+ bob.mesh.setRoster(["did:alice", "did:bob"])
631
+ await settle()
632
+
633
+ await Promise.all([
634
+ alice.mesh.replaceTrack("audio", track("audio")),
635
+ bob.mesh.replaceTrack("audio", track("audio")),
636
+ ])
637
+ await settle()
638
+ await settle()
639
+ await settle()
640
+
641
+ expect(alice.connections[0].signalingState).toBe("stable")
642
+ expect(bob.connections[0].signalingState).toBe("stable")
643
+ expect(alice.errors).toEqual([])
644
+ expect(bob.errors).toEqual([])
645
+ })
646
+
647
+ it("determines the polite side by DID comparison (higher DID = polite)", async () => {
648
+ // 'did:bob' > 'did:alice', so Bob is polite and yields; Alice's offer wins.
649
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
650
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
651
+
652
+ alice.mesh.setRoster(["did:alice", "did:bob"])
653
+ bob.mesh.setRoster(["did:alice", "did:bob"])
654
+ await settleAll()
655
+
656
+ expect(bob.connections[0].localDescription?.type).toBe("answer")
657
+ expect(alice.connections[0].localDescription?.type).toBe("offer")
658
+ })
659
+
660
+ it("tears down a connection when presence drops the peer from the roster", async () => {
661
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
662
+ await makeMesh(bus, "did:bob", CALL_ID)
663
+
664
+ alice.mesh.setRoster(["did:alice", "did:bob"])
665
+ await settle()
666
+ expect(alice.connections[0].closed).toBe(false)
667
+
668
+ // Bob's laptop closed. Presence evicts him; no leave message is ever sent.
669
+ alice.mesh.setRoster(["did:alice"])
670
+ expect(alice.connections[0].closed).toBe(true)
671
+ expect(alice.mesh.getParticipants()).toEqual([])
672
+ expect(alice.mesh.peerStates().size).toBe(0)
673
+ })
674
+
675
+ it("emits participant-joined from setRoster and participant-left when the roster drops the peer", async () => {
676
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
677
+
678
+ alice.mesh.setRoster(["did:alice", "did:bob"])
679
+ expect(alice.joins).toEqual(["did:bob"])
680
+
681
+ // Listing an existing peer again is not a second join.
682
+ alice.mesh.setRoster(["did:alice", "did:bob"])
683
+ expect(alice.joins).toEqual(["did:bob"])
684
+
685
+ alice.mesh.setRoster(["did:alice"])
686
+ expect(alice.leaves).toEqual(["did:bob"])
687
+ })
688
+
689
+ it("filters self from the roster", async () => {
690
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
691
+
692
+ alice.mesh.setRoster(["did:alice"])
693
+ expect(alice.connections).toHaveLength(0)
694
+ expect(alice.joins).toEqual([])
695
+ })
696
+
697
+ it("returns participants from getParticipants()", async () => {
698
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
699
+
700
+ expect(alice.mesh.getParticipants()).toEqual([])
701
+
702
+ alice.mesh.setRoster(["did:alice", "did:bob", "did:carol"])
703
+ const participants = alice.mesh.getParticipants()
704
+ expect(participants).toHaveLength(2)
705
+ expect(participants.map((p) => p.did).sort()).toEqual(["did:bob", "did:carol"])
706
+ expect(participants.every((p) => !p.hasAudio && !p.hasVideo)).toBe(true)
707
+ })
708
+
709
+ it("ignores signalling from an agent the roster does not include", async () => {
710
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
711
+ alice.mesh.setRoster(["did:alice"])
712
+
713
+ // A stranger offers out of the blue. Without the roster check this would open a connection.
714
+ bus.deliver("did:mallory", {
715
+ v: CALL_PROTOCOL_VERSION,
716
+ call: CALL_ID,
717
+ to: "did:alice",
718
+ kind: "description",
719
+ description: { type: "offer", sdp: "x" },
720
+ })
721
+ await settle()
722
+
723
+ expect(alice.connections).toHaveLength(0)
724
+ expect(alice.errors).toEqual([])
725
+ })
726
+
727
+ it("ignores traffic for a different call in the same space", async () => {
728
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
729
+ alice.mesh.setRoster(["did:alice", "did:bob"])
730
+ await settle()
731
+
732
+ const before = alice.connections[0].remoteDescription
733
+ bus.deliver("did:bob", {
734
+ v: CALL_PROTOCOL_VERSION,
735
+ call: "call:rec-other",
736
+ to: "did:alice",
737
+ kind: "description",
738
+ description: { type: "offer", sdp: "wrong-call" },
739
+ })
740
+ await settle()
741
+
742
+ expect(alice.connections[0].remoteDescription).toBe(before)
743
+ })
744
+
745
+ it("ignores signalling addressed to another agent", async () => {
746
+ // A fanout-only transport delivers everything to everyone; the `to`
747
+ // in the payload stops a bystander negotiating.
748
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
749
+ alice.mesh.setRoster(["did:alice", "did:bob"])
750
+ await settle()
751
+
752
+ bus.deliver("did:bob", {
753
+ v: CALL_PROTOCOL_VERSION,
754
+ call: CALL_ID,
755
+ to: "did:carol",
756
+ kind: "description",
757
+ description: { type: "offer", sdp: "for-carol" },
758
+ })
759
+ await settle()
760
+
761
+ expect(alice.connections[0].remoteDescription).toBeNull()
762
+ expect(alice.errors).toEqual([])
763
+ })
764
+
765
+ it("drops its own echo", async () => {
766
+ // A transport that echoes a publish back to its sender must not make
767
+ // the mesh negotiate with itself.
768
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
769
+ alice.mesh.setRoster(["did:alice", "did:bob"])
770
+ await settle()
771
+
772
+ const echo = alice.sent.find((payload) => (payload as { kind?: string }).kind === "description")
773
+ expect(echo).toBeDefined()
774
+ // Handed back to Alice as from herself, bypassing the bus's own self filter.
775
+ // Readdressed to Alice, so only the sender check stands between it and her.
776
+ bus.deliverTo("did:alice", "did:alice", { ...(echo as object), to: "did:alice" })
777
+
778
+ await settle()
779
+ expect(alice.connections).toHaveLength(1)
780
+ expect(alice.connections[0].remoteDescription).toBeNull()
781
+ expect(alice.errors).toEqual([])
782
+ })
783
+
784
+ it("re-emits when an inbound track stops receiving, and again when it comes back", async () => {
785
+ // A remote track does not END when its sender goes away — it goes
786
+ // `muted`. Only `ended` was wired up, so a peer's tile went on
787
+ // painting its last frame. Both edges, so a recovered connection's
788
+ // tile comes back without waiting for some unrelated event.
789
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
790
+ alice.mesh.setRoster(["did:alice", "did:bob"])
791
+ await settle()
792
+
793
+ const remote = new FakeTrack("video")
794
+ const added: MediaStreamTrack[] = []
795
+ alice.mesh.on("stream-added", (_stream: MediaStream, t: MediaStreamTrack) => added.push(t))
796
+
797
+ alice.connections[0].ontrack?.({ track: remote })
798
+ expect(added).toEqual([remote])
799
+ expect(remote.listening("mute")).toBe(true)
800
+ expect(remote.listening("unmute")).toBe(true)
801
+ expect(alice.mesh.getParticipants()[0].hasVideo).toBe(true)
802
+ const afterArrival = alice.updates.length
803
+
804
+ remote.fire("mute")
805
+ expect(alice.updates).toHaveLength(afterArrival + 1)
806
+ expect(alice.updates[alice.updates.length - 1].hasVideo).toBe(false)
807
+
808
+ remote.fire("unmute")
809
+ expect(alice.updates).toHaveLength(afterArrival + 2)
810
+ expect(alice.updates[alice.updates.length - 1].hasVideo).toBe(true)
811
+
812
+ // The track stays in the stream through both: muting is not removal.
813
+ expect(alice.mesh.getParticipants()[0].stream.getVideoTracks()).toEqual([remote])
814
+ })
815
+
816
+ it("removes an inbound track that ends, and says so", async () => {
817
+ // Camera → screen arrives as a new track and the old one ends.
818
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
819
+ alice.mesh.setRoster(["did:alice", "did:bob"])
820
+ await settle()
821
+
822
+ const camera = new FakeTrack("video")
823
+ const removed: unknown[] = []
824
+ alice.mesh.on("stream-removed", (_stream: MediaStream, t: unknown) => removed.push(t))
825
+ alice.connections[0].ontrack?.({ track: camera })
826
+
827
+ camera.fire("ended")
828
+ expect(removed).toEqual([camera])
829
+ expect(alice.mesh.getParticipants()[0].stream.getVideoTracks()).toEqual([])
830
+ expect(alice.updates[alice.updates.length - 1].hasVideo).toBe(false)
831
+ })
832
+
833
+ it("does not report a muted track for a connection that has been replaced", async () => {
834
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
835
+ alice.mesh.setRoster(["did:alice", "did:bob"])
836
+ await settle()
837
+
838
+ const remote = new FakeTrack("video")
839
+ alice.connections[0].ontrack?.({ track: remote })
840
+ alice.mesh.reconnect("did:bob")
841
+ const before = alice.updates.length
842
+
843
+ remote.fire("mute")
844
+ expect(alice.updates).toHaveLength(before)
845
+ })
846
+
847
+ it("does not report an ended track for a connection that has been replaced", async () => {
848
+ // Closing a peer connection ends its remote tracks; the rebuilt pair's
849
+ // listeners must not hear about a stream nobody holds any more.
850
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
851
+ alice.mesh.setRoster(["did:alice", "did:bob"])
852
+ await settle()
853
+
854
+ const remote = new FakeTrack("video")
855
+ const removed: unknown[] = []
856
+ alice.mesh.on("stream-removed", (_stream: MediaStream, t: unknown) => removed.push(t))
857
+ alice.connections[0].ontrack?.({ track: remote })
858
+ alice.mesh.reconnect("did:bob")
859
+ const before = alice.updates.length
860
+
861
+ remote.fire("ended")
862
+ expect(removed).toEqual([])
863
+ expect(alice.updates).toHaveLength(before)
864
+ })
865
+
866
+ it("replaces rather than re-adds when an outbound track changes", async () => {
867
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
868
+ alice.mesh.setRoster(["did:alice", "did:bob"])
869
+ await settle()
870
+
871
+ const camera = track("video")
872
+ const screen = track("video")
873
+
874
+ await alice.mesh.replaceTrack("video", camera)
875
+ await alice.mesh.replaceTrack("video", screen)
876
+
877
+ // One sender, swapped, and no topology change at all.
878
+ expect(alice.connections[0].addedTracks).toEqual([])
879
+ expect(alice.connections[0].getSenders().filter((s) => s.track)).toHaveLength(1)
880
+ expect(alice.connections[0].getSenders().find((s) => s.track)?.track).toBe(screen)
881
+ })
882
+
883
+ it("reuses the sender after the outbound track is cleared, rather than adding a second one", async () => {
884
+ // The frozen-screen bug: a sender whose track is null cannot be found
885
+ // by kind, so sharing again added a second video track and the peer's
886
+ // view stayed on the dead first one.
887
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
888
+ alice.mesh.setRoster(["did:alice", "did:bob"])
889
+ await settle()
890
+
891
+ const screen = track("video")
892
+ const screenAgain = track("video")
893
+
894
+ await alice.mesh.replaceTrack("video", screen)
895
+ await alice.mesh.replaceTrack("video", null)
896
+ await alice.mesh.replaceTrack("video", screenAgain)
897
+
898
+ expect(alice.connections[0].addedTracks).toEqual([])
899
+ expect(alice.connections[0].getSenders().filter((s) => s.track)).toHaveLength(1)
900
+ expect(alice.connections[0].getSenders().find((s) => s.track)?.track).toBe(screenAgain)
901
+ })
902
+
903
+ it("stops sending when the outbound track is cleared", async () => {
904
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
905
+ alice.mesh.setRoster(["did:alice", "did:bob"])
906
+ await settle()
907
+
908
+ await alice.mesh.replaceTrack("video", track("video"))
909
+ await alice.mesh.replaceTrack("video", null)
910
+
911
+ expect(alice.connections[0].getSenders().every((sender) => sender.track === null)).toBe(true)
912
+ })
913
+
914
+ it("sends a peer joining mid-call the media already being sent", async () => {
915
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
916
+ alice.mesh.setRoster(["did:alice"])
917
+ const mic = track("audio")
918
+ await alice.mesh.replaceTrack("audio", mic)
919
+
920
+ // Bob arrives after Alice's mic was already on.
921
+ alice.mesh.setRoster(["did:alice", "did:bob"])
922
+ await settle()
923
+
924
+ // Attached to the section created with the connection, rather than added as a new one.
925
+ expect(alice.connections[0].addedTracks).toEqual([])
926
+ expect(alice.connections[0].getSenders().find((sender) => sender.track)?.track).toBe(mic)
927
+ })
928
+
929
+ it("attaches the tracks handed to join, one per kind", async () => {
930
+ const mic = track("audio")
931
+ const camera = track("video")
932
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { localStream: stream(mic, camera) })
933
+ alice.mesh.setRoster(["did:alice", "did:bob"])
934
+ await settle()
935
+
936
+ expect(alice.connections[0].addedTracks).toEqual([])
937
+ expect(alice.connections[0].getSenders().map((sender) => sender.track)).toEqual([mic, camera])
938
+ })
939
+
940
+ it("stops negotiating once left", async () => {
941
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
942
+ alice.mesh.setRoster(["did:alice", "did:bob"])
943
+ await settle()
944
+
945
+ await alice.mesh.leave()
946
+ expect(alice.connections[0].closed).toBe(true)
947
+
948
+ bus.deliver("did:bob", {
949
+ v: CALL_PROTOCOL_VERSION,
950
+ call: CALL_ID,
951
+ to: "did:alice",
952
+ kind: "description",
953
+ description: { type: "offer", sdp: "late" },
954
+ })
955
+ await settle()
956
+
957
+ expect(alice.connections).toHaveLength(1)
958
+ expect(alice.errors).toEqual([])
959
+ })
960
+
961
+ it("ignores setRoster after leave()", async () => {
962
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
963
+ await alice.mesh.leave()
964
+
965
+ alice.mesh.setRoster(["did:alice", "did:bob"])
966
+ expect(alice.connections).toHaveLength(0)
967
+ })
968
+
969
+ it("destroy() clears all state", async () => {
970
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
971
+ alice.mesh.setRoster(["did:alice", "did:bob"])
972
+ await settle()
973
+
974
+ let eventFired = false
975
+ alice.mesh.on("error", () => { eventFired = true })
976
+
977
+ await alice.mesh.destroy()
978
+ expect(alice.connections[0].closed).toBe(true)
979
+ expect(alice.mesh.getParticipants()).toEqual([])
980
+
981
+ bus.deliver("did:bob", {
982
+ v: CALL_PROTOCOL_VERSION,
983
+ call: CALL_ID,
984
+ kind: "description",
985
+ description: { type: "offer", sdp: "late" },
986
+ })
987
+ await settle()
988
+ expect(eventFired).toBe(false)
989
+ })
990
+
991
+ it("forwards ICE candidates between peers", async () => {
992
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
993
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
994
+
995
+ alice.mesh.setRoster(["did:alice", "did:bob"])
996
+ bob.mesh.setRoster(["did:alice", "did:bob"])
997
+ await settleAll()
998
+
999
+ alice.connections[0].emitCandidate({ candidate: "candidate:1" })
1000
+ await settle()
1001
+
1002
+ expect(bob.connections[0].candidates).toEqual([{ candidate: "candidate:1" }])
1003
+ expect(bob.errors).toEqual([])
1004
+ })
1005
+
1006
+ it("handles three peers with correct connection count", async () => {
1007
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1008
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
1009
+ const carol = await makeMesh(bus, "did:carol", CALL_ID)
1010
+
1011
+ const roster = ["did:alice", "did:bob", "did:carol"]
1012
+ alice.mesh.setRoster(roster)
1013
+ bob.mesh.setRoster(roster)
1014
+ carol.mesh.setRoster(roster)
1015
+ await settleAll()
1016
+
1017
+ // Each peer connects to the two others, and every pair settles.
1018
+ for (const peer of [alice, bob, carol]) {
1019
+ expect(peer.connections).toHaveLength(2)
1020
+ expect(peer.connections.every((pc) => pc.signalingState === "stable")).toBe(true)
1021
+ expect(peer.errors).toEqual([])
1022
+ }
1023
+ expect(alice.mesh.getParticipants()).toHaveLength(2)
1024
+ })
1025
+
1026
+ it("reports each pair's connection state", async () => {
1027
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1028
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1029
+ await settle()
1030
+
1031
+ alice.live().setConnectionState("connecting")
1032
+ alice.live().setConnectionState("connected")
1033
+
1034
+ expect(alice.states).toEqual([["did:bob", "connecting"], ["did:bob", "connected"]])
1035
+ expect(alice.mesh.peerStates().get("did:bob")).toBe("connected")
1036
+ })
1037
+ })
1038
+
1039
+ // ── Events ──────────────────────────────────────────────────────────
1040
+
1041
+ describe("MeshManager events", () => {
1042
+ let bus: InMemoryBus
1043
+
1044
+ beforeEach(() => {
1045
+ bus = new InMemoryBus()
1046
+ })
1047
+
1048
+ it("on() registers and off() removes callbacks", async () => {
1049
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1050
+
1051
+ let calls = 0
1052
+ const cb = () => calls++
1053
+ alice.mesh.on("participant-joined", cb)
1054
+
1055
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1056
+ expect(calls).toBe(1)
1057
+
1058
+ alice.mesh.off("participant-joined", cb)
1059
+ alice.mesh.setRoster(["did:alice", "did:bob", "did:carol"])
1060
+ expect(calls).toBe(1)
1061
+ })
1062
+
1063
+ it("off() with no callback removes all listeners for that event", async () => {
1064
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1065
+ alice.mesh.off("participant-joined")
1066
+
1067
+ let calls = 0
1068
+ alice.mesh.on("participant-joined", () => calls++)
1069
+ alice.mesh.on("participant-joined", () => calls++)
1070
+
1071
+ alice.mesh.off("participant-joined")
1072
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1073
+ expect(calls).toBe(0)
1074
+ })
1075
+
1076
+ it("event handler errors do not break other handlers", async () => {
1077
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1078
+
1079
+ let secondCalled = false
1080
+ const consoleError = jest.spyOn(console, "error").mockImplementation()
1081
+
1082
+ alice.mesh.on("participant-joined", () => { throw new Error("boom") })
1083
+ alice.mesh.on("participant-joined", () => { secondCalled = true })
1084
+
1085
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1086
+ expect(secondCalled).toBe(true)
1087
+ expect(consoleError).toHaveBeenCalled()
1088
+
1089
+ consoleError.mockRestore()
1090
+ })
1091
+ })
1092
+
1093
+ // ── Data ────────────────────────────────────────────────────────────
1094
+
1095
+ describe("data over signalling", () => {
1096
+ let bus: InMemoryBus
1097
+
1098
+ beforeEach(() => {
1099
+ bus = new InMemoryBus()
1100
+ })
1101
+
1102
+ async function pair(callId = CALL_ID) {
1103
+ const alice = await makeMesh(bus, "did:alice", callId)
1104
+ const bob = await makeMesh(bus, "did:bob", callId)
1105
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1106
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1107
+ await settle()
1108
+ return { alice, bob }
1109
+ }
1110
+
1111
+ it("sends data via the signalling channel", async () => {
1112
+ const { alice, bob } = await pair()
1113
+
1114
+ const received: { label: string; data: string; binary: boolean; sender: string }[] = []
1115
+ bob.mesh.subscribeDataChannel((msg) => {
1116
+ received.push({ label: msg.channelLabel, data: msg.data, binary: msg.binary, sender: msg.senderDid })
1117
+ })
1118
+
1119
+ alice.mesh.sendData("chat", "hello world", false)
1120
+ await settle()
1121
+
1122
+ expect(received).toEqual([{ label: "chat", data: "hello world", binary: false, sender: "did:alice" }])
1123
+ // Data goes to everyone, not to one peer.
1124
+ expect(alice.sent[alice.sent.length - 1]).toMatchObject({ kind: "data", to: "*" })
1125
+ })
1126
+
1127
+ it("sends binary data with binary flag", async () => {
1128
+ const { alice, bob } = await pair()
1129
+
1130
+ const received: { binary: boolean }[] = []
1131
+ bob.mesh.subscribeDataChannel((msg) => received.push({ binary: msg.binary }))
1132
+
1133
+ alice.mesh.sendData("file", "base64payload", true)
1134
+ await settle()
1135
+
1136
+ expect(received).toEqual([{ binary: true }])
1137
+ })
1138
+
1139
+ it("unsubscribes data listener on returned function call", async () => {
1140
+ const { alice, bob } = await pair()
1141
+
1142
+ let count = 0
1143
+ const unsub = bob.mesh.subscribeDataChannel(() => count++)
1144
+
1145
+ alice.mesh.sendData("x", "1")
1146
+ await settle()
1147
+ expect(count).toBe(1)
1148
+
1149
+ unsub()
1150
+ alice.mesh.sendData("x", "2")
1151
+ await settle()
1152
+ expect(count).toBe(1)
1153
+ })
1154
+
1155
+ it("populates roomName on data messages from callId", async () => {
1156
+ const { alice, bob } = await pair("my-room")
1157
+
1158
+ let roomName = ""
1159
+ bob.mesh.subscribeDataChannel((msg) => { roomName = msg.roomName })
1160
+
1161
+ alice.mesh.sendData("x", "y")
1162
+ await settle()
1163
+
1164
+ expect(roomName).toBe("my-room")
1165
+ })
1166
+
1167
+ it("drops data from an agent the roster does not list, rather than holding it", async () => {
1168
+ // Data is not signalling: there is nothing to replay it into later,
1169
+ // and holding it would buffer strangers' traffic.
1170
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1171
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
1172
+ const received: string[] = []
1173
+ bob.mesh.subscribeDataChannel((msg) => received.push(msg.data))
1174
+
1175
+ alice.mesh.sendData("chat", "before the roster")
1176
+ await settle()
1177
+ expect(received).toEqual([])
1178
+
1179
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1180
+ await settle()
1181
+ expect(received).toEqual([])
1182
+
1183
+ alice.mesh.sendData("chat", "after")
1184
+ await settle()
1185
+ expect(received).toEqual(["after"])
1186
+ })
1187
+ })
1188
+
1189
+ // ── An unordered transport ──────────────────────────────────────────
1190
+
1191
+ describe("an unordered transport", () => {
1192
+ /**
1193
+ * Telepresence dispatches sends concurrently and confirms only that the
1194
+ * executor took a message, so a candidate overtaking the description it
1195
+ * belongs to is the ordinary case, not a race.
1196
+ */
1197
+ let bus: InMemoryBus
1198
+
1199
+ beforeEach(() => {
1200
+ bus = new InMemoryBus()
1201
+ })
1202
+
1203
+ const offerFrom = (from: string) => ({
1204
+ v: CALL_PROTOCOL_VERSION,
1205
+ call: CALL_ID,
1206
+ to: "did:alice",
1207
+ kind: "description" as const,
1208
+ description: { type: "offer" as const, sdp: `${from}-offer` },
1209
+ })
1210
+
1211
+ const candidateFrom = (candidate: string) => ({
1212
+ v: CALL_PROTOCOL_VERSION,
1213
+ call: CALL_ID,
1214
+ to: "did:alice",
1215
+ kind: "ice" as const,
1216
+ candidate: { candidate },
1217
+ })
1218
+
1219
+ it("holds candidates that arrive before the description, and applies them after", async () => {
1220
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1221
+ alice.mesh.setRoster(["did:alice", "did:aaron"])
1222
+ await settle()
1223
+
1224
+ bus.deliver("did:aaron", candidateFrom("a"))
1225
+ bus.deliver("did:aaron", candidateFrom("b"))
1226
+ bus.deliver("did:aaron", candidateFrom("c"))
1227
+ await settle()
1228
+
1229
+ expect(alice.live().candidates).toEqual([])
1230
+ expect(alice.errors).toEqual([])
1231
+
1232
+ bus.deliver("did:aaron", offerFrom("did:aaron"))
1233
+ await settle()
1234
+
1235
+ // All three, in the order they were sent.
1236
+ expect(alice.live().candidates.map((c) => c.candidate)).toEqual(["a", "b", "c"])
1237
+ expect(alice.errors).toEqual([])
1238
+ })
1239
+
1240
+ it("does not hold candidates without bound, for a peer whose description never comes", async () => {
1241
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1242
+ alice.mesh.setRoster(["did:alice", "did:aaron"])
1243
+ await settle()
1244
+
1245
+ for (let n = 0; n < 500; n += 1) bus.deliver("did:aaron", candidateFrom(`c${n}`))
1246
+ await settle()
1247
+ bus.deliver("did:aaron", offerFrom("did:aaron"))
1248
+ await settle()
1249
+
1250
+ // Bounded, and it kept the earliest — host candidates come first.
1251
+ expect(alice.live().candidates.length).toBeLessThanOrEqual(64)
1252
+ expect(alice.live().candidates[0]?.candidate).toBe("c0")
1253
+ })
1254
+
1255
+ it("applies signalling one message at a time", async () => {
1256
+ // Two descriptions in one tick used to run concurrently and read the
1257
+ // collision state at a moment that was already stale.
1258
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1259
+ alice.mesh.setRoster(["did:alice", "did:aaron"])
1260
+ await settle()
1261
+
1262
+ bus.deliver("did:aaron", offerFrom("first"))
1263
+ bus.deliver("did:aaron", {
1264
+ ...offerFrom("second"),
1265
+ description: { type: "offer" as const, sdp: "second-offer" },
1266
+ })
1267
+ await settle()
1268
+ await settle()
1269
+
1270
+ expect(alice.live().remoteDescription?.sdp).toBe("second-offer")
1271
+ expect(alice.errors).toEqual([])
1272
+ })
1273
+ })
1274
+
1275
+ // ── Recovery ────────────────────────────────────────────────────────
1276
+
1277
+ describe("recovering a pair that did not connect", () => {
1278
+ let bus: InMemoryBus
1279
+
1280
+ beforeEach(() => {
1281
+ bus = new InMemoryBus()
1282
+ })
1283
+
1284
+ it("resends a description that was lost, rather than rebuilding the connection", async () => {
1285
+ // Alice is impolite, so on a collision she ignores Bob's offer and
1286
+ // expects her own to win — and hers is the one the transport drops.
1287
+ const clock = makeClock()
1288
+ let losing = true
1289
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, {
1290
+ now: clock.now,
1291
+ drop: (payload) => losing && (payload as { kind?: string }).kind === "description",
1292
+ })
1293
+ const bob = await makeMesh(bus, "did:bob", CALL_ID, { now: clock.now })
1294
+
1295
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1296
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1297
+ await settle()
1298
+ await settle()
1299
+ await settle()
1300
+
1301
+ expect(alice.live().signalingState).toBe("have-local-offer")
1302
+ expect(alice.live().remoteDescription).toBeNull()
1303
+
1304
+ losing = false
1305
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
1306
+ alice.mesh.tick()
1307
+ await settle()
1308
+ await settle()
1309
+ await settle()
1310
+
1311
+ expect(alice.recoveries.map((r) => r.rung)).toEqual(["resend"])
1312
+ expect(alice.recoveries[0]).toEqual({ peerId: "did:bob", rung: "resend", attempts: 1 })
1313
+ expect(alice.connections).toHaveLength(1)
1314
+ expect(bob.live().remoteDescription?.type).toBe("offer")
1315
+ expect(alice.live().signalingState).toBe("stable")
1316
+ expect(alice.errors).toEqual([])
1317
+ expect(bob.errors).toEqual([])
1318
+ })
1319
+
1320
+ it("resends the answer when that is the half that was lost", async () => {
1321
+ // The answerer believes it is done while the offerer waits: a rung
1322
+ // gated on "no remote description" would skip the cheap fix.
1323
+ const clock = makeClock()
1324
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1325
+ // Bob answers and his answer never arrives. He is polite: doubled deadline.
1326
+ const bob = await makeMesh(bus, "did:bob", CALL_ID, {
1327
+ now: clock.now,
1328
+ drop: (payload) => (payload as { kind?: string }).kind === "description",
1329
+ })
1330
+
1331
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1332
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1333
+ await settle()
1334
+ await settle()
1335
+ await settle()
1336
+
1337
+ expect(bob.live().remoteDescription?.type).toBe("offer")
1338
+ expect(bob.live().localDescription?.type).toBe("answer")
1339
+ expect(alice.live().remoteDescription).toBeNull()
1340
+
1341
+ clock.advance(HANDSHAKE_GRACE_MS * 2 + 1)
1342
+ bob.mesh.tick()
1343
+ await settle()
1344
+
1345
+ expect(bob.recoveries.map((r) => r.rung)).toEqual(["resend"])
1346
+ expect(bob.connections).toHaveLength(1)
1347
+ const resent = bob.sent.filter((payload) => (payload as { kind?: string }).kind === "description")
1348
+ // Bob's own opening offer (ignored by impolite Alice), his answer, and the same answer again.
1349
+ const [answer, again] = resent.slice(-2).map((payload) => (payload as { description: RTCSessionDescriptionInit }).description)
1350
+ expect(answer.type).toBe("answer")
1351
+ expect(again).toEqual(answer)
1352
+ })
1353
+
1354
+ it("holds the answerer's own offer until the pair connects", async () => {
1355
+ // Bob answers Alice and the answer is lost. An offer from Bob now would
1356
+ // reach Alice with hers still out: glare, a fresh negotiation, and both
1357
+ // sides taking the same DTLS role.
1358
+ const bobLoses = { answer: true }
1359
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1360
+ const bob = await makeMesh(bus, "did:bob", CALL_ID, {
1361
+ drop: (payload) =>
1362
+ bobLoses.answer && (payload as { description?: { type?: string } }).description?.type === "answer",
1363
+ })
1364
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1365
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1366
+ // As in a browser: Bob's own sections are not in Alice's offer, so his
1367
+ // answer leaves them to negotiate, and `negotiationneeded` fires while
1368
+ // the answer is still being set.
1369
+ const pc = bob.live() as unknown as {
1370
+ setLocalDescription(d?: RTCSessionDescriptionInit): Promise<void>
1371
+ localDescription: RTCSessionDescriptionInit | null
1372
+ queueNegotiation(): void
1373
+ }
1374
+ const setLocal = pc.setLocalDescription.bind(pc)
1375
+ pc.setLocalDescription = async (d) => {
1376
+ await setLocal(d)
1377
+ if (pc.localDescription?.type === "answer") pc.queueNegotiation()
1378
+ }
1379
+ await settleAll()
1380
+ const lastFromBob = () =>
1381
+ bob.sent
1382
+ .map((p) => (p as { description?: { type?: string } }).description?.type)
1383
+ .filter(Boolean)
1384
+ .slice(-1)[0]
1385
+ expect(bob.live().localDescription?.type).toBe("answer")
1386
+ expect(lastFromBob()).toBe("answer")
1387
+ expect(alice.live().signalingState).toBe("have-local-offer")
1388
+
1389
+ // Connected: Alice must have applied the answer, so the offer goes.
1390
+ bob.live().setConnectionState("connected")
1391
+ await settleAll()
1392
+ expect(lastFromBob()).toBe("offer")
1393
+ expect(bob.errors).toEqual([])
1394
+ })
1395
+
1396
+ it("resends a description once, then escalates rather than repeating it", async () => {
1397
+ const clock = makeClock()
1398
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, {
1399
+ now: clock.now,
1400
+ drop: (payload) => (payload as { kind?: string }).kind === "description",
1401
+ })
1402
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1403
+ await settle()
1404
+ await settle()
1405
+
1406
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
1407
+ alice.mesh.tick()
1408
+ await settle()
1409
+ clock.advance(RECOVERY_INTERVAL_MS + 1)
1410
+ alice.mesh.tick()
1411
+ await settle()
1412
+ await settle()
1413
+
1414
+ expect(alice.recoveries.map((r) => r.rung)).toEqual(["resend", "rebuild"])
1415
+ })
1416
+
1417
+ it("restarts ICE when a connected pair fails, before throwing anything away", async () => {
1418
+ const clock = makeClock()
1419
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1420
+ const bob = await makeMesh(bus, "did:bob", CALL_ID, { now: clock.now })
1421
+
1422
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1423
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1424
+ await settle()
1425
+ await settle()
1426
+ await settle()
1427
+
1428
+ alice.live().setConnectionState("connected")
1429
+ alice.live().setConnectionState("failed")
1430
+ await settle()
1431
+
1432
+ clock.advance(RECOVERY_INTERVAL_MS + 1)
1433
+ alice.mesh.tick()
1434
+ await settle()
1435
+
1436
+ // The connection, its transceivers and its DTLS session all survive.
1437
+ expect(alice.live().restartIceCalls).toBe(1)
1438
+ expect(alice.recoveries.map((r) => r.rung)).toEqual(["ice-restart"])
1439
+ expect(alice.connections).toHaveLength(1)
1440
+ })
1441
+
1442
+ it("gives a disconnected pair a shorter grace, since it often comes back by itself", async () => {
1443
+ const clock = makeClock()
1444
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1445
+ const bob = await makeMesh(bus, "did:bob", CALL_ID, { now: clock.now })
1446
+
1447
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1448
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1449
+ await settle()
1450
+ await settle()
1451
+ await settle()
1452
+
1453
+ alice.live().setConnectionState("connected")
1454
+ alice.live().setConnectionState("disconnected")
1455
+
1456
+ clock.advance(DISCONNECT_GRACE_MS - 1)
1457
+ alice.mesh.tick()
1458
+ expect(alice.live().restartIceCalls).toBe(0)
1459
+
1460
+ clock.advance(2)
1461
+ alice.mesh.tick()
1462
+ await settle()
1463
+ expect(alice.live().restartIceCalls).toBe(1)
1464
+ })
1465
+
1466
+ it("does nothing for a disconnected pair that comes back by itself", async () => {
1467
+ const clock = makeClock()
1468
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1469
+ // A negotiated pair, so no offer of Alice's is left pending.
1470
+ const bob = await makeMesh(bus, "did:bob", CALL_ID, { now: clock.now })
1471
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1472
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1473
+ await settleAll()
1474
+ expect(alice.live().signalingState).toBe("stable")
1475
+
1476
+ alice.live().setConnectionState("connected")
1477
+ alice.live().setConnectionState("disconnected")
1478
+ clock.advance(DISCONNECT_GRACE_MS - 1)
1479
+ alice.live().setConnectionState("connected")
1480
+
1481
+ clock.advance(DISCONNECT_GRACE_MS * 4)
1482
+ alice.mesh.tick()
1483
+ await settle()
1484
+ expect(alice.recoveries).toEqual([])
1485
+ })
1486
+
1487
+ it("rebuilds the pair, and says so, once the cheaper rungs have not worked", async () => {
1488
+ const clock = makeClock()
1489
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1490
+ const bob = await makeMesh(bus, "did:bob", CALL_ID, { now: clock.now })
1491
+
1492
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1493
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1494
+ await settle()
1495
+ await settle()
1496
+ await settle()
1497
+
1498
+ // Connected, so nothing to resend — and the host has no `restartIce`.
1499
+ alice.live().setConnectionState("connected")
1500
+ alice.live().setConnectionState("failed")
1501
+ ;(alice.live() as { restartIce?: unknown }).restartIce = undefined
1502
+
1503
+ const streamBefore = alice.mesh.getParticipants()[0].stream
1504
+ clock.advance(RECOVERY_INTERVAL_MS + 1)
1505
+ alice.mesh.tick()
1506
+ await settle()
1507
+ await settle()
1508
+
1509
+ expect(alice.recoveries.map((r) => r.rung)).toEqual(["rebuild"])
1510
+ expect(alice.connections).toHaveLength(2)
1511
+ expect(alice.connections[0].closed).toBe(true)
1512
+ // The peer is told, or it would hold a connection to a session that is gone.
1513
+ expect(kinds(alice.sent)).toContain("reset")
1514
+ expect(bob.connections).toHaveLength(2)
1515
+ // A consumer holding the old stream object would render a dead stream.
1516
+ const streamAfter = alice.mesh.getParticipants()[0].stream
1517
+ expect(streamAfter).not.toBe(streamBefore)
1518
+ expect(alice.updates[alice.updates.length - 1].stream).toBe(streamAfter)
1519
+ })
1520
+
1521
+ it("answers a reset without sending one back", async () => {
1522
+ // Two peers answering resets with resets is a loop with no floor.
1523
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1524
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1525
+ await settle()
1526
+
1527
+ bus.deliver("did:bob", {
1528
+ v: CALL_PROTOCOL_VERSION,
1529
+ call: CALL_ID,
1530
+ to: "did:alice",
1531
+ kind: "reset",
1532
+ })
1533
+ await settle()
1534
+ await settle()
1535
+
1536
+ expect(alice.connections).toHaveLength(2)
1537
+ expect(alice.connections[0].closed).toBe(true)
1538
+ expect(kinds(alice.sent)).not.toContain("reset")
1539
+ expect(alice.recoveries.map((r) => r.rung)).toEqual(["rebuild"])
1540
+ })
1541
+
1542
+ it("stops repairing after a few attempts, so a spinner is not a promise", async () => {
1543
+ const clock = makeClock()
1544
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1545
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1546
+ await settle()
1547
+
1548
+ for (let n = 0; n < MAX_RECOVERY_ATTEMPTS + 3; n += 1) {
1549
+ clock.advance(HANDSHAKE_GRACE_MS + RECOVERY_INTERVAL_MS + 1)
1550
+ alice.mesh.tick()
1551
+ await settle()
1552
+ }
1553
+
1554
+ expect(alice.recoveries.length).toBe(MAX_RECOVERY_ATTEMPTS)
1555
+ expect(alice.recoveries.map((r) => r.attempts)).toEqual(
1556
+ Array.from({ length: MAX_RECOVERY_ATTEMPTS }, (_, i) => i + 1),
1557
+ )
1558
+ })
1559
+
1560
+ it("lets the impolite peer repair first, and the polite one wait", async () => {
1561
+ const clock = makeClock()
1562
+ // Alice is impolite for this pair; Bob is polite. Neither ever hears from the other.
1563
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now, drop: () => true })
1564
+ const bob = await makeMesh(bus, "did:bob", CALL_ID, { now: clock.now, drop: () => true })
1565
+
1566
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1567
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1568
+ await settle()
1569
+ await settle()
1570
+
1571
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
1572
+ alice.mesh.tick()
1573
+ bob.mesh.tick()
1574
+ await settle()
1575
+
1576
+ expect(alice.recoveries).toHaveLength(1)
1577
+ expect(bob.recoveries).toHaveLength(0)
1578
+
1579
+ // The polite side covers an impolite side with no slot for this pair at all.
1580
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
1581
+ bob.mesh.tick()
1582
+ await settle()
1583
+ expect(bob.recoveries).toHaveLength(1)
1584
+ })
1585
+
1586
+ it("waits while a send is still outstanding, rather than piling onto a stalled transport", async () => {
1587
+ // An offer not yet delivered and an offer lost look the same; the
1588
+ // first broadcast on a fresh neighbourhood has taken eighteen seconds.
1589
+ const clock = makeClock()
1590
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now, holdResults: true })
1591
+
1592
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1593
+ await settle()
1594
+ const duringHandshake = alice.sent.length
1595
+ expect(kinds(alice.sent)).toContain("description")
1596
+ expect(alice.results.held).toBe(duringHandshake)
1597
+
1598
+ clock.advance(HANDSHAKE_GRACE_MS * 4)
1599
+ alice.mesh.tick()
1600
+ await settle()
1601
+
1602
+ expect(alice.sent).toHaveLength(duringHandshake)
1603
+ expect(alice.recoveries).toEqual([])
1604
+
1605
+ // The transport reports, so now the silence means something.
1606
+ alice.results.release()
1607
+ await settle()
1608
+ alice.mesh.tick()
1609
+ await settle()
1610
+
1611
+ expect(alice.sent.length).toBeGreaterThan(duringHandshake)
1612
+ expect(alice.recoveries.map((r) => r.rung)).toEqual(["resend"])
1613
+ })
1614
+
1615
+ it("counts a failed publish as accounted for, so a rejected send does not hold repair forever", async () => {
1616
+ const clock = makeClock()
1617
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now, holdResults: true })
1618
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1619
+ await settle()
1620
+
1621
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
1622
+ alice.results.release({ ok: false, ms: 30_000 })
1623
+ await settle()
1624
+
1625
+ expect(alice.recoveries.map((r) => r.rung)).toEqual(["resend"])
1626
+ })
1627
+
1628
+ it("repairs on a transport that reports nothing, as though every send landed", async () => {
1629
+ // A count that went up and never came down would hold the ladder
1630
+ // closed for the life of the call.
1631
+ const clock = makeClock()
1632
+ let published = 0
1633
+ const channel: SignallingChannel = {
1634
+ publish: () => { published += 1 },
1635
+ onMessage: () => () => {},
1636
+ }
1637
+ const mesh = new MeshManager({
1638
+ channel,
1639
+ callId: CALL_ID,
1640
+ selfId: "did:alice",
1641
+ now: clock.now,
1642
+ sweepMs: 0,
1643
+ createPeerConnection: () => new FakePeerConnection() as unknown as RTCPeerConnection,
1644
+ })
1645
+ meshes.push(mesh)
1646
+ const rungs: RecoveryRung[] = []
1647
+ mesh.on("peer-recovery", (_peerId: string, attempt: { rung: RecoveryRung }) => rungs.push(attempt.rung))
1648
+ await mesh.join(stream())
1649
+
1650
+ mesh.setRoster(["did:alice", "did:bob"])
1651
+ await settle()
1652
+ const before = published
1653
+
1654
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
1655
+ mesh.tick()
1656
+ await settle()
1657
+
1658
+ expect(rungs).toEqual(["resend"])
1659
+ expect(published).toBe(before + 1)
1660
+ })
1661
+
1662
+ it("forgets a pair's failures once it connects", async () => {
1663
+ // The budget bounds one failure, not a session.
1664
+ const clock = makeClock()
1665
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1666
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1667
+ await settle()
1668
+
1669
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
1670
+ alice.mesh.tick()
1671
+ await settle()
1672
+ expect(alice.recoveries).toHaveLength(1)
1673
+
1674
+ alice.live().setConnectionState("connected")
1675
+ alice.live().setConnectionState("failed")
1676
+
1677
+ for (let n = 0; n < MAX_RECOVERY_ATTEMPTS; n += 1) {
1678
+ clock.advance(RECOVERY_INTERVAL_MS + 1)
1679
+ alice.mesh.tick()
1680
+ await settle()
1681
+ }
1682
+
1683
+ expect(alice.recoveries).toHaveLength(1 + MAX_RECOVERY_ATTEMPTS)
1684
+ })
1685
+
1686
+ it("reconnects one peer on request, whatever the connection claims to be", async () => {
1687
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1688
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
1689
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1690
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1691
+ await settle()
1692
+ await settle()
1693
+ await settle()
1694
+
1695
+ // Deliberately healthy: the person watching judges better than `connectionState`.
1696
+ alice.live().setConnectionState("connected")
1697
+ alice.mesh.reconnect("did:bob")
1698
+ await settle()
1699
+ await settle()
1700
+
1701
+ expect(alice.connections).toHaveLength(2)
1702
+ expect(alice.connections[0].closed).toBe(true)
1703
+ expect(kinds(alice.sent)).toContain("reset")
1704
+ expect(bob.connections).toHaveLength(2)
1705
+ expect(alice.recoveries).toEqual([{ peerId: "did:bob", rung: "rebuild", attempts: 1 }])
1706
+ })
1707
+
1708
+ it("resets the automatic budget when reconnecting by hand", async () => {
1709
+ const clock = makeClock()
1710
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1711
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1712
+ await settle()
1713
+
1714
+ for (let n = 0; n < MAX_RECOVERY_ATTEMPTS + 1; n += 1) {
1715
+ clock.advance(HANDSHAKE_GRACE_MS + RECOVERY_INTERVAL_MS + 1)
1716
+ alice.mesh.tick()
1717
+ await settle()
1718
+ }
1719
+ expect(alice.recoveries).toHaveLength(MAX_RECOVERY_ATTEMPTS)
1720
+
1721
+ alice.mesh.reconnect("did:bob")
1722
+ await settle()
1723
+ clock.advance(HANDSHAKE_GRACE_MS + RECOVERY_INTERVAL_MS + 1)
1724
+ alice.mesh.tick()
1725
+ await settle()
1726
+
1727
+ expect(alice.recoveries.slice(MAX_RECOVERY_ATTEMPTS).map((r) => r.attempts)).toEqual([1, 2])
1728
+ })
1729
+
1730
+ it("does nothing when asked to reconnect someone who is not in the call", async () => {
1731
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
1732
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1733
+ await settle()
1734
+
1735
+ alice.mesh.reconnect("did:nobody")
1736
+ await settle()
1737
+
1738
+ expect(alice.connections).toHaveLength(1)
1739
+ expect(kinds(alice.sent)).not.toContain("reset")
1740
+ })
1741
+
1742
+ it("repairs one pair per sweep", async () => {
1743
+ // A network that just came back has every pair due at once, and a
1744
+ // burst of offers is what made them fail.
1745
+ const clock = makeClock()
1746
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1747
+ alice.mesh.setRoster(["did:alice", "did:bob", "did:carol", "did:dave"])
1748
+ await settle()
1749
+
1750
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
1751
+ alice.mesh.tick()
1752
+ await settle()
1753
+
1754
+ expect(alice.recoveries).toHaveLength(1)
1755
+ })
1756
+
1757
+ it("spaces repairs by REPAIR_SPACING_MS, whatever asks for them", async () => {
1758
+ // A settled send calls `tick`, and a repair publishes: without a
1759
+ // floor the two chase each other through every pair in the call.
1760
+ const clock = makeClock()
1761
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1762
+ alice.mesh.setRoster(["did:alice", "did:bob", "did:carol"])
1763
+ await settle()
1764
+
1765
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
1766
+ alice.mesh.tick()
1767
+ await settle()
1768
+ expect(alice.recoveries).toHaveLength(1)
1769
+
1770
+ alice.mesh.tick()
1771
+ clock.advance(REPAIR_SPACING_MS - 1)
1772
+ alice.mesh.tick()
1773
+ await settle()
1774
+ expect(alice.recoveries).toHaveLength(1)
1775
+
1776
+ clock.advance(1)
1777
+ alice.mesh.tick()
1778
+ await settle()
1779
+ expect(alice.recoveries.map((r) => r.peerId).sort()).toEqual(["did:bob", "did:carol"])
1780
+ })
1781
+
1782
+ it("acts on a failed connection at once, without waiting for the sweep", async () => {
1783
+ const clock = makeClock()
1784
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, { now: clock.now })
1785
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1786
+ await settle()
1787
+
1788
+ clock.advance(RECOVERY_INTERVAL_MS + 1)
1789
+ alice.live().setConnectionState("failed")
1790
+ await settle()
1791
+
1792
+ expect(alice.recoveries).toHaveLength(1)
1793
+ })
1794
+ })
1795
+
1796
+ describe("a connected pair whose renegotiation went unanswered", () => {
1797
+ let bus: InMemoryBus
1798
+
1799
+ beforeEach(() => {
1800
+ bus = new InMemoryBus()
1801
+ })
1802
+
1803
+ /** Alice and Bob, negotiated and connected, with Bob's descriptions and Alice's answers droppable from here on. */
1804
+ async function connectedPair() {
1805
+ const clock = makeClock()
1806
+ const bobLoses = { description: false }
1807
+ const aliceLoses = { answer: false }
1808
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, {
1809
+ now: clock.now,
1810
+ drop: (payload) =>
1811
+ aliceLoses.answer &&
1812
+ (payload as { description?: { type?: string } }).description?.type === "answer",
1813
+ })
1814
+ const bob = await makeMesh(bus, "did:bob", CALL_ID, {
1815
+ now: clock.now,
1816
+ drop: (payload) => bobLoses.description && (payload as { kind?: string }).kind === "description",
1817
+ })
1818
+ alice.mesh.setRoster(["did:alice", "did:bob"])
1819
+ bob.mesh.setRoster(["did:alice", "did:bob"])
1820
+ for (let i = 0; i < 4; i += 1) await settle()
1821
+ alice.live().setConnectionState("connected")
1822
+ bob.live().setConnectionState("connected")
1823
+ expect(alice.live().signalingState).toBe("stable")
1824
+ expect(bob.live().signalingState).toBe("stable")
1825
+ return { clock, alice, bob, bobLoses, aliceLoses }
1826
+ }
1827
+
1828
+ /** The descriptions a mesh has published, newest last. */
1829
+ const descriptions = (sent: unknown[]) =>
1830
+ sent.filter((payload) => (payload as { kind?: string }).kind === "description")
1831
+
1832
+ it("repairs a renegotiation reordered behind the answer it follows", async () => {
1833
+ // The case T20 found, pinned without timing: Bob answers Alice's
1834
+ // offer, then offers his own media. His offer reaches Alice first,
1835
+ // while hers is still out; Alice is impolite, so she reads it as glare
1836
+ // and ignores it. Then the answer lands and the pair looks settled.
1837
+ const { clock, alice, bob, bobLoses } = await connectedPair()
1838
+ bobLoses.description = true
1839
+
1840
+ alice.live().restartIce()
1841
+ await settleAll()
1842
+ expect(bob.live().signalingState).toBe("stable")
1843
+ bob.live().restartIce()
1844
+ await settleAll()
1845
+ const [answer, offer] = descriptions(bob.sent).slice(-2)
1846
+ expect((answer as { description: { type: string } }).description.type).toBe("answer")
1847
+ expect((offer as { description: { type: string } }).description.type).toBe("offer")
1848
+
1849
+ bus.deliverTo("did:alice", "did:bob", offer)
1850
+ await settleAll()
1851
+ bus.deliverTo("did:alice", "did:bob", answer)
1852
+ await settleAll()
1853
+ expect(alice.live().signalingState).toBe("stable")
1854
+ expect(bob.live().signalingState).toBe("have-local-offer")
1855
+
1856
+ bobLoses.description = false
1857
+ clock.advance(RECOVERY_INTERVAL_MS)
1858
+ bob.mesh.tick()
1859
+ await settleAll()
1860
+
1861
+ expect(bob.recoveries.map((r) => r.rung)).toEqual(["resend"])
1862
+ expect(bob.live().signalingState).toBe("stable")
1863
+ expect(alice.live().remoteDescription?.type).toBe("offer")
1864
+ expect(alice.errors).toEqual([])
1865
+ expect(bob.errors).toEqual([])
1866
+ })
1867
+
1868
+ it("drops a late duplicate answer instead of reporting an error", async () => {
1869
+ // Slow rather than lost: the resend fires, the peer answers both
1870
+ // copies, and the second answer arrives with nothing left to settle.
1871
+ const { clock, alice, bob, aliceLoses } = await connectedPair()
1872
+
1873
+ aliceLoses.answer = true
1874
+ bob.live().restartIce()
1875
+ await settleAll()
1876
+ const late = descriptions(alice.sent).slice(-1)[0]
1877
+ expect(bob.live().signalingState).toBe("have-local-offer")
1878
+
1879
+ aliceLoses.answer = false
1880
+ clock.advance(RECOVERY_INTERVAL_MS)
1881
+ bob.mesh.tick()
1882
+ await settleAll()
1883
+ expect(bob.live().signalingState).toBe("stable")
1884
+
1885
+ bus.deliverTo("did:bob", "did:alice", late)
1886
+ await settleAll()
1887
+
1888
+ expect(bob.errors).toEqual([])
1889
+ expect(bob.live().signalingState).toBe("stable")
1890
+ })
1891
+
1892
+ it("drops an answer to an offer the connection has since replaced", async () => {
1893
+ // A late copy of the answer to Bob's last offer reaches him while his
1894
+ // next offer is out. Applied, the browser refuses it ("The order of
1895
+ // m-lines in answer doesn't match order in offer").
1896
+ const { clock, alice, bob, aliceLoses } = await connectedPair()
1897
+ bob.live().restartIce()
1898
+ await settleAll()
1899
+ const stale = descriptions(alice.sent).slice(-1)[0] as { description: { type: string } }
1900
+ expect(stale.description.type).toBe("answer")
1901
+
1902
+ aliceLoses.answer = true
1903
+ bob.live().restartIce()
1904
+ await settleAll()
1905
+ expect(bob.live().signalingState).toBe("have-local-offer")
1906
+ bus.deliverTo("did:bob", "did:alice", stale)
1907
+ await settleAll()
1908
+ expect(bob.errors).toEqual([])
1909
+ expect(bob.live().signalingState).toBe("have-local-offer")
1910
+
1911
+ // The answer to the current offer still settles it.
1912
+ aliceLoses.answer = false
1913
+ clock.advance(RECOVERY_INTERVAL_MS)
1914
+ bob.mesh.tick()
1915
+ await settleAll()
1916
+ expect(bob.live().signalingState).toBe("stable")
1917
+ expect(bob.errors).toEqual([])
1918
+ })
1919
+
1920
+ it("answers the peer's offer when negotiation is asked for while it is applied", async () => {
1921
+ // The browser can fire `negotiationneeded` during the rollback that
1922
+ // accepting the peer's offer starts. A description picked from the
1923
+ // state when the handler runs is then the answer, and the answering
1924
+ // path, finding the connection stable, makes an offer in its place.
1925
+ const { alice, bob } = await connectedPair()
1926
+ const pc = bob.live() as unknown as {
1927
+ setRemoteDescription(description: RTCSessionDescriptionInit): Promise<void>
1928
+ onnegotiationneeded: (() => void) | null
1929
+ }
1930
+ const setRemote = pc.setRemoteDescription.bind(pc)
1931
+ pc.setRemoteDescription = async (description) => {
1932
+ await setRemote(description)
1933
+ if (description.type === "offer") pc.onnegotiationneeded?.()
1934
+ }
1935
+ const before = descriptions(bob.sent).length
1936
+
1937
+ alice.live().restartIce()
1938
+ await settleAll()
1939
+
1940
+ const sent = descriptions(bob.sent).slice(before) as { description: { type: string } }[]
1941
+ expect(sent.map((message) => message.description.type)).toEqual(["answer"])
1942
+ expect(alice.live().signalingState).toBe("stable")
1943
+ expect(bob.live().signalingState).toBe("stable")
1944
+ expect(bob.errors).toEqual([])
1945
+ })
1946
+
1947
+ it("ignores an offer overtaken by a later one", async () => {
1948
+ // Alice's earlier offer arrives after Bob applied her next one.
1949
+ const { alice, bob } = await connectedPair()
1950
+ alice.live().restartIce()
1951
+ await settleAll()
1952
+ const overtaken = descriptions(alice.sent).slice(-1)[0] as { description: { type: string } }
1953
+ expect(overtaken.description.type).toBe("offer")
1954
+ alice.live().restartIce()
1955
+ await settleAll()
1956
+ expect(bob.live().signalingState).toBe("stable")
1957
+
1958
+ bus.deliverTo("did:bob", "did:alice", overtaken)
1959
+ await settleAll()
1960
+ expect(bob.errors).toEqual([])
1961
+ expect(bob.live().signalingState).toBe("stable")
1962
+ })
1963
+
1964
+ it("stops repairing a peer that never answers a renegotiation, across rebuilds", async () => {
1965
+ // Each rebuilt connection connects before it renegotiates, which resets
1966
+ // a slot's own budget. The renegotiation budget is the peer's, so the
1967
+ // resend → rebuild → connect → unanswered cycle still runs out.
1968
+ const { clock, bob, bobLoses } = await connectedPair()
1969
+ bobLoses.description = true
1970
+
1971
+ for (let round = 0; round < MAX_RECOVERY_ATTEMPTS + 2; round += 1) {
1972
+ bob.live().setConnectionState("connected")
1973
+ bob.live().restartIce()
1974
+ await settleAll()
1975
+ clock.advance(RECOVERY_INTERVAL_MS)
1976
+ bob.mesh.tick()
1977
+ await settleAll()
1978
+ }
1979
+ const spent = bob.recoveries.length
1980
+ expect(spent).toBeGreaterThan(0)
1981
+
1982
+ bob.live().setConnectionState("connected")
1983
+ bob.live().restartIce()
1984
+ await settleAll()
1985
+ for (let i = 0; i < 4; i += 1) {
1986
+ clock.advance(RECOVERY_INTERVAL_MS)
1987
+ bob.mesh.tick()
1988
+ await settleAll()
1989
+ }
1990
+
1991
+ expect(bob.recoveries).toHaveLength(spent)
1992
+ expect(bob.recoveries.filter((r) => r.rung !== "ice-restart").length).toBeLessThanOrEqual(MAX_RECOVERY_ATTEMPTS)
1993
+ })
1994
+
1995
+ it("gives a peer its renegotiation budget back once one is answered", async () => {
1996
+ const { clock, bob, bobLoses } = await connectedPair()
1997
+
1998
+ bobLoses.description = true
1999
+ bob.live().restartIce()
2000
+ await settleAll()
2001
+ clock.advance(RECOVERY_INTERVAL_MS)
2002
+ bob.mesh.tick()
2003
+ await settleAll()
2004
+ expect(bob.recoveries.map((r) => r.rung)).toEqual(["resend"])
2005
+
2006
+ // The next renegotiation is answered, and the one after that is lost.
2007
+ bobLoses.description = false
2008
+ clock.advance(RECOVERY_INTERVAL_MS)
2009
+ bob.mesh.tick()
2010
+ await settleAll()
2011
+ expect(bob.live().signalingState).toBe("stable")
2012
+
2013
+ for (let round = 0; round < MAX_RECOVERY_ATTEMPTS + 1; round += 1) {
2014
+ bobLoses.description = true
2015
+ bob.live().setConnectionState("connected")
2016
+ bob.live().restartIce()
2017
+ await settleAll()
2018
+ bobLoses.description = false
2019
+ clock.advance(RECOVERY_INTERVAL_MS)
2020
+ bob.mesh.tick()
2021
+ await settleAll()
2022
+ expect(bob.live().signalingState).toBe("stable")
2023
+ }
2024
+ })
2025
+
2026
+ it("resends an offer that never got its answer, though the pair reads connected", async () => {
2027
+ // The answerer's media travels in an offer of its own, sent once the
2028
+ // pair is up. Reordered behind the answer it follows, an impolite peer
2029
+ // reads it as glare and ignores it; lost, it never arrives. Either way
2030
+ // the pair reads `connected` with one direction silent. Found by T20.
2031
+ const { clock, alice, bob, bobLoses } = await connectedPair()
2032
+
2033
+ bobLoses.description = true
2034
+ bob.live().restartIce()
2035
+ await settle()
2036
+ await settle()
2037
+ expect(bob.live().signalingState).toBe("have-local-offer")
2038
+ expect(alice.live().signalingState).toBe("stable")
2039
+
2040
+ bobLoses.description = false
2041
+ clock.advance(RECOVERY_INTERVAL_MS - 1)
2042
+ bob.mesh.tick()
2043
+ expect(bob.recoveries).toEqual([])
2044
+
2045
+ clock.advance(1)
2046
+ bob.mesh.tick()
2047
+ for (let i = 0; i < 3; i += 1) await settle()
2048
+
2049
+ expect(bob.recoveries.map((r) => r.rung)).toEqual(["resend"])
2050
+ expect(bob.connections).toHaveLength(1)
2051
+ expect(bob.live().signalingState).toBe("stable")
2052
+ expect(alice.errors).toEqual([])
2053
+ expect(bob.errors).toEqual([])
2054
+ })
2055
+
2056
+ it("leaves a connected pair alone while nothing it offered is pending", async () => {
2057
+ const { clock, alice, bob } = await connectedPair()
2058
+
2059
+ clock.advance(RECOVERY_INTERVAL_MS * 4)
2060
+ alice.mesh.tick()
2061
+ bob.mesh.tick()
2062
+ await settle()
2063
+
2064
+ expect(alice.recoveries).toEqual([])
2065
+ expect(bob.recoveries).toEqual([])
2066
+ })
2067
+
2068
+ it("rebuilds the pair when the resent offer goes unanswered too", async () => {
2069
+ const { clock, bob, bobLoses } = await connectedPair()
2070
+
2071
+ bobLoses.description = true
2072
+ bob.live().restartIce()
2073
+ await settle()
2074
+ await settle()
2075
+
2076
+ clock.advance(RECOVERY_INTERVAL_MS)
2077
+ bob.mesh.tick()
2078
+ await settle()
2079
+ clock.advance(RECOVERY_INTERVAL_MS)
2080
+ bob.mesh.tick()
2081
+ await settle()
2082
+
2083
+ expect(bob.recoveries.map((r) => r.rung)).toEqual(["resend", "rebuild"])
2084
+ expect(kinds(bob.sent)).toContain("reset")
2085
+ })
2086
+ })
2087
+
2088
+ // ── Diagnostics and configuration ───────────────────────────────────
2089
+
2090
+ describe("what a call is told about its own connections", () => {
2091
+ let bus: InMemoryBus
2092
+
2093
+ beforeEach(() => {
2094
+ bus = new InMemoryBus()
2095
+ })
2096
+
2097
+ it("uses the ICE servers it is given, and its own when given none", async () => {
2098
+ const mine = [{ urls: "turn:relay.example.org:3478", username: "u", credential: "p" }]
2099
+ const configured = await makeMesh(bus, "did:alice", CALL_ID, { iceServers: mine })
2100
+ configured.mesh.setRoster(["did:alice", "did:bob"])
2101
+ await settle()
2102
+ expect(configured.configs[0].iceServers).toEqual(mine)
2103
+
2104
+ const bare = await makeMesh(bus, "did:zoe", CALL_ID)
2105
+ bare.mesh.setRoster(["did:zoe", "did:bob"])
2106
+ await settle()
2107
+ expect(bare.configs[0].iceServers?.[0]).toMatchObject({
2108
+ urls: expect.arrayContaining(["stun:stun.l.google.com:19302"]),
2109
+ })
2110
+ expect(bare.configs[0].iceServers).toEqual(DEFAULT_ICE_SERVERS)
2111
+
2112
+ // An empty list is "none given", not "no servers at all".
2113
+ const empty = await makeMesh(bus, "did:yan", CALL_ID, { iceServers: [] })
2114
+ empty.mesh.setRoster(["did:yan", "did:bob"])
2115
+ expect(empty.configs[0].iceServers).toEqual(DEFAULT_ICE_SERVERS)
2116
+ })
2117
+
2118
+ it("pre-gathers one candidate set", async () => {
2119
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2120
+ alice.mesh.setRoster(["did:alice", "did:bob"])
2121
+ expect(alice.configs[0].iceCandidatePoolSize).toBe(1)
2122
+ })
2123
+
2124
+ it("says how the media is actually reaching the other end", async () => {
2125
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2126
+ alice.mesh.setRoster(["did:alice", "did:bob"])
2127
+ await settle()
2128
+
2129
+ alice.live().stats = [
2130
+ { id: "pair-1", type: "candidate-pair", state: "failed", localCandidateId: "cand-1" },
2131
+ { id: "pair-2", type: "candidate-pair", state: "succeeded", localCandidateId: "cand-2" },
2132
+ { id: "cand-1", type: "local-candidate", candidateType: "host" },
2133
+ { id: "cand-2", type: "local-candidate", candidateType: "relay" },
2134
+ ]
2135
+
2136
+ expect(await alice.mesh.transportOf("did:bob")).toBe("relay")
2137
+ expect(await alice.mesh.transportOf("did:nobody")).toBeNull()
2138
+ })
2139
+
2140
+ it("answers nothing rather than guessing when no pair has succeeded", async () => {
2141
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2142
+ alice.mesh.setRoster(["did:alice", "did:bob"])
2143
+ await settle()
2144
+
2145
+ alice.live().stats = [{ id: "pair-1", type: "candidate-pair", state: "in-progress", localCandidateId: "cand-1" }]
2146
+ expect(await alice.mesh.transportOf("did:bob")).toBeNull()
2147
+ })
2148
+
2149
+ it("reports a stats failure as an error and answers nothing", async () => {
2150
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2151
+ alice.mesh.setRoster(["did:alice", "did:bob"])
2152
+ await settle()
2153
+
2154
+ alice.live().getStats = async () => { throw new Error("stats unavailable") }
2155
+ expect(await alice.mesh.transportOf("did:bob")).toBeNull()
2156
+ expect(alice.errors).toHaveLength(1)
2157
+ })
2158
+
2159
+ it("sweeps on its own timer when it is given one", async () => {
2160
+ // Every other test drives `tick()` by hand, which would leave the line
2161
+ // that makes this run in production untested.
2162
+ const { channel } = bus.channel("did:alice")
2163
+ const clock = makeClock()
2164
+ const recoveries: RecoveryRung[] = []
2165
+ const mesh = new MeshManager({
2166
+ channel,
2167
+ callId: CALL_ID,
2168
+ selfId: "did:alice",
2169
+ now: clock.now,
2170
+ sweepMs: 1,
2171
+ createPeerConnection: () => new FakePeerConnection() as unknown as RTCPeerConnection,
2172
+ })
2173
+ meshes.push(mesh)
2174
+ mesh.on("peer-recovery", (_peerId: string, attempt: { rung: RecoveryRung }) => recoveries.push(attempt.rung))
2175
+ await mesh.join(stream())
2176
+
2177
+ mesh.setRoster(["did:alice", "did:bob"])
2178
+ await settle()
2179
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
2180
+ await new Promise((resolve) => setTimeout(resolve, 10))
2181
+
2182
+ expect(recoveries.length).toBeGreaterThan(0)
2183
+ await mesh.leave()
2184
+
2185
+ // And the timer goes with the mesh.
2186
+ const after = recoveries.length
2187
+ clock.advance(HANDSHAKE_GRACE_MS * 10)
2188
+ await new Promise((resolve) => setTimeout(resolve, 10))
2189
+ expect(recoveries).toHaveLength(after)
2190
+ })
2191
+ })
2192
+
2193
+ // ── Signalling before the roster ────────────────────────────────────
2194
+
2195
+ describe("signalling that arrives before the roster", () => {
2196
+ /**
2197
+ * A peer who denied the microphone has no outbound tracks and never fires
2198
+ * `negotiationneeded` again after its offer is dropped, so dropping it
2199
+ * left that peer connected to nobody.
2200
+ */
2201
+ let bus: InMemoryBus
2202
+
2203
+ beforeEach(() => {
2204
+ bus = new InMemoryBus()
2205
+ })
2206
+
2207
+ it("keeps the held offer when its candidates overflow the buffer", async () => {
2208
+ // An offer is followed by many candidates; held for a peer the roster
2209
+ // has not listed yet, the overflow must not take the offer with it.
2210
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2211
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
2212
+
2213
+ alice.mesh.setRoster(["did:alice", "did:bob"])
2214
+ await settle()
2215
+ await settle()
2216
+ for (let i = 0; i < 40; i += 1) {
2217
+ alice.live().emitCandidate({ candidate: `candidate:${i} 1 udp 1 10.0.0.${i} 9 typ host`, sdpMid: "0" })
2218
+ }
2219
+
2220
+ bob.mesh.setRoster(["did:alice", "did:bob"])
2221
+ await settleAll()
2222
+
2223
+ expect(bob.live().remoteDescription?.type).toBe("offer")
2224
+ expect(bob.errors).toEqual([])
2225
+ })
2226
+
2227
+ it("connects a peer whose roster arrived after the offer, with no tracks of their own", async () => {
2228
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2229
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
2230
+
2231
+ alice.mesh.setRoster(["did:alice", "did:bob"])
2232
+ await alice.mesh.replaceTrack("audio", track("audio"))
2233
+ await settle()
2234
+ await settle()
2235
+
2236
+ expect(bob.connections).toHaveLength(0)
2237
+
2238
+ bob.mesh.setRoster(["did:alice", "did:bob"])
2239
+ await settle()
2240
+ await settle()
2241
+
2242
+ // Held rather than dropped, and replayed the moment the roster vouches for Alice.
2243
+ expect(bob.connections).toHaveLength(1)
2244
+ expect(bob.connections[0].remoteDescription?.type).toBe("offer")
2245
+ expect(bob.errors).toEqual([])
2246
+ expect(alice.errors).toEqual([])
2247
+ })
2248
+
2249
+ it("does not negotiate with an agent the roster never lists", async () => {
2250
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2251
+ const stranger = await makeMesh(bus, "did:stranger", CALL_ID)
2252
+
2253
+ stranger.mesh.setRoster(["did:stranger", "did:alice"])
2254
+ await stranger.mesh.replaceTrack("audio", track("audio"))
2255
+ await settle()
2256
+ await settle()
2257
+
2258
+ // Holding a message is not a promise to negotiate.
2259
+ alice.mesh.setRoster(["did:alice", "did:bob"])
2260
+ await settle()
2261
+
2262
+ expect(alice.connections).toHaveLength(1)
2263
+ expect(alice.connections[0].remoteDescription).toBeNull()
2264
+
2265
+ // And what was held for the stranger is gone, not waiting: listed
2266
+ // later, after the stranger has stopped talking, nothing is replayed.
2267
+ await stranger.mesh.leave()
2268
+ alice.mesh.setRoster(["did:alice", "did:bob", "did:stranger"])
2269
+ await settle()
2270
+ expect(alice.connections[1].remoteDescription).toBeNull()
2271
+ })
2272
+
2273
+ it("bounds what it holds for an agent nobody has vouched for", async () => {
2274
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2275
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
2276
+
2277
+ bob.mesh.setRoster(["did:alice", "did:bob"])
2278
+ for (let n = 0; n < 40; n += 1) {
2279
+ await bob.mesh.replaceTrack("audio", track("audio"))
2280
+ await bob.mesh.replaceTrack("audio", null)
2281
+ bob.live().emitCandidate({ candidate: `c${n}` })
2282
+ }
2283
+ await settle()
2284
+
2285
+ alice.mesh.setRoster(["did:alice", "did:bob"])
2286
+ await settle()
2287
+ await settle()
2288
+
2289
+ // It replayed something rather than nothing, and did not replay everything.
2290
+ expect(alice.connections[0].remoteDescription).not.toBeNull()
2291
+ expect(alice.connections[0].candidates.length).toBeLessThan(40)
2292
+ })
2293
+ })
2294
+
2295
+ // ── Generations ─────────────────────────────────────────────────────
2296
+
2297
+ describe("a description from a different connection", () => {
2298
+ /**
2299
+ * A message from one of the peer's connections used to be applied to
2300
+ * whichever connection this side held, and the browser refuses that:
2301
+ * "The order of m-lines in subsequent offer doesn't match order from
2302
+ * previous offer/answer". Each case is a way the two sides come to hold
2303
+ * different generations of the pair.
2304
+ */
2305
+ let bus: InMemoryBus
2306
+
2307
+ beforeEach(() => {
2308
+ bus = new InMemoryBus()
2309
+ })
2310
+
2311
+ async function connected(aliceOptions: MeshOptions = {}) {
2312
+ const alice = await makeMesh(bus, "did:alice", CALL_ID, aliceOptions)
2313
+ const bob = await makeMesh(bus, "did:bob", CALL_ID)
2314
+ alice.mesh.setRoster(["did:alice", "did:bob"])
2315
+ bob.mesh.setRoster(["did:alice", "did:bob"])
2316
+ await settleAll()
2317
+ expect(alice.live().signalingState).toBe("stable")
2318
+ expect(bob.live().signalingState).toBe("stable")
2319
+ return { alice, bob }
2320
+ }
2321
+
2322
+ it("names both connections on everything it sends", async () => {
2323
+ const { alice, bob } = await connected()
2324
+ const answer = bob.sent.find((payload) =>
2325
+ (payload as { description?: { type?: string } }).description?.type === "answer") as
2326
+ { gen?: string; peerGen?: string }
2327
+ const offer = alice.sent.find((payload) =>
2328
+ (payload as { description?: { type?: string } }).description?.type === "offer") as
2329
+ { gen?: string; peerGen?: string }
2330
+
2331
+ expect(typeof offer.gen).toBe("string")
2332
+ // Bob's answer names Alice's connection as the one it is for.
2333
+ expect(answer.peerGen).toBe(offer.gen)
2334
+ expect(typeof answer.gen).toBe("string")
2335
+ })
2336
+
2337
+ it("follows a peer that reloaded while it was still on the roster", async () => {
2338
+ // A reload starts a new connection and offers from it with no reset;
2339
+ // presence has not noticed, so this side's connection survives.
2340
+ const { alice, bob } = await connected()
2341
+ await bob.mesh.leave()
2342
+
2343
+ const bobAgain = await makeMesh(bus, "did:bob", CALL_ID)
2344
+ bobAgain.mesh.setRoster(["did:alice", "did:bob"])
2345
+ await settleAll()
2346
+
2347
+ expect(alice.errors).toEqual([])
2348
+ expect(bobAgain.errors).toEqual([])
2349
+ // Alice started over to match, rather than applying the offer to a connection it was not for.
2350
+ expect(alice.connections).toHaveLength(2)
2351
+ expect(alice.connections[0].closed).toBe(true)
2352
+ expect(alice.live().signalingState).toBe("stable")
2353
+ expect(bobAgain.live().signalingState).toBe("stable")
2354
+ expect(bobAgain.live().remoteDescription?.type).toBe("answer")
2355
+ })
2356
+
2357
+ it("is not undone by the reset that the new offer overtook", async () => {
2358
+ // A rebuild sends `reset` and then offers from the new connection; on
2359
+ // an unordered transport the offer can arrive first.
2360
+ let holding = false
2361
+ const held: unknown[] = []
2362
+ const { alice, bob } = await connected({
2363
+ drop: (payload) => {
2364
+ if (!holding || (payload as { kind?: string }).kind !== "reset") return false
2365
+ held.push(payload)
2366
+ return true
2367
+ },
2368
+ })
2369
+
2370
+ holding = true
2371
+ alice.mesh.reconnect("did:bob")
2372
+ await settleAll()
2373
+
2374
+ expect(held).toHaveLength(1)
2375
+ expect(bob.errors).toEqual([])
2376
+ expect(bob.connections).toHaveLength(2)
2377
+
2378
+ // Now the reset turns up.
2379
+ bus.deliver("did:alice", held[0])
2380
+ await settleAll()
2381
+
2382
+ expect(bob.connections).toHaveLength(2)
2383
+ expect(bob.live().closed).toBe(false)
2384
+ expect(bob.live().signalingState).toBe("stable")
2385
+ expect(alice.live().signalingState).toBe("stable")
2386
+ expect(bob.errors).toEqual([])
2387
+ expect(alice.errors).toEqual([])
2388
+ })
2389
+
2390
+ it("ignores an offer from a connection the peer has since replaced", async () => {
2391
+ const { alice, bob } = await connected()
2392
+ const staleOffer = bob.sent.find((payload) => (payload as { kind?: string }).kind === "description")
2393
+ await bob.mesh.leave()
2394
+
2395
+ const bobAgain = await makeMesh(bus, "did:bob", CALL_ID)
2396
+ bobAgain.mesh.setRoster(["did:alice", "did:bob"])
2397
+ await settleAll()
2398
+ const before = alice.connections.length
2399
+
2400
+ // The first Bob's message, delayed until after Alice has moved on to the second.
2401
+ bus.deliver("did:bob", staleOffer)
2402
+ await settleAll()
2403
+
2404
+ expect(alice.connections).toHaveLength(before)
2405
+ expect(alice.live().signalingState).toBe("stable")
2406
+ expect(alice.errors).toEqual([])
2407
+ })
2408
+
2409
+ it("ignores signalling addressed to a connection of its own that it has replaced", async () => {
2410
+ const { alice, bob } = await connected()
2411
+ const toOldAlice = bob.sent.filter((payload) => (payload as { kind?: string }).kind === "description")
2412
+
2413
+ // Alice rebuilds; Bob follows. Anything Bob said to the first Alice is now about nothing.
2414
+ alice.mesh.reconnect("did:bob")
2415
+ await settleAll()
2416
+ const before = { alice: alice.connections.length, bob: bob.connections.length }
2417
+
2418
+ for (const payload of toOldAlice) bus.deliver("did:bob", payload)
2419
+ await settleAll()
2420
+
2421
+ expect(alice.connections).toHaveLength(before.alice)
2422
+ expect(bob.connections).toHaveLength(before.bob)
2423
+ expect(alice.errors).toEqual([])
2424
+ })
2425
+
2426
+ it("still answers a peer that does not say which connection it is", async () => {
2427
+ // A peer predating generations sends none; mixed versions still connect.
2428
+ const alice = await makeMesh(bus, "did:alice", CALL_ID)
2429
+ alice.mesh.setRoster(["did:alice", "did:aaron"])
2430
+ await settle()
2431
+
2432
+ bus.deliver("did:aaron", {
2433
+ v: CALL_PROTOCOL_VERSION,
2434
+ call: CALL_ID,
2435
+ to: "did:alice",
2436
+ kind: "description",
2437
+ description: { type: "offer", sdp: "offer-sdp@legacy" },
2438
+ })
2439
+ await settleAll()
2440
+
2441
+ expect(alice.live().remoteDescription?.sdp).toBe("offer-sdp@legacy")
2442
+ expect(alice.errors).toEqual([])
2443
+ })
2444
+ })
2445
+
2446
+ // ── Telepresence channel ────────────────────────────────────────────
2447
+
2448
+ describe("createTelepresenceChannel", () => {
2449
+ const PREDICATE = "ad4m://session/rtc"
2450
+
2451
+ function fakeProxy() {
2452
+ const handlers = new Set<(payload: PerspectiveExpression) => void>()
2453
+ const sends: { resolve(ok: boolean): void; reject(error: unknown): void; links: unknown[] }[] = []
2454
+ const proxy: TelepresenceProxy = {
2455
+ sendBroadcastU: (status) =>
2456
+ new Promise<boolean>((resolve, reject) => {
2457
+ sends.push({ resolve, reject, links: status.links })
2458
+ }),
2459
+ addSignalHandler: async (handler) => { handlers.add(handler) },
2460
+ removeSignalHandler: (handler) => { handlers.delete(handler) },
2461
+ }
2462
+ /** A signal as the executor delivers it, with both proofs checked and recorded in `valid`. */
2463
+ const signal = (
2464
+ author: string,
2465
+ data: { source?: unknown; predicate?: unknown; target?: unknown },
2466
+ proofs: { signer?: string; signalValid?: boolean | null; linkValid?: boolean } = {},
2467
+ ) => {
2468
+ const expression = {
2469
+ author: proofs.signer ?? author,
2470
+ // `null`: a proof the executor never evaluated.
2471
+ proof: proofs.signalValid === null ? {} : { valid: proofs.signalValid ?? true },
2472
+ data: { links: [{ author, data, proof: { valid: proofs.linkValid ?? true } }] },
2473
+ } as unknown as PerspectiveExpression
2474
+ for (const handler of [...handlers]) handler(expression)
2475
+ }
2476
+ return { proxy, sends, handlers, signal }
2477
+ }
2478
+
2479
+ it("accepts only a link whose author signed it, inside a signal that author signed", async () => {
2480
+ // The mesh acts on the sender id — offers, answers, resets, rebuilds —
2481
+ // so an author claim the executor could not verify must never reach it.
2482
+ const { proxy, signal } = fakeProxy()
2483
+ const channel = createTelepresenceChannel(proxy, "did:alice")
2484
+ const heard: [string, unknown][] = []
2485
+ channel.onMessage((from, payload) => heard.push([from, payload]))
2486
+ await settle()
2487
+ const message = (n: number) => ({ source: JSON.stringify({ n }), predicate: PREDICATE, target: "*" })
2488
+
2489
+ signal("did:bob", message(1), { linkValid: false })
2490
+ signal("did:bob", message(2), { signalValid: false })
2491
+ signal("did:bob", message(3), { signer: "did:mallory" })
2492
+ signal("did:bob", message(4), { signalValid: null })
2493
+ signal("did:bob", message(5))
2494
+
2495
+ expect(heard).toEqual([["did:bob", { n: 5 }]])
2496
+ })
2497
+
2498
+ it("lets a forged reset change nothing on the mesh", async () => {
2499
+ // End to end through the adapter: a reset whose link claims Bob but
2500
+ // whose proof does not hold must not rebuild Alice's pair with Bob.
2501
+ const { proxy, signal } = fakeProxy()
2502
+ const alice = new MeshManager({
2503
+ channel: createTelepresenceChannel(proxy, "did:alice"),
2504
+ callId: CALL_ID,
2505
+ selfId: "did:alice",
2506
+ createPeerConnection: () => new FakePeerConnection() as unknown as RTCPeerConnection,
2507
+ sweepMs: 0,
2508
+ })
2509
+ meshes.push(alice)
2510
+ await alice.join(stream())
2511
+ alice.setRoster(["did:alice", "did:bob"])
2512
+ await settle()
2513
+ const before = alice.getParticipants()[0]?.stream
2514
+ const recoveries: unknown[] = []
2515
+ alice.on("peer-recovery", (...args: unknown[]) => recoveries.push(args))
2516
+
2517
+ const reset = { source: JSON.stringify({ v: CALL_PROTOCOL_VERSION, call: CALL_ID, to: "did:alice", kind: "reset" }), predicate: PREDICATE, target: "did:alice" }
2518
+ signal("did:bob", reset, { linkValid: false })
2519
+ signal("did:bob", reset, { signer: "did:mallory" })
2520
+ await settleAll()
2521
+
2522
+ expect(recoveries).toEqual([])
2523
+ expect(alice.getParticipants()[0]?.stream).toBe(before)
2524
+
2525
+ signal("did:bob", reset)
2526
+ await settleAll()
2527
+ expect(recoveries).toHaveLength(1)
2528
+ })
2529
+
2530
+ it("publishes over broadcast, addressed in the link target", () => {
2531
+ const { proxy, sends } = fakeProxy()
2532
+ const channel = createTelepresenceChannel(proxy, "did:alice")
2533
+
2534
+ channel.publish({ hello: 1 }, { agentId: "did:bob" })
2535
+ channel.publish({ hello: 2 })
2536
+
2537
+ expect(sends.map((send) => send.links)).toEqual([
2538
+ [{ source: JSON.stringify({ hello: 1 }), predicate: PREDICATE, target: "did:bob" }],
2539
+ [{ source: JSON.stringify({ hello: 2 }), predicate: PREDICATE, target: "*" }],
2540
+ ])
2541
+ })
2542
+
2543
+ it("delivers what is for this agent, with the author as the sender", async () => {
2544
+ const { proxy, signal, handlers } = fakeProxy()
2545
+ const channel = createTelepresenceChannel(proxy, "did:alice")
2546
+ const heard: [string, unknown][] = []
2547
+ const unsubscribe = channel.onMessage((from, payload) => heard.push([from, payload]))
2548
+ await settle()
2549
+
2550
+ signal("did:bob", { source: JSON.stringify({ n: 1 }), predicate: PREDICATE, target: "did:alice" })
2551
+ signal("did:bob", { source: JSON.stringify({ n: 2 }), predicate: PREDICATE, target: "*" })
2552
+ signal("did:bob", { source: JSON.stringify({ n: 3 }), predicate: PREDICATE, target: "did:carol" })
2553
+ signal("did:bob", { source: JSON.stringify({ n: 4 }), predicate: "other://predicate", target: "*" })
2554
+ signal("did:alice", { source: JSON.stringify({ n: 5 }), predicate: PREDICATE, target: "*" })
2555
+ signal("did:bob", { source: "{not json", predicate: PREDICATE, target: "*" })
2556
+
2557
+ expect(heard).toEqual([["did:bob", { n: 1 }], ["did:bob", { n: 2 }]])
2558
+
2559
+ unsubscribe()
2560
+ expect(handlers.size).toBe(0)
2561
+ })
2562
+
2563
+ it("reports one result per publish, failed when the send is refused or rejected", async () => {
2564
+ const { proxy, sends } = fakeProxy()
2565
+ const channel = createTelepresenceChannel(proxy, "did:alice")
2566
+ const results: { ok: boolean; ms: number }[] = []
2567
+ const unwatch = channel.onPublishResult!((result) => results.push(result))
2568
+ const consoleError = jest.spyOn(console, "error").mockImplementation()
2569
+
2570
+ channel.publish({ n: 1 })
2571
+ channel.publish({ n: 2 })
2572
+ channel.publish({ n: 3 })
2573
+ await settle()
2574
+ // Nothing is reported while the sends are outstanding.
2575
+ expect(results).toEqual([])
2576
+
2577
+ sends[1].resolve(false)
2578
+ sends[0].resolve(true)
2579
+ sends[2].reject(new Error("executor gone"))
2580
+ await settle()
2581
+
2582
+ expect(results.map((result) => result.ok)).toEqual([false, true, false])
2583
+ expect(results.every((result) => typeof result.ms === "number" && result.ms >= 0)).toBe(true)
2584
+ expect(consoleError).toHaveBeenCalled()
2585
+
2586
+ unwatch()
2587
+ channel.publish({ n: 4 })
2588
+ sends[3].resolve(true)
2589
+ await settle()
2590
+ expect(results).toHaveLength(3)
2591
+
2592
+ consoleError.mockRestore()
2593
+ })
2594
+
2595
+ it("reports a failed result when the send throws synchronously", async () => {
2596
+ // An unreported publish stays outstanding and holds the mesh's repairs off for good.
2597
+ const proxy: TelepresenceProxy = {
2598
+ sendBroadcastU: () => { throw new Error("not connected") },
2599
+ addSignalHandler: async () => {},
2600
+ removeSignalHandler: () => {},
2601
+ }
2602
+ const channel = createTelepresenceChannel(proxy, "did:alice")
2603
+ const results: { ok: boolean; ms: number }[] = []
2604
+ channel.onPublishResult!((result) => results.push(result))
2605
+ const consoleError = jest.spyOn(console, "error").mockImplementation()
2606
+
2607
+ expect(() => channel.publish({ n: 1 })).not.toThrow()
2608
+ await settle()
2609
+
2610
+ expect(results.map((result) => result.ok)).toEqual([false])
2611
+ consoleError.mockRestore()
2612
+ })
2613
+
2614
+ it("lets the mesh defer repair until telepresence has reported", async () => {
2615
+ const { proxy, sends } = fakeProxy()
2616
+ const clock = makeClock()
2617
+ const mesh = new MeshManager({
2618
+ channel: createTelepresenceChannel(proxy, "did:alice"),
2619
+ callId: CALL_ID,
2620
+ selfId: "did:alice",
2621
+ now: clock.now,
2622
+ sweepMs: 0,
2623
+ createPeerConnection: () => new FakePeerConnection() as unknown as RTCPeerConnection,
2624
+ })
2625
+ meshes.push(mesh)
2626
+ const rungs: RecoveryRung[] = []
2627
+ mesh.on("peer-recovery", (_peerId: string, attempt: { rung: RecoveryRung }) => rungs.push(attempt.rung))
2628
+ await mesh.join(stream())
2629
+
2630
+ mesh.setRoster(["did:alice", "did:bob"])
2631
+ await settle()
2632
+ clock.advance(HANDSHAKE_GRACE_MS + 1)
2633
+ mesh.tick()
2634
+ expect(rungs).toEqual([])
2635
+
2636
+ for (const send of [...sends]) send.resolve(true)
2637
+ await settle()
2638
+ expect(rungs).toEqual(["resend"])
2639
+ })
2640
+ })