peerpigeon 1.0.4 → 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.
Files changed (42) hide show
  1. package/README.md +60 -1
  2. package/dist/peerpigeon-browser.js +800 -36
  3. package/dist/peerpigeon-browser.js.map +3 -3
  4. package/docs/BINARY_IMPLEMENTATION_SUMMARY.md +304 -0
  5. package/docs/BINARY_MESSAGES.md +332 -0
  6. package/docs/BROADCAST_STREAMING.md +388 -0
  7. package/docs/PEER_DISCOVERY_FIXES.md +140 -0
  8. package/docs/STREAMING_API.md +542 -0
  9. package/docs/STREAMING_IMPLEMENTATION_SUMMARY.md +286 -0
  10. package/examples/binary-message-demo.html +496 -0
  11. package/examples/broadcast-stream-demo.html +539 -0
  12. package/examples/browser-2/EXPRESS_SOLUTION.md +183 -0
  13. package/examples/browser-2/ICE_DEBUG.md +171 -0
  14. package/examples/browser-2/IMPLEMENTATION.md +218 -0
  15. package/examples/browser-2/QUICK_START.md +149 -0
  16. package/examples/browser-2/README.md +303 -0
  17. package/examples/browser-2/dist/assets/index-Cck_6WJV.css +1 -0
  18. package/examples/browser-2/dist/assets/index-D8-cNlWQ.js +57 -0
  19. package/examples/browser-2/dist/index.html +32 -0
  20. package/examples/browser-2/dist/peerpigeon-browser.js +12483 -0
  21. package/examples/browser-2/index.html +2 -1
  22. package/examples/browser-2/package-lock.json +1276 -0
  23. package/examples/browser-2/package.json +5 -3
  24. package/examples/browser-2/public/peerpigeon-browser.js +12483 -0
  25. package/examples/browser-2/src/App.vue +7 -4
  26. package/examples/browser-2/src/components/CryptoView.vue +4 -4
  27. package/examples/browser-2/src/components/TestingView.vue +794 -0
  28. package/examples/browser-2/src/main.js +7 -1
  29. package/examples/browser-2/src/router.js +63 -0
  30. package/examples/browser-2/src/stores/peerpigeon.js +68 -7
  31. package/examples/browser-2/vite.config.js +15 -1
  32. package/examples/stream-file-transfer-demo.html +935 -0
  33. package/package.json +1 -1
  34. package/server/index.js +175 -38
  35. package/src/ConnectionManager.js +68 -8
  36. package/src/GossipManager.js +22 -0
  37. package/src/PeerConnection.js +421 -11
  38. package/src/PeerDiscovery.js +33 -18
  39. package/src/PeerPigeonMesh.js +453 -1
  40. package/src/SignalingClient.js +12 -5
  41. package/src/SignalingHandler.js +18 -5
  42. package/src/browser-entry.js +5 -1
@@ -18,6 +18,14 @@ export class PeerConnection extends EventEmitter {
18
18
  this.iceTimeoutId = null; // Timeout ID for ICE negotiation
19
19
  this._forcedStatus = null; // Track forced status (e.g., failed)
20
20
 
21
+ // Binary payload coordination (standard + streaming chunks)
22
+ this._pendingBinaryPayloads = [];
23
+
24
+ // Stream handling
25
+ this._activeStreams = new Map(); // streamId -> { reader/writer, type, metadata }
26
+ this._streamChunks = new Map(); // streamId -> chunks array for reassembly
27
+ this._streamMetadata = new Map(); // streamId -> metadata
28
+
21
29
  // Media stream support
22
30
  this.localStream = options.localStream || null;
23
31
  this.remoteStream = null;
@@ -262,27 +270,32 @@ export class PeerConnection extends EventEmitter {
262
270
  if (this.connection &&
263
271
  this.connection.iceConnectionState === 'disconnected' &&
264
272
  !this.isClosing) {
265
- // 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
266
276
  const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
267
277
  const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
268
278
 
269
279
  if (hasSignaling || hasMeshConnectivity) {
270
- 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})`);
271
281
  try {
272
282
  this.restartIceViaSignaling().catch(error => {
273
283
  this.debug.error('Failed to restart ICE after disconnection:', error);
274
- 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}`);
275
286
  });
