peerpigeon 1.0.6 → 1.0.7

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.
package/server/index.js CHANGED
@@ -99,11 +99,36 @@ export class PeerPigeonServer extends EventEmitter {
99
99
  /**
100
100
  * Get all connected hubs
101
101
  */
102
+ /**
103
+ * Get all connected hubs (directly connected via WebSocket)
104
+ */
102
105
  getConnectedHubs(excludePeerId = null) {
103
106
  const hubList = [];
104
107
  for (const [peerId, hubInfo] of this.hubs) {
105
108
  if (peerId !== excludePeerId && this.connections.has(peerId)) {
106
- hubList.push({ peerId, ...hubInfo });
109
+ hubList.push({
110
+ peerId,
111
+ connected: true,
112
+ ...hubInfo
113
+ });
114
+ }
115
+ }
116
+ return hubList;
117
+ }
118
+
119
+ /**
120
+ * Get all known hubs (both directly connected and remotely discovered)
121
+ */
122
+ getAllKnownHubs(excludePeerId = null) {
123
+ const hubList = [];
124
+ for (const [peerId, hubInfo] of this.hubs) {
125
+ if (peerId !== excludePeerId) {
126
+ hubList.push({
127
+ peerId,
128
+ connected: this.connections.has(peerId),
129
+ remote: hubInfo.remote || false,
130
+ ...hubInfo
131
+ });
107
132
  }
108
133
  }
109
134
  return hubList;
@@ -219,7 +244,7 @@ export class PeerPigeonServer extends EventEmitter {
219
244
  res.end(JSON.stringify({
220
245
  timestamp: new Date().toISOString(),
221
246
  totalHubs: this.hubs.size,
222
- hubs: this.getConnectedHubs()
247
+ hubs: this.getAllKnownHubs()
223
248
  }));
224
249
  return;
225
250
  }
@@ -398,18 +423,17 @@ export class PeerPigeonServer extends EventEmitter {
398
423
  return;
399
424
  }
400
425
 
401
- // If no bootstrap hubs specified, try default port 3000
426
+ // Default Fly.io bootstrap hubs
427
+ const DEFAULT_FLY_HUBS = [
428
+ 'wss://pigeonhub.fly.dev',
429
+ 'wss://pigeonhub-c.fly.dev'
430
+ ];
431
+
432
+ // Use provided bootstrap hubs, or default to Fly.io hubs
402
433
  let bootstrapUris = this.bootstrapHubs;
403
434
  if (!bootstrapUris || bootstrapUris.length === 0) {
404
- // Don't connect to ourselves
405
- const defaultPort = 3000;
406
- if (this.port !== defaultPort) {
407
- bootstrapUris = [`ws://${this.host}:${defaultPort}`];
408
- console.log(`🔗 No bootstrap hubs specified, trying default: ws://${this.host}:${defaultPort}`);
409
- } else {
410
- console.log('â„šī¸ No bootstrap hubs to connect to (running on default port 3000)');
411
- return;
412
- }
435
+ bootstrapUris = DEFAULT_FLY_HUBS;
436
+ console.log(`🔗 No bootstrap hubs specified, using default Fly.io hubs: ${bootstrapUris.join(', ')}`);
413
437
  }
414
438
 
415
439
  console.log(`🔗 Connecting to ${bootstrapUris.length} bootstrap hub(s)...`);
@@ -484,7 +508,19 @@ export class PeerPigeonServer extends EventEmitter {
484
508
 
485
509
  this.emit('bootstrapDisconnected', { uri, code, reason });
486
510
 
487
- // Attempt to reconnect
511
+ // Don't reconnect to localhost hubs - they're likely just not running
512
+ const url = new URL(uri);
513
+ const isLocalhost = url.hostname === 'localhost' ||
514
+ url.hostname === '127.0.0.1' ||
515
+ url.hostname === '0.0.0.0';
516
+
517
+ if (isLocalhost) {
518
+ console.log(`â„šī¸ Not reconnecting to localhost hub ${uri} - assuming it's not running`);
519
+ this.bootstrapConnections.delete(uri);
520
+ return;
521
+ }
522
+
523
+ // Attempt to reconnect for non-localhost hubs
488
524
  if (this.isRunning && attemptNumber < this.maxReconnectAttempts) {
489
525
  connectionInfo.reconnectTimer = setTimeout(() => {
490
526
  console.log(`🔄 Reconnecting to ${uri}...`);
@@ -499,7 +535,22 @@ export class PeerPigeonServer extends EventEmitter {
499
535
  ws.on('error', (error) => {
500
536
  console.error(`❌ WebSocket error for ${uri}:`, error.message);
501
537
 
502
- // Only reject on first attempt, otherwise we'll retry
538
+ // Check if it's a localhost hub
539
+ const url = new URL(uri);
540
+ const isLocalhost = url.hostname === 'localhost' ||
541
+ url.hostname === '127.0.0.1' ||
542
+ url.hostname === '0.0.0.0';
543
+
544
+ if (isLocalhost) {
545
+ console.log(`â„šī¸ Localhost hub ${uri} not available - skipping reconnection attempts`);
546
+ this.bootstrapConnections.delete(uri);
547
+ if (attemptNumber === 0) {
548
+ reject(error);
549
+ }
550
+ return;
551
+ }
552
+
553
+ // Only reject on first attempt for non-localhost, otherwise we'll retry
503
554
  if (attemptNumber === 0) {
504
555
  this.bootstrapConnections.delete(uri);
505
556
  reject(error);
@@ -521,6 +572,7 @@ export class PeerPigeonServer extends EventEmitter {
521
572
  type: 'announce',
522
573
  networkName: this.hubMeshNamespace,
523
574
  data: {
575
+ peerId: this.hubPeerId, // CRITICAL: Include hub's peerId so it can be properly registered
524
576
  isHub: true,
525
577
  port: this.port,
526
578
  host: this.host,
@@ -530,7 +582,7 @@ export class PeerPigeonServer extends EventEmitter {
530
582
  };
531
583
 
532
584
  ws.send(JSON.stringify(announcement));
533
- console.log(`đŸ“ĸ Announced to bootstrap hub on ${this.hubMeshNamespace}`);
585
+ console.log(`đŸ“ĸ Announced hub ${this.hubPeerId.substring(0, 8)}... to bootstrap hub on namespace '${this.hubMeshNamespace}'`);
534
586
 
535
587
  // Announce all existing local peers to the bootstrap hub
536
588
  this.announceLocalPeersToHub(ws);
@@ -664,30 +716,59 @@ export class PeerPigeonServer extends EventEmitter {
664
716
 
665
717
  case 'peer-discovered':
666
718
  if (data?.isHub) {
667
- console.log(`đŸĸ Discovered hub via bootstrap: ${data.peerId?.substring(0, 8)}...`);
668
- this.emit('hubDiscovered', { peerId: data.peerId, via: uri, data });
719
+ const hubPeerId = data.peerId;
720
+ console.log(`đŸĸ Discovered hub via bootstrap: ${hubPeerId?.substring(0, 8)}...`);
721
+
722
+ // Register this remotely discovered hub (even though it's not directly connected to us)
723
+ // This helps with hub awareness and statistics
724
+ if (hubPeerId && !this.hubs.has(hubPeerId)) {
725
+ this.hubs.set(hubPeerId, {
726
+ peerId: hubPeerId,
727
+ registeredAt: Date.now(),
728
+ lastActivity: Date.now(),
729
+ discoveredVia: uri,
730
+ remote: true, // Not directly connected to us
731
+ ...data
732
+ });
733
+ console.log(`📝 Registered remote hub: ${hubPeerId.substring(0, 8)}... (${this.hubs.size} total hubs)`);
734
+ }
735
+
736
+ this.emit('hubDiscovered', { peerId: hubPeerId, via: uri, data });
669
737
  } else if (data?.peerId) {
670
- // Regular peer discovered on another hub - notify our local peers in same network
738
+ // Regular peer discovered on another hub - notify our local CLIENT peers in same network
671
739
  const discoveredPeerId = data.peerId;
672
740
  const discoveredNetwork = networkName || 'global';
673
741
 
674
742
  console.log(`đŸ“Ĩ Peer ${discoveredPeerId.substring(0, 8)}... discovered on another hub (network: ${discoveredNetwork})`);
675
743
 
676
- // Forward to all our local peers in the same network
677
- const localPeers = this.getActivePeers(null, discoveredNetwork);
678
- localPeers.forEach(localPeerId => {
679
- const localConnection = this.connections.get(localPeerId);
680
- if (localConnection) {
681
- this.sendToConnection(localConnection, {
682
- type: 'peer-discovered',
683
- data,
684
- networkName: discoveredNetwork,
685
- fromPeerId: 'system',
686
- targetPeerId: localPeerId,
687
- timestamp: Date.now()
688
- });
744
+ // Forward to all our local CLIENT peers in the same network (exclude hubs)
745
+ const localPeersInNetwork = this.networkPeers.get(discoveredNetwork);
746
+ if (localPeersInNetwork && localPeersInNetwork.size > 0) {
747
+ let forwardedCount = 0;
748
+ for (const localPeerId of localPeersInNetwork) {
749
+ // Skip hubs - only forward to client peers
750
+ const localPeerData = this.peerData.get(localPeerId);
751
+ if (localPeerData?.isHub) {
752
+ continue;
753
+ }
754
+
755
+ const localConnection = this.connections.get(localPeerId);
756
+ if (localConnection && localConnection.readyState === WebSocket.OPEN) {
757
+ this.sendToConnection(localConnection, {
758
+ type: 'peer-discovered',
759
+ data,
760
+ networkName: discoveredNetwork,
761
+ fromPeerId: 'system',
762
+ targetPeerId: localPeerId,
763
+ timestamp: Date.now()
764
+ });
765
+ forwardedCount++;
766
+ }
689
767
  }
690
- });
768
+ console.log(`✅ Forwarded peer-discovered to ${forwardedCount} local client peer(s) in network '${discoveredNetwork}'`);
769
+ } else {
770
+ console.log(`â„šī¸ No local peers in network '${discoveredNetwork}' to forward to`);
771
+ }
691
772
  }
692
773
  break;
693
774
 
@@ -954,8 +1035,8 @@ export class PeerPigeonServer extends EventEmitter {
954
1035
  }
955
1036
  this.networkPeers.get(peerNetworkName).add(peerId);
956
1037
 
957
- // If this is a hub, broadcast this peer to ALL other connected hubs (both bootstrap and incoming)
958
- if (this.isHub && !isHub) {
1038
+ // If this is a hub, broadcast BOTH hubs and regular peers to ALL other connected hubs
1039
+ if (this.isHub) {
959
1040
  const connectedHubs = [];
960
1041
 
961
1042
  // 1. Add outgoing bootstrap connections
@@ -978,12 +1059,13 @@ export class PeerPigeonServer extends EventEmitter {
978
1059
  }
979
1060
 
980
1061
  if (connectedHubs.length > 0) {
981
- console.log(`📡 Broadcasting peer ${peerId.substring(0, 8)}... to ${connectedHubs.length} connected hub(s)`);
1062
+ const peerType = isHub ? 'hub' : 'peer';
1063
+ console.log(`📡 Broadcasting ${peerType} ${peerId.substring(0, 8)}... (network: ${peerNetworkName}) to ${connectedHubs.length} connected hub(s)`);
982
1064
  const peerAnnouncement = {
983
1065
  type: 'peer-discovered',
984
1066
  data: {
985
1067
  peerId,
986
- isHub: false,
1068
+ isHub,
987
1069
  ...message.data
988
1070
  },
989
1071
  networkName: peerNetworkName,
@@ -994,14 +1076,19 @@ export class PeerPigeonServer extends EventEmitter {
994
1076
  for (const hub of connectedHubs) {
995
1077
  try {
996
1078
  if (hub.type === 'bootstrap') {
1079
+ console.log(` → Sending to bootstrap hub: ${hub.id}`);
997
1080
  hub.ws.send(JSON.stringify(peerAnnouncement));
998
1081
  } else {
1082
+ console.log(` → Sending to incoming hub: ${hub.id.substring(0, 8)}...`);
999
1083
  this.sendToConnection(hub.ws, peerAnnouncement);
1000
1084
  }
1001
1085
  } catch (error) {
1002
1086
  console.error(`❌ Error broadcasting to hub ${hub.id}:`, error.message);
1003
1087
  }
1004
1088
  }
1089
+ } else if (!isHub) {
1090
+ // Log when we have no hubs to broadcast to (only for client peers, not hubs)
1091
+ console.log(`âš ī¸ No connected hubs to broadcast peer ${peerId.substring(0, 8)}... to`);
1005
1092
  }
1006
1093
  }
1007
1094
 
@@ -1182,9 +1269,10 @@ export class PeerPigeonServer extends EventEmitter {
1182
1269
  return;
1183
1270
  }
1184
1271
 
1185
- // Check if sender is a hub
1272
+ // Check if sender is a hub or if it's from bootstrap
1273
+ const isFromBootstrap = fromHubPeerId === 'bootstrap' || message.fromPeerId === 'system';
1186
1274
  const senderPeerData = this.peerData.get(fromHubPeerId);
1187
- const isFromHub = senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
1275
+ const isFromHub = isFromBootstrap || senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
1188
1276
 
1189
1277
  if (!isFromHub) {
1190
1278
  console.log(`âš ī¸ Received peer-discovered from non-hub peer ${fromHubPeerId.substring(0, 8)}... - ignoring`);
@@ -1193,6 +1281,55 @@ export class PeerPigeonServer extends EventEmitter {
1193
1281
 
1194
1282
  console.log(`🔍 Received peer discovery from hub ${fromHubPeerId.substring(0, 8)}... - Peer ${discoveredPeerId.substring(0, 8)}... in network '${networkName}'`);
1195
1283
 
1284
+ // If this is a hub, relay this peer to OTHER connected hubs as well (to ensure full mesh awareness)
1285
+ if (this.isHub) {
1286
+ const relayedToHubs = [];
1287
+
1288
+ // Relay to outgoing bootstrap connections (except the one we received from)
1289
+ for (const [uri, connInfo] of this.bootstrapConnections) {
1290
+ if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
1291
+ try {
1292
+ connInfo.ws.send(JSON.stringify({
1293
+ type: 'peer-discovered',
1294
+ data: messageData,
1295
+ networkName,
1296
+ fromPeerId: 'system',
1297
+ timestamp: Date.now()
1298
+ }));
1299
+ relayedToHubs.push(uri);
1300
+ } catch (error) {
1301
+ console.error(`❌ Error relaying to bootstrap hub ${uri}:`, error.message);
1302
+ }
1303
+ }
1304
+ }
1305
+
1306
+ // Relay to incoming hub connections (except the sender)
1307
+ for (const [hubPeerId, hubInfo] of this.hubs) {
1308
+ if (hubPeerId === fromHubPeerId || hubPeerId === this.hubPeerId) {
1309
+ continue; // Skip sender and self
1310
+ }
1311
+ const hubConnection = this.connections.get(hubPeerId);
1312
+ if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
1313
+ try {
1314
+ this.sendToConnection(hubConnection, {
1315
+ type: 'peer-discovered',
1316
+ data: messageData,
1317
+ networkName,
1318
+ fromPeerId: 'system',
1319
+ timestamp: Date.now()
1320
+ });
1321
+ relayedToHubs.push(hubPeerId.substring(0, 8) + '...');
1322
+ } catch (error) {
1323
+ console.error(`❌ Error relaying to hub ${hubPeerId.substring(0, 8)}...:`, error.message);
1324
+ }
1325
+ }
1326
+ }
1327
+
1328
+ if (relayedToHubs.length > 0) {
1329
+ console.log(`🔄 Relayed peer-discovered to ${relayedToHubs.length} other hub(s): ${relayedToHubs.join(', ')}`);
1330
+ }
1331
+ }
1332
+
1196
1333
  // Forward to all local CLIENT peers in the same network (exclude hubs)
1197
1334
  const localPeers = this.networkPeers.get(networkName);
1198
1335
  if (localPeers && localPeers.size > 0) {
@@ -65,14 +65,37 @@ export class ConnectionManager extends EventEmitter {
65
65
 
66
66
  // Enhanced duplicate connection prevention
67
67
  if (this.peers.has(targetPeerId)) {
68
- this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}...`);
69
- return;
68
+ const existingPeer = this.peers.get(targetPeerId);
69
+ const status = existingPeer.getStatus();
70
+
71
+ // If already connected, don't retry
72
+ if (status === 'connected') {
73
+ this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}... (status: ${status})`);
74
+ return;
75
+ }
76
+
77
+ // If connecting but stuck, allow retry after timeout
78
+ if (status === 'connecting') {
79
+ const connectionAge = Date.now() - (existingPeer.createdAt || 0);
80
+ if (connectionAge < 10000) { // Wait 10 seconds before considering it stuck
81
+ this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... still in progress (${Math.round(connectionAge / 1000)}s)`);
82
+ return;
83
+ }
84
+ this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... appears stuck (${Math.round(connectionAge / 1000)}s), will retry`);
85
+ this.cleanupFailedConnection(targetPeerId);
86
+ }
70
87
  }
71
88
 
72
89
  // Check if we're already attempting through PeerDiscovery
73
90
  if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
74
- this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
75
- return;
91
+ const attemptAge = Date.now() - (this.lastConnectionAttempt.get(targetPeerId) || 0);
92
+ // Allow retry if attempt is old (more than 10 seconds)
93
+ if (attemptAge < 10000) {
94
+ this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery (${Math.round(attemptAge / 1000)}s ago)`);
95
+ return;
96
+ }
97
+ this.debug.log(`Old connection attempt to ${targetPeerId.substring(0, 8)}... (${Math.round(attemptAge / 1000)}s ago), allowing retry`);
98
+ this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
76
99
  }
77
100
 
78
101
  // INITIATOR LOGIC: Use deterministic peer ID comparison to prevent race conditions
@@ -102,15 +125,22 @@ export class ConnectionManager extends EventEmitter {
102
125
 
103
126
  if (now - lastAttempt < retryDelay) {
104
127
  const remaining = retryDelay - (now - lastAttempt);
105
- this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining / 1000)}s remaining, isolated: ${connectedCount === 0})`);
128
+ this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining)}ms remaining, isolated: ${connectedCount === 0})`);
106
129
  return;
107
130
  }
108
131
  }
109
132
 
110
- // Check connection attempt count
111
- if (attempts >= this.maxConnectionAttempts) {
133
+ // Check connection attempt count - be more lenient for isolated peers
134
+ const connectedCount = this.getConnectedPeerCount();
135
+ const maxAttempts = connectedCount === 0 ? this.maxConnectionAttempts * 2 : this.maxConnectionAttempts;
136
+
137
+ if (attempts >= maxAttempts) {
138
+ this.debug.log(`Max connection attempts (${maxAttempts}) reached for ${targetPeerId.substring(0, 8)}...`);
112
139
  this.mesh.emit('statusChanged', { type: 'warning', message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
113
- this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
140
+ // Don't remove from discovered peers immediately - might reconnect later
141
+ this.connectionAttempts.delete(targetPeerId);
142
+ this.lastConnectionAttempt.delete(targetPeerId);
143
+ this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
114
144
  return;
115
145
  }
116
146
 
@@ -240,6 +240,28 @@ export class GossipManager extends EventEmitter {
240
240
  } else if (subtype === 'mediaEvent') {
241
241
  // Handle media streaming events
242
242
  this.handleMediaEvent(content, originPeerId);
243
+ } else if (subtype === 'stream-chunk') {
244
+ // Handle gossip stream chunks - pass directly to mesh
245
+ this.emit('messageReceived', {
246
+ from: originPeerId,
247
+ message: {
248
+ type: 'stream-chunk',
249
+ ...content
250
+ },
251
+ timestamp,
252
+ messageId
253
+ });
254
+ } else if (subtype === 'stream-control') {
255
+ // Handle gossip stream control messages - pass directly to mesh
256
+ this.emit('messageReceived', {
257
+ from: originPeerId,
258
+ message: {
259
+ type: 'stream-control',
260
+ ...content
261
+ },
262
+ timestamp,
263
+ messageId
264
+ });
243
265
  } else if (subtype === 'dm') {
244
266
  // Direct message logic
245
267
  if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
@@ -270,27 +270,32 @@ export class PeerConnection extends EventEmitter {
270
270
  if (this.connection &&
271
271
  this.connection.iceConnectionState === 'disconnected' &&
272
272
  !this.isClosing) {
273
- // Check if signaling is available before attempting ICE restart
273
+ // ICE "disconnected" state is temporary - WebRTC connections are peer-to-peer
274
+ // and should persist even without signaling. Only disconnect on "failed" state.
275
+ // Check if we have signaling or mesh connectivity for ICE restart attempts
274
276
  const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
275
277
  const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
276
278
 
277
279
  if (hasSignaling || hasMeshConnectivity) {
278
- this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
280
+ this.debug.log(`âš ī¸ ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
279
281
  try {
280
282
  this.restartIceViaSignaling().catch(error => {
281
283
  this.debug.error('Failed to restart ICE after disconnection:', error);
282
- this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
284
+ // Don't disconnect on restart failure - wait for ICE to reach "failed" state naturally
285
+ this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
283
286
  });
284
287
  } catch (error) {
285
288
  this.debug.error('Failed to restart ICE after disconnection:', error);
286
- this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
289
+ // Don't disconnect on restart failure - wait for ICE to reach "failed" state naturally
290
+ this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
287
291
  }
288
292
  } else {
289
- this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, disconnecting`);
290
- this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
293
+ // No signaling available, but WebRTC is peer-to-peer
294
+ // Don't disconnect unless ICE reaches "failed" state
295
+ this.debug.log(`âš ī¸ ICE disconnected for ${this.peerId} without signaling - waiting for ICE state to resolve naturally`);
291
296
  }
292
297
  }
293
- }, 5000); // Faster ICE reconnection - 5 seconds
298
+ }, 5000); // Wait 5 seconds for potential ICE reconnection
294
299
  }
295
300
  };
296
301
 
@@ -38,27 +38,46 @@ export class PeerDiscovery extends EventEmitter {
38
38
  }
39
39
 
40
40
  addDiscoveredPeer(peerId) {
41
- // Skip if we already know about this peer (prevent duplicate processing)
42
- if (this.discoveredPeers.has(peerId)) {
43
- // Update timestamp but don't emit events or trigger connections
44
- this.discoveredPeers.set(peerId, Date.now());
45
- return;
41
+ const wasKnown = this.discoveredPeers.has(peerId);
42
+ const now = Date.now();
43
+
44
+ // Update or add peer with current timestamp
45
+ this.discoveredPeers.set(peerId, now);
46
+
47
+ if (wasKnown) {
48
+ this.debug.log(`Re-discovered peer ${peerId.substring(0, 8)}... (updating timestamp)`);
49
+
50
+ // Clean up stale connection attempt if it's been more than 5 seconds
51
+ if (this.connectionAttempts.has(peerId)) {
52
+ const attemptTime = this.connectionAttempts.get(peerId);
53
+ if (now - attemptTime > 5000) {
54
+ this.debug.log(`Clearing stale connection attempt for ${peerId.substring(0, 8)}...`);
55
+ this.connectionAttempts.delete(peerId);
56
+ }
57
+ }
58
+ } else {
59
+ this.debug.log(`Discovered new peer ${peerId.substring(0, 8)}...`);
60
+ this.emit('peerDiscovered', { peerId });
46
61
  }
47
62
 
48
- this.discoveredPeers.set(peerId, Date.now());
49
- this.emit('peerDiscovered', { peerId });
50
-
51
- this.debug.log(`Discovered peer ${peerId.substring(0, 8)}...`);
52
-
53
- // Only auto-connect if we should initiate to this peer and we're not already trying
54
- if (this.autoDiscovery && this.shouldInitiateConnection(peerId) && !this.connectionAttempts.has(peerId)) {
55
- this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
63
+ // Check if we should initiate connection
64
+ const alreadyTrying = this.connectionAttempts.has(peerId);
65
+ const shouldInitiate = this.shouldInitiateConnection(peerId);
66
+
67
+ if (this.autoDiscovery && shouldInitiate && !alreadyTrying) {
68
+ this.debug.log(`Considering connection to ${peerId.substring(0, 8)}... (shouldInitiate: ${shouldInitiate}, alreadyTrying: ${alreadyTrying})`);
56
69
 
57
70
  const canAccept = this.canAcceptMorePeers();
58
71
  if (canAccept) {
59
- this.debug.log(`Connecting to ${peerId.substring(0, 8)}...`);
72
+ this.debug.log(`🔗 Initiating connection to ${peerId.substring(0, 8)}...`);
60
73
  this.emit('connectToPeer', { peerId });
74
+ } else {
75
+ this.debug.log(`Cannot connect to ${peerId.substring(0, 8)}... (at max peers)`);
61
76
  }
77
+ } else if (alreadyTrying) {
78
+ this.debug.log(`Already attempting connection to ${peerId.substring(0, 8)}...`);
79
+ } else if (!shouldInitiate) {
80
+ this.debug.log(`Not initiating to ${peerId.substring(0, 8)}... (should wait for them to initiate)`);
62
81
  }
63
82
 
64
83
  this.scheduleMeshOptimization();
@@ -94,10 +113,6 @@ export class PeerDiscovery extends EventEmitter {
94
113
  }
95
114
 
96
115
  shouldInitiateConnection(targetPeerId) {
97
- if (this.connectionAttempts.has(targetPeerId)) {
98
- return false;
99
- }
100
-
101
116
  // Check current connection count to handle isolation
102
117
  this.emit('checkCapacity');
103
118
  const currentConnectionCount = this._currentConnectionCount || 0;