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