276
287
  } catch (error) {
277
288
  this.debug.error('Failed to restart ICE after disconnection:', error);
278
- 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}`);
279
291
  }
280
292
  } else {
281
- this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, disconnecting`);
282
- 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`);
283
296
  }
284
297
  }
285
- }, 5000); // Faster ICE reconnection - 5 seconds
298
+ }, 5000); // Wait 5 seconds for potential ICE reconnection
286
299
  }
287
300
  };
288
301
 
@@ -325,6 +338,13 @@ export class PeerConnection extends EventEmitter {
325
338
  }
326
339
 
327
340
  setupDataChannel() {
341
+ if (!this.dataChannel) {
342
+ this.debug.error('setupDataChannel called without data channel instance');
343
+ return;
344
+ }
345
+
346
+ this.dataChannel.binaryType = 'arraybuffer';
347
+
328
348
  this.dataChannel.onopen = () => {
329
349
  this.debug.log(`Data channel opened with ${this.peerId}`);
330
350
  this.dataChannelReady = true;
@@ -334,16 +354,75 @@ export class PeerConnection extends EventEmitter {
334
354
  this.dataChannel.onclose = () => {
335
355
  this.debug.log(`Data channel closed with ${this.peerId}`);
336
356
  this.dataChannelReady = false;
357
+ this._pendingBinaryPayloads.length = 0;
337
358
 
338
- // Only emit disconnection if we're not intentionally closing
339
359
  if (!this.isClosing) {
340
360
  this.emit('disconnected', { peerId: this.peerId, reason: 'data channel closed' });
341
361
  }
342
362
  };
343
363
 
344
364
  this.dataChannel.onmessage = (event) => {
365
+ const handleBinaryPayload = (buffer) => {
366
+ if (!buffer) return;
367
+
368
+ if (this._pendingBinaryPayloads.length === 0) {
369
+ this.debug.warn('Received unexpected binary payload without metadata');
370
+ return;
371
+ }
372
+
373
+ const payload = this._pendingBinaryPayloads.shift();
374
+ const uint8Array = new Uint8Array(buffer);
375
+
376
+ if (payload.type === 'binaryMessage') {
377
+ if (payload.size && payload.size !== uint8Array.byteLength) {
378
+ this.debug.warn(`Binary message size mismatch: expected ${payload.size}, got ${uint8Array.byteLength}`);
379
+ }
380
+ this.debug.log(`📦 Received binary message (${uint8Array.byteLength} bytes) from ${this.peerId.substring(0, 8)}...`);
381
+ this.emit('message', {
382
+ peerId: this.peerId,
383
+ message: {
384
+ type: 'binary',
385
+ data: uint8Array,
386
+ size: uint8Array.byteLength
387
+ }
388
+ });
389
+ return;
390
+ }
391
+
392
+ if (payload.type === 'streamChunk') {
393
+ this._handleStreamChunkBinary(payload.header, uint8Array);
394
+ return;
395
+ }
396
+
397
+ this.debug.warn(`Received binary payload with unknown handler type: ${payload.type}`);
398
+ };
399
+
400
+ if (event.data instanceof ArrayBuffer) {
401
+ handleBinaryPayload(event.data);
402
+ return;
403
+ }
404
+
405
+ if (typeof Blob !== 'undefined' && event.data instanceof Blob) {
406
+ event.data.arrayBuffer()
407
+ .then(handleBinaryPayload)
408
+ .catch(error => this.debug.error('Failed to read binary payload:', error));
409
+ return;
410
+ }
411
+
345
412
  try {
346
413
  const message = JSON.parse(event.data);
414
+
415
+ if (message.type === '__BINARY__') {
416
+ this._pendingBinaryPayloads.push({ type: 'binaryMessage', size: message.size });
417
+ this.debug.log(`📦 Binary message header received, expecting ${message.size} bytes`);
418
+ return;
419
+ }
420
+
421
+ if (message.type && message.type.startsWith('__STREAM_')) {
422
+ this._handleStreamMessage(message);
423
+ return;
424
+ }
425
+
347
426
  this.emit('message', { peerId: this.peerId, message });
348
427
  } catch (error) {
349
428
  this.debug.error('Failed to parse message:', error);
@@ -354,8 +433,8 @@ export class PeerConnection extends EventEmitter {
354
433
  this.dataChannel.onerror = (error) => {
355
434
  this.debug.error(`Data channel error with ${this.peerId}:`, error);
356
435
  this.dataChannelReady = false;
436
+ this._pendingBinaryPayloads.length = 0;
357
437
 
358
- // Only emit disconnection if we're not intentionally closing
359
438
  if (!this.isClosing) {
360
439
  this.emit('disconnected', { peerId: this.peerId, reason: 'data channel error' });
361
440
  }
@@ -636,8 +715,25 @@ export class PeerConnection extends EventEmitter {
636
715
  sendMessage(message) {
637
716
  if (this.dataChannel && this.dataChannel.readyState === 'open') {
638
717
  try {
639
- this.dataChannel.send(JSON.stringify(message));
640
- return true;
718
+ // Check if message is binary data (ArrayBuffer or TypedArray like Uint8Array)
719
+ if (message instanceof ArrayBuffer || ArrayBuffer.isView(message)) {
720
+ this.debug.log(`📦 Sending binary message (${message.byteLength || message.buffer.byteLength} bytes) to ${this.peerId.substring(0, 8)}...`);
721
+
722
+ // For TypedArray views, send the underlying buffer
723
+ const buffer = ArrayBuffer.isView(message) ? message.buffer : message;
724
+
725
+ // Send a small JSON header first to indicate binary message follows
726
+ const header = JSON.stringify({ type: '__BINARY__', size: buffer.byteLength });
727
+ this.dataChannel.send(header);
728
+
729
+ // Then send the actual binary data
730
+ this.dataChannel.send(buffer);
731
+ return true;
732
+ } else {
733
+ // Regular JSON message
734
+ this.dataChannel.send(JSON.stringify(message));
735
+ return true;
736
+ }
641
737
  } catch (error) {
642
738
  this.debug.error(`Failed to send message to ${this.peerId}:`, error);
643
739
  return false;
@@ -646,6 +742,320 @@ export class PeerConnection extends EventEmitter {
646
742
  return false;
647
743
  }
648
744
 
745
+ /**
746
+ * Create a WritableStream for sending data to this peer
747
+ * @param {object} options - Stream options
748
+ * @returns {WritableStream} A writable stream for sending data
749
+ */
750
+ createWritableStream(options = {}) {
751
+ const streamId = options.streamId || this._generateStreamId();
752
+ const metadata = {
753
+ streamId,
754
+ type: options.type || 'binary',
755
+ filename: options.filename,
756
+ mimeType: options.mimeType,
757
+ totalSize: options.totalSize,
758
+ chunkSize: options.chunkSize,
759
+ timestamp: Date.now()
760
+ };
761
+
762
+ this.debug.log(`📤 Creating writable stream ${streamId} to ${this.peerId.substring(0, 8)}...`);
763
+
764
+ const configuredChunkSize = (typeof metadata.chunkSize === 'number' && Number.isFinite(metadata.chunkSize))
765
+ ? metadata.chunkSize
766
+ : 16384;
767
+
768
+ const chunkSize = Math.max(4096, Math.min(configuredChunkSize, 65536));
769
+ metadata.chunkSize = chunkSize;
770
+
771
+ const highWaterMark = chunkSize * 32;
772
+ const lowWaterMark = chunkSize * 8;
773
+
774
+ const ensureChannelOpen = () => {
775
+ if (!this.dataChannel || this.dataChannel.readyState !== 'open') {
776
+ throw new Error('Data channel not open');
777
+ }
778
+ };
779
+
780
+ const waitForBufferDrain = () => {
781
+ if (!this.dataChannel || this.dataChannel.readyState !== 'open') {
782
+ return Promise.resolve();
783
+ }
784
+
785
+ if (this.dataChannel.bufferedAmount <= lowWaterMark) {
786
+ return Promise.resolve();
787
+ }
788
+
789
+ return new Promise((resolve) => {
790
+ const checkBuffer = () => {
791
+ if (!this.dataChannel || this.dataChannel.readyState !== 'open') {
792
+ resolve();
793
+ return;
794
+ }
795
+
796
+ if (this.dataChannel.bufferedAmount <= lowWaterMark) {
797
+ resolve();
798
+ } else {
799
+ setTimeout(checkBuffer, 20);
800
+ }
801
+ };
802
+
803
+ checkBuffer();
804
+ });
805
+ };
806
+
807
+ // Send stream initialization message
808
+ this.sendMessage({
809
+ type: '__STREAM_INIT__',
810
+ streamId,
811
+ metadata
812
+ });
813
+
814
+ let chunkIndex = 0;
815
+ const self = this;
816
+
817
+ return new WritableStream({
818
+ async write(chunk) {
819
+ ensureChannelOpen();
820
+
821
+ const data = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
822
+ let offset = 0;
823
+
824
+ while (offset < data.byteLength) {
825
+ ensureChannelOpen();
826
+
827
+ const sliceEnd = Math.min(offset + chunkSize, data.byteLength);
828
+ const slice = data.subarray(offset, sliceEnd);
829
+ const sliceBuffer = (slice.byteOffset === 0 && slice.byteLength === slice.buffer.byteLength)
830
+ ? slice.buffer
831
+ : slice.buffer.slice(slice.byteOffset, slice.byteOffset + slice.byteLength);
832
+
833
+ const chunkMessage = {
834
+ type: '__STREAM_CHUNK__',
835
+ streamId,
836
+ chunkIndex: chunkIndex++,
837
+ size: slice.byteLength,
838
+ encoding: 'binary'
839
+ };
840
+
841
+ try {
842
+ self.dataChannel.send(JSON.stringify(chunkMessage));
843
+ self.dataChannel.send(sliceBuffer);
844
+ } catch (error) {
845
+ throw error;
846
+ }
847
+
848
+ offset = sliceEnd;
849
+
850
+ if (self.dataChannel && self.dataChannel.bufferedAmount > highWaterMark) {
851
+ await waitForBufferDrain();
852
+ }
853
+ }
854
+ },
855
+
856
+ async close() {
857
+ if (self.dataChannel && self.dataChannel.readyState === 'open') {
858
+ await waitForBufferDrain();
859
+ self.sendMessage({
860
+ type: '__STREAM_END__',
861
+ streamId,
862
+ totalChunks: chunkIndex
863
+ });
864
+ }
865
+
866
+ self._activeStreams.delete(streamId);
867
+ self.debug.log(`📤 Closed writable stream ${streamId}`);
868
+ },
869
+
870
+ async abort(reason) {
871
+ if (self.dataChannel && self.dataChannel.readyState === 'open') {
872
+ self.sendMessage({
873
+ type: '__STREAM_ABORT__',
874
+ streamId,
875
+ reason: reason?.message || 'Stream aborted'
876
+ });
877
+ }
878
+
879
+ self._activeStreams.delete(streamId);
880
+ self.debug.log(`❌ Aborted writable stream ${streamId}: ${reason}`);
881
+ }
882
+ });
883
+ }
884
+
885
+ /**
886
+ * Handle incoming stream messages and create ReadableStream
887
+ * @private
888
+ */
889
+ _handleStreamMessage(message) {
890
+ const { type } = message;
891
+
892
+ switch (type) {
893
+ case '__STREAM_INIT__':
894
+ this._handleStreamInit(message);
895
+ break;
896
+
897
+ case '__STREAM_CHUNK__':
898
+ if (message.encoding === 'binary') {
899
+ this._pendingBinaryPayloads.push({
900
+ type: 'streamChunk',
901
+ header: message
902
+ });
903
+ } else {
904
+ this._handleStreamChunkLegacy(message);
905
+ }
906
+ break;
907
+
908
+ case '__STREAM_END__':
909
+ this._handleStreamEnd(message);
910
+ break;
911
+
912
+ case '__STREAM_ABORT__':
913
+ this._handleStreamAbort(message);
914
+ break;
915
+ }
916
+ }
917
+
918
+ _handleStreamInit(message) {
919
+ const { streamId, metadata } = message;
920
+
921
+ this.debug.log(`📥 Receiving stream ${streamId} from ${this.peerId.substring(0, 8)}...`);
922
+
923
+ // Store metadata
924
+ this._streamMetadata.set(streamId, metadata);
925
+ this._streamChunks.set(streamId, []);
926
+
927
+ // Create ReadableStream
928
+ const chunks = this._streamChunks.get(streamId);
929
+ let controller;
930
+
931
+ const readable = new ReadableStream({
932
+ start(ctrl) {
933
+ controller = ctrl;
934
+ },
935
+ cancel: (reason) => {
936
+ this.debug.log(`📥 Stream ${streamId} cancelled: ${reason}`);
937
+ }
938
+ });
939
+
940
+ this._activeStreams.set(streamId, {
941
+ type: 'readable',
942
+ stream: readable,
943
+ controller,
944
+ metadata,
945
+ chunks
946
+ });
947
+
948
+ // Emit stream event
949
+ this.emit('streamReceived', {
950
+ peerId: this.peerId,
951
+ streamId,
952
+ stream: readable,
953
+ metadata
954
+ });
955
+ }
956
+
957
+ _handleStreamChunkLegacy(message) {
958
+ const { streamId, chunkIndex, data } = message;
959
+ const streamData = this._activeStreams.get(streamId);
960
+
961
+ if (!streamData) {
962
+ this.debug.warn(`Received chunk for unknown stream ${streamId}`);
963
+ return;
964
+ }
965
+
966
+ // Convert array back to Uint8Array
967
+ const chunk = new Uint8Array(data);
968
+
969
+ // Enqueue chunk to readable stream
970
+ if (streamData.controller) {
971
+ streamData.controller.enqueue(chunk);
972
+ }
973
+
974
+ if (Array.isArray(streamData.chunks)) {
975
+ streamData.chunks.push(chunk);
976
+ }
977
+
978
+ this.debug.log(`📥 Received chunk ${chunkIndex} for stream ${streamId} (${chunk.length} bytes)`);
979
+ }
980
+
981
+ _handleStreamChunkBinary(header, chunk) {
982
+ const { streamId, chunkIndex, size } = header;
983
+ const streamData = this._activeStreams.get(streamId);
984
+
985
+ if (!streamData) {
986
+ this.debug.warn(`Received binary chunk for unknown stream ${streamId}`);
987
+ return;
988
+ }
989
+
990
+ if (size && size !== chunk.byteLength) {
991
+ this.debug.warn(`Stream ${streamId} chunk ${chunkIndex} size mismatch: expected ${size}, got ${chunk.byteLength}`);
992
+ }
993
+
994
+ if (streamData.controller) {
995
+ streamData.controller.enqueue(chunk);
996
+ }
997
+
998
+ if (Array.isArray(streamData.chunks)) {
999
+ streamData.chunks.push(chunk);
1000
+ }
1001
+
1002
+ this.debug.log(`📥 Received chunk ${chunkIndex} for stream ${streamId} (${chunk.byteLength} bytes)`);
1003
+ }
1004
+
1005
+ _handleStreamEnd(message) {
1006
+ const { streamId, totalChunks } = message;
1007
+ const streamData = this._activeStreams.get(streamId);
1008
+
1009
+ if (!streamData) {
1010
+ this.debug.warn(`Received end for unknown stream ${streamId}`);
1011
+ return;
1012
+ }
1013
+
1014
+ // Close the readable stream
1015
+ if (streamData.controller) {
1016
+ streamData.controller.close();
1017
+ }
1018
+
1019
+ this.debug.log(`📥 Stream ${streamId} completed (${totalChunks} chunks)`);
1020
+
1021
+ // Cleanup
1022
+ this._activeStreams.delete(streamId);
1023
+ this._streamChunks.delete(streamId);
1024
+ this._streamMetadata.delete(streamId);
1025
+
1026
+ this.emit('streamCompleted', {
1027
+ peerId: this.peerId,
1028
+ streamId,
1029
+ totalChunks
1030
+ });
1031
+ }
1032
+
1033
+ _handleStreamAbort(message) {
1034
+ const { streamId, reason } = message;
1035
+ const streamData = this._activeStreams.get(streamId);
1036
+
1037
+ if (streamData && streamData.controller) {
1038
+ streamData.controller.error(new Error(reason));
1039
+ }
1040
+
1041
+ this.debug.log(`❌ Stream ${streamId} aborted: ${reason}`);
1042
+
1043
+ // Cleanup
1044
+ this._activeStreams.delete(streamId);
1045
+ this._streamChunks.delete(streamId);
1046
+ this._streamMetadata.delete(streamId);
1047
+
1048
+ this.emit('streamAborted', {
1049
+ peerId: this.peerId,
1050
+ streamId,
1051
+ reason
1052
+ });
1053
+ }
1054
+
1055
+ _generateStreamId() {
1056
+ return `stream-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1057
+ }
1058
+
649
1059
  /**
650
1060
  * CRITICAL FIX: Manually check for new remote tracks after renegotiation
651
1061
  * This is needed because replaceTrack() doesn't trigger ontrack events
@@ -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;