peerpigeon 0.1.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +141 -1365
  2. package/cli.js +1382 -0
  3. package/dist/peerpigeon-browser.js +12290 -0
  4. package/dist/peerpigeon-browser.js.map +7 -0
  5. package/docs/API_DOCUMENTATION.md +1945 -0
  6. package/docs/BOOTSTRAP_HUBS.md +319 -0
  7. package/docs/CLI_README.md +371 -0
  8. package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
  9. package/docs/HUB_QUICK_REF.md +107 -0
  10. package/docs/HUB_SCRIPTS.md +331 -0
  11. package/docs/HUB_SYSTEM.md +552 -0
  12. package/docs/MIGRATION_COMPLETE.md +93 -0
  13. package/docs/NETWORK_NAMESPACES.md +212 -0
  14. package/docs/README.md +107 -0
  15. package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
  16. package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
  17. package/examples/bootstrap-hub-example.js +292 -0
  18. package/examples/browser/README.md +278 -0
  19. package/examples/browser/app.js +2426 -49
  20. package/examples/browser/index.html +481 -630
  21. package/examples/browser/minimal/README.md +55 -0
  22. package/examples/browser/minimal/index.html +75 -0
  23. package/examples/browser/minimal/minimal.js +234 -0
  24. package/examples/browser/styles.css +687 -1425
  25. package/examples/browser/test-bundle.html +35 -0
  26. package/examples/browser-2/index.html +30 -0
  27. package/examples/browser-2/package.json +21 -0
  28. package/examples/browser-2/src/App-simple.vue +21 -0
  29. package/examples/browser-2/src/App.vue +420 -0
  30. package/examples/browser-2/src/components/CryptoView.vue +1661 -0
  31. package/examples/browser-2/src/components/DHTView.vue +1281 -0
  32. package/examples/browser-2/src/components/DebugView.vue +1773 -0
  33. package/examples/browser-2/src/components/MediaView.vue +1048 -0
  34. package/examples/browser-2/src/components/MessagingView.vue +775 -0
  35. package/examples/browser-2/src/components/NetworkView.vue +930 -0
  36. package/examples/browser-2/src/components/StorageView.vue +1376 -0
  37. package/examples/browser-2/src/main.js +5 -0
  38. package/examples/browser-2/src/stores/peerpigeon.js +895 -0
  39. package/examples/browser-2/vite.config.js +6 -0
  40. package/examples/hub-example.js +186 -0
  41. package/examples/multi-hub-test.js +186 -0
  42. package/examples/node/README.md +2 -2
  43. package/examples/selective-streaming-demo.html +698 -0
  44. package/examples/standard-events-demo.js +126 -0
  45. package/package.json +33 -16
  46. package/server/index.js +1032 -98
  47. package/server/start.js +49 -0
  48. package/src/ConnectionManager.js +239 -225
  49. package/src/CryptoManager.js +147 -18
  50. package/src/DebugLogger.js +0 -7
  51. package/src/DistributedStorageManager.js +224 -205
  52. package/src/EnvironmentDetector.js +109 -2
  53. package/src/EventEmitter.js +79 -1
  54. package/src/EvictionManager.js +10 -9
  55. package/src/GossipManager.js +163 -11
  56. package/src/PeerConnection.js +333 -310
  57. package/src/PeerPigeonMesh.js +577 -135
  58. package/src/SignalingClient.js +14 -243
  59. package/src/SignalingHandler.js +31 -10
  60. package/src/StorageManager.js +0 -39
  61. package/src/WebDHT-Simple.js +389 -0
  62. package/src/WebDHT.js +363 -1165
  63. package/src/browser-entry.js +40 -0
  64. package/examples/browser/assets/images/favicon.png +0 -0
  65. package/examples/browser/assets/images/pigeon.png +0 -0
  66. package/examples/browser/crypto-test.html +0 -427
  67. package/examples/browser/ui-old.js +0 -1926
  68. package/examples/browser/ui.js +0 -3391
  69. package/websocket-server/README.md +0 -247
  70. package/websocket-server/server.js +0 -391
