peerpigeon 0.0.8 → 0.1.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.
@@ -1,6 +1,7 @@
1
1
  import { EventEmitter } from './EventEmitter.js';
2
2
  import { PeerConnection } from './PeerConnection.js';
3
3
  import { environmentDetector } from './EnvironmentDetector.js';
4
+ import DebugLogger from './DebugLogger.js';
4
5
 
5
6
  /**
6
7
  * Manages individual peer connections, timeouts, and connection attempts
@@ -9,6 +10,7 @@ export class ConnectionManager extends EventEmitter {
9
10
  constructor(mesh) {
10
11
  super();
11
12
  this.mesh = mesh;
13
+ this.debug = DebugLogger.create('ConnectionManager');
12
14
  this.peers = new Map();
13
15
  this.connectionAttempts = new Map();
14
16
  this.connectionTimeouts = new Map();
@@ -24,31 +26,34 @@ export class ConnectionManager extends EventEmitter {
24
26
 
25
27
  // Start periodic cleanup of stale peers
26
28
  this.startPeriodicCleanup();
29
+
30
+ // Start monitoring for stuck connections
31
+ this.startStuckConnectionMonitoring();
27
32
  }
28
33
 
29
34
  async connectToPeer(targetPeerId) {
30
- console.log(`connectToPeer called for ${targetPeerId.substring(0, 8)}...`);
35
+ this.debug.log(`connectToPeer called for ${targetPeerId.substring(0, 8)}...`);
31
36
 
32
37
  // Enhanced duplicate connection prevention
33
38
  if (this.peers.has(targetPeerId)) {
34
- console.log(`Already connected to ${targetPeerId.substring(0, 8)}...`);
39
+ this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}...`);
35
40
  return;
36
41
  }
37
42
 
38
43
  // Check if we're already in the process of connecting
39
44
  if (this.connectionTimeouts.has(targetPeerId)) {
40
- console.log(`Already connecting to ${targetPeerId.substring(0, 8)}... (connection in progress)`);
45
+ this.debug.log(`Already connecting to ${targetPeerId.substring(0, 8)}... (connection in progress)`);
41
46
  return;
42
47
  }
43
48
 
44
49
  // Check if we're already attempting through PeerDiscovery
45
50
  if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
46
- console.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
51
+ this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
47
52
  return;
48
53
  }
49
54
 
50
55
  if (!this.mesh.canAcceptMorePeers()) {
51
- console.log(`Cannot connect to ${targetPeerId.substring(0, 8)}... (max peers reached: ${this.mesh.maxPeers})`);
56
+ this.debug.log(`Cannot connect to ${targetPeerId.substring(0, 8)}... (max peers reached: ${this.mesh.maxPeers})`);
52
57
  return;
53
58
  }
54
59
 
@@ -64,7 +69,7 @@ export class ConnectionManager extends EventEmitter {
64
69
 
65
70
  if (now - lastAttempt < retryDelay) {
66
71
  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})`);
72
+ this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining / 1000)}s remaining, isolated: ${connectedCount === 0})`);
68
73
  return;
69
74
  }
70
75
  }
@@ -76,7 +81,7 @@ export class ConnectionManager extends EventEmitter {
76
81
  return;
77
82
  }
78
83
 
79
- console.log(`Starting connection to ${targetPeerId.substring(0, 8)}... (attempt ${attempts + 1})`);
84
+ this.debug.log(`Starting connection to ${targetPeerId.substring(0, 8)}... (attempt ${attempts + 1})`);
80
85
  this.connectionAttempts.set(targetPeerId, attempts + 1);
81
86
  this.lastConnectionAttempt.set(targetPeerId, now);
82
87
  this.mesh.peerDiscovery.trackConnectionAttempt(targetPeerId);
@@ -85,26 +90,26 @@ export class ConnectionManager extends EventEmitter {
85
90
  const hasMedia = this.mesh.mediaManager.localStream !== null;
86
91
  const timeoutDuration = hasMedia ? 45000 : 30000; // 45s for media, 30s for data-only
87
92
 
88
- console.log(`Setting connection timeout for ${targetPeerId.substring(0, 8)}... - ${timeoutDuration / 1000}s (media: ${hasMedia})`);
93
+ this.debug.log(`Setting connection timeout for ${targetPeerId.substring(0, 8)}... - ${timeoutDuration / 1000}s (media: ${hasMedia})`);
89
94
 
90
95
  const timeoutId = setTimeout(() => {
91
96
  if (this.peers.has(targetPeerId)) {
92
97
  const peer = this.peers.get(targetPeerId);
93
98
  const status = peer.getStatus();
94
99
  const detailedStatus = peer.getDetailedStatus();
95
- console.log(`Connection timeout check for ${targetPeerId.substring(0, 8)}... - current status: ${status}`);
96
- console.log('Detailed status:', detailedStatus);
100
+ this.debug.log(`Connection timeout check for ${targetPeerId.substring(0, 8)}... - current status: ${status}`);
101
+ this.debug.log('Detailed status:', detailedStatus);
97
102
 
98
103
  // Cleanup if not fully connected (includes 'connecting', 'new', 'failed', etc.)
99
104
  if (status !== 'connected') {
100
105
  this.mesh.emit('statusChanged', { type: 'warning', message: `Connection timeout for ${targetPeerId.substring(0, 8)}... (status: ${status}, media: ${hasMedia})` });
101
106
  this.handleConnectionTimeout(targetPeerId);
102
107
  } else {
103
- console.log(`Connection to ${targetPeerId.substring(0, 8)}... is connected, clearing timeout`);
108
+ this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... is connected, clearing timeout`);
104
109
  this.connectionTimeouts.delete(targetPeerId);
105
110
  }
106
111
  } else {
107
- console.log(`Peer ${targetPeerId.substring(0, 8)}... no longer in peers Map, cleaning up timeout`);
112
+ this.debug.log(`Peer ${targetPeerId.substring(0, 8)}... no longer in peers Map, cleaning up timeout`);
108
113
  this.connectionTimeouts.delete(targetPeerId);
109
114
  }
110
115
  }, timeoutDuration);
@@ -112,14 +117,16 @@ export class ConnectionManager extends EventEmitter {
112
117
  this.connectionTimeouts.set(targetPeerId, timeoutId);
113
118
 
114
119
  try {
115
- console.log(`Creating PeerConnection for ${targetPeerId.substring(0, 8)}...`);
120
+ this.debug.log(`Creating PeerConnection for ${targetPeerId.substring(0, 8)}...`);
116
121
 
117
122
  // Get current media stream if available
118
123
  const localStream = this.mesh.mediaManager.localStream;
119
124
  const options = {
120
125
  localStream,
121
- enableAudio: hasMedia && localStream.getAudioTracks().length > 0,
122
- enableVideo: hasMedia && localStream.getVideoTracks().length > 0
126
+ // ALWAYS enable both audio and video transceivers for maximum compatibility
127
+ // This allows peers to receive media even if they don't have media when connecting
128
+ enableAudio: true,
129
+ enableVideo: true
123
130
  };
124
131
 
125
132
  const peerConnection = new PeerConnection(targetPeerId, true, options);
@@ -128,36 +135,35 @@ export class ConnectionManager extends EventEmitter {
128
135
  this.setupPeerConnectionHandlers(peerConnection);
129
136
  this.peers.set(targetPeerId, peerConnection);
130
137
 
131
- console.log(`Creating WebRTC connection for ${targetPeerId.substring(0, 8)}...`);
138
+ this.debug.log(`Creating WebRTC connection for ${targetPeerId.substring(0, 8)}...`);
132
139
  await peerConnection.createConnection();
133
140
 
134
- console.log(`Creating offer for ${targetPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
141
+ this.debug.log(`Creating offer for ${targetPeerId.substring(0, 8)}... (with media: ${hasMedia})`);
135
142
  const offer = await peerConnection.createOffer();
136
143
 
137
- console.log(`Offer created for ${targetPeerId.substring(0, 8)}...`, {
144
+ this.debug.log(`Offer created for ${targetPeerId.substring(0, 8)}...`, {
138
145
  type: offer.type,
139
146
  sdpLength: offer.sdp?.length || 0,
140
147
  hasAudio: offer.sdp?.includes('m=audio') || false,
141
148
  hasVideo: offer.sdp?.includes('m=video') || false
142
149
  });
143
150
 
144
- console.log(`Sending offer to ${targetPeerId.substring(0, 8)}...`);
145
- await this.mesh.signalingClient.sendSignalingMessage({
151
+ this.debug.log(`Sending offer to ${targetPeerId.substring(0, 8)}...`);
152
+ await this.mesh.sendSignalingMessage({
146
153
  type: 'offer',
147
- data: offer,
148
- targetPeerId
149
- });
154
+ data: offer
155
+ }, targetPeerId);
150
156
 
151
157
  this.mesh.emit('statusChanged', { type: 'info', message: `Offer sent to ${targetPeerId.substring(0, 8)}...` });
152
158
  } catch (error) {
153
- console.error('Failed to connect to peer:', error);
159
+ this.debug.error('Failed to connect to peer:', error);
154
160
  this.mesh.emit('statusChanged', { type: 'error', message: `Failed to connect to ${targetPeerId.substring(0, 8)}...: ${error.message}` });
155
161
  this.cleanupFailedConnection(targetPeerId);
156
162
  }
157
163
  }
158
164
 
159
165
  handleConnectionTimeout(peerId) {
160
- console.log(`Connection timeout for ${peerId.substring(0, 8)}...`);
166
+ this.debug.log(`Connection timeout for ${peerId.substring(0, 8)}...`);
161
167
 
162
168
  const attempts = this.connectionAttempts.get(peerId) || 0;
163
169
  if (attempts >= this.maxConnectionAttempts) {
@@ -166,7 +172,7 @@ export class ConnectionManager extends EventEmitter {
166
172
  this.connectionAttempts.delete(peerId);
167
173
  } else {
168
174
  this.mesh.peerDiscovery.clearConnectionAttempt(peerId);
169
- console.log(`Will retry connection to ${peerId.substring(0, 8)}... (attempt ${attempts}/${this.maxConnectionAttempts})`);
175
+ this.debug.log(`Will retry connection to ${peerId.substring(0, 8)}... (attempt ${attempts}/${this.maxConnectionAttempts})`);
170
176
  }
171
177
 
172
178
  // Always cleanup the failed connection and ensure it's removed from peers Map
@@ -174,21 +180,21 @@ export class ConnectionManager extends EventEmitter {
174
180
 
175
181
  // Double-check that the peer is actually removed from the UI
176
182
  if (this.peers.has(peerId)) {
177
- console.warn(`Peer ${peerId.substring(0, 8)}... still in peers Map after timeout cleanup, force removing`);
183
+ this.debug.warn(`Peer ${peerId.substring(0, 8)}... still in peers Map after timeout cleanup, force removing`);
178
184
  this.peers.delete(peerId);
179
185
  this.emit('peersUpdated');
180
186
  }
181
187
  }
182
188
 
183
189
  cleanupFailedConnection(peerId) {
184
- console.log(`Cleaning up failed connection for ${peerId.substring(0, 8)}...`);
190
+ this.debug.log(`Cleaning up failed connection for ${peerId.substring(0, 8)}...`);
185
191
 
186
192
  // Clear timeout
187
193
  const timeoutId = this.connectionTimeouts.get(peerId);
188
194
  if (timeoutId) {
189
195
  clearTimeout(timeoutId);
190
196
  this.connectionTimeouts.delete(peerId);
191
- console.log(`Cleared timeout for ${peerId.substring(0, 8)}...`);
197
+ this.debug.log(`Cleared timeout for ${peerId.substring(0, 8)}...`);
192
198
  }
193
199
 
194
200
  // Remove peer connection
@@ -196,7 +202,7 @@ export class ConnectionManager extends EventEmitter {
196
202
  if (this.peers.has(peerId)) {
197
203
  const peer = this.peers.get(peerId);
198
204
  const status = peer.getStatus();
199
- console.log(`Removing peer ${peerId.substring(0, 8)}... with status: ${status}`);
205
+ this.debug.log(`Removing peer ${peerId.substring(0, 8)}... with status: ${status}`);
200
206
 
201
207
  try {
202
208
  if (typeof peer.markAsFailed === 'function') {
@@ -204,13 +210,13 @@ export class ConnectionManager extends EventEmitter {
204
210
  }
205
211
  peer.close();
206
212
  } catch (error) {
207
- console.error('Error closing failed connection:', error);
213
+ this.debug.error('Error closing failed connection:', error);
208
214
  }
209
215
  this.peers.delete(peerId);
210
216
  peerRemoved = true;
211
- console.log(`Successfully removed peer ${peerId.substring(0, 8)}... from peers Map`);
217
+ this.debug.log(`Successfully removed peer ${peerId.substring(0, 8)}... from peers Map`);
212
218
  } else {
213
- console.log(`Peer ${peerId.substring(0, 8)}... was not in peers Map`);
219
+ this.debug.log(`Peer ${peerId.substring(0, 8)}... was not in peers Map`);
214
220
  }
215
221
 
216
222
  // Clean up related data
@@ -219,7 +225,7 @@ export class ConnectionManager extends EventEmitter {
219
225
 
220
226
  // Always emit peersUpdated if we removed a peer or to force UI refresh
221
227
  if (peerRemoved) {
222
- console.log(`Emitting peersUpdated after removing ${peerId.substring(0, 8)}...`);
228
+ this.debug.log(`Emitting peersUpdated after removing ${peerId.substring(0, 8)}...`);
223
229
  this.emit('peersUpdated');
224
230
  }
225
231
  }
@@ -238,7 +244,7 @@ export class ConnectionManager extends EventEmitter {
238
244
  try {
239
245
  peer.close();
240
246
  } catch (error) {
241
- console.error('Error closing race condition connection:', error);
247
+ this.debug.error('Error closing race condition connection:', error);
242
248
  }
243
249
  this.peers.delete(peerId);
244
250
  }
@@ -251,19 +257,18 @@ export class ConnectionManager extends EventEmitter {
251
257
  setupPeerConnectionHandlers(peerConnection) {
252
258
  peerConnection.addEventListener('iceCandidate', async (event) => {
253
259
  try {
254
- console.log('Sending ICE candidate to', event.peerId);
255
- await this.mesh.signalingClient.sendSignalingMessage({
260
+ this.debug.log('Sending ICE candidate to', event.peerId);
261
+ await this.mesh.sendSignalingMessage({
256
262
  type: 'ice-candidate',
257
- data: event.candidate,
258
- targetPeerId: event.peerId
259
- });
263
+ data: event.candidate
264
+ }, event.peerId);
260
265
  } catch (error) {
261
- console.error('Failed to send ICE candidate:', error);
266
+ this.debug.error('Failed to send ICE candidate:', error);
262
267
  }
263
268
  });
264
269
 
265
270
  peerConnection.addEventListener('connected', (event) => {
266
- console.log(`[EVENT] Connected event received from ${event.peerId.substring(0, 8)}...`);
271
+ this.debug.log(`[EVENT] Connected event received from ${event.peerId.substring(0, 8)}...`);
267
272
 
268
273
  // Clear connection timeout on successful connection
269
274
  const timeoutId = this.connectionTimeouts.get(event.peerId);
@@ -289,7 +294,7 @@ export class ConnectionManager extends EventEmitter {
289
294
  });
290
295
 
291
296
  peerConnection.addEventListener('dataChannelOpen', (event) => {
292
- console.log(`[EVENT] DataChannelOpen event received from ${event.peerId.substring(0, 8)}...`);
297
+ this.debug.log(`[EVENT] DataChannelOpen event received from ${event.peerId.substring(0, 8)}...`);
293
298
 
294
299
  this.mesh.emit('statusChanged', { type: 'info', message: `Data channel ready with ${event.peerId.substring(0, 8)}...` });
295
300
  this.emit('peersUpdated');
@@ -301,11 +306,11 @@ export class ConnectionManager extends EventEmitter {
301
306
 
302
307
  // Automatically initiate key exchange when crypto is enabled
303
308
  if (this.mesh.cryptoManager) {
304
- console.log(`🔐 Automatically exchanging keys with newly connected peer ${event.peerId.substring(0, 8)}...`);
309
+ this.debug.log(`🔐 Automatically exchanging keys with newly connected peer ${event.peerId.substring(0, 8)}...`);
305
310
  // Use setTimeout to ensure the connection is fully established
306
311
  setTimeout(() => {
307
312
  this.mesh.exchangeKeysWithPeer(event.peerId).catch(error => {
308
- console.error(`🔐 Failed to exchange keys with ${event.peerId.substring(0, 8)}:`, error);
313
+ this.debug.error(`🔐 Failed to exchange keys with ${event.peerId.substring(0, 8)}:`, error);
309
314
  });
310
315
  }, 100);
311
316
  }
@@ -318,52 +323,117 @@ export class ConnectionManager extends EventEmitter {
318
323
  });
319
324
 
320
325
  peerConnection.addEventListener('remoteStream', (event) => {
321
- console.log(`[EVENT] Remote stream received from ${event.peerId.substring(0, 8)}...`);
326
+ this.debug.log(`[EVENT] Remote stream received from ${event.peerId.substring(0, 8)}...`);
322
327
  this.emit('remoteStream', event);
328
+
329
+ // CRITICAL: Forward the stream to other connected peers (media forwarding)
330
+ this._forwardStreamToOtherPeers(event.stream, event.peerId);
323
331
  });
324
332
 
325
333
  peerConnection.addEventListener('renegotiationNeeded', async (event) => {
326
- console.log(`🔄 Renegotiation needed for ${event.peerId.substring(0, 8)}...`);
334
+ this.debug.log(`🔄 Renegotiation needed for ${event.peerId.substring(0, 8)}...`);
327
335
 
328
336
  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})`);
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})`);
332
342
  return;
333
343
  }
334
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
+
335
386
  // Additional check for connection state
336
387
  if (peerConnection.connection.connectionState !== 'connected') {
337
- console.log(`Skipping renegotiation for ${event.peerId.substring(0, 8)}... - not connected (${peerConnection.connection.connectionState})`);
388
+ this.debug.log(`Skipping renegotiation for ${event.peerId.substring(0, 8)}... - not connected (${peerConnection.connection.connectionState})`);
338
389
  return;
339
390
  }
340
391
 
341
- console.log(`🔄 Creating renegotiation offer for ${event.peerId.substring(0, 8)}...`);
392
+ this.debug.log(`🔄 Creating renegotiation offer for ${event.peerId.substring(0, 8)}... (signaling state: ${signalingState})`);
342
393
 
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
- };
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}`);
349
406
 
350
- const offer = await peerConnection.connection.createOffer(offerOptions);
351
407
  await peerConnection.connection.setLocalDescription(offer);
352
408
 
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
358
- });
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);
359
414
 
360
- console.log(`🔄 Sent renegotiation offer to ${event.peerId.substring(0, 8)}...`);
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})`);
361
431
  } catch (error) {
362
- console.error(`Failed to renegotiate with ${event.peerId}:`, error);
432
+ this.debug.error(`Failed to renegotiate with ${event.peerId}:`, error);
363
433
 
364
434
  // If renegotiation fails due to m-line order, log but don't crash
365
435
  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`);
436
+ this.debug.log(`🔄 M-line order error detected for ${event.peerId.substring(0, 8)}... - this is expected with replaceTrack approach`);
367
437
  }
368
438
  }
369
439
  });
@@ -374,11 +444,11 @@ export class ConnectionManager extends EventEmitter {
374
444
  handlePeerDisconnection(peerId, reason) {
375
445
  // Prevent duplicate disconnection handling
376
446
  if (this.disconnectionInProgress.has(peerId)) {
377
- console.log(`Disconnection already in progress for ${peerId.substring(0, 8)}..., skipping duplicate`);
447
+ this.debug.log(`Disconnection already in progress for ${peerId.substring(0, 8)}..., skipping duplicate`);
378
448
  return;
379
449
  }
380
450
 
381
- console.log(`Handling peer disconnection: ${peerId.substring(0, 8)}... (${reason})`);
451
+ this.debug.log(`Handling peer disconnection: ${peerId.substring(0, 8)}... (${reason})`);
382
452
 
383
453
  // Mark disconnection in progress
384
454
  this.disconnectionInProgress.add(peerId);
@@ -397,7 +467,7 @@ export class ConnectionManager extends EventEmitter {
397
467
  try {
398
468
  peerConnection.close();
399
469
  } catch (error) {
400
- console.error('Error closing peer connection:', error);
470
+ this.debug.error('Error closing peer connection:', error);
401
471
  }
402
472
 
403
473
  this.peers.delete(peerId);
@@ -417,7 +487,7 @@ export class ConnectionManager extends EventEmitter {
417
487
  } else if (reason === 'connection failed' || reason === 'connection disconnected' || reason === 'ICE connection closed') {
418
488
  // For connection failures, clear the attempt so we can retry later
419
489
  this.connectionAttempts.delete(peerId);
420
- console.log(`Cleared connection attempt for ${peerId.substring(0, 8)}... due to ${reason} - will retry later`);
490
+ this.debug.log(`Cleared connection attempt for ${peerId.substring(0, 8)}... due to ${reason} - will retry later`);
421
491
  }
422
492
 
423
493
  this.mesh.emit('peerDisconnected', { peerId, reason });
@@ -428,19 +498,19 @@ export class ConnectionManager extends EventEmitter {
428
498
  const needsOptimization = connectedCount === 0; // Only optimize if completely disconnected
429
499
 
430
500
  if (needsOptimization && this.mesh.autoDiscovery && this.mesh.peerDiscovery.getDiscoveredPeers().length > 0) {
431
- console.log(`Completely disconnected (${connectedCount}/${this.mesh.maxPeers}), scheduling mesh optimization`);
501
+ this.debug.log(`Completely disconnected (${connectedCount}/${this.mesh.maxPeers}), scheduling mesh optimization`);
432
502
  setTimeout(() => {
433
503
  // Check if we still need optimization
434
504
  const currentCount = this.getConnectedPeerCount();
435
505
  if (currentCount === 0) {
436
- console.log(`Still completely disconnected (${currentCount}/${this.mesh.maxPeers}), attempting optimization`);
506
+ this.debug.log(`Still completely disconnected (${currentCount}/${this.mesh.maxPeers}), attempting optimization`);
437
507
  this.mesh.peerDiscovery.optimizeMeshConnections(this.peers);
438
508
  } else {
439
- console.log(`Connection recovered (${currentCount}/${this.mesh.maxPeers}), skipping optimization`);
509
+ this.debug.log(`Connection recovered (${currentCount}/${this.mesh.maxPeers}), skipping optimization`);
440
510
  }
441
511
  }, 2000); // Wait 2 seconds before optimizing to allow connections to stabilize
442
512
  } else {
443
- console.log(`Peer count appropriate at ${connectedCount}/${this.mesh.maxPeers}, no optimization needed`);
513
+ this.debug.log(`Peer count appropriate at ${connectedCount}/${this.mesh.maxPeers}, no optimization needed`);
444
514
  }
445
515
  } finally {
446
516
  // Always clean up the disconnection tracking
@@ -498,12 +568,12 @@ export class ConnectionManager extends EventEmitter {
498
568
 
499
569
  // Accept if we have stale peers that can be cleaned up
500
570
  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`);
571
+ this.debug.log(`At capacity (${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total) but have ${stalePeerCount} stale peers that can be evicted`);
502
572
  return true;
503
573
  }
504
574
 
505
575
  // 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`);
576
+ this.debug.log(`Cannot accept more peers: ${connectedCount}/${this.mesh.maxPeers} connected, ${totalPeerCount} total peers in Map`);
507
577
  return false;
508
578
  }
509
579
 
@@ -554,22 +624,22 @@ export class ConnectionManager extends EventEmitter {
554
624
 
555
625
  sendMessage(content) {
556
626
  if (!content || typeof content !== 'string') {
557
- console.error('Invalid message content:', content);
627
+ this.debug.error('Invalid message content:', content);
558
628
  return 0;
559
629
  }
560
630
 
561
631
  // Use gossip protocol to broadcast messages throughout the mesh network
562
- console.log(`Broadcasting message via gossip protocol: "${content}"`);
632
+ this.debug.log(`Broadcasting message via gossip protocol: "${content}"`);
563
633
  const messageId = this.mesh.gossipManager.broadcastMessage(content, 'chat');
564
634
 
565
635
  if (messageId) {
566
636
  // Return the number of directly connected peers for UI feedback
567
637
  // (the message will propagate to the entire network via gossip)
568
638
  const connectedCount = this.getConnectedPeerCount();
569
- console.log(`Message broadcasted via gossip to ${connectedCount} directly connected peer(s), will propagate to entire network`);
639
+ this.debug.log(`Message broadcasted via gossip to ${connectedCount} directly connected peer(s), will propagate to entire network`);
570
640
  return connectedCount;
571
641
  } else {
572
- console.error('Failed to broadcast message via gossip protocol');
642
+ this.debug.error('Failed to broadcast message via gossip protocol');
573
643
  return 0;
574
644
  }
575
645
  }
@@ -583,33 +653,33 @@ export class ConnectionManager extends EventEmitter {
583
653
  sendDirectMessage(peerId, message) {
584
654
  const peerConnection = this.peers.get(peerId);
585
655
  if (!peerConnection) {
586
- console.warn(`Cannot send direct message to ${peerId?.substring(0, 8)}: peer not connected`);
656
+ this.debug.warn(`Cannot send direct message to ${peerId?.substring(0, 8)}: peer not connected`);
587
657
  return false;
588
658
  }
589
659
 
590
660
  try {
591
- console.log(`📤 Sending direct message to ${peerId?.substring(0, 8)}:`, message);
661
+ this.debug.log(`📤 Sending direct message to ${peerId?.substring(0, 8)}:`, message);
592
662
  peerConnection.sendMessage(message);
593
663
  return true;
594
664
  } catch (error) {
595
- console.error(`Failed to send direct message to ${peerId?.substring(0, 8)}:`, error);
665
+ this.debug.error(`Failed to send direct message to ${peerId?.substring(0, 8)}:`, error);
596
666
  return false;
597
667
  }
598
668
  }
599
669
 
600
670
  async handleIceCandidate(candidate, fromPeerId) {
601
- console.log('Handling ICE candidate from', fromPeerId);
671
+ this.debug.log('Handling ICE candidate from', fromPeerId);
602
672
 
603
673
  const peerConnection = this.peers.get(fromPeerId);
604
674
  if (peerConnection) {
605
675
  try {
606
676
  await peerConnection.handleIceCandidate(candidate);
607
677
  } catch (error) {
608
- console.error('Failed to add ICE candidate:', error);
678
+ this.debug.error('Failed to add ICE candidate:', error);
609
679
  }
610
680
  } else {
611
681
  // 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)');
682
+ this.debug.log('Buffering ICE candidate for', fromPeerId, '(no peer connection yet)');
613
683
  if (!this.pendingIceCandidates.has(fromPeerId)) {
614
684
  this.pendingIceCandidates.set(fromPeerId, []);
615
685
  }
@@ -620,7 +690,7 @@ export class ConnectionManager extends EventEmitter {
620
690
  async processPendingIceCandidates(peerId) {
621
691
  const candidates = this.pendingIceCandidates.get(peerId);
622
692
  if (candidates && candidates.length > 0) {
623
- console.log(`Processing ${candidates.length} buffered ICE candidates for`, peerId);
693
+ this.debug.log(`Processing ${candidates.length} buffered ICE candidates for`, peerId);
624
694
  const peerConnection = this.peers.get(peerId);
625
695
 
626
696
  if (peerConnection) {
@@ -628,7 +698,7 @@ export class ConnectionManager extends EventEmitter {
628
698
  try {
629
699
  await peerConnection.handleIceCandidate(candidate);
630
700
  } catch (error) {
631
- console.error('Failed to add buffered ICE candidate:', error);
701
+ this.debug.error('Failed to add buffered ICE candidate:', error);
632
702
  }
633
703
  }
634
704
 
@@ -696,19 +766,19 @@ export class ConnectionManager extends EventEmitter {
696
766
 
697
767
  // Immediately clean up disconnected peers
698
768
  if (status === 'disconnected' && connectionAge > DISCONNECTED_THRESHOLD) {
699
- console.log(`Disconnected peer detected: ${peerId.substring(0, 8)}... (status: ${status}, age: ${Math.round(connectionAge / 1000)}s)`);
769
+ this.debug.log(`Disconnected peer detected: ${peerId.substring(0, 8)}... (status: ${status}, age: ${Math.round(connectionAge / 1000)}s)`);
700
770
  peersToCleanup.push(peerId);
701
771
  } else if (connectionAge > STALE_THRESHOLD) {
702
772
  if (status === 'connecting' || status === 'channel-connecting' ||
703
773
  status === 'failed' || status === 'closed') {
704
- console.log(`Stale peer detected: ${peerId.substring(0, 8)}... (status: ${status}, age: ${Math.round(connectionAge / 1000)}s)`);
774
+ this.debug.log(`Stale peer detected: ${peerId.substring(0, 8)}... (status: ${status}, age: ${Math.round(connectionAge / 1000)}s)`);
705
775
  peersToCleanup.push(peerId);
706
776
  }
707
777
  }
708
778
  });
709
779
 
710
780
  if (peersToCleanup.length > 0) {
711
- console.log(`Cleaning up ${peersToCleanup.length} stale peer(s)`);
781
+ this.debug.log(`Cleaning up ${peersToCleanup.length} stale peer(s)`);
712
782
  peersToCleanup.forEach(peerId => {
713
783
  this.cleanupFailedConnection(peerId);
714
784
  });
@@ -719,24 +789,24 @@ export class ConnectionManager extends EventEmitter {
719
789
  * Force cleanup of peers that are not in connected state (for debugging)
720
790
  */
