peerpigeon 0.0.5 → 0.0.6

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.
@@ -6,847 +6,866 @@ import { environmentDetector } from './EnvironmentDetector.js';
6
6
  * Manages individual peer connections, timeouts, and connection attempts
7
7
  */
8
8
  export class ConnectionManager extends EventEmitter {
9
- constructor(mesh) {
10
- super();
11
- this.mesh = mesh;
12
- this.peers = new Map();
13
- this.connectionAttempts = new Map();
14
- this.connectionTimeouts = new Map();
15
- this.pendingIceCandidates = new Map();
16
- this.disconnectionInProgress = new Set();
17
- this.cleanupInProgress = new Set();
18
- this.lastConnectionAttempt = new Map(); // Track last attempt time per peer
19
-
20
- // Configuration
21
- this.maxConnectionAttempts = 3;
22
- this.connectionTimeout = 30000; // Reduced to 30 seconds for faster retry
23
- this.retryDelay = 1500; // 1.5 second cooldown between attempts to same peer
24
-
25
- // Start periodic cleanup of stale peers
26
- this.startPeriodicCleanup();
27
- }
28
-
29
- async connectToPeer(targetPeerId) {
30
- console.log(`connectToPeer called for ${targetPeerId.substring(0, 8)}...`);
31
-
32
- // Enhanced duplicate connection prevention
33
- if (this.peers.has(targetPeerId)) {
34
- console.log(`Already connected to ${targetPeerId.substring(0, 8)}...`);
35
- return;
36
- }
9
+ constructor(mesh) {
10
+ super();
11
+ this.mesh = mesh;
12
+ this.peers = new Map();
13
+ this.connectionAttempts = new Map();
14
+ this.connectionTimeouts = new Map();
15
+ this.pendingIceCandidates = new Map();
16
+ this.disconnectionInProgress = new Set();
17
+ this.cleanupInProgress = new Set();
18
+ this.lastConnectionAttempt = new Map(); // Track last attempt time per peer
19
+
20
+ // Configuration
21
+ this.maxConnectionAttempts = 3;
22
+ this.connectionTimeout = 30000; // Reduced to 30 seconds for faster retry
23
+ this.retryDelay = 1500; // 1.5 second cooldown between attempts to same peer
24
+
25
+ // Start periodic cleanup of stale peers
26
+ this.startPeriodicCleanup();
27
+ }
28
+
29
+ async connectToPeer(targetPeerId) {
30
+ console.log(`connectToPeer called for ${targetPeerId.substring(0, 8)}...`);
31
+
32
+ // Enhanced duplicate connection prevention
33
+ if (this.peers.has(targetPeerId)) {
34
+ console.log(`Already connected to ${targetPeerId.substring(0, 8)}...`);
35
+ return;
36
+ }
37
37
 
38
- // Check if we're already in the process of connecting
39
- if (this.connectionTimeouts.has(targetPeerId)) {
40
- console.log(`Already connecting to ${targetPeerId.substring(0, 8)}... (connection in progress)`);
41
- return;
42
- }
38
+ // Check if we're already in the process of connecting
39
+ if (this.connectionTimeouts.has(targetPeerId)) {
40
+ console.log(`Already connecting to ${targetPeerId.substring(0, 8)}... (connection in progress)`);
41
+ return;
42
+ }
43
43
 
44
- // Check if we're already attempting through PeerDiscovery
45
- if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
46
- console.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
47
- return;
48
- }
44
+ // Check if we're already attempting through PeerDiscovery
45
+ if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
46
+ console.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
47
+ return;
48
+ }
49
49
 
50
- if (!this.mesh.canAcceptMorePeers()) {
51
- console.log(`Cannot connect to ${targetPeerId.substring(0, 8)}... (max peers reached: ${this.mesh.maxPeers})`);
52
- return;
53
- }
50
+ if (!this.mesh.canAcceptMorePeers()) {
51
+ console.log(`Cannot connect to ${targetPeerId.substring(0, 8)}... (max peers reached: ${this.mesh.maxPeers})`);
52
+ return;
53
+ }
54
54
 
55
- // Check retry cooldown (only apply after first attempt)
56
- const now = Date.now();
57
- const attempts = this.connectionAttempts.get(targetPeerId) || 0;
58
- if (attempts > 0) {
59
- const lastAttempt = this.lastConnectionAttempt.get(targetPeerId) || 0;
60
-
61
- // Use shorter delay for isolated peers to help them connect faster
62
- const connectedCount = this.getConnectedPeerCount();
63
- const retryDelay = connectedCount === 0 ? 500 : this.retryDelay; // 500ms for isolated peers, 1500ms otherwise
64
-
65
- if (now - lastAttempt < retryDelay) {
66
- const remaining = retryDelay - (now - lastAttempt);
67
- console.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining/1000)}s remaining, isolated: ${connectedCount === 0})`);
68
- return;
69
- }
70
- }
55
+ // Check retry cooldown (only apply after first attempt)
56
+ const now = Date.now();
57
+ const attempts = this.connectionAttempts.get(targetPeerId) || 0;
58
+ if (attempts > 0) {
59
+ const lastAttempt = this.lastConnectionAttempt.get(targetPeerId) || 0;
60
+
61
+ // Use shorter delay for isolated peers to help them connect faster
62
+ const connectedCount = this.getConnectedPeerCount();
63
+ const retryDelay = connectedCount === 0 ? 500 : this.retryDelay; // 500ms for isolated peers, 1500ms otherwise
64
+
65
+ if (now - lastAttempt < retryDelay) {
66
+ const remaining = retryDelay - (now - lastAttempt);
67
+ console.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining / 1000)}s remaining, isolated: ${connectedCount === 0})`);
68
+ return;
69
+ }
70
+ }
71
71
 