@@ -13,22 +13,51 @@ export class ConnectionManager extends EventEmitter {
13
13
  this.debug = DebugLogger.create('ConnectionManager');
14
14
  this.peers = new Map();
15
15
  this.connectionAttempts = new Map();
16
- this.connectionTimeouts = new Map();
17
16
  this.pendingIceCandidates = new Map();
18
17
  this.disconnectionInProgress = new Set();
19
18
  this.cleanupInProgress = new Set();
20
19
  this.lastConnectionAttempt = new Map(); // Track last attempt time per peer
21
20
 
21
+ // Renegotiation management to prevent conflicts
22
+ this.activeRenegotiations = new Set();
23
+ this.renegotiationQueue = new Map();
24
+ this.maxConcurrentRenegotiations = 1; // Only allow 1 renegotiation at a time
25
+
22
26
  // Configuration
23
27
  this.maxConnectionAttempts = 3;
24
- this.connectionTimeout = 30000; // Reduced to 30 seconds for faster retry
25
- this.retryDelay = 1500; // 1.5 second cooldown between attempts to same peer
28
+ this.retryDelay = 500; // Faster retry - 500ms between attempts to same peer
26
29
 
27
30
  // Start periodic cleanup of stale peers
28
31
  this.startPeriodicCleanup();
29
32
 
30
33
  // Start monitoring for stuck connections
31
34
  this.startStuckConnectionMonitoring();
35
+
36
+ // Set up mesh-level event listeners for crypto-gated media
37
+ this.setupMeshEventListeners();
38
+ }
39
+
40
+ /**
41
+ * Set up event listeners for mesh-level events
42
+ */
43
+ setupMeshEventListeners() {
44
+ // Listen for successful key exchanges to enable media sharing
45
+ this.mesh.addEventListener('peerKeyAdded', (event) => {
46
+ this.handlePeerKeyAdded(event.peerId);
47
+ });
48
+ }
49
+
50
+ /**
51
+ * Handle when a peer's crypto key is successfully added
52
+ * @param {string} peerId - The peer ID whose key was added
53
+ */
54
+ async handlePeerKeyAdded(peerId) {
55
+ this.debug.log(`🔐 Key added for ${peerId.substring(0, 8)}... - crypto verification complete`);
56
+
57
+ // NOTE: We do NOT automatically enable remote streams here
58
+ // Media streams (both local and remote) must be manually invoked by the user via the "Start Media" button
59
+ // This ensures complete control over when ANY media streams are allowed
60
+ this.debug.log(`🔐 Crypto verified for ${peerId.substring(0, 8)}... - user must manually invoke media to enable streams`);
32
61
  }
33
62
 
34
63
  async connectToPeer(targetPeerId) {
@@ -40,18 +69,22 @@ export class ConnectionManager extends EventEmitter {
40
69
  return;
41
70
  }
42
71
 
43
- // Check if we're already in the process of connecting
44
- if (this.connectionTimeouts.has(targetPeerId)) {
45
- this.debug.log(`Already connecting to ${targetPeerId.substring(0, 8)}... (connection in progress)`);
46
- return;
47
- }
48
-
49
72
  // Check if we're already attempting through PeerDiscovery
50
73
  if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
51
74
  this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
52
75
  return;
53
76
  }
54
77
 