721
791
  forceCleanupInvalidPeers() {
722
- console.log('Force cleaning up peers not in connected state...');
792
+ this.debug.log('Force cleaning up peers not in connected state...');
723
793
  const peersToRemove = [];
724
794
 
725
795
  this.peers.forEach((peerConnection, peerId) => {
726
796
  const status = peerConnection.getStatus();
727
797
  if (status !== 'connected') {
728
- console.log(`Found peer ${peerId.substring(0, 8)}... in invalid state: ${status}`);
798
+ this.debug.log(`Found peer ${peerId.substring(0, 8)}... in invalid state: ${status}`);
729
799
  peersToRemove.push(peerId);
730
800
  }
731
801
  });
732
802
 
733
803
  peersToRemove.forEach(peerId => {
734
- console.log(`Force removing peer ${peerId.substring(0, 8)}...`);
804
+ this.debug.log(`Force removing peer ${peerId.substring(0, 8)}...`);
735
805
  this.cleanupFailedConnection(peerId);
736
806
  });
737
807
 
738
808
  if (peersToRemove.length > 0) {
739
- console.log(`Force cleaned up ${peersToRemove.length} invalid peers`);
809
+ this.debug.log(`Force cleaned up ${peersToRemove.length} invalid peers`);
740
810
  this.emit('peersUpdated');
741
811
  }
742
812
 
@@ -813,7 +883,7 @@ export class ConnectionManager extends EventEmitter {
813
883
  */
814
884
  handleIncomingMessage(message, fromPeerId) {
815
885
  if (!message || typeof message !== 'object') {
816
- console.warn('Received invalid message from', fromPeerId?.substring(0, 8));
886
+ this.debug.warn('Received invalid message from', fromPeerId?.substring(0, 8));
817
887
  return;
818
888
  }
819
889
 
@@ -822,7 +892,7 @@ export class ConnectionManager extends EventEmitter {
822
892
  case 'gossip':
823
893
  // Gossip protocol messages (async call, but we don't wait for it)
824
894
  this.mesh.gossipManager.handleGossipMessage(message, fromPeerId).catch(error => {
825
- console.error('Error handling gossip message:', error);
895
+ this.debug.error('Error handling gossip message:', error);
826
896
  });
827
897
  break;
828
898
 
@@ -838,11 +908,39 @@ export class ConnectionManager extends EventEmitter {
838
908
  }
839
909
  break;
840
910
 
911
+ case 'renegotiation-offer':
912
+ // Handle renegotiation offers from peers
913
+ this.handleRenegotiationOffer(message, fromPeerId);
914
+ break;
915
+
916
+ case 'renegotiation-answer':
917
+ // Handle renegotiation answers from peers
918
+ this.handleRenegotiationAnswer(message, fromPeerId);
919
+ break;
920
+
921
+ case 'signaling':
922
+ // Handle wrapped signaling messages sent via mesh
923
+ this.debug.log(`🔄 MESH SIGNALING: Received ${message.data?.type} from ${fromPeerId?.substring(0, 8)}...`);
924
+ if (message.data && message.data.type) {
925
+ // Unwrap and handle the signaling message
926
+ const signalingMessage = {
927
+ type: message.data.type,
928
+ data: message.data.data,
929
+ fromPeerId: message.fromPeerId || fromPeerId,
930
+ targetPeerId: this.mesh.peerId,
931
+ timestamp: message.timestamp
932
+ };
933
+
934
+ // Route to signaling handler
935
+ this.mesh.signalingHandler.handleSignalingMessage(signalingMessage);
936
+ }
937
+ break;
938
+
841
939
  default:
842
940
  // 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`);
941
+ this.debug.warn(`Unknown message type '${message.type}' from ${fromPeerId?.substring(0, 8)}, trying gossip handler`);
844
942
  this.mesh.gossipManager.handleGossipMessage(message, fromPeerId).catch(error => {
845
- console.error('Error handling unknown message as gossip:', error);
943
+ this.debug.error('Error handling unknown message as gossip:', error);
846
944
  });
847
945
  break;
848
946
  }
@@ -852,7 +950,7 @@ export class ConnectionManager extends EventEmitter {
852
950
  * Handle eviction messages
853
951
  */
854
952
  handleEvictionMessage(message, fromPeerId) {
855
- console.log(`Received eviction notice from ${fromPeerId?.substring(0, 8)}: ${message.reason}`);
953
+ this.debug.log(`Received eviction notice from ${fromPeerId?.substring(0, 8)}: ${message.reason}`);
856
954
 
857
955
  // Emit eviction event for UI notification
858
956
  this.mesh.emit('peerEvicted', {
@@ -868,4 +966,211 @@ export class ConnectionManager extends EventEmitter {
868
966
  this.peers.delete(fromPeerId);
869
967
  }
870
968
  }
969
+
970
+ /**
971
+ * Handle renegotiation offers from peers
972
+ */
973
+ async handleRenegotiationOffer(message, fromPeerId) {
974
+ this.debug.log(`🔄 Handling renegotiation offer via mesh from ${fromPeerId.substring(0, 8)}...`);
975
+
976
+ // Find the existing peer connection
977
+ const peerConnection = this.peers.get(fromPeerId);
978
+ if (!peerConnection) {
979
+ this.debug.error(`No peer connection found for renegotiation from ${fromPeerId.substring(0, 8)}...`);
980
+ return;
981
+ }
982
+
983
+ try {
984
+ // Handle the renegotiation offer and get the answer
985
+ const answer = await peerConnection.handleOffer(message.data);
986
+ this.debug.log(`✅ Renegotiation offer processed, sending answer to ${fromPeerId.substring(0, 8)}...`);
987
+
988
+ // Send the answer back to complete the renegotiation handshake
989
+ await this.mesh.sendSignalingMessage({
990
+ type: 'renegotiation-answer',
991
+ data: answer
992
+ }, fromPeerId);
993
+
994
+ this.debug.log(`✅ Renegotiation completed via mesh with ${fromPeerId.substring(0, 8)}...`);
995
+ } catch (error) {
996
+ this.debug.error(`❌ Failed to handle renegotiation offer via mesh from ${fromPeerId.substring(0, 8)}...`, error);
997
+ }
998
+ }
999
+
1000
+ async handleRenegotiationAnswer(message, fromPeerId) {
1001
+ this.debug.log(`🔄 Handling renegotiation answer via mesh from ${fromPeerId.substring(0, 8)}...`);
1002
+
1003
+ // Find the existing peer connection
1004
+ const peerConnection = this.peers.get(fromPeerId);
1005
+ if (!peerConnection) {
1006
+ this.debug.error(`No peer connection found for renegotiation answer from ${fromPeerId.substring(0, 8)}...`);
1007
+ return;
1008
+ }
1009
+
1010
+ try {
1011
+ // Handle the renegotiation answer
1012
+ await peerConnection.handleAnswer(message.data);
1013
+ this.debug.log(`✅ Renegotiation answer processed from ${fromPeerId.substring(0, 8)}... - renegotiation complete`);
1014
+ } catch (error) {
1015
+ this.debug.error(`❌ Failed to handle renegotiation answer via mesh from ${fromPeerId.substring(0, 8)}...`, error);
1016
+ }
1017
+ }
1018
+
1019
+ /**
1020
+ * Monitor and fix stuck connections that remain in "have-local-offer" state
1021
+ * This is called periodically to detect and fix connections that get stuck
1022
+ */
1023
+ monitorAndFixStuckConnections() {
1024
+ if (!this.mesh.connected) return;
1025
+
1026
+ const stuckConnections = [];
1027
+
1028
+ for (const [peerId, peerConnection] of this.peers) {
1029
+ if (peerConnection.connection?.signalingState === 'have-local-offer') {
1030
+ const connectionAge = Date.now() - peerConnection.connectionStartTime;
1031
+
1032
+ // If connection has been stuck in "have-local-offer" for more than 10 seconds, fix it
1033
+ if (connectionAge > 10000) {
1034
+ stuckConnections.push(peerId);
1035
+ }
1036
+ }
1037
+ }
1038
+
1039
+ if (stuckConnections.length > 0) {
1040
+ this.debug.log(`🚨 STUCK MONITOR: Found ${stuckConnections.length} stuck connections - forcing recovery`);
1041
+
1042
+ for (const peerId of stuckConnections) {
1043
+ this.forceConnectionRecovery(peerId).catch(error => {
1044
+ this.debug.error(`Failed to recover stuck connection for ${peerId}:`, error);
1045
+ });
1046
+ }
1047
+ }
1048
+ }
1049
+
1050
+ /**
1051
+ * Force recovery of a stuck connection by completely recreating it
1052
+ */
1053
+ async forceConnectionRecovery(peerId) {
1054
+ const peerConnection = this.getPeer(peerId);
1055
+ if (!peerConnection) {
1056
+ this.debug.error(`Cannot recover - peer ${peerId} not found`);
1057
+ return null;
1058
+ }
1059
+
1060
+ this.debug.log(`🔄 FORCE RECOVERY: Completely recreating connection for ${peerId.substring(0, 8)}...`);
1061
+
1062
+ try {
1063
+ // Preserve the current media stream
1064
+ const currentLocalStream = peerConnection.getLocalStream();
1065
+
1066
+ // Close the stuck connection
1067
+ peerConnection.close();
1068
+
1069
+ // Remove from peers map
1070
+ this.peers.delete(peerId);
1071
+
1072
+ // Create a completely fresh connection
1073
+ const freshConnection = await this.connectToPeer(peerId, false, {
1074
+ localStream: currentLocalStream
1075
+ });
1076
+
1077
+ if (freshConnection && currentLocalStream) {
1078
+ // Apply the media stream to the fresh connection
1079
+ await freshConnection.setLocalStream(currentLocalStream);
1080
+ this.debug.log(`✅ FORCE RECOVERY: Fresh connection created with media for ${peerId.substring(0, 8)}...`);
1081
+ }
1082
+
1083
+ return freshConnection;
1084
+ } catch (error) {
1085
+ this.debug.error(`❌ FORCE RECOVERY: Failed to recreate connection for ${peerId.substring(0, 8)}...`, error);
1086
+ throw error;
1087
+ }
1088
+ }
1089
+
1090
+ /**
1091
+ * Start monitoring for stuck connections
1092
+ */
1093
+ startStuckConnectionMonitoring() {
1094
+ // Check every 15 seconds for stuck connections
1095
+ setInterval(() => {
1096
+ this.monitorAndFixStuckConnections();
1097
+ }, 15000);
1098
+
1099
+ this.debug.log('🔍 Started stuck connection monitoring');
1100
+ }
1101
+
1102
+ /**
1103
+ * Forward a received stream to all other connected peers (except the sender)
1104
+ * This implements media forwarding through the mesh topology
1105
+ * @param {MediaStream} stream - The stream to forward
1106
+ * @param {string} sourcePeerId - The peer ID that sent the stream (don't forward back to them)
1107
+ * @private
1108
+ */
1109
+ async _forwardStreamToOtherPeers(stream, sourcePeerId) {
1110
+ if (!stream || !sourcePeerId) {
1111
+ this.debug.warn('Cannot forward stream - invalid parameters');
1112
+ return;
1113
+ }
1114
+
1115
+ this.debug.log(`🔄 FORWARD STREAM: Forwarding stream from ${sourcePeerId.substring(0, 8)}... to other connected peers`);
1116
+
1117
+ // Get the original source peer ID from the stream metadata
1118
+ const originalSourcePeerId = stream._peerPigeonSourcePeerId || sourcePeerId;
1119
+
1120
+ // Count how many peers we're forwarding to
1121
+ let forwardCount = 0;
1122
+
1123
+ // Forward to all connected peers except the source and the original sender
1124
+ for (const [peerId, connection] of this.peers) {
1125
+ // Skip the peer who sent us the stream
1126
+ if (peerId === sourcePeerId) {
1127
+ this.debug.log(`🔄 FORWARD STREAM: Skipping source peer ${peerId.substring(0, 8)}...`);
1128
+ continue;
1129
+ }
1130
+
1131
+ // Skip the original peer who created the stream (to prevent loops)
1132
+ if (peerId === originalSourcePeerId) {
1133
+ this.debug.log(`🔄 FORWARD STREAM: Skipping original stream creator ${peerId.substring(0, 8)}...`);
1134
+ continue;
1135
+ }
1136
+
1137
+ // Only forward to connected peers
1138
+ if (connection.getStatus() !== 'connected') {
1139
+ this.debug.log(`🔄 FORWARD STREAM: Skipping disconnected peer ${peerId.substring(0, 8)}...`);
1140
+ continue;
1141
+ }
1142
+
1143
+ try {
1144
+ this.debug.log(`🔄 FORWARD STREAM: Setting forwarded stream for peer ${peerId.substring(0, 8)}...`);
1145
+
1146
+ // CRITICAL: Clone the stream to avoid conflicts
1147
+ const forwardedStream = stream.clone();
1148
+
1149
+ // Mark the forwarded stream with original source information
1150
+ Object.defineProperty(forwardedStream, '_peerPigeonSourcePeerId', {
1151
+ value: originalSourcePeerId,
1152
+ writable: false,
1153
+ enumerable: false,
1154
+ configurable: false
1155
+ });
1156
+
1157
+ Object.defineProperty(forwardedStream, '_peerPigeonOrigin', {
1158
+ value: 'forwarded',
1159
+ writable: false,
1160
+ enumerable: false,
1161
+ configurable: false
1162
+ });
1163
+
1164
+ // Set the cloned stream as the local stream for this connection
1165
+ await connection.setLocalStream(forwardedStream);
1166
+
1167
+ forwardCount++;
1168
+ this.debug.log(`✅ FORWARD STREAM: Successfully forwarded stream to peer ${peerId.substring(0, 8)}...`);
1169
+ } catch (error) {
1170
+ this.debug.error(`❌ FORWARD STREAM: Failed to forward stream to peer ${peerId.substring(0, 8)}...`, error);
1171
+ }
1172
+ }
1173
+
1174
+ this.debug.log(`🔄 FORWARD STREAM: Forwarded stream from ${sourcePeerId.substring(0, 8)}... to ${forwardCount} peer(s)`);
1175
+ }
871
1176
  }