72
- // Check connection attempt count
73
- if (attempts >= this.maxConnectionAttempts) {
74
- this.mesh.emit('statusChanged', { type: 'warning', message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
75
- this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
76
- return;
77
- }
72
+ // Check connection attempt count
73
+ if (attempts >= this.maxConnectionAttempts) {
74
+ this.mesh.emit('statusChanged', { type: 'warning', message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
75
+ this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
76
+ return;
77
+ }
78
+
79
+ console.log(`Starting connection to ${targetPeerId.substring(0, 8)}... (attempt ${attempts + 1})`);
80
+ this.connectionAttempts.set(targetPeerId, attempts + 1);
81
+ this.lastConnectionAttempt.set(targetPeerId, now);
82
+ this.mesh.peerDiscovery.trackConnectionAttempt(targetPeerId);
83
+
84
+ // Set connection timeout - longer for media-enabled connections
85
+ const hasMedia = this.mesh.mediaManager.localStream !== null;
86
+ const timeoutDuration = hasMedia ? 45000 : 30000; // 45s for media, 30s for data-only
87
+
88
+ console.log(`Setting connection timeout for ${targetPeerId.substring(0, 8)}... - ${timeoutDuration / 1000}s (media: ${hasMedia})`);
89
+
90
+ const timeoutId = setTimeout(() => {
91
+ if (this.peers.has(targetPeerId)) {
92
+ const peer = this.peers.get(targetPeerId);
93
+ const status = peer.getStatus();
94
+ const detailedStatus = peer.getDetailedStatus();
95
+ console.log(`Connection timeout check for ${targetPeerId.substring(0, 8)}... - current status: ${status}`);
96
+ console.log('Detailed status:', detailedStatus);
97
+
98
+ // Cleanup if not fully connected (includes 'connecting', 'new', 'failed', etc.)
99
+ if (status !== 'connected') {
100
+ this.mesh.emit('statusChanged', { type: 'warning', message: `Connection timeout for ${targetPeerId.substring(0, 8)}... (status: ${status}, media: ${hasMedia})` });
101
+ this.handleConnectionTimeout(targetPeerId);
102
+ } else {
103
+ console.log(`Connection to ${targetPeerId.substring(0, 8)}... is connected, clearing timeout`);
104
+ this.connectionTimeouts.delete(targetPeerId);
105
+ }
106
+ } else {
107
+ console.log(`Peer ${targetPeerId.substring(0, 8)}... no longer in peers Map, cleaning up timeout`);
108
+ this.connectionTimeouts.delete(targetPeerId);
109
+ }
110
+ }, timeoutDuration);
111
+
112
+ this.connectionTimeouts.set(targetPeerId, timeoutId);
113
+
114
+ try {
115
+ console.log(`Creating PeerConnection for ${targetPeerId.substring(0, 8)}...`);
116
+
117
+ // Get current media stream if available
118
+ const localStream = this.mesh.mediaManager.localStream;
119
+ const options = {
120
+ localStream,
121
+ enableAudio: hasMedia && localStream.getAudioTracks().length > 0,
122
+ enableVideo: hasMedia && localStream.getVideoTracks().length > 0
123
+ };
124
+
125
+ const peerConnection = new PeerConnection(targetPeerId, true, options);
126
+
127
+ // Set up event handlers BEFORE creating connection to catch all events
128
+ this.setupPeerConnectionHandlers(peerConnection);
129
+ this.peers.set(targetPeerId, peerConnection);
130
+
131
+ console.log(`Creating WebRTC connection for ${targetPeerId.substring(0, 8)}...`);
132
+ await peerConnection.createConnection();
133
+
134
+ console.log(`Creating offer for ${targetPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
135
+ const offer = await peerConnection.createOffer();
136
+
137
+ console.log(`Offer created for ${targetPeerId.substring(0, 8)}...`, {
138
+ type: offer.type,
139
+ sdpLength: offer.sdp?.length || 0,
140
+ hasAudio: offer.sdp?.includes('m=audio') || false,
141
+ hasVideo: offer.sdp?.includes('m=video') || false
142
+ });
143
+
144
+ console.log(`Sending offer to ${targetPeerId.substring(0, 8)}...`);
145
+ await this.mesh.signalingClient.sendSignalingMessage({
146
+ type: 'offer',
147
+ data: offer,
148
+ targetPeerId
149
+ });
150
+
151
+ this.mesh.emit('statusChanged', { type: 'info', message: `Offer sent to ${targetPeerId.substring(0, 8)}...` });
152
+ } catch (error) {
153
+ console.error('Failed to connect to peer:', error);
154
+ this.mesh.emit('statusChanged', { type: 'error', message: `Failed to connect to ${targetPeerId.substring(0, 8)}...: ${error.message}` });
155
+ this.cleanupFailedConnection(targetPeerId);
156
+ }
157
+ }
158
+
159
+ handleConnectionTimeout(peerId) {
160
+ console.log(`Connection timeout for ${peerId.substring(0, 8)}...`);
161
+
162
+ const attempts = this.connectionAttempts.get(peerId) || 0;
163
+ if (attempts >= this.maxConnectionAttempts) {
164
+ this.mesh.emit('statusChanged', { type: 'warning', message: `Removing unresponsive peer ${peerId.substring(0, 8)}... after ${attempts} attempts` });
165
+ this.mesh.peerDiscovery.removeDiscoveredPeer(peerId);
166
+ this.connectionAttempts.delete(peerId);
167
+ } else {
168
+ this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
169
+ console.log(`Will retry connection to ${peerId.substring(0, 8)}... (attempt ${attempts}/${this.maxConnectionAttempts})`);
170
+ }
78
171
 
79
- console.log(`Starting connection to ${targetPeerId.substring(0, 8)}... (attempt ${attempts + 1})`);
80
- this.connectionAttempts.set(targetPeerId, attempts + 1);
81
- this.lastConnectionAttempt.set(targetPeerId, now);
82
- this.mesh.peerDiscovery.trackConnectionAttempt(targetPeerId);
83
-
84
- // Set connection timeout - longer for media-enabled connections
85
- const hasMedia = this.mesh.mediaManager.localStream !== null;
86
- const timeoutDuration = hasMedia ? 45000 : 30000; // 45s for media, 30s for data-only
87
-
88
- console.log(`Setting connection timeout for ${targetPeerId.substring(0, 8)}... - ${timeoutDuration/1000}s (media: ${hasMedia})`);
89
-
90
- const timeoutId = setTimeout(() => {
91
- if (this.peers.has(targetPeerId)) {
92
- const peer = this.peers.get(targetPeerId);
93
- const status = peer.getStatus();
94
- const detailedStatus = peer.getDetailedStatus();
95
- console.log(`Connection timeout check for ${targetPeerId.substring(0, 8)}... - current status: ${status}`);
96
- console.log(`Detailed status:`, detailedStatus);
97
-
98
- // Cleanup if not fully connected (includes 'connecting', 'new', 'failed', etc.)
99
- if (status !== 'connected') {
100
- this.mesh.emit('statusChanged', { type: 'warning', message: `Connection timeout for ${targetPeerId.substring(0, 8)}... (status: ${status}, media: ${hasMedia})` });
101
- this.handleConnectionTimeout(targetPeerId);
102
- } else {
103
- console.log(`Connection to ${targetPeerId.substring(0, 8)}... is connected, clearing timeout`);
104
- this.connectionTimeouts.delete(targetPeerId);
105
- }
106
- } else {
107
- console.log(`Peer ${targetPeerId.substring(0, 8)}... no longer in peers Map, cleaning up timeout`);
108
- this.connectionTimeouts.delete(targetPeerId);
109
- }
110
- }, timeoutDuration);
111
-
112
- this.connectionTimeouts.set(targetPeerId, timeoutId);
172
+ // Always cleanup the failed connection and ensure it's removed from peers Map
173
+ this.cleanupFailedConnection(peerId);
113
174
 
114
- try {
115
- console.log(`Creating PeerConnection for ${targetPeerId.substring(0, 8)}...`);
116
-
117
- // Get current media stream if available
118
- const localStream = this.mesh.mediaManager.localStream;
119
- const options = {
120
- localStream,
121
- enableAudio: hasMedia && localStream.getAudioTracks().length > 0,
122
- enableVideo: hasMedia && localStream.getVideoTracks().length > 0
123
- };
124
-
125
- const peerConnection = new PeerConnection(targetPeerId, true, options);
126
-
127
- // Set up event handlers BEFORE creating connection to catch all events
128
- this.setupPeerConnectionHandlers(peerConnection);
129
- this.peers.set(targetPeerId, peerConnection);
130
-
131
- console.log(`Creating WebRTC connection for ${targetPeerId.substring(0, 8)}...`);
132
- await peerConnection.createConnection();
133
-
134
- console.log(`Creating offer for ${targetPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
135
- const offer = await peerConnection.createOffer();
136
-
137
- console.log(`Offer created for ${targetPeerId.substring(0, 8)}...`, {
138
- type: offer.type,
139
- sdpLength: offer.sdp?.length || 0,
140
- hasAudio: offer.sdp?.includes('m=audio') || false,
141
- hasVideo: offer.sdp?.includes('m=video') || false
142
- });
143
-
144
- console.log(`Sending offer to ${targetPeerId.substring(0, 8)}...`);
145
- await this.mesh.signalingClient.sendSignalingMessage({
146
- type: 'offer',
147
- data: offer,
148
- targetPeerId
149
- });
150
-
151
- this.mesh.emit('statusChanged', { type: 'info', message: `Offer sent to ${targetPeerId.substring(0, 8)}...` });
152
- } catch (error) {
153
- console.error('Failed to connect to peer:', error);
154
- this.mesh.emit('statusChanged', { type: 'error', message: `Failed to connect to ${targetPeerId.substring(0, 8)}...: ${error.message}` });
155
- this.cleanupFailedConnection(targetPeerId);
156
- }
175
+ // Double-check that the peer is actually removed from the UI
176
+ if (this.peers.has(peerId)) {
177
+ console.warn(`Peer ${peerId.substring(0, 8)}... still in peers Map after timeout cleanup, force removing`);
178
+ this.peers.delete(peerId);
179
+ this.emit('peersUpdated');
157
180
  }
181
+ }
158
182
 
159
- handleConnectionTimeout(peerId) {
160
- console.log(`Connection timeout for ${peerId.substring(0, 8)}...`);
161
-
162
- const attempts = this.connectionAttempts.get(peerId) || 0;
163
- if (attempts >= this.maxConnectionAttempts) {
164
- this.mesh.emit('statusChanged', { type: 'warning', message: `Removing unresponsive peer ${peerId.substring(0, 8)}... after ${attempts} attempts` });
165
- this.mesh.peerDiscovery.removeDiscoveredPeer(peerId);
166
- this.connectionAttempts.delete(peerId);
167
- } else {
168
- this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
169
- console.log(`Will retry connection to ${peerId.substring(0, 8)}... (attempt ${attempts}/${this.maxConnectionAttempts})`);
170
- }
171
-
172
- // Always cleanup the failed connection and ensure it's removed from peers Map
173
- this.cleanupFailedConnection(peerId);
174
-
175
- // Double-check that the peer is actually removed from the UI
176
- if (this.peers.has(peerId)) {
177
- console.warn(`Peer ${peerId.substring(0, 8)}... still in peers Map after timeout cleanup, force removing`);
178
- this.peers.delete(peerId);
179
- this.emit('peersUpdated');
180
- }
183
+ cleanupFailedConnection(peerId) {
184
+ console.log(`Cleaning up failed connection for ${peerId.substring(0, 8)}...`);
185
+
186
+ // Clear timeout
187
+ const timeoutId = this.connectionTimeouts.get(peerId);
188
+ if (timeoutId) {
189
+ clearTimeout(timeoutId);
190
+ this.connectionTimeouts.delete(peerId);
191
+ console.log(`Cleared timeout for ${peerId.substring(0, 8)}...`);
181
192
  }
182
193
 
183
- cleanupFailedConnection(peerId) {
184
- console.log(`Cleaning up failed connection for ${peerId.substring(0, 8)}...`);
185
-
186
- // Clear timeout
187
- const timeoutId = this.connectionTimeouts.get(peerId);
188
- if (timeoutId) {
189
- clearTimeout(timeoutId);
190
- this.connectionTimeouts.delete(peerId);
191
- console.log(`Cleared timeout for ${peerId.substring(0, 8)}...`);
192
- }
193
-
194
- // Remove peer connection
195
- let peerRemoved = false;
196
- if (this.peers.has(peerId)) {
197
- const peer = this.peers.get(peerId);
198
- const status = peer.getStatus();
199
- console.log(`Removing peer ${peerId.substring(0, 8)}... with status: ${status}`);
200
-
201
- try {
202
- if (typeof peer.markAsFailed === 'function') {
203
- peer.markAsFailed('failed');
204
- }
205
- peer.close();
206
- } catch (error) {
207
- console.error('Error closing failed connection:', error);
208
- }
209
- this.peers.delete(peerId);
210
- peerRemoved = true;
211
- console.log(`Successfully removed peer ${peerId.substring(0, 8)}... from peers Map`);
212
- } else {
213
- console.log(`Peer ${peerId.substring(0, 8)}... was not in peers Map`);
214
- }
215
-
216
- // Clean up related data
217
- this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
218
- this.pendingIceCandidates.delete(peerId);
219
-
220
- // Always emit peersUpdated if we removed a peer or to force UI refresh
221
- if (peerRemoved) {
222
- console.log(`Emitting peersUpdated after removing ${peerId.substring(0, 8)}...`);
223
- this.emit('peersUpdated');
224
- }
194
+ // Remove peer connection
195
+ let peerRemoved = false;
196
+ if (this.peers.has(peerId)) {
197
+ const peer = this.peers.get(peerId);
198
+ const status = peer.getStatus();
199
+ console.log(`Removing peer ${peerId.substring(0, 8)}... with status: ${status}`);
200
+
201
+ try {
202
+ if (typeof peer.markAsFailed === 'function') {
203
+ peer.markAsFailed('failed');
204
+ }
205
+ peer.close();
206
+ } catch (error) {
207
+ console.error('Error closing failed connection:', error);
208
+ }
209
+ this.peers.delete(peerId);
210
+ peerRemoved = true;
211
+ console.log(`Successfully removed peer ${peerId.substring(0, 8)}... from peers Map`);
212
+ } else {
213
+ console.log(`Peer ${peerId.substring(0, 8)}... was not in peers Map`);
225
214
  }
226
215
 
227
- cleanupRaceCondition(peerId) {
228
- // Clear timeout
229
- const timeoutId = this.connectionTimeouts.get(peerId);
230
- if (timeoutId) {
231
- clearTimeout(timeoutId);
232
- this.connectionTimeouts.delete(peerId);
233
- }
234
-
235
- // Remove peer connection but preserve connection attempts
236
- if (this.peers.has(peerId)) {
237
- const peer = this.peers.get(peerId);
238
- try {
239
- peer.close();
240
- } catch (error) {
241
- console.error('Error closing race condition connection:', error);
242
- }
243
- this.peers.delete(peerId);
244
- }
245
-
246
- // Don't clear connection attempts or discovery data - just the active connection
247
- this.pendingIceCandidates.delete(peerId);
248
- this.emit('peersUpdated');
249
- }
250
-
251
- setupPeerConnectionHandlers(peerConnection) {
252
- peerConnection.addEventListener('iceCandidate', async (event) => {
253
- try {
254
- console.log('Sending ICE candidate to', event.peerId);
255
- await this.mesh.signalingClient.sendSignalingMessage({
256
- type: 'ice-candidate',
257
- data: event.candidate,
258
- targetPeerId: event.peerId
259
- });
260
- } catch (error) {
261
- console.error('Failed to send ICE candidate:', error);
262
- }
263
- });
216
+ // Clean up related data
217
+ this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
218
+ this.pendingIceCandidates.delete(peerId);
264
219
 
265
- peerConnection.addEventListener('connected', (event) => {
266
- console.log(`[EVENT] Connected event received from ${event.peerId.substring(0, 8)}...`);
267
-
268
- // Clear connection timeout on successful connection
269
- const timeoutId = this.connectionTimeouts.get(event.peerId);
270
- if (timeoutId) {
271
- clearTimeout(timeoutId);
272
- this.connectionTimeouts.delete(event.peerId);
273
- }
274
-
275
- // Reset connection attempts on successful connection
276
- this.connectionAttempts.delete(event.peerId);
277
-
278
- // Don't emit peerConnected here - wait for data channel to be ready
279
- this.mesh.emit('statusChanged', { type: 'info', message: `WebRTC connected to ${event.peerId.substring(0, 8)}...` });
280
- this.mesh.peerDiscovery.clearConnectionAttempt(event.peerId);
281
- this.mesh.peerDiscovery.updateDiscoveryTimestamp(event.peerId);
282
-
283
- this.emit('peersUpdated');
284
- });
220
+ // Always emit peersUpdated if we removed a peer or to force UI refresh
221
+ if (peerRemoved) {
222
+ console.log(`Emitting peersUpdated after removing ${peerId.substring(0, 8)}...`);
223
+ this.emit('peersUpdated');
224
+ }
225
+ }
226
+
227
+ cleanupRaceCondition(peerId) {
228
+ // Clear timeout
229
+ const timeoutId = this.connectionTimeouts.get(peerId);
230
+ if (timeoutId) {
231
+ clearTimeout(timeoutId);
232
+ this.connectionTimeouts.delete(peerId);
233
+ }
285
234
 
286
- peerConnection.addEventListener('disconnected', (event) => {
287
- this.mesh.emit('statusChanged', { type: 'info', message: `Disconnected from ${event.peerId.substring(0, 8)}...` });
288
- this.handlePeerDisconnection(event.peerId, event.reason);
289
- });
235
+ // Remove peer connection but preserve connection attempts
236
+ if (this.peers.has(peerId)) {
237
+ const peer = this.peers.get(peerId);
238
+ try {
239
+ peer.close();
240
+ } catch (error) {
241
+ console.error('Error closing race condition connection:', error);
242
+ }
243
+ this.peers.delete(peerId);
244
+ }
290
245
 
291
- peerConnection.addEventListener('dataChannelOpen', (event) => {
292
- console.log(`[EVENT] DataChannelOpen event received from ${event.peerId.substring(0, 8)}...`);
293
-
294
- this.mesh.emit('statusChanged', { type: 'info', message: `Data channel ready with ${event.peerId.substring(0, 8)}...` });
295
- this.emit('peersUpdated');
296
- this.mesh.emit('peerConnected', { peerId: event.peerId });
246
+ // Don't clear connection attempts or discovery data - just the active connection
247
+ this.pendingIceCandidates.delete(peerId);
248
+ this.emit('peersUpdated');
249
+ }
250
+
251
+ setupPeerConnectionHandlers(peerConnection) {
252
+ peerConnection.addEventListener('iceCandidate', async (event) => {
253
+ try {
254
+ console.log('Sending ICE candidate to', event.peerId);
255
+ await this.mesh.signalingClient.sendSignalingMessage({
256
+ type: 'ice-candidate',
257
+ data: event.candidate,
258
+ targetPeerId: event.peerId
297
259
  });
260
+ } catch (error) {
261
+ console.error('Failed to send ICE candidate:', error);
262
+ }
263
+ });
264
+
265
+ peerConnection.addEventListener('connected', (event) => {
266
+ console.log(`[EVENT] Connected event received from ${event.peerId.substring(0, 8)}...`);
267
+
268
+ // Clear connection timeout on successful connection
269
+ const timeoutId = this.connectionTimeouts.get(event.peerId);
270
+ if (timeoutId) {
271
+ clearTimeout(timeoutId);
272
+ this.connectionTimeouts.delete(event.peerId);
273
+ }
274
+
275
+ // Reset connection attempts on successful connection
276
+ this.connectionAttempts.delete(event.peerId);
277
+
278
+ // Don't emit peerConnected here - wait for data channel to be ready
279
+ this.mesh.emit('statusChanged', { type: 'info', message: `WebRTC connected to ${event.peerId.substring(0, 8)}...` });
280
+ this.mesh.peerDiscovery.clearConnectionAttempt(event.peerId);
281
+ this.mesh.peerDiscovery.updateDiscoveryTimestamp(event.peerId);
282
+
283
+ this.emit('peersUpdated');
284
+ });
285
+
286
+ peerConnection.addEventListener('disconnected', (event) => {
287
+ this.mesh.emit('statusChanged', { type: 'info', message: `Disconnected from ${event.peerId.substring(0, 8)}...` });
288
+ this.handlePeerDisconnection(event.peerId, event.reason);
289
+ });
290
+
291
+ peerConnection.addEventListener('dataChannelOpen', (event) => {
292
+ console.log(`[EVENT] DataChannelOpen event received from ${event.peerId.substring(0, 8)}...`);
293
+
294
+ this.mesh.emit('statusChanged', { type: 'info', message: `Data channel ready with ${event.peerId.substring(0, 8)}...` });
295
+ this.emit('peersUpdated');
296
+
297
+ // Track successful connections to reset isolation timer
298
+ if (this.mesh.peerDiscovery) {
299
+ this.mesh.peerDiscovery.onConnectionEstablished();
300
+ }
301
+
302
+ // Automatically initiate key exchange when crypto is enabled
303
+ if (this.mesh.cryptoManager) {
304
+ console.log(`🔐 Automatically exchanging keys with newly connected peer ${event.peerId.substring(0, 8)}...`);
305
+ // Use setTimeout to ensure the connection is fully established
306
+ setTimeout(() => {
307
+ this.mesh.exchangeKeysWithPeer(event.peerId).catch(error => {
308
+ console.error(`🔐 Failed to exchange keys with ${event.peerId.substring(0, 8)}:`, error);
309
+ });
310
+ }, 100);
311
+ }
312
+
313
+ this.mesh.emit('peerConnected', { peerId: event.peerId });
314
+ });
315
+
316
+ peerConnection.addEventListener('message', (event) => {
317
+ this.handleIncomingMessage(event.message, event.peerId);
318
+ });
319
+
320
+ peerConnection.addEventListener('remoteStream', (event) => {
321
+ console.log(`[EVENT] Remote stream received from ${event.peerId.substring(0, 8)}...`);
322
+ this.emit('remoteStream', event);
323
+ });
324
+
325
+ peerConnection.addEventListener('renegotiationNeeded', async (event) => {
326
+ console.log(`🔄 Renegotiation needed for ${event.peerId.substring(0, 8)}...`);
327
+
328
+ try {
329
+ // Check connection state before attempting renegotiation
330
+ if (peerConnection.connection.signalingState !== 'stable') {
331
+ console.log(`Skipping renegotiation for ${event.peerId.substring(0, 8)}... - connection not stable (${peerConnection.connection.signalingState})`);
332
+ return;
333
+ }
334
+
335
+ // Additional check for connection state
336
+ if (peerConnection.connection.connectionState !== 'connected') {
337
+ console.log(`Skipping renegotiation for ${event.peerId.substring(0, 8)}... - not connected (${peerConnection.connection.connectionState})`);
338
+ return;
339
+ }
340
+
341
+ console.log(`🔄 Creating renegotiation offer for ${event.peerId.substring(0, 8)}...`);
342
+
343
+ // Create new offer with restartIce flag to avoid m-line issues
344
+ const offerOptions = {
345
+ iceRestart: false, // Don't restart ICE unless necessary
346
+ offerToReceiveAudio: true,
347
+ offerToReceiveVideo: true
348
+ };
298
349
 
299
- peerConnection.addEventListener('message', (event) => {
300
- this.handleIncomingMessage(event.message, event.peerId);
301
- });
350
+ const offer = await peerConnection.connection.createOffer(offerOptions);
351
+ await peerConnection.connection.setLocalDescription(offer);
302
352
 
303
- peerConnection.addEventListener('remoteStream', (event) => {
304
- console.log(`[EVENT] Remote stream received from ${event.peerId.substring(0, 8)}...`);
305
- this.emit('remoteStream', event);
353
+ // Send the new offer to the peer using the correct signaling method
354
+ await this.mesh.signalingClient.sendSignalingMessage({
355
+ type: 'offer',
356
+ data: offer,
357
+ targetPeerId: event.peerId
306
358
  });
307
359
 
308
- peerConnection.addEventListener('renegotiationNeeded', async (event) => {
309
- console.log(`🔄 Renegotiation needed for ${event.peerId.substring(0, 8)}...`);
310
-
311
- try {
312
- // Check connection state before attempting renegotiation
313
- if (peerConnection.connection.signalingState !== 'stable') {
314
- console.log(`Skipping renegotiation for ${event.peerId.substring(0, 8)}... - connection not stable (${peerConnection.connection.signalingState})`);
315
- return;
316
- }
317
-
318
- // Additional check for connection state
319
- if (peerConnection.connection.connectionState !== 'connected') {
320
- console.log(`Skipping renegotiation for ${event.peerId.substring(0, 8)}... - not connected (${peerConnection.connection.connectionState})`);
321
- return;
322
- }
323
-
324
- console.log(`🔄 Creating renegotiation offer for ${event.peerId.substring(0, 8)}...`);
325
-
326
- // Create new offer with restartIce flag to avoid m-line issues
327
- const offerOptions = {
328
- iceRestart: false, // Don't restart ICE unless necessary
329
- offerToReceiveAudio: true,
330
- offerToReceiveVideo: true
331
- };
332
-
333
- const offer = await peerConnection.connection.createOffer(offerOptions);
334
- await peerConnection.connection.setLocalDescription(offer);
335
-
336
- // Send the new offer to the peer using the correct signaling method
337
- await this.mesh.signalingClient.sendSignalingMessage({
338
- type: 'offer',
339
- data: offer,
340
- targetPeerId: event.peerId
341
- });
342
-
343
- console.log(`🔄 Sent renegotiation offer to ${event.peerId.substring(0, 8)}...`);
344
- } catch (error) {
345
- console.error(`Failed to renegotiate with ${event.peerId}:`, error);
346
-
347
- // If renegotiation fails due to m-line order, log but don't crash
348
- if (error.name === 'InvalidAccessError' && error.message.includes('m-line')) {
349
- console.log(`🔄 M-line order error detected for ${event.peerId.substring(0, 8)}... - this is expected with replaceTrack approach`);
350
- }
351
- }
352
- });
360
+ console.log(`🔄 Sent renegotiation offer to ${event.peerId.substring(0, 8)}...`);
361
+ } catch (error) {
362
+ console.error(`Failed to renegotiate with ${event.peerId}:`, error);
353
363
 
354
- // ...existing code...
364
+ // If renegotiation fails due to m-line order, log but don't crash
365
+ if (error.name === 'InvalidAccessError' && error.message.includes('m-line')) {
366
+ console.log(`🔄 M-line order error detected for ${event.peerId.substring(0, 8)}... - this is expected with replaceTrack approach`);
367
+ }
368
+ }
369
+ });
370
+
371
+ // ...existing code...
372
+ }
373
+
374
+ handlePeerDisconnection(peerId, reason) {
375
+ // Prevent duplicate disconnection handling
376
+ if (this.disconnectionInProgress.has(peerId)) {
377
+ console.log(`Disconnection already in progress for ${peerId.substring(0, 8)}..., skipping duplicate`);
378
+ return;
355
379
  }
356
380
 
357
- handlePeerDisconnection(peerId, reason) {
358
- // Prevent duplicate disconnection handling
359
- if (this.disconnectionInProgress.has(peerId)) {
360
- console.log(`Disconnection already in progress for ${peerId.substring(0, 8)}..., skipping duplicate`);
361
- return;
362
- }
363
-
364
- console.log(`Handling peer disconnection: ${peerId.substring(0, 8)}... (${reason})`);
365
-
366
- // Mark disconnection in progress
367
- this.disconnectionInProgress.add(peerId);
368
-
381
+ console.log(`Handling peer disconnection: ${peerId.substring(0, 8)}... (${reason})`);
382
+
383
+ // Mark disconnection in progress
384
+ this.disconnectionInProgress.add(peerId);
385
+
386
+ try {
387
+ // Clear all related data
388
+ const timeoutId = this.connectionTimeouts.get(peerId);
389
+ if (timeoutId) {
390
+ clearTimeout(timeoutId);
391
+ this.connectionTimeouts.delete(peerId);
392
+ }
393
+
394
+ if (this.peers.has(peerId)) {
395
+ const peerConnection = this.peers.get(peerId);
396
+
369
397
  try {
370
- // Clear all related data
371
- const timeoutId = this.connectionTimeouts.get(peerId);
372
- if (timeoutId) {
373
- clearTimeout(timeoutId);
374
- this.connectionTimeouts.delete(peerId);
375
- }
376
-
377
- if (this.peers.has(peerId)) {
378
- const peerConnection = this.peers.get(peerId);
379
-
380
- try {
381
- peerConnection.close();
382
- } catch (error) {
383
- console.error('Error closing peer connection:', error);
384
- }
385
-
386
- this.peers.delete(peerId);
387
- }
388
-
389
- this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
390
- this.pendingIceCandidates.delete(peerId);
391
-
392
- // Clean up eviction tracking
393
- this.mesh.evictionManager.clearEvictionTracking(peerId);
394
-
395
- // Don't remove from discovered peers immediately - let it timeout naturally
396
- // unless it's a goodbye or explicit removal
397
- if (reason === 'left network' || reason === 'manually removed') {
398
- this.mesh.peerDiscovery.removeDiscoveredPeer(peerId);
399
- this.connectionAttempts.delete(peerId);
400
- } else if (reason === 'connection failed' || reason === 'connection disconnected' || reason === 'ICE connection closed') {
401
- // For connection failures, clear the attempt so we can retry later
402
- this.connectionAttempts.delete(peerId);
403
- console.log(`Cleared connection attempt for ${peerId.substring(0, 8)}... due to ${reason} - will retry later`);
404
- }
405
-
406
- this.mesh.emit('peerDisconnected', { peerId, reason });
407
- this.emit('peersUpdated');
408
-
409
- // Only trigger optimization if we're significantly under capacity
410
- const connectedCount = this.getConnectedPeerCount();
411
- const needsOptimization = connectedCount === 0; // Only optimize if completely disconnected
412
-
413
- if (needsOptimization && this.mesh.autoDiscovery && this.mesh.peerDiscovery.getDiscoveredPeers().length > 0) {
414
- console.log(`Completely disconnected (${connectedCount}/${this.mesh.maxPeers}), scheduling mesh optimization`);
415
- setTimeout(() => {
416
- // Check if we still need optimization
417
- const currentCount = this.getConnectedPeerCount();
418
- if (currentCount === 0) {
419
- console.log(`Still completely disconnected (${currentCount}/${this.mesh.maxPeers}), attempting optimization`);
420
- this.mesh.peerDiscovery.optimizeMeshConnections(this.peers);
421
- } else {
422
- console.log(`Connection recovered (${currentCount}/${this.mesh.maxPeers}), skipping optimization`);
423
- }
424
- }, 2000); // Wait 2 seconds before optimizing to allow connections to stabilize
425
- } else {
426
- console.log(`Peer count appropriate at ${connectedCount}/${this.mesh.maxPeers}, no optimization needed`);
427
- }
428
- } finally {
429
- // Always clean up the disconnection tracking
430
- this.disconnectionInProgress.delete(peerId);
398
+ peerConnection.close();
399
+ } catch (error) {
400
+ console.error('Error closing peer connection:', error);
431
401
  }
432
- }
433
402
 
434
- disconnectAllPeers() {
435
- this.peers.forEach((peerConnection, peerId) => {
436
- peerConnection.close();
437
- this.mesh.emit('peerDisconnected', { peerId, reason: 'mesh disconnected' });
438
- });
439
- }
403
+ this.peers.delete(peerId);
404
+ }
440
405
 
441
- disconnectPeer(peerId, reason) {
442
- this.handlePeerDisconnection(peerId, reason);
443
- }
406
+ this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
407
+ this.pendingIceCandidates.delete(peerId);
444
408
 
445
- removePeer(peerId) {
409
+ // Clean up eviction tracking
410
+ this.mesh.evictionManager.clearEvictionTracking(peerId);
411
+
412
+ // Don't remove from discovered peers immediately - let it timeout naturally
413
+ // unless it's a goodbye or explicit removal
414
+ if (reason === 'left network' || reason === 'manually removed') {
446
415
  this.mesh.peerDiscovery.removeDiscoveredPeer(peerId);
447
- this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
448
416
  this.connectionAttempts.delete(peerId);
449
-
450
- // Clear timeout if exists
451
- const timeoutId = this.connectionTimeouts.get(peerId);
452
- if (timeoutId) {
453
- clearTimeout(timeoutId);
454
- this.connectionTimeouts.delete(peerId);
455
- }
456
-
457
- if (this.peers.has(peerId)) {
458
- const peer = this.peers.get(peerId);
459
- if (peer.connection) {
460
- peer.connection.close();
461
- }
462
- this.peers.delete(peerId);
463
- this.mesh.emit('peerDisconnected', { peerId, reason: 'manually removed' });
464
- }
465
-
466
- this.emit('peersUpdated');
417
+ } else if (reason === 'connection failed' || reason === 'connection disconnected' || reason === 'ICE connection closed') {
418
+ // For connection failures, clear the attempt so we can retry later
419
+ this.connectionAttempts.delete(peerId);
420
+ console.log(`Cleared connection attempt for ${peerId.substring(0, 8)}... due to ${reason} - will retry later`);
421
+ }
422
+
423
+ this.mesh.emit('peerDisconnected', { peerId, reason });
424
+ this.emit('peersUpdated');
425
+
426
+ // Only trigger optimization if we're significantly under capacity
427
+ const connectedCount = this.getConnectedPeerCount();
428
+ const needsOptimization = connectedCount === 0; // Only optimize if completely disconnected
429
+
430
+ if (needsOptimization && this.mesh.autoDiscovery && this.mesh.peerDiscovery.getDiscoveredPeers().length > 0) {
431
+ console.log(`Completely disconnected (${connectedCount}/${this.mesh.maxPeers}), scheduling mesh optimization`);
432
+ setTimeout(() => {
433
+ // Check if we still need optimization
434
+ const currentCount = this.getConnectedPeerCount();
435
+ if (currentCount === 0) {
436
+ console.log(`Still completely disconnected (${currentCount}/${this.mesh.maxPeers}), attempting optimization`);
437
+ this.mesh.peerDiscovery.optimizeMeshConnections(this.peers);
438
+ } else {
439
+ console.log(`Connection recovered (${currentCount}/${this.mesh.maxPeers}), skipping optimization`);
440
+ }
441
+ }, 2000); // Wait 2 seconds before optimizing to allow connections to stabilize
442
+ } else {
443
+ console.log(`Peer count appropriate at ${connectedCount}/${this.mesh.maxPeers}, no optimization needed`);
444
+ }
445
+ } finally {
446
+ // Always clean up the disconnection tracking
447
+ this.disconnectionInProgress.delete(peerId);
467
448
  }
468
-
469
- canAcceptMorePeers() {
470
- // Count connected peers first (these are guaranteed slots)
471
- const connectedCount = this.getConnectedPeerCount();
472
-
473
- // If we have room for connected peers, always accept
474
- if (connectedCount < this.mesh.maxPeers) {
475
- return true;
476
- }
477
-
478
- // If at max connected peers, check if we have stale peers we can evict
479
- const stalePeerCount = this.getStalePeerCount();
480
- const totalPeerCount = this.peers.size;
481
-
482
- // Accept if we have stale peers that can be cleaned up
483
- if (stalePeerCount > 0 && totalPeerCount >= this.mesh.maxPeers) {
484
- console.log(`At capacity (${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total) but have ${stalePeerCount} stale peers that can be evicted`);
485
- return true;
486
- }
487
-
488
- // Reject if we're at capacity with all viable peers
489
- console.log(`Cannot accept more peers: ${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers in Map`);
490
- return false;
449
+ }
450
+
451
+ disconnectAllPeers() {
452
+ this.peers.forEach((peerConnection, peerId) => {
453
+ peerConnection.close();
454
+ this.mesh.emit('peerDisconnected', { peerId, reason: 'mesh disconnected' });
455
+ });
456
+ }
457
+
458
+ disconnectPeer(peerId, reason) {
459
+ this.handlePeerDisconnection(peerId, reason);
460
+ }
461
+
462
+ removePeer(peerId) {
463
+ this.mesh.peerDiscovery.removeDiscoveredPeer(peerId);
464
+ this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
465
+ this.connectionAttempts.delete(peerId);
466
+
467
+ // Clear timeout if exists
468
+ const timeoutId = this.connectionTimeouts.get(peerId);
469
+ if (timeoutId) {
470
+ clearTimeout(timeoutId);
471
+ this.connectionTimeouts.delete(peerId);
491
472
  }
492
473
 
493
- /**
494
- * Count peers that are in stale/non-viable states
495
- */
496
- getStalePeerCount() {
497
- const now = Date.now();
498
- const STALE_THRESHOLD = 45000; // 45 seconds (shorter than cleanup threshold)
499
-
500
- return Array.from(this.peers.values()).filter(peerConnection => {
501
- const status = peerConnection.getStatus();
502
- const connectionAge = now - peerConnection.connectionStartTime;
503
-
504
- return connectionAge > STALE_THRESHOLD &&
505
- (status === 'failed' || status === 'disconnected' || status === 'closed');
506
- }).length;
474
+ if (this.peers.has(peerId)) {
475
+ const peer = this.peers.get(peerId);
476
+ if (peer.connection) {
477
+ peer.connection.close();
478
+ }
479
+ this.peers.delete(peerId);
480
+ this.mesh.emit('peerDisconnected', { peerId, reason: 'manually removed' });
507
481
  }
508
482
 
509
- getConnectedPeerCount() {
510
- return Array.from(this.peers.values()).filter(peerConnection =>
511
- peerConnection.getStatus() === 'connected'
512
- ).length;
513
- }
483
+ this.emit('peersUpdated');
484
+ }
514
485
 
515
- getConnectedPeers() {
516
- return Array.from(this.peers.values()).filter(peerConnection =>
517
- peerConnection.getStatus() === 'connected'
518
- );
519
- }
486
+ canAcceptMorePeers() {
487
+ // Count connected peers first (these are guaranteed slots)
488
+ const connectedCount = this.getConnectedPeerCount();
520
489
 
521
- getPeers() {
522
- return Array.from(this.peers.entries()).map(([peerId, peerConnection]) => ({
523
- peerId,
524
- status: peerConnection.getStatus(),
525
- isInitiator: peerConnection.isInitiator,
526
- connectionStartTime: peerConnection.connectionStartTime
527
- }));
490
+ // If we have room for connected peers, always accept
491
+ if (connectedCount < this.mesh.maxPeers) {
492
+ return true;
528
493
  }
529
494
 
530
- hasPeer(peerId) {
531
- return this.peers.has(peerId);
532
- }
495
+ // If at max connected peers, check if we have stale peers we can evict
496
+ const stalePeerCount = this.getStalePeerCount();
497
+ const totalPeerCount = this.peers.size;
533
498
 
534
- getPeer(peerId) {
535
- return this.peers.get(peerId);
499
+ // Accept if we have stale peers that can be cleaned up
500
+ if (stalePeerCount > 0 && totalPeerCount >= this.mesh.maxPeers) {
501
+ console.log(`At capacity (${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total) but have ${stalePeerCount} stale peers that can be evicted`);
502
+ return true;
536
503
  }
537
504
 
538
- sendMessage(content) {
539
- if (!content || typeof content !== 'string') {
540
- console.error('Invalid message content:', content);
541
- return 0;
542
- }
505
+ // Reject if we're at capacity with all viable peers
506
+ console.log(`Cannot accept more peers: ${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers in Map`);
507
+ return false;
508
+ }
543
509
 
544
- // Use gossip protocol to broadcast messages throughout the mesh network
545
- console.log(`Broadcasting message via gossip protocol: "${content}"`);
546
- const messageId = this.mesh.gossipManager.broadcastMessage(content, 'chat');
547
-
548
- if (messageId) {
549
- // Return the number of directly connected peers for UI feedback
550
- // (the message will propagate to the entire network via gossip)
551
- const connectedCount = this.getConnectedPeerCount();
552
- console.log(`Message broadcasted via gossip to ${connectedCount} directly connected peer(s), will propagate to entire network`);
553
- return connectedCount;
554
- } else {
555
- console.error('Failed to broadcast message via gossip protocol');
556
- return 0;
557
- }
510
+ /**
511
+ * Count peers that are in stale/non-viable states
512
+ */
513
+ getStalePeerCount() {
514
+ const now = Date.now();
515
+ const STALE_THRESHOLD = 45000; // 45 seconds (shorter than cleanup threshold)
516
+
517
+ return Array.from(this.peers.values()).filter(peerConnection => {
518
+ const status = peerConnection.getStatus();
519
+ const connectionAge = now - peerConnection.connectionStartTime;
520
+
521
+ return connectionAge > STALE_THRESHOLD &&
522
+ (status === 'failed' || status === 'disconnected' || status === 'closed');
523
+ }).length;
524
+ }
525
+
526
+ getConnectedPeerCount() {
527
+ return Array.from(this.peers.values()).filter(peerConnection =>
528
+ peerConnection.getStatus() === 'connected'
529
+ ).length;
530
+ }
531
+
532
+ getConnectedPeers() {
533
+ return Array.from(this.peers.values()).filter(peerConnection =>
534
+ peerConnection.getStatus() === 'connected'
535
+ );
536
+ }
537
+
538
+ getPeers() {
539
+ return Array.from(this.peers.entries()).map(([peerId, peerConnection]) => ({
540
+ peerId,
541
+ status: peerConnection.getStatus(),
542
+ isInitiator: peerConnection.isInitiator,
543
+ connectionStartTime: peerConnection.connectionStartTime
544
+ }));
545
+ }
546
+
547
+ hasPeer(peerId) {
548
+ return this.peers.has(peerId);
549
+ }
550
+
551
+ getPeer(peerId) {
552
+ return this.peers.get(peerId);
553
+ }
554
+
555
+ sendMessage(content) {
556
+ if (!content || typeof content !== 'string') {
557
+ console.error('Invalid message content:', content);
558
+ return 0;
559
+ }
560
+
561
+ // Use gossip protocol to broadcast messages throughout the mesh network
562
+ console.log(`Broadcasting message via gossip protocol: "${content}"`);
563
+ const messageId = this.mesh.gossipManager.broadcastMessage(content, 'chat');
564
+
565
+ if (messageId) {
566
+ // Return the number of directly connected peers for UI feedback
567
+ // (the message will propagate to the entire network via gossip)
568
+ const connectedCount = this.getConnectedPeerCount();
569
+ console.log(`Message broadcasted via gossip to ${connectedCount} directly connected peer(s), will propagate to entire network`);
570
+ return connectedCount;
571
+ } else {
572
+ console.error('Failed to broadcast message via gossip protocol');
573
+ return 0;
558
574
  }
575
+ }
559
576
 
560
- /**
577
+ /**
561
578
  * Send a message directly to a specific peer via data channel
562
579
  * @param {string} peerId - The peer ID to send to
563
580
  * @param {Object} message - The message object to send
564
581
  * @returns {boolean} - True if message was sent successfully
565
582
  */
566
- sendDirectMessage(peerId, message) {
567
- const peerConnection = this.peers.get(peerId);
568
- if (!peerConnection) {
569
- console.warn(`Cannot send direct message to ${peerId?.substring(0, 8)}: peer not connected`);
570
- return false;
571
- }
572
-
573
- try {
574
- console.log(`📤 Sending direct message to ${peerId?.substring(0, 8)}:`, message);
575
- peerConnection.sendMessage(message);
576
- return true;
577
- } catch (error) {
578
- console.error(`Failed to send direct message to ${peerId?.substring(0, 8)}:`, error);
579
- return false;
580
- }
583
+ sendDirectMessage(peerId, message) {
584
+ const peerConnection = this.peers.get(peerId);
585
+ if (!peerConnection) {
586
+ console.warn(`Cannot send direct message to ${peerId?.substring(0, 8)}: peer not connected`);
587
+ return false;
581
588
  }
582
589
 
583
- async handleIceCandidate(candidate, fromPeerId) {
584
- console.log('Handling ICE candidate from', fromPeerId);
585
-
586
- const peerConnection = this.peers.get(fromPeerId);
587
- if (peerConnection) {
588
- try {
589
- await peerConnection.handleIceCandidate(candidate);
590
- } catch (error) {
591
- console.error('Failed to add ICE candidate:', error);
592
- }
593
- } else {
594
- // No peer connection exists yet - buffer the candidate for when it's created
595
- console.log('Buffering ICE candidate for', fromPeerId, '(no peer connection yet)');
596
- if (!this.pendingIceCandidates.has(fromPeerId)) {
597
- this.pendingIceCandidates.set(fromPeerId, []);
598
- }
599
- this.pendingIceCandidates.get(fromPeerId).push(candidate);
600
- }
590
+ try {
591
+ console.log(`📤 Sending direct message to ${peerId?.substring(0, 8)}:`, message);
592
+ peerConnection.sendMessage(message);
593
+ return true;
594
+ } catch (error) {
595
+ console.error(`Failed to send direct message to ${peerId?.substring(0, 8)}:`, error);
596
+ return false;
597
+ }
598
+ }
599
+
600
+ async handleIceCandidate(candidate, fromPeerId) {
601
+ console.log('Handling ICE candidate from', fromPeerId);
602
+
603
+ const peerConnection = this.peers.get(fromPeerId);
604
+ if (peerConnection) {
605
+ try {
606
+ await peerConnection.handleIceCandidate(candidate);
607
+ } catch (error) {
608
+ console.error('Failed to add ICE candidate:', error);
609
+ }
610
+ } else {
611
+ // No peer connection exists yet - buffer the candidate for when it's created
612
+ console.log('Buffering ICE candidate for', fromPeerId, '(no peer connection yet)');
613
+ if (!this.pendingIceCandidates.has(fromPeerId)) {
614
+ this.pendingIceCandidates.set(fromPeerId, []);
615
+ }
616
+ this.pendingIceCandidates.get(fromPeerId).push(candidate);
601
617
  }
618
+ }
602
619
 
603
- async processPendingIceCandidates(peerId) {
604
- const candidates = this.pendingIceCandidates.get(peerId);
605
- if (candidates && candidates.length > 0) {
606
- console.log(`Processing ${candidates.length} buffered ICE candidates for`, peerId);
607
- const peerConnection = this.peers.get(peerId);
608
-
609
- if (peerConnection) {
610
- for (const candidate of candidates) {
611
- try {
612
- await peerConnection.handleIceCandidate(candidate);
613
- } catch (error) {
614
- console.error('Failed to add buffered ICE candidate:', error);
615
- }
616
- }
617
-
618
- // Clear the buffer after processing
619
- this.pendingIceCandidates.delete(peerId);
620
- }
620
+ async processPendingIceCandidates(peerId) {
621
+ const candidates = this.pendingIceCandidates.get(peerId);
622
+ if (candidates && candidates.length > 0) {
623
+ console.log(`Processing ${candidates.length} buffered ICE candidates for`, peerId);
624
+ const peerConnection = this.peers.get(peerId);
625
+
626
+ if (peerConnection) {
627
+ for (const candidate of candidates) {
628
+ try {
629
+ await peerConnection.handleIceCandidate(candidate);
630
+ } catch (error) {
631
+ console.error('Failed to add buffered ICE candidate:', error);
632
+ }
621
633
  }
622
- }
623
634
 
624
- cleanup() {
625
- // Stop periodic cleanup
626
- this.stopPeriodicCleanup();
627
-
628
- this.peers.clear();
629
- this.connectionAttempts.clear();
630
- this.connectionTimeouts.clear();
631
- this.pendingIceCandidates.clear();
632
- this.disconnectionInProgress.clear();
633
- this.cleanupInProgress.clear();
634
- this.lastConnectionAttempt.clear();
635
+ // Clear the buffer after processing
636
+ this.pendingIceCandidates.delete(peerId);
637
+ }
635
638
  }
636
-
637
- /**
639
+ }
640
+
641
+ cleanup() {
642
+ // Stop periodic cleanup
643
+ this.stopPeriodicCleanup();
644
+
645
+ this.peers.clear();
646
+ this.connectionAttempts.clear();
647
+ this.connectionTimeouts.clear();
648
+ this.pendingIceCandidates.clear();
649
+ this.disconnectionInProgress.clear();
650
+ this.cleanupInProgress.clear();
651
+ this.lastConnectionAttempt.clear();
652
+ }
653
+
654
+ /**
638
655
  * Start periodic cleanup of stale peer connections
639
656
  */
640
- startPeriodicCleanup() {
641
- if (this.cleanupInterval) {
642
- clearInterval(this.cleanupInterval);
643
- }
644
-
645
- // Run cleanup every 30 seconds - environment-aware timer
646
- if (environmentDetector.isBrowser) {
647
- this.cleanupInterval = window.setInterval(() => {
648
- this.cleanupStalePeers();
649
- }, 30000);
650
- } else {
651
- this.cleanupInterval = setInterval(() => {
652
- this.cleanupStalePeers();
653
- }, 30000);
654
- }
657
+ startPeriodicCleanup() {
658
+ if (this.cleanupInterval) {
659
+ clearInterval(this.cleanupInterval);
655
660
  }
656
661
 
657
- /**
662
+ // Run cleanup every 30 seconds - environment-aware timer
663
+ if (environmentDetector.isBrowser) {
664
+ this.cleanupInterval = window.setInterval(() => {
665
+ this.cleanupStalePeers();
666
+ }, 30000);
667
+ } else {
668
+ this.cleanupInterval = setInterval(() => {
669
+ this.cleanupStalePeers();
670
+ }, 30000);
671
+ }
672
+ }
673
+
674
+ /**
658
675
  * Stop periodic cleanup
659
676
  */
660
- stopPeriodicCleanup() {
661
- if (this.cleanupInterval) {
662
- clearInterval(this.cleanupInterval);
663
- this.cleanupInterval = null;
664
- }
677
+ stopPeriodicCleanup() {
678
+ if (this.cleanupInterval) {
679
+ clearInterval(this.cleanupInterval);
680
+ this.cleanupInterval = null;
665
681
  }
682
+ }
666
683
 
667
- /**
684
+ /**
668
685
  * Clean up peers that are in non-viable states for too long
669
686
  */
670
- cleanupStalePeers() {
671
- const now = Date.now();
672
- const STALE_THRESHOLD = 60000; // 60 seconds
673
- const DISCONNECTED_THRESHOLD = 5000; // 5 seconds for disconnected peers
674
- const peersToCleanup = [];
675
-
676
- this.peers.forEach((peerConnection, peerId) => {
677
- const status = peerConnection.getStatus();
678
- const connectionAge = now - peerConnection.connectionStartTime;
679
-
680
- // Immediately clean up disconnected peers
681
- if (status === 'disconnected' && connectionAge > DISCONNECTED_THRESHOLD) {
682
- console.log(`Disconnected peer detected: ${peerId.substring(0, 8)}... (status: ${status}, age: ${Math.round(connectionAge/1000)}s)`);
683
- peersToCleanup.push(peerId);
684
- }
685
- // Clean up peers that have been in non-connected states for too long
686
- else if (connectionAge > STALE_THRESHOLD) {
687
- if (status === 'connecting' || status === 'channel-connecting' ||
687
+ cleanupStalePeers() {
688
+ const now = Date.now();
689
+ const STALE_THRESHOLD = 60000; // 60 seconds
690
+ const DISCONNECTED_THRESHOLD = 5000; // 5 seconds for disconnected peers
691
+ const peersToCleanup = [];
692
+
693
+ this.peers.forEach((peerConnection, peerId) => {
694
+ const status = peerConnection.getStatus();
695
+ const connectionAge = now - peerConnection.connectionStartTime;
696
+
697
+ // Immediately clean up disconnected peers
698
+ if (status === 'disconnected' && connectionAge > DISCONNECTED_THRESHOLD) {
699
+ console.log(`Disconnected peer detected: ${peerId.substring(0, 8)}... (status: ${status}, age: ${Math.round(connectionAge / 1000)}s)`);
700
+ peersToCleanup.push(peerId);
701
+ } else if (connectionAge > STALE_THRESHOLD) {
702
+ if (status === 'connecting' || status === 'channel-connecting' ||
688
703
  status === 'failed' || status === 'closed') {
689
- console.log(`Stale peer detected: ${peerId.substring(0, 8)}... (status: ${status}, age: ${Math.round(connectionAge/1000)}s)`);
690
- peersToCleanup.push(peerId);
691
- }
692
- }
693
- });
694
-
695
- if (peersToCleanup.length > 0) {
696
- console.log(`Cleaning up ${peersToCleanup.length} stale peer(s)`);
697
- peersToCleanup.forEach(peerId => {
698
- this.cleanupFailedConnection(peerId);
699
- });
704
+ console.log(`Stale peer detected: ${peerId.substring(0, 8)}... (status: ${status}, age: ${Math.round(connectionAge / 1000)}s)`);
705
+ peersToCleanup.push(peerId);
700
706
  }
707
+ }
708
+ });
709
+
710
+ if (peersToCleanup.length > 0) {
711
+ console.log(`Cleaning up ${peersToCleanup.length} stale peer(s)`);
712
+ peersToCleanup.forEach(peerId => {
713
+ this.cleanupFailedConnection(peerId);
714
+ });
701
715
  }
716
+ }
702
717
 
703
- /**
718
+ /**
704
719
  * Force cleanup of peers that are not in connected state (for debugging)
705
720
  */
706
- forceCleanupInvalidPeers() {
707
- console.log('Force cleaning up peers not in connected state...');
708
- const peersToRemove = [];
709
-
710
- this.peers.forEach((peerConnection, peerId) => {
711
- const status = peerConnection.getStatus();
712
- if (status !== 'connected') {
713
- console.log(`Found peer ${peerId.substring(0, 8)}... in invalid state: ${status}`);
714
- peersToRemove.push(peerId);
715
- }
716
- });
717
-
718
- peersToRemove.forEach(peerId => {
719
- console.log(`Force removing peer ${peerId.substring(0, 8)}...`);
720
- this.cleanupFailedConnection(peerId);
721
- });
722
-
723
- if (peersToRemove.length > 0) {
724
- console.log(`Force cleaned up ${peersToRemove.length} invalid peers`);
725
- this.emit('peersUpdated');
726
- }
727
-
728
- return peersToRemove.length;
721
+ forceCleanupInvalidPeers() {
722
+ console.log('Force cleaning up peers not in connected state...');
723
+ const peersToRemove = [];
724
+
725
+ this.peers.forEach((peerConnection, peerId) => {
726
+ const status = peerConnection.getStatus();
727
+ if (status !== 'connected') {
728
+ console.log(`Found peer ${peerId.substring(0, 8)}... in invalid state: ${status}`);
729
+ peersToRemove.push(peerId);
730
+ }
731
+ });
732
+
733
+ peersToRemove.forEach(peerId => {
734
+ console.log(`Force removing peer ${peerId.substring(0, 8)}...`);
735
+ this.cleanupFailedConnection(peerId);
736
+ });
737
+
738
+ if (peersToRemove.length > 0) {
739
+ console.log(`Force cleaned up ${peersToRemove.length} invalid peers`);
740
+ this.emit('peersUpdated');
729
741
  }
730
742
 
731
- /**
743
+ return peersToRemove.length;
744
+ }
745
+
746
+ /**
732
747
  * Get a summary of all peer states for debugging
733
748
  */
734
- getPeerStateSummary() {
735
- const summary = {
736
- total: this.peers.size,
737
- connected: 0,
738
- connecting: 0,
739
- channelConnecting: 0,
740
- failed: 0,
741
- disconnected: 0,
742
- closed: 0,
743
- other: 0,
744
- stale: this.getStalePeerCount()
745
- };
746
-
747
- this.peers.forEach((peerConnection) => {
748
- const status = peerConnection.getStatus();
749
- switch (status) {
750
- case 'connected':
751
- summary.connected++;
752
- break;
753
- case 'connecting':
754
- summary.connecting++;
755
- break;
756
- case 'channel-connecting':
757
- summary.channelConnecting++;
758
- break;
759
- case 'failed':
760
- summary.failed++;
761
- break;
762
- case 'disconnected':
763
- summary.disconnected++;
764
- break;
765
- case 'closed':
766
- summary.closed++;
767
- break;
768
- default:
769
- summary.other++;
770
- }
771
- });
772
-
773
- return summary;
749
+ getPeerStateSummary() {
750
+ const summary = {
751
+ total: this.peers.size,
752
+ connected: 0,
753
+ connecting: 0,
754
+ channelConnecting: 0,
755
+ failed: 0,
756
+ disconnected: 0,
757
+ closed: 0,
758
+ other: 0,
759
+ stale: this.getStalePeerCount()
760
+ };
761
+
762
+ this.peers.forEach((peerConnection) => {
763
+ const status = peerConnection.getStatus();
764
+ switch (status) {
765
+ case 'connected':
766
+ summary.connected++;
767
+ break;
768
+ case 'connecting':
769
+ summary.connecting++;
770
+ break;
771
+ case 'channel-connecting':
772
+ summary.channelConnecting++;
773
+ break;
774
+ case 'failed':
775
+ summary.failed++;
776
+ break;
777
+ case 'disconnected':
778
+ summary.disconnected++;
779
+ break;
780
+ case 'closed':
781
+ summary.closed++;
782
+ break;
783
+ default:
784
+ summary.other++;
785
+ }
786
+ });
787
+
788
+ return summary;
789
+ }
790
+
791
+ getDetailedPeerStatus() {
792
+ const peerStatuses = {};
793
+ this.peers.forEach((peerConnection, peerId) => {
794
+ peerStatuses[peerId.substring(0, 8) + '...'] = {
795
+ status: peerConnection.getStatus(),
796
+ isInitiator: peerConnection.isInitiator,
797
+ dataChannelReady: peerConnection.dataChannelReady,
798
+ connectionStartTime: peerConnection.connectionStartTime,
799
+ connectionState: peerConnection.connection?.connectionState,
800
+ iceConnectionState: peerConnection.connection?.iceConnectionState
801
+ };
802
+ });
803
+ return peerStatuses;
804
+ }
805
+
806
+ // Get all peer connections
807
+ getAllConnections() {
808
+ return Array.from(this.peers.values());
809
+ }
810
+
811
+ /**
812
+ * Route incoming messages based on their type
813
+ */
814
+ handleIncomingMessage(message, fromPeerId) {
815
+ if (!message || typeof message !== 'object') {
816
+ console.warn('Received invalid message from', fromPeerId?.substring(0, 8));
817
+ return;
774
818
  }
775
819
 
776
- getDetailedPeerStatus() {
777
- const peerStatuses = {};
778
- this.peers.forEach((peerConnection, peerId) => {
779
- peerStatuses[peerId.substring(0, 8) + '...'] = {
780
- status: peerConnection.getStatus(),
781
- isInitiator: peerConnection.isInitiator,
782
- dataChannelReady: peerConnection.dataChannelReady,
783
- connectionStartTime: peerConnection.connectionStartTime,
784
- connectionState: peerConnection.connection?.connectionState,
785
- iceConnectionState: peerConnection.connection?.iceConnectionState
786
- };
820
+ // Route based on message type
821
+ switch (message.type) {
822
+ case 'gossip':
823
+ // Gossip protocol messages (async call, but we don't wait for it)
824
+ this.mesh.gossipManager.handleGossipMessage(message, fromPeerId).catch(error => {
825
+ console.error('Error handling gossip message:', error);
787
826
  });
788
- return peerStatuses;
789
- }
827
+ break;
790
828
 
791
- // Get all peer connections
792
- getAllConnections() {
793
- return Array.from(this.peers.values());
794
- }
829
+ case 'eviction':
830
+ // Handle eviction notices
831
+ this.handleEvictionMessage(message, fromPeerId);
832
+ break;
795
833
 
796
- /**
797
- * Route incoming messages based on their type
798
- */
799
- handleIncomingMessage(message, fromPeerId) {
800
- if (!message || typeof message !== 'object') {
801
- console.warn('Received invalid message from', fromPeerId?.substring(0, 8));
802
- return;
834
+ case 'dht':
835
+ // WebDHT messages
836
+ if (this.mesh.webDHT) {
837
+ this.mesh.webDHT.handleMessage(message, fromPeerId);
803
838
  }
839
+ break;
804
840
 
805
- // Route based on message type
806
- switch (message.type) {
807
- case 'gossip':
808
- // Gossip protocol messages
809
- this.mesh.gossipManager.handleGossipMessage(message, fromPeerId);
810
- break;
811
-
812
- case 'eviction':
813
- // Handle eviction notices
814
- this.handleEvictionMessage(message, fromPeerId);
815
- break;
816
-
817
- case 'dht':
818
- // WebDHT messages
819
- if (this.mesh.webDHT) {
820
- this.mesh.webDHT.handleMessage(message, fromPeerId);
821
- }
822
- break;
823
-
824
- default:
825
- // Unknown message type - try gossip as fallback for backward compatibility
826
- console.warn(`Unknown message type '${message.type}' from ${fromPeerId?.substring(0, 8)}, trying gossip handler`);
827
- this.mesh.gossipManager.handleGossipMessage(message, fromPeerId);
828
- break;
829
- }
841
+ default:
842
+ // Unknown message type - try gossip as fallback for backward compatibility
843
+ console.warn(`Unknown message type '${message.type}' from ${fromPeerId?.substring(0, 8)}, trying gossip handler`);
844
+ this.mesh.gossipManager.handleGossipMessage(message, fromPeerId).catch(error => {
845
+ console.error('Error handling unknown message as gossip:', error);
846
+ });
847
+ break;
830
848
  }
849
+ }
831
850
 
832
- /**
851
+ /**
833
852
  * Handle eviction messages
834
853
  */
835
- handleEvictionMessage(message, fromPeerId) {
836
- console.log(`Received eviction notice from ${fromPeerId?.substring(0, 8)}: ${message.reason}`);
837
-
838
- // Emit eviction event for UI notification
839
- this.mesh.emit('peerEvicted', {
840
- peerId: fromPeerId,
841
- reason: message.reason,
842
- initiatedByPeer: true
843
- });
844
-
845
- // Close the connection gracefully
846
- const peerConnection = this.peers.get(fromPeerId);
847
- if (peerConnection) {
848
- peerConnection.close();
849
- this.peers.delete(fromPeerId);
850
- }
854
+ handleEvictionMessage(message, fromPeerId) {
855
+ console.log(`Received eviction notice from ${fromPeerId?.substring(0, 8)}: ${message.reason}`);
856
+
857
+ // Emit eviction event for UI notification
858
+ this.mesh.emit('peerEvicted', {
859
+ peerId: fromPeerId,
860
+ reason: message.reason,
861
+ initiatedByPeer: true
862
+ });
863
+
864
+ // Close the connection gracefully
865
+ const peerConnection = this.peers.get(fromPeerId);
866
+ if (peerConnection) {
867
+ peerConnection.close();
868
+ this.peers.delete(fromPeerId);
851
869
  }
870
+ }
852
871
  }