78
+ // INITIATOR LOGIC: Use deterministic peer ID comparison to prevent race conditions
79
+ // Only become initiator if our peer ID is lexicographically greater than target's
80
+ const shouldBeInitiator = this.mesh.peerId > targetPeerId;
81
+ if (!shouldBeInitiator) {
82
+ this.debug.log(`🔄 INITIATOR LOGIC: Not becoming initiator for ${targetPeerId.substring(0, 8)}... (our ID: ${this.mesh.peerId.substring(0, 8)}... is smaller)`);
83
+ return; // Let the other peer initiate
84
+ }
85
+
86
+ this.debug.log(`🔄 INITIATOR LOGIC: Becoming initiator for ${targetPeerId.substring(0, 8)}... (our ID: ${this.mesh.peerId.substring(0, 8)}... is greater)`);
87
+
55
88
  if (!this.mesh.canAcceptMorePeers()) {
56
89
  this.debug.log(`Cannot connect to ${targetPeerId.substring(0, 8)}... (max peers reached: ${this.mesh.maxPeers})`);
57
90
  return;
@@ -65,7 +98,7 @@ export class ConnectionManager extends EventEmitter {
65
98
 
66
99
  // Use shorter delay for isolated peers to help them connect faster
67
100
  const connectedCount = this.getConnectedPeerCount();
68
- const retryDelay = connectedCount === 0 ? 500 : this.retryDelay; // 500ms for isolated peers, 1500ms otherwise
101
+ const retryDelay = connectedCount === 0 ? 200 : this.retryDelay; // 200ms for isolated peers, 500ms otherwise
69
102
 
70
103
  if (now - lastAttempt < retryDelay) {
71
104
  const remaining = retryDelay - (now - lastAttempt);
@@ -86,49 +119,20 @@ export class ConnectionManager extends EventEmitter {
86
119
  this.lastConnectionAttempt.set(targetPeerId, now);
87
120
  this.mesh.peerDiscovery.trackConnectionAttempt(targetPeerId);
88
121
 
89
- // Set connection timeout - longer for media-enabled connections
90
- const hasMedia = this.mesh.mediaManager.localStream !== null;
91
- const timeoutDuration = hasMedia ? 45000 : 30000; // 45s for media, 30s for data-only
92
-
93
- this.debug.log(`Setting connection timeout for ${targetPeerId.substring(0, 8)}... - ${timeoutDuration / 1000}s (media: ${hasMedia})`);
94
-
95
- const timeoutId = setTimeout(() => {
96
- if (this.peers.has(targetPeerId)) {
97
- const peer = this.peers.get(targetPeerId);
98
- const status = peer.getStatus();
99
- const detailedStatus = peer.getDetailedStatus();
100
- this.debug.log(`Connection timeout check for ${targetPeerId.substring(0, 8)}... - current status: ${status}`);
101
- this.debug.log('Detailed status:', detailedStatus);
102
-
103
- // Cleanup if not fully connected (includes 'connecting', 'new', 'failed', etc.)
104
- if (status !== 'connected') {
105
- this.mesh.emit('statusChanged', { type: 'warning', message: `Connection timeout for ${targetPeerId.substring(0, 8)}... (status: ${status}, media: ${hasMedia})` });
106
- this.handleConnectionTimeout(targetPeerId);
107
- } else {
108
- this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... is connected, clearing timeout`);
109
- this.connectionTimeouts.delete(targetPeerId);
110
- }
111
- } else {
112
- this.debug.log(`Peer ${targetPeerId.substring(0, 8)}... no longer in peers Map, cleaning up timeout`);
113
- this.connectionTimeouts.delete(targetPeerId);
114
- }
115
- }, timeoutDuration);
116
-
117
- this.connectionTimeouts.set(targetPeerId, timeoutId);
118
-
119
122
  try {
120
123
  this.debug.log(`Creating PeerConnection for ${targetPeerId.substring(0, 8)}...`);
121
124
 
122
- // Get current media stream if available
123
- const localStream = this.mesh.mediaManager.localStream;
125
+ // SECURITY: NO automatic media sharing - all media must be manually invoked
124
126
  const options = {
125
- localStream,
127
+ localStream: null, // Always null - media must be manually added later
126
128
  // ALWAYS enable both audio and video transceivers for maximum compatibility
127
129
  // This allows peers to receive media even if they don't have media when connecting
128
130
  enableAudio: true,
129
131
  enableVideo: true
132
+ // allowRemoteStreams defaults to false - streams only invoked when user clicks "Start Media"
130
133
  };
131
134
 
135
+ this.debug.log(`🔄 INITIATOR SETUP: Creating PeerConnection(${targetPeerId.substring(0, 8)}..., isInitiator=true)`);
132
136
  const peerConnection = new PeerConnection(targetPeerId, true, options);
133
137
 
134
138
  // Set up event handlers BEFORE creating connection to catch all events
@@ -138,7 +142,7 @@ export class ConnectionManager extends EventEmitter {
138
142
  this.debug.log(`Creating WebRTC connection for ${targetPeerId.substring(0, 8)}...`);
139
143
  await peerConnection.createConnection();
140
144
 
141
- this.debug.log(`Creating offer for ${targetPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
145
+ this.debug.log(`Creating offer for ${targetPeerId.substring(0, 8)}...`);
142
146
  const offer = await peerConnection.createOffer();
143
147
 
144
148
  this.debug.log(`Offer created for ${targetPeerId.substring(0, 8)}...`, {
@@ -162,41 +166,9 @@ export class ConnectionManager extends EventEmitter {
162
166
  }
163
167
  }
164
168
 
165
- handleConnectionTimeout(peerId) {
166
- this.debug.log(`Connection timeout for ${peerId.substring(0, 8)}...`);
167
-
168
- const attempts = this.connectionAttempts.get(peerId) || 0;
169
- if (attempts >= this.maxConnectionAttempts) {
170
- this.mesh.emit('statusChanged', { type: 'warning', message: `Removing unresponsive peer ${peerId.substring(0, 8)}... after ${attempts} attempts` });
171
- this.mesh.peerDiscovery.removeDiscoveredPeer(peerId);
172
- this.connectionAttempts.delete(peerId);
173
- } else {
174
- this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
175
- this.debug.log(`Will retry connection to ${peerId.substring(0, 8)}... (attempt ${attempts}/${this.maxConnectionAttempts})`);
176
- }
177
-
178
- // Always cleanup the failed connection and ensure it's removed from peers Map
179
- this.cleanupFailedConnection(peerId);
180
-
181
- // Double-check that the peer is actually removed from the UI
182
- if (this.peers.has(peerId)) {
183
- this.debug.warn(`Peer ${peerId.substring(0, 8)}... still in peers Map after timeout cleanup, force removing`);
184
- this.peers.delete(peerId);
185
- this.emit('peersUpdated');
186
- }
187
- }
188
-
189
169
  cleanupFailedConnection(peerId) {
190
170
  this.debug.log(`Cleaning up failed connection for ${peerId.substring(0, 8)}...`);
191
171
 
192
- // Clear timeout
193
- const timeoutId = this.connectionTimeouts.get(peerId);
194
- if (timeoutId) {
195
- clearTimeout(timeoutId);
196
- this.connectionTimeouts.delete(peerId);
197
- this.debug.log(`Cleared timeout for ${peerId.substring(0, 8)}...`);
198
- }
199
-
200
172
  // Remove peer connection
201
173
  let peerRemoved = false;
202
174
  if (this.peers.has(peerId)) {
@@ -231,13 +203,6 @@ export class ConnectionManager extends EventEmitter {
231
203
  }
232
204
 
233
205
  cleanupRaceCondition(peerId) {
234
- // Clear timeout
235
- const timeoutId = this.connectionTimeouts.get(peerId);
236
- if (timeoutId) {
237
- clearTimeout(timeoutId);
238
- this.connectionTimeouts.delete(peerId);
239
- }
240
-
241
206
  // Remove peer connection but preserve connection attempts
242
207
  if (this.peers.has(peerId)) {
243
208
  const peer = this.peers.get(peerId);
@@ -270,13 +235,6 @@ export class ConnectionManager extends EventEmitter {
270
235
  peerConnection.addEventListener('connected', (event) => {
271
236
  this.debug.log(`[EVENT] Connected event received from ${event.peerId.substring(0, 8)}...`);
272
237
 
273
- // Clear connection timeout on successful connection
274
- const timeoutId = this.connectionTimeouts.get(event.peerId);
275
- if (timeoutId) {
276
- clearTimeout(timeoutId);
277
- this.connectionTimeouts.delete(event.peerId);
278
- }
279
-
280
238
  // Reset connection attempts on successful connection
281
239
  this.connectionAttempts.delete(event.peerId);
282
240
 
@@ -306,13 +264,19 @@ export class ConnectionManager extends EventEmitter {
306
264
 
307
265
  // Automatically initiate key exchange when crypto is enabled
308
266
  if (this.mesh.cryptoManager) {
309
- this.debug.log(`🔐 Automatically exchanging keys with newly connected peer ${event.peerId.substring(0, 8)}...`);
310
- // Use setTimeout to ensure the connection is fully established
311
- setTimeout(() => {
312
- this.mesh.exchangeKeysWithPeer(event.peerId).catch(error => {
313
- this.debug.error(`🔐 Failed to exchange keys with ${event.peerId.substring(0, 8)}:`, error);
314
- });
315
- }, 100);
267
+ // Check if we already have this peer's key to avoid duplicate exchanges
268
+ const hasExistingKey = this.mesh.cryptoManager.peerKeys.has(event.peerId);
269
+ if (!hasExistingKey) {
270
+ this.debug.log(`🔐 Automatically exchanging keys with newly connected peer ${event.peerId.substring(0, 8)}...`);
271
+ // PERFORMANCE: Defer key exchange to prevent blocking data channel establishment
272
+ setTimeout(() => {
273
+ this.mesh.exchangeKeysWithPeer(event.peerId).catch(error => {
274
+ this.debug.error(`🔐 Failed to exchange keys with ${event.peerId.substring(0, 8)}:`, error);
275
+ });
276
+ }, 0);
277
+ } else {
278
+ this.debug.log(`🔐 Skipping key exchange with ${event.peerId.substring(0, 8)}... - key already exists`);
279
+ }
316
280
  }
317
281
 
318
282
  this.mesh.emit('peerConnected', { peerId: event.peerId });
@@ -326,116 +290,23 @@ export class ConnectionManager extends EventEmitter {
326
290
  this.debug.log(`[EVENT] Remote stream received from ${event.peerId.substring(0, 8)}...`);
327
291
  this.emit('remoteStream', event);
328
292
 
329
- // CRITICAL: Forward the stream to other connected peers (media forwarding)
330
- this._forwardStreamToOtherPeers(event.stream, event.peerId);
293
+ // DISABLED: Media forwarding causes cascade renegotiation issues with 3+ peers
294
+ // Each peer should manage their own direct streams to avoid conflicts
295
+ // this._forwardStreamToOtherPeers(event.stream, event.peerId);
296
+ this.debug.log('🔄 MEDIA FORWARDING: Disabled to prevent renegotiation conflicts with 3+ peers');
331
297
  });
332
298
 
333
299
  peerConnection.addEventListener('renegotiationNeeded', async (event) => {
334
300
  this.debug.log(`🔄 Renegotiation needed for ${event.peerId.substring(0, 8)}...`);
335
301
 
336
- try {
337
- // Check connection state - allow renegotiation for stable connections or those stuck in "have-local-offer"
338
- // The latter case indicates an incomplete initial handshake that needs to be completed
339
- const signalingState = peerConnection.connection.signalingState;
340
- if (signalingState !== 'stable' && signalingState !== 'have-local-offer') {
341
- this.debug.log(`Skipping renegotiation for ${event.peerId.substring(0, 8)}... - connection in unsupported state (${signalingState})`);
342
- return;
343
- }
344
-
345
- // CRITICAL FIX: Check for stuck "have-local-offer" connections and force recovery
346
- if (signalingState === 'have-local-offer') {
347
- this.debug.log(`� STUCK CONNECTION RECOVERY: Connection with ${event.peerId.substring(0, 8)}... stuck in "have-local-offer" - forcing complete recovery`);
348
-
349
- try {
350
- // DIRECT FIX: Force the connection back to working state by bypassing the stuck offer
351
- this.debug.log(`🔄 RECOVERY: Creating bypass connection for stuck peer ${event.peerId.substring(0, 8)}...`);
352
-
353
- // Get the current local stream to preserve media state
354
- const currentLocalStream = peerConnection.getLocalStream();
355
-
356
- // Close and recreate the connection completely
357
- peerConnection.close();
358
-
359
- // Remove the old connection
360
- this.peers.delete(event.peerId);
361
-
362
- // Create a fresh connection with media
363
- const freshConnection = await this.connectToPeer(event.peerId, false, {
364
- localStream: currentLocalStream
365
- });
366
-
367
- if (freshConnection) {
368
- this.debug.log(`✅ RECOVERY: Successfully created fresh connection for ${event.peerId.substring(0, 8)}... - media should work now`);
369
-
370
- // Apply media stream to the fresh connection
371
- if (currentLocalStream) {
372
- await freshConnection.setLocalStream(currentLocalStream);
373
- this.debug.log(`✅ RECOVERY: Applied media stream to fresh connection for ${event.peerId.substring(0, 8)}...`);
374
- }
375
- } else {
376
- this.debug.error(`❌ RECOVERY: Failed to create fresh connection for ${event.peerId.substring(0, 8)}...`);
377
- }
378
-
379
- return; // Exit early - fresh connection will handle renegotiation naturally
380
- } catch (error) {
381
- this.debug.error(`❌ RECOVERY: Complete recovery failed for ${event.peerId.substring(0, 8)}...`, error);
382
- // Continue with existing fallback logic
383
- }
384
- }
385
-
386
- // Additional check for connection state
387
- if (peerConnection.connection.connectionState !== 'connected') {
388
- this.debug.log(`Skipping renegotiation for ${event.peerId.substring(0, 8)}... - not connected (${peerConnection.connection.connectionState})`);
389
- return;
390
- }
391
-
392
- this.debug.log(`🔄 Creating renegotiation offer for ${event.peerId.substring(0, 8)}... (signaling state: ${signalingState})`);
393
-
394
- // Create new offer for renegotiation - no need for special options since we have pre-allocated transceivers
395
- const offer = await peerConnection.connection.createOffer();
396
-
397
- // CRITICAL DEBUG: Check if offer SDP contains media information
398
- this.debug.log('🔍 RENEGOTIATION OFFER SDP DEBUG:');
399
- this.debug.log(` SDP length: ${offer.sdp.length}`);
400
- this.debug.log(` Contains video: ${offer.sdp.includes('m=video')}`);
401
- this.debug.log(` Contains audio: ${offer.sdp.includes('m=audio')}`);
402
- this.debug.log(` Send recv: ${offer.sdp.includes('sendrecv')}`);
403
- const videoLines = offer.sdp.split('\n').filter(line => line.includes('video')).length;
404
- const audioLines = offer.sdp.split('\n').filter(line => line.includes('audio')).length;
405
- this.debug.log(` Video lines: ${videoLines}, Audio lines: ${audioLines}`);
406
-
407
- await peerConnection.connection.setLocalDescription(offer);
408
-
409
- // Send the renegotiation offer via regular signaling (NOT as a new offer, but as renegotiation)
410
- await this.mesh.sendSignalingMessage({
411
- type: 'renegotiation-offer',
412
- data: offer
413
- }, event.peerId);
414
-
415
- // AGGRESSIVE FIX: Set up stuck connection watchdog timer
416
- setTimeout(() => {
417
- if (peerConnection.connection.signalingState === 'have-local-offer') {
418
- this.debug.log(`⚠️ WATCHDOG: Connection with ${event.peerId.substring(0, 8)}... still stuck after 10 seconds - forcing emergency recovery`);
419
-
420
- // Emergency recovery: Create immediate bypass
421
- this.connectToPeer(event.peerId, false, {
422
- localStream: peerConnection.getLocalStream(),
423
- emergency: true
424
- }).catch(err => {
425
- this.debug.error(`❌ EMERGENCY: Failed emergency recovery for ${event.peerId.substring(0, 8)}...`, err);
426
- });
427
- }
428
- }, 10000); // 10 second watchdog
429
-
430
- this.debug.log(`🔄 Sent renegotiation offer to ${event.peerId.substring(0, 8)}... (signaling state: ${signalingState})`);
431
- } catch (error) {
432
- this.debug.error(`Failed to renegotiate with ${event.peerId}:`, error);
433
-
434
- // If renegotiation fails due to m-line order, log but don't crash
435
- if (error.name === 'InvalidAccessError' && error.message.includes('m-line')) {
436
- this.debug.log(`🔄 M-line order error detected for ${event.peerId.substring(0, 8)}... - this is expected with replaceTrack approach`);
437
- }
302
+ // SMART RENEGOTIATION: Queue renegotiations to prevent conflicts
303
+ if (this.activeRenegotiations.size >= this.maxConcurrentRenegotiations) {
304
+ this.debug.log(`🔄 QUEUE: Renegotiation for ${event.peerId.substring(0, 8)}... queued (${this.activeRenegotiations.size} active)`);
305
+ this.renegotiationQueue.set(event.peerId, event);
306
+ return;
438
307
  }
308
+
309
+ await this._performRenegotiation(peerConnection, event);
439
310
  });
440
311
 
441
312
  // ...existing code...
@@ -455,12 +326,6 @@ export class ConnectionManager extends EventEmitter {
455
326
 
456
327
  try {
457
328
  // Clear all related data
458
- const timeoutId = this.connectionTimeouts.get(peerId);
459
- if (timeoutId) {
460
- clearTimeout(timeoutId);
461
- this.connectionTimeouts.delete(peerId);
462
- }
463
-
464
329
  if (this.peers.has(peerId)) {
465
330
  const peerConnection = this.peers.get(peerId);
466
331
 
@@ -508,7 +373,7 @@ export class ConnectionManager extends EventEmitter {
508
373
  } else {
509
374
  this.debug.log(`Connection recovered (${currentCount}/${this.mesh.maxPeers}), skipping optimization`);
510
375
  }
511
- }, 2000); // Wait 2 seconds before optimizing to allow connections to stabilize
376
+ }, 500); // Wait 500ms before optimizing - faster response
512
377
  } else {
513
378
  this.debug.log(`Peer count appropriate at ${connectedCount}/${this.mesh.maxPeers}, no optimization needed`);
514
379
  }
@@ -534,13 +399,6 @@ export class ConnectionManager extends EventEmitter {
534
399
  this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
535
400
  this.connectionAttempts.delete(peerId);
536
401
 
537
- // Clear timeout if exists
538
- const timeoutId = this.connectionTimeouts.get(peerId);
539
- if (timeoutId) {
540
- clearTimeout(timeoutId);
541
- this.connectionTimeouts.delete(peerId);
542
- }
543
-
544
402
  if (this.peers.has(peerId)) {
545
403
  const peer = this.peers.get(peerId);
546
404
  if (peer.connection) {
@@ -714,7 +572,6 @@ export class ConnectionManager extends EventEmitter {
714
572
 
715
573
  this.peers.clear();
716
574
  this.connectionAttempts.clear();
717
- this.connectionTimeouts.clear();
718
575
  this.pendingIceCandidates.clear();
719
576
  this.disconnectionInProgress.clear();
720
577
  this.cleanupInProgress.clear();
@@ -887,6 +744,22 @@ export class ConnectionManager extends EventEmitter {
887
744
  return;
888
745
  }
889
746
 
747
+ // Define message types that should be filtered from peer-readable messages
748
+ // These messages are processed but not emitted as regular messages to UI/applications
749
+ const filteredMessageTypes = new Set([
750
+ 'signaling-relay',
751
+ 'peer-announce-relay',
752
+ 'bootstrap-keepalive',
753
+ 'client-peer-announcement',
754
+ 'cross-bootstrap-signaling'
755
+ ]);
756
+
757
+ // Check if this message type should be filtered from peer-readable messages
758
+ const isFilteredMessage = filteredMessageTypes.has(message.type);
759
+ if (isFilteredMessage) {
760
+ this.debug.log(`🔇 FILTER: Processing filtered message type '${message.type}' from ${fromPeerId?.substring(0, 8)} (not emitted to UI)`);
761
+ }
762
+
890
763
  // Route based on message type
891
764
  switch (message.type) {
892
765
  case 'gossip':
@@ -936,12 +809,76 @@ export class ConnectionManager extends EventEmitter {
936
809
  }
937
810
  break;
938
811
 
812
+ case 'signaling-relay':
813
+ // Process signaling relay messages but don't emit as peer-readable
814
+ this.debug.log(`🔇 FILTER: Processing signaling-relay from ${fromPeerId?.substring(0, 8)} (filtered from UI)`);
815
+ // Handle the signaling relay internally - extract and process the actual signaling message
816
+ if (message.data && message.targetPeerId === this.mesh.peerId) {
817
+ this.mesh.signalingHandler.handleSignalingMessage({
818
+ type: message.data.type,
819
+ data: message.data.data,
820
+ fromPeerId: message.fromPeerId || fromPeerId,
821
+ targetPeerId: message.targetPeerId,
822
+ timestamp: message.timestamp
823
+ });
824
+ }
825
+ return; // Early return to prevent fallback to gossip handler
826
+
827
+ case 'peer-announce-relay':
828
+ // Process peer announce relay messages but don't emit as peer-readable
829
+ this.debug.log(`🔇 FILTER: Processing peer-announce-relay from ${fromPeerId?.substring(0, 8)} (filtered from UI)`);
830
+ // Handle the peer announcement internally
831
+ if (message.data && this.mesh.signalingHandler) {
832
+ this.mesh.signalingHandler.handlePeerAnnouncement(message.data, fromPeerId);
833
+ }
834
+ return; // Early return to prevent fallback to gossip handler
835
+
836
+ case 'bootstrap-keepalive':
837
+ // Process bootstrap keepalive messages but don't emit as peer-readable
838
+ this.debug.log(`🔇 FILTER: Processing bootstrap-keepalive from ${fromPeerId?.substring(0, 8)} (filtered from UI)`);
839
+ // Handle keepalive internally - update peer discovery timestamps
840
+ if (this.mesh.peerDiscovery) {
841
+ this.mesh.peerDiscovery.updateDiscoveryTimestamp(fromPeerId);
842
+ }
843
+ return; // Early return to prevent fallback to gossip handler
844
+
845
+ case 'client-peer-announcement':
846
+ // Process client peer announcement messages but don't emit as peer-readable
847
+ this.debug.log(`🔇 FILTER: Processing client-peer-announcement from ${fromPeerId?.substring(0, 8)} (filtered from UI)`);
848
+ // Handle client peer announcement internally
849
+ if (message.clientPeerId && this.mesh.signalingHandler) {
850
+ this.mesh.signalingHandler.handlePeerAnnouncement(message.clientPeerId);
851
+ }
852
+ return; // Early return to prevent fallback to gossip handler
853
+
854
+ case 'cross-bootstrap-signaling':
855
+ // Process cross-bootstrap signaling messages but don't emit as peer-readable
856
+ this.debug.log(`🔇 FILTER: Processing cross-bootstrap-signaling from ${fromPeerId?.substring(0, 8)} (filtered from UI)`);
857
+ // Handle cross-bootstrap signaling internally
858
+ if (message.originalMessage && message.targetPeerId === this.mesh.peerId && this.mesh.signalingHandler) {
859
+ // Extract and process the wrapped signaling message
860
+ this.mesh.signalingHandler.handleSignalingMessage({
861
+ type: message.originalMessage.type,
862
+ data: message.originalMessage.data,
863
+ fromPeerId: message.originalMessage.fromPeerId || fromPeerId,
864
+ targetPeerId: message.targetPeerId,
865
+ timestamp: message.originalMessage.timestamp || message.timestamp
866
+ });
867
+ }
868
+ return; // Early return to prevent fallback to gossip handler
869
+
939
870
  default:
940
- // Unknown message type - try gossip as fallback for backward compatibility
941
- this.debug.warn(`Unknown message type '${message.type}' from ${fromPeerId?.substring(0, 8)}, trying gossip handler`);
942
- this.mesh.gossipManager.handleGossipMessage(message, fromPeerId).catch(error => {
943
- this.debug.error('Error handling unknown message as gossip:', error);
944
- });
871
+ // For non-filtered message types, check if they should be emitted
872
+ if (!isFilteredMessage) {
873
+ // Unknown message type - try gossip as fallback for backward compatibility
874
+ this.debug.warn(`Unknown message type '${message.type}' from ${fromPeerId?.substring(0, 8)}, trying gossip handler`);
875
+ this.mesh.gossipManager.handleGossipMessage(message, fromPeerId).catch(error => {
876
+ this.debug.error('Error handling unknown message as gossip:', error);
877
+ });
878
+ } else {
879
+ // This is a filtered message type that doesn't have a specific handler
880
+ this.debug.log(`🔇 FILTER: Filtered message type '${message.type}' processed but not emitted`);
881
+ }
945
882
  break;
946
883
  }
947
884
  }
@@ -967,6 +904,83 @@ export class ConnectionManager extends EventEmitter {
967
904
  }
968
905
  }
969
906
 
907
+ /**
908
+ * Perform a single renegotiation with conflict prevention
909
+ * @private
910
+ */
911
+ async _performRenegotiation(peerConnection, event) {
912
+ const peerId = event.peerId;
913
+
914
+ // Mark this renegotiation as active
915
+ this.activeRenegotiations.add(peerId);
916
+
917
+ try {
918
+ this.debug.log(`🔄 ACTIVE: Starting renegotiation for ${peerId.substring(0, 8)}... (${this.activeRenegotiations.size} active)`);
919
+
920
+ // Check connection state - allow renegotiation for stable connections or those stuck in "have-local-offer"
921
+ const signalingState = peerConnection.connection.signalingState;
922
+ if (signalingState !== 'stable' && signalingState !== 'have-local-offer') {
923
+ this.debug.log(`Skipping renegotiation for ${peerId.substring(0, 8)}... - connection in unsupported state (${signalingState})`);
924
+ return;
925
+ }
926
+
927
+ // Additional check for connection state
928
+ if (peerConnection.connection.connectionState !== 'connected') {
929
+ this.debug.log(`Skipping renegotiation for ${peerId.substring(0, 8)}... - not connected (${peerConnection.connection.connectionState})`);
930
+ return;
931
+ }
932
+
933
+ this.debug.log(`🔄 Creating renegotiation offer for ${peerId.substring(0, 8)}... (signaling state: ${signalingState})`);
934
+
935
+ // Create new offer for renegotiation
936
+ const offer = await peerConnection.connection.createOffer();
937
+
938
+ this.debug.log('🔍 RENEGOTIATION OFFER SDP DEBUG:');
939
+ this.debug.log(` SDP length: ${offer.sdp.length}`);
940
+ this.debug.log(` Contains video: ${offer.sdp.includes('m=video')}`);
941
+ this.debug.log(` Contains audio: ${offer.sdp.includes('m=audio')}`);
942
+
943
+ await peerConnection.connection.setLocalDescription(offer);
944
+
945
+ // Send the renegotiation offer
946
+ await this.mesh.sendSignalingMessage({
947
+ type: 'renegotiation-offer',
948
+ data: offer
949
+ }, peerId);
950
+
951
+ this.debug.log(`✅ ACTIVE: Sent renegotiation offer to ${peerId.substring(0, 8)}...`);
952
+ } catch (error) {
953
+ this.debug.error(`❌ ACTIVE: Failed to renegotiate with ${peerId.substring(0, 8)}...`, error);
954
+ } finally {
955
+ // Always clean up and process queue
956
+ this.activeRenegotiations.delete(peerId);
957
+ this.debug.log(`🔄 ACTIVE: Completed renegotiation for ${peerId.substring(0, 8)}... (${this.activeRenegotiations.size} active)`);
958
+
959
+ // Process next queued renegotiation
960
+ this._processRenegotiationQueue();
961
+ }
962
+ }
963
+
964
+ /**
965
+ * Process the next renegotiation in the queue
966
+ * @private
967
+ */
968
+ _processRenegotiationQueue() {
969
+ if (this.activeRenegotiations.size >= this.maxConcurrentRenegotiations || this.renegotiationQueue.size === 0) {
970
+ return;
971
+ }
972
+
973
+ // Get next queued renegotiation
974
+ const [nextPeerId, nextEvent] = this.renegotiationQueue.entries().next().value;
975
+ this.renegotiationQueue.delete(nextPeerId);
976
+
977
+ const peerConnection = this.peers.get(nextPeerId);
978
+ if (peerConnection) {
979
+ this.debug.log(`🔄 QUEUE: Processing queued renegotiation for ${nextPeerId.substring(0, 8)}...`);
980
+ this._performRenegotiation(peerConnection, nextEvent);
981
+ }
982
+ }
983
+
970
984
  /**
971
985
  * Handle renegotiation offers from peers
972
986
  */
@@ -1029,8 +1043,8 @@ export class ConnectionManager extends EventEmitter {
1029
1043
  if (peerConnection.connection?.signalingState === 'have-local-offer') {
1030
1044
  const connectionAge = Date.now() - peerConnection.connectionStartTime;
1031
1045
 
1032
- // If connection has been stuck in "have-local-offer" for more than 10 seconds, fix it
1033
- if (connectionAge > 10000) {
1046
+ // If connection has been stuck in "have-local-offer" for more than 2 seconds, fix it
1047
+ if (connectionAge > 2000) {
1034
1048
  stuckConnections.push(peerId);
1035
1049
  }
1036
1050
  }
@@ -1091,10 +1105,10 @@ export class ConnectionManager extends EventEmitter {
1091
1105
  * Start monitoring for stuck connections
1092
1106
  */
1093
1107
  startStuckConnectionMonitoring() {
1094
- // Check every 15 seconds for stuck connections
1108
+ // Check every 2 seconds for stuck connections - much more responsive
1095
1109
  setInterval(() => {
1096
1110
  this.monitorAndFixStuckConnections();
1097
- }, 15000);
1111
+ }, 2000);
1098
1112
 
1099
1113
  this.debug.log('🔍 Started stuck connection monitoring');
1100
1114
  }