peerpigeon 0.0.3 → 0.0.5

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.
@@ -0,0 +1,1930 @@
1
+ // Updated: 2025-07-04 - Fixed getConnectionStatus method name
2
+ export class PeerPigeonUI {
3
+ constructor(mesh) {
4
+ this.mesh = mesh;
5
+ this.lastCleanupTime = 0; // Track when we last did cleanup
6
+ this.setupEventListeners();
7
+ this.bindDOMEvents();
8
+ this.initializeMedia();
9
+ }
10
+
11
+ setupEventListeners() {
12
+ this.mesh.addEventListener('statusChanged', (data) => {
13
+ this.handleStatusChange(data);
14
+ });
15
+
16
+ this.mesh.addEventListener('peerDiscovered', (data) => {
17
+ this.updateDiscoveredPeers();
18
+ });
19
+
20
+ this.mesh.addEventListener('peerConnected', (data) => {
21
+ this.updateUI();
22
+ this.updateDiscoveredPeers();
23
+ });
24
+
25
+ this.mesh.addEventListener('peerDisconnected', (data) => {
26
+ this.addMessage('System', `Peer ${data.peerId.substring(0, 8)}... disconnected (${data.reason})`);
27
+ this.updateUI();
28
+ this.updateDiscoveredPeers();
29
+ });
30
+
31
+ this.mesh.addEventListener('messageReceived', (data) => {
32
+ // Only show messages from other peers, not self
33
+ if (data.from !== this.mesh.peerId) {
34
+ if (data.direct) {
35
+ this.addMessage(`${data.from.substring(0, 8)}...`, `(DM) ${data.content}`, 'dm');
36
+ } else {
37
+ this.addMessage(`${data.from.substring(0, 8)}...`, data.content);
38
+ }
39
+ }
40
+ });
41
+
42
+ this.mesh.addEventListener('peerEvicted', (data) => {
43
+ this.updateUI();
44
+ this.updateDiscoveredPeers();
45
+ });
46
+
47
+ this.mesh.addEventListener('peersUpdated', () => {
48
+ this.updateDiscoveredPeers();
49
+ });
50
+
51
+ this.mesh.addEventListener('connectionStats', (stats) => {
52
+ // Handle connection stats if needed
53
+ });
54
+
55
+ // DHT event listeners
56
+ this.mesh.addEventListener('dhtValueChanged', (data) => {
57
+ const { key, newValue, timestamp } = data;
58
+ this.addDHTLogEntry(`🔔 Value Changed: ${key} = ${JSON.stringify(newValue)} (timestamp: ${timestamp})`);
59
+ });
60
+
61
+ // Media event listeners
62
+ this.mesh.addEventListener('localStreamStarted', (data) => {
63
+ this.handleLocalStreamStarted(data);
64
+ });
65
+
66
+ this.mesh.addEventListener('localStreamStopped', () => {
67
+ this.handleLocalStreamStopped();
68
+ });
69
+
70
+ this.mesh.addEventListener('mediaError', (data) => {
71
+ this.addMessage('System', `Media error: ${data.error.message}`, 'error');
72
+ });
73
+
74
+ // Listen for remote streams
75
+ this.mesh.addEventListener('remoteStream', (data) => {
76
+ this.handleRemoteStream(data);
77
+ });
78
+ }
79
+
80
+ handleStatusChange(data) {
81
+ switch (data.type) {
82
+ case 'initialized':
83
+ this.updateUI();
84
+ break;
85
+ case 'connecting':
86
+ this.addMessage('System', 'Connecting to signaling server...');
87
+ this.updateUI();
88
+ break;
89
+ case 'connected':
90
+ this.addMessage('System', 'Connected to signaling server');
91
+ this.updateUI();
92
+ break;
93
+ case 'disconnected':
94
+ this.addMessage('System', 'Disconnected from signaling server');
95
+ this.updateUI();
96
+ this.updateDiscoveredPeers();
97
+ break;
98
+ case 'error':
99
+ this.addMessage('System', data.message, 'error');
100
+ this.updateUI();
101
+ break;
102
+ case 'warning':
103
+ this.addMessage('System', data.message, 'warning');
104
+ break;
105
+ case 'info':
106
+ this.addMessage('System', data.message);
107
+ break;
108
+ case 'urlLoaded':
109
+ document.getElementById('signaling-url').value = data.signalingUrl;
110
+ this.addMessage('System', `API Gateway URL loaded: ${data.signalingUrl}`);
111
+ break;
112
+ case 'setting':
113
+ const settingName = data.setting === 'autoDiscovery' ? 'Auto discovery' :
114
+ data.setting === 'evictionStrategy' ? 'Smart eviction strategy' :
115
+ data.setting === 'xorRouting' ? 'XOR-based routing' :
116
+ data.setting === 'connectionType' ? 'Connection type' : data.setting;
117
+
118
+ if (data.setting === 'connectionType') {
119
+ this.addMessage('System', `${settingName} set to: ${data.value}`);
120
+ } else {
121
+ this.addMessage('System', `${settingName} ${data.value ? 'enabled' : 'disabled'}`);
122
+ }
123
+ break;
124
+ }
125
+ }
126
+
127
+ bindDOMEvents() {
128
+ // Connection controls
129
+ document.getElementById('connect-btn').addEventListener('click', () => {
130
+ this.handleConnect();
131
+ });
132
+
133
+ document.getElementById('disconnect-btn').addEventListener('click', () => {
134
+ this.handleDisconnect();
135
+ });
136
+
137
+ document.getElementById('cleanup-btn').addEventListener('click', () => {
138
+ this.handleCleanup();
139
+ });
140
+
141
+ document.getElementById('health-check-btn').addEventListener('click', () => {
142
+ this.handleHealthCheck();
143
+ });
144
+
145
+ document.getElementById('refresh-btn').addEventListener('click', () => {
146
+ window.location.reload();
147
+ });
148
+
149
+ // Messaging
150
+ document.getElementById('send-message-btn').addEventListener('click', () => {
151
+ this.sendMessage();
152
+ });
153
+
154
+ document.getElementById('message-input').addEventListener('keypress', (e) => {
155
+ if (e.key === 'Enter') {
156
+ this.sendMessage();
157
+ }
158
+ });
159
+
160
+ // Manual connection
161
+ document.getElementById('connect-peer-btn').addEventListener('click', () => {
162
+ this.connectToPeer();
163
+ });
164
+
165
+ document.getElementById('target-peer').addEventListener('keypress', (e) => {
166
+ if (e.key === 'Enter') {
167
+ this.connectToPeer();
168
+ }
169
+ });
170
+
171
+ // Settings
172
+ document.getElementById('min-peers').addEventListener('change', (e) => {
173
+ this.mesh.setMinPeers(parseInt(e.target.value));
174
+ });
175
+
176
+ document.getElementById('max-peers').addEventListener('change', (e) => {
177
+ this.mesh.setMaxPeers(parseInt(e.target.value));
178
+ });
179
+
180
+ document.getElementById('auto-discovery-toggle').addEventListener('change', (e) => {
181
+ this.mesh.setAutoDiscovery(e.target.checked);
182
+ });
183
+
184
+ document.getElementById('eviction-strategy-toggle').addEventListener('change', (e) => {
185
+ this.mesh.setEvictionStrategy(e.target.checked);
186
+ });
187
+
188
+ document.getElementById('xor-routing-toggle').addEventListener('change', (e) => {
189
+ this.mesh.setXorRouting(e.target.checked);
190
+ });
191
+
192
+ // DHT controls
193
+ this.setupDHTControls();
194
+
195
+ // Collapsible sections
196
+ this.setupCollapsibleSections();
197
+
198
+ // Media controls
199
+ this.setupMediaControls();
200
+ }
201
+
202
+ setupDHTControls() {
203
+ // DHT input fields and controls
204
+ const dhtKey = document.getElementById('dht-key');
205
+ const dhtValue = document.getElementById('dht-value');
206
+ const dhtGetKey = document.getElementById('dht-get-key'); // Separate key field for retrieval
207
+ const dhtPutBtn = document.getElementById('dht-put-btn');
208
+ const dhtUpdateBtn = document.getElementById('dht-update-btn');
209
+ const dhtGetBtn = document.getElementById('dht-get-btn');
210
+ const dhtSubscribeBtn = document.getElementById('dht-subscribe-btn');
211
+ const dhtUnsubscribeBtn = document.getElementById('dht-unsubscribe-btn');
212
+ const dhtEnableTtl = document.getElementById('dht-enable-ttl');
213
+ const dhtTtlGroup = document.getElementById('dht-ttl-group');
214
+ const dhtTtl = document.getElementById('dht-ttl');
215
+
216
+ // Debug: Check if elements are found
217
+ console.log('DHT Controls setup - Elements found:', {
218
+ dhtKey: !!dhtKey,
219
+ dhtValue: !!dhtValue,
220
+ dhtGetKey: !!dhtGetKey,
221
+ dhtPutBtn: !!dhtPutBtn,
222
+ dhtUpdateBtn: !!dhtUpdateBtn,
223
+ dhtGetBtn: !!dhtGetBtn,
224
+ dhtSubscribeBtn: !!dhtSubscribeBtn,
225
+ dhtUnsubscribeBtn: !!dhtUnsubscribeBtn
226
+ });
227
+
228
+ if (!dhtKey) {
229
+ console.error('DHT key input element not found!');
230
+ this.addDHTLogEntry('❌ Error: DHT key input field not found in DOM');
231
+ }
232
+
233
+ if (!dhtValue) {
234
+ console.error('DHT value input element not found!');
235
+ this.addDHTLogEntry('❌ Error: DHT value input field not found in DOM');
236
+ }
237
+
238
+ if (!dhtGetKey) {
239
+ console.error('DHT get-key input element not found!');
240
+ this.addDHTLogEntry('❌ Error: DHT get-key input field not found in DOM');
241
+ }
242
+
243
+ // Toggle TTL input visibility
244
+ if (dhtEnableTtl && dhtTtlGroup) {
245
+ dhtEnableTtl.addEventListener('change', (e) => {
246
+ dhtTtlGroup.style.display = e.target.checked ? 'block' : 'none';
247
+ });
248
+ }
249
+
250
+ // Store in DHT
251
+ if (dhtPutBtn) {
252
+ dhtPutBtn.addEventListener('click', async () => {
253
+ const key = dhtKey?.value?.trim();
254
+ const value = dhtValue?.value?.trim();
255
+
256
+ // Debug logging
257
+ console.log('DHT PUT - Elements found:', {
258
+ dhtKey: !!dhtKey,
259
+ dhtValue: !!dhtValue,
260
+ keyValue: key,
261
+ valueValue: value
262
+ });
263
+
264
+ if (!key || !value) {
265
+ this.addDHTLogEntry('❌ Error: Both key and value are required');
266
+ this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
267
+ return;
268
+ }
269
+
270
+ if (!this.mesh.isDHTEnabled()) {
271
+ this.addDHTLogEntry('❌ Error: WebDHT is disabled');
272
+ return;
273
+ }
274
+
275
+ try {
276
+ let parsedValue;
277
+ try {
278
+ parsedValue = JSON.parse(value);
279
+ } catch {
280
+ parsedValue = value; // Use as string if not valid JSON
281
+ }
282
+
283
+ const options = {};
284
+ if (dhtEnableTtl?.checked && dhtTtl?.value) {
285
+ options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
286
+ }
287
+
288
+ const success = await this.mesh.dhtPut(key, parsedValue, options);
289
+ if (success) {
290
+ this.addDHTLogEntry(`✅ Stored: ${key} = ${JSON.stringify(parsedValue)}`);
291
+ if (options.ttl) {
292
+ this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
293
+ }
294
+ this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
295
+
296
+ // Auto-subscribe to the key we just stored (essential for original storing peers)
297
+ try {
298
+ await this.mesh.dhtSubscribe(key);
299
+ this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
300
+ this.addDHTLogEntry(` 📡 Will receive and relay all future updates for this key`);
301
+ } catch (subscribeError) {
302
+ this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
303
+ }
304
+ } else {
305
+ this.addDHTLogEntry(`❌ Failed to store: ${key}`);
306
+ }
307
+ } catch (error) {
308
+ this.addDHTLogEntry(`❌ Error storing ${key}: ${error.message}`);
309
+ }
310
+ });
311
+ }
312
+
313
+ // Update in DHT
314
+ if (dhtUpdateBtn) {
315
+ dhtUpdateBtn.addEventListener('click', async () => {
316
+ const key = dhtKey?.value?.trim();
317
+ const value = dhtValue?.value?.trim();
318
+
319
+ // Debug logging
320
+ console.log('DHT UPDATE - Elements found:', {
321
+ dhtKey: !!dhtKey,
322
+ dhtValue: !!dhtValue,
323
+ keyValue: key,
324
+ valueValue: value
325
+ });
326
+
327
+ if (!key || !value) {
328
+ this.addDHTLogEntry('❌ Error: Both key and value are required');
329
+ this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
330
+ return;
331
+ }
332
+
333
+ if (!this.mesh.isDHTEnabled()) {
334
+ this.addDHTLogEntry('❌ Error: WebDHT is disabled');
335
+ return;
336
+ }
337
+
338
+ try {
339
+ let parsedValue;
340
+ try {
341
+ parsedValue = JSON.parse(value);
342
+ } catch {
343
+ parsedValue = value; // Use as string if not valid JSON
344
+ }
345
+
346
+ const options = {};
347
+ if (dhtEnableTtl?.checked && dhtTtl?.value) {
348
+ options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
349
+ }
350
+
351
+ const success = await this.mesh.dhtUpdate(key, parsedValue, options);
352
+ if (success) {
353
+ this.addDHTLogEntry(`🔄 Updated: ${key} = ${JSON.stringify(parsedValue)}`);
354
+ if (options.ttl) {
355
+ this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
356
+ }
357
+ this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
358
+
359
+ // Auto-subscribe to the key we just updated (essential for original storing peers)
360
+ try {
361
+ await this.mesh.dhtSubscribe(key);
362
+ this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
363
+ this.addDHTLogEntry(` 📡 Will receive and relay all future updates for this key`);
364
+ } catch (subscribeError) {
365
+ this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
366
+ }
367
+ } else {
368
+ this.addDHTLogEntry(`❌ Failed to update: ${key}`);
369
+ }
370
+ } catch (error) {
371
+ this.addDHTLogEntry(`❌ Error updating ${key}: ${error.message}`);
372
+ }
373
+ });
374
+ }
375
+
376
+ // Get from DHT
377
+ if (dhtGetBtn) {
378
+ dhtGetBtn.addEventListener('click', async () => {
379
+ const key = dhtGetKey?.value?.trim(); // Fixed: Use dhtGetKey instead of dhtKey
380
+
381
+ // Debug logging
382
+ console.log('DHT GET - Elements found:', {
383
+ dhtGetKey: !!dhtGetKey,
384
+ keyValue: key
385
+ });
386
+
387
+ if (!key) {
388
+ this.addDHTLogEntry('❌ Error: Key is required');
389
+ this.addDHTLogEntry(` Debug: key="${key}"`);
390
+ return;
391
+ }
392
+
393
+ if (!this.mesh.isDHTEnabled()) {
394
+ this.addDHTLogEntry('❌ Error: WebDHT is disabled');
395
+ return;
396
+ }
397
+
398
+ try {
399
+ this.addDHTLogEntry(`🔍 Fetching from ORIGINAL STORING PEERS: ${key}`);
400
+ this.addDHTLogEntry(` 📡 Bypassing local cache to ensure fresh data`);
401
+
402
+ // Force fresh retrieval from original storing peers
403
+ const value = await this.mesh.dhtGet(key, { forceRefresh: true });
404
+ if (value !== null) {
405
+ this.addDHTLogEntry(`📥 Retrieved from original peers: ${key} = ${JSON.stringify(value)}`);
406
+ this.addDHTLogEntry(` ✅ Data is FRESH from authoritative source`);
407
+ if (dhtValue) {
408
+ dhtValue.value = typeof value === 'string' ? value : JSON.stringify(value);
409
+ }
410
+
411
+ // Auto-subscribe to the key we just retrieved for future updates
412
+ try {
413
+ await this.mesh.dhtSubscribe(key);
414
+ this.addDHTLogEntry(`🔔 Auto-subscribed for future updates: ${key}`);
415
+ this.addDHTLogEntry(` 📡 Will receive notifications when original peers update this key`);
416
+ } catch (subscribeError) {
417
+ this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
418
+ }
419
+ } else {
420
+ this.addDHTLogEntry(`❌ Not found on original storing peers: ${key}`);
421
+ this.addDHTLogEntry(` 💡 Key may not exist or all original storing peers are offline`);
422
+ }
423
+ } catch (error) {
424
+ this.addDHTLogEntry(`❌ Error retrieving ${key}: ${error.message}`);
425
+ }
426
+ });
427
+ }
428
+
429
+ // Subscribe to DHT key
430
+ if (dhtSubscribeBtn) {
431
+ dhtSubscribeBtn.addEventListener('click', async () => {
432
+ // Check both key fields - use whichever has a value
433
+ const putKey = dhtKey?.value?.trim();
434
+ const getKey = dhtGetKey?.value?.trim();
435
+ const key = putKey || getKey;
436
+
437
+ if (!key) {
438
+ this.addDHTLogEntry('❌ Error: Key is required (enter key in either Put/Update or Get field)');
439
+ return;
440
+ }
441
+
442
+ if (!this.mesh.isDHTEnabled()) {
443
+ this.addDHTLogEntry('❌ Error: WebDHT is disabled');
444
+ return;
445
+ }
446
+
447
+ try {
448
+ this.addDHTLogEntry(`🔔 Explicitly subscribing to key: ${key}`);
449
+ this.addDHTLogEntry(` 📡 Will receive notifications when original storing peers update this key`);
450
+
451
+ const value = await this.mesh.dhtSubscribe(key);
452
+ this.addDHTLogEntry(`✅ Subscribed to: ${key}`);
453
+ if (value !== null) {
454
+ this.addDHTLogEntry(` Current value from original storing peers: ${JSON.stringify(value)}`);
455
+ if (dhtValue) {
456
+ dhtValue.value = typeof value === 'string' ? value : JSON.stringify(value);
457
+ }
458
+ } else {
459
+ this.addDHTLogEntry(` No current value found on original storing peers`);
460
+ }
461
+ } catch (error) {
462
+ this.addDHTLogEntry(`❌ Error subscribing to ${key}: ${error.message}`);
463
+ }
464
+ });
465
+ }
466
+
467
+ // Unsubscribe from DHT key
468
+ if (dhtUnsubscribeBtn) {
469
+ dhtUnsubscribeBtn.addEventListener('click', async () => {
470
+ // Check both key fields - use whichever has a value
471
+ const putKey = dhtKey?.value?.trim();
472
+ const getKey = dhtGetKey?.value?.trim();
473
+ const key = putKey || getKey;
474
+
475
+ if (!key) {
476
+ this.addDHTLogEntry('❌ Error: Key is required (enter key in either Put/Update or Get field)');
477
+ return;
478
+ }
479
+
480
+ if (!this.mesh.isDHTEnabled()) {
481
+ this.addDHTLogEntry('❌ Error: WebDHT is disabled');
482
+ return;
483
+ }
484
+
485
+ try {
486
+ await this.mesh.dhtUnsubscribe(key);
487
+ this.addDHTLogEntry(`🔕 Unsubscribed from: ${key}`);
488
+ } catch (error) {
489
+ this.addDHTLogEntry(`❌ Error unsubscribing from ${key}: ${error.message}`);
490
+ }
491
+ });
492
+ }
493
+ }
494
+
495
+ setupMediaControls() {
496
+ // Start media button
497
+ document.getElementById('start-media-btn').addEventListener('click', async () => {
498
+ await this.startMedia();
499
+ });
500
+
501
+ // Stop media button
502
+ document.getElementById('stop-media-btn').addEventListener('click', async () => {
503
+ await this.stopMedia();
504
+ });
505
+
506
+ // Toggle video button
507
+ document.getElementById('toggle-video-btn').addEventListener('click', () => {
508
+ this.toggleVideo();
509
+ });
510
+
511
+ // Toggle audio button
512
+ document.getElementById('toggle-audio-btn').addEventListener('click', () => {
513
+ this.toggleAudio();
514
+ });
515
+
516
+ // Audio test button
517
+ document.getElementById('test-audio-btn').addEventListener('click', () => {
518
+ this.testAudio();
519
+ });
520
+
521
+ // Media type checkboxes
522
+ document.getElementById('enable-video').addEventListener('change', () => {
523
+ this.updateMediaButtonStates();
524
+ });
525
+
526
+ document.getElementById('enable-audio').addEventListener('change', () => {
527
+ this.updateMediaButtonStates();
528
+ });
529
+
530
+ // Device selection dropdowns
531
+ document.getElementById('camera-select').addEventListener('change', () => {
532
+ // Auto-restart media if it's currently active
533
+ if (this.mesh.getMediaState().hasLocalStream) {
534
+ this.startMedia();
535
+ }
536
+ });
537
+
538
+ document.getElementById('microphone-select').addEventListener('change', () => {
539
+ // Auto-restart media if it's currently active
540
+ if (this.mesh.getMediaState().hasLocalStream) {
541
+ this.startMedia();
542
+ }
543
+ });
544
+ }
545
+
546
+ setupCollapsibleSections() {
547
+ const sections = [
548
+ 'discovered-peers',
549
+ 'connected-peers',
550
+ 'manual-connection',
551
+ 'settings',
552
+ 'dht',
553
+ 'media'
554
+ ];
555
+
556
+ sections.forEach(sectionId => {
557
+ const toggle = document.getElementById(`${sectionId}-toggle`);
558
+ const content = document.getElementById(`${sectionId}-content`);
559
+
560
+ if (toggle && content) {
561
+ toggle.addEventListener('click', () => {
562
+ this.toggleSection(sectionId);
563
+ });
564
+ }
565
+ });
566
+ }
567
+
568
+ toggleSection(sectionId) {
569
+ const toggle = document.getElementById(`${sectionId}-toggle`);
570
+ const content = document.getElementById(`${sectionId}-content`);
571
+
572
+ if (!toggle || !content) {
573
+ console.warn(`Could not find elements for section: ${sectionId}`);
574
+ return;
575
+ }
576
+
577
+ const section = toggle.closest(`.${sectionId}`);
578
+
579
+ if (!section) {
580
+ console.warn(`Could not find section container for: ${sectionId}`, {
581
+ toggle: toggle,
582
+ toggleParent: toggle.parentElement,
583
+ toggleParentParent: toggle.parentElement?.parentElement,
584
+ classList: toggle.parentElement?.parentElement?.classList
585
+ });
586
+ return;
587
+ }
588
+
589
+ const isExpanded = toggle.getAttribute('aria-expanded') === 'true';
590
+
591
+ toggle.setAttribute('aria-expanded', !isExpanded);
592
+
593
+ // Add null check before calling setAttribute
594
+ if (section) {
595
+ section.setAttribute('aria-expanded', !isExpanded);
596
+ }
597
+
598
+ if (isExpanded) {
599
+ content.style.display = 'none';
600
+ toggle.textContent = toggle.textContent.replace('▼', '▶');
601
+ } else {
602
+ content.style.display = 'block';
603
+ toggle.textContent = toggle.textContent.replace('▶', '▼');
604
+ }
605
+ }
606
+
607
+ // Media-related methods
608
+ async initializeMedia() {
609
+ try {
610
+ // Initialize media manager
611
+ await this.mesh.initializeMedia();
612
+
613
+ // Populate device lists
614
+ await this.updateDeviceLists();
615
+
616
+ // Update button states
617
+ this.updateMediaButtonStates();
618
+
619
+ console.log('Media initialized successfully');
620
+ } catch (error) {
621
+ console.error('Failed to initialize media:', error);
622
+ this.addMessage('System', `Failed to initialize media: ${error.message}`, 'error');
623
+ }
624
+ }
625
+
626
+ async updateDeviceLists() {
627
+ try {
628
+ const devices = await this.mesh.enumerateMediaDevices();
629
+
630
+ // Update camera list
631
+ const cameraSelect = document.getElementById('camera-select');
632
+ if (cameraSelect) {
633
+ cameraSelect.innerHTML = '<option value="">Select camera...</option>';
634
+ devices.cameras.forEach(device => {
635
+ const option = document.createElement('option');
636
+ option.value = device.deviceId;
637
+ option.textContent = device.label || `Camera ${device.deviceId.substring(0, 8)}...`;
638
+ cameraSelect.appendChild(option);
639
+ });
640
+ cameraSelect.disabled = devices.cameras.length === 0;
641
+ }
642
+
643
+ // Update microphone list
644
+ const micSelect = document.getElementById('microphone-select');
645
+ if (micSelect) {
646
+ micSelect.innerHTML = '<option value="">Select microphone...</option>';
647
+ devices.microphones.forEach(device => {
648
+ const option = document.createElement('option');
649
+ option.value = device.deviceId;
650
+ option.textContent = device.label || `Microphone ${device.deviceId.substring(0, 8)}...`;
651
+ micSelect.appendChild(option);
652
+ });
653
+ micSelect.disabled = devices.microphones.length === 0;
654
+ }
655
+
656
+ } catch (error) {
657
+ console.error('Failed to update device lists:', error);
658
+ }
659
+ }
660
+
661
+ updateMediaButtonStates() {
662
+ const videoEnabled = document.getElementById('enable-video')?.checked || false;
663
+ const audioEnabled = document.getElementById('enable-audio')?.checked || false;
664
+ const mediaState = this.mesh.getMediaState();
665
+
666
+ // Enable start button if at least one media type is selected
667
+ const startBtn = document.getElementById('start-media-btn');
668
+ if (startBtn) {
669
+ startBtn.disabled = !(videoEnabled || audioEnabled) || mediaState.hasLocalStream;
670
+ }
671
+
672
+ // Enable stop button if media is active
673
+ const stopBtn = document.getElementById('stop-media-btn');
674
+ if (stopBtn) {
675
+ stopBtn.disabled = !mediaState.hasLocalStream;
676
+ }
677
+
678
+ // Enable toggle buttons if media is active
679
+ const toggleVideoBtn = document.getElementById('toggle-video-btn');
680
+ const toggleAudioBtn = document.getElementById('toggle-audio-btn');
681
+
682
+ if (toggleVideoBtn) {
683
+ toggleVideoBtn.disabled = !mediaState.hasLocalStream;
684
+ toggleVideoBtn.textContent = mediaState.videoEnabled ? 'Turn Off Video' : 'Turn On Video';
685
+ }
686
+
687
+ if (toggleAudioBtn) {
688
+ toggleAudioBtn.disabled = !mediaState.hasLocalStream;
689
+ toggleAudioBtn.textContent = mediaState.audioEnabled ? 'Turn Off Audio' : 'Turn On Audio';
690
+ }
691
+ }
692
+
693
+ async startMedia() {
694
+ try {
695
+ const videoEnabled = document.getElementById('enable-video')?.checked || false;
696
+ const audioEnabled = document.getElementById('enable-audio')?.checked || false;
697
+
698
+ // Initialize audio context for better audio support
699
+ if (audioEnabled && (window.AudioContext || window.webkitAudioContext)) {
700
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
701
+ try {
702
+ const audioContext = new AudioContext();
703
+ if (audioContext.state === 'suspended') {
704
+ await audioContext.resume();
705
+ console.log('Audio context resumed for local media');
706
+ }
707
+ console.log('Audio context state:', audioContext.state);
708
+ } catch (e) {
709
+ console.log('Could not initialize audio context:', e);
710
+ }
711
+ }
712
+
713
+ const deviceIds = {};
714
+ const cameraSelect = document.getElementById('camera-select');
715
+ const micSelect = document.getElementById('microphone-select');
716
+
717
+ if (cameraSelect?.value) {
718
+ deviceIds.camera = cameraSelect.value;
719
+ }
720
+
721
+ if (micSelect?.value) {
722
+ deviceIds.microphone = micSelect.value;
723
+ }
724
+
725
+ await this.mesh.startMedia({
726
+ video: videoEnabled,
727
+ audio: audioEnabled,
728
+ deviceIds
729
+ });
730
+
731
+ this.addMessage('System', 'Media started successfully');
732
+ this.updateMediaButtonStates();
733
+
734
+ } catch (error) {
735
+ console.error('Failed to start media:', error);
736
+ this.addMessage('System', `Failed to start media: ${error.message}`, 'error');
737
+ }
738
+ }
739
+
740
+ async stopMedia() {
741
+ try {
742
+ await this.mesh.stopMedia();
743
+ this.addMessage('System', 'Media stopped');
744
+ this.updateMediaButtonStates();
745
+ this.clearLocalVideo();
746
+
747
+ } catch (error) {
748
+ console.error('Failed to stop media:', error);
749
+ this.addMessage('System', `Failed to stop media: ${error.message}`, 'error');
750
+ }
751
+ }
752
+
753
+ toggleVideo() {
754
+ try {
755
+ const enabled = this.mesh.toggleVideo();
756
+ this.addMessage('System', `Video ${enabled ? 'enabled' : 'disabled'}`);
757
+ this.updateMediaButtonStates();
758
+ } catch (error) {
759
+ console.error('Failed to toggle video:', error);
760
+ this.addMessage('System', `Failed to toggle video: ${error.message}`, 'error');
761
+ }
762
+ }
763
+
764
+ toggleAudio() {
765
+ try {
766
+ const enabled = this.mesh.toggleAudio();
767
+ this.addMessage('System', `Audio ${enabled ? 'enabled' : 'disabled'}`);
768
+ this.updateMediaButtonStates();
769
+ } catch (error) {
770
+ console.error('Failed to toggle audio:', error);
771
+ this.addMessage('System', `Failed to toggle audio: ${error.message}`, 'error');
772
+ }
773
+ }
774
+
775
+ async testAudio() {
776
+ try {
777
+ console.log('🔊 Starting audio test...');
778
+ this.addMessage('System', '🔊 Testing audio system...', 'info');
779
+
780
+ // First, run diagnostics to understand current state
781
+ this.logPeerDiagnostics();
782
+
783
+ // Test 0: Verify we have actual peer connections (not just self)
784
+ const allPeers = this.mesh.getPeers();
785
+ const connectedPeers = allPeers.filter(peer => peer.status === 'connected');
786
+ const peersWithMedia = allPeers.filter(peer => {
787
+ const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
788
+ return peerConnection && (peerConnection.remoteStream || peerConnection.connection?.connectionState === 'connected');
789
+ });
790
+
791
+ console.log('🔊 All peers:', allPeers.length);
792
+ console.log('🔊 Connected peers (data channel):', connectedPeers.length);
793
+ console.log('🔊 Peers with media/WebRTC:', peersWithMedia.length);
794
+
795
+ // Log detailed peer status
796
+ allPeers.forEach(peer => {
797
+ const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
798
+ console.log(`🔊 Peer ${peer.peerId.substring(0, 8)}:`, {
799
+ status: peer.status,
800
+ webrtcState: peerConnection?.connection?.connectionState,
801
+ dataChannelState: peerConnection?.dataChannel?.readyState,
802
+ hasRemoteStream: !!peerConnection?.remoteStream,
803
+ hasLocalStream: !!peerConnection?.localStream
804
+ });
805
+ });
806
+
807
+ this.addMessage('System', `🔊 Found ${allPeers.length} total peers (${connectedPeers.length} with data channel, ${peersWithMedia.length} with media)`, 'info');
808
+
809
+ if (peersWithMedia.length === 0) {
810
+ this.addMessage('System', '❌ No peers with active media! You need to open this in TWO different browser tabs/windows and connect them.', 'error');
811
+ console.log('❌ NO PEERS WITH MEDIA: Open this URL in two different browser tabs and ensure they connect to each other');
812
+ return;
813
+ }
814
+
815
+ // Test each peer connection individually
816
+ peersWithMedia.forEach((peer, index) => {
817
+ const connection = this.mesh.connectionManager.peers.get(peer.peerId);
818
+ if (connection) {
819
+ console.log(`🔊 Peer ${index + 1} (${peer.peerId.substring(0, 8)}...):`);
820
+
821
+ const localStream = connection.getLocalStream();
822
+ const remoteStream = connection.getRemoteStream();
823
+
824
+ // Check local stream
825
+ if (localStream) {
826
+ const localAudioTracks = localStream.getAudioTracks();
827
+ console.log(` - Local audio tracks: ${localAudioTracks.length}`);
828
+ this.addMessage('System', ` Peer ${index + 1} - Local audio: ${localAudioTracks.length} tracks`, 'info');
829
+ localAudioTracks.forEach((track, i) => {
830
+ console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}...`);
831
+ });
832
+ } else {
833
+ console.log(' - No local stream');
834
+ this.addMessage('System', ` Peer ${index + 1} - No local stream`, 'warning');
835
+ }
836
+
837
+ // Check remote stream
838
+ if (remoteStream) {
839
+ const remoteAudioTracks = remoteStream.getAudioTracks();
840
+ console.log(` - Remote audio tracks: ${remoteAudioTracks.length}`);
841
+ this.addMessage('System', ` Peer ${index + 1} - Remote audio: ${remoteAudioTracks.length} tracks`, remoteAudioTracks.length > 0 ? 'success' : 'warning');
842
+
843
+ remoteAudioTracks.forEach((track, i) => {
844
+ console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}..., readyState=${track.readyState}`);
845
+ });
846
+
847
+ // CRITICAL: Check if remote stream ID matches local stream ID (loopback detection)
848
+ if (localStream && remoteStream.id === localStream.id) {
849
+ console.error(`❌ LOOPBACK DETECTED: Remote stream ID matches local stream ID!`);
850
+ this.addMessage('System', `❌ Peer ${index + 1} - LOOPBACK: Getting own audio back!`, 'error');
851
+ } else {
852
+ console.log(`✅ Stream IDs different: local=${localStream?.id.substring(0, 8) || 'none'}, remote=${remoteStream.id.substring(0, 8)}`);
853
+ this.addMessage('System', `✅ Peer ${index + 1} - Stream IDs are different (good!)`, 'success');
854
+ }
855
+
856
+ // Check video elements playing this stream
857
+ const videoElements = document.querySelectorAll('video');
858
+ let foundVideoElement = false;
859
+ videoElements.forEach(video => {
860
+ if (video.srcObject === remoteStream) {
861
+ foundVideoElement = true;
862
+ console.log(` - Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}, readyState=${video.readyState}`);
863
+ this.addMessage('System', ` Peer ${index + 1} - Video element: volume=${video.volume}, muted=${video.muted}`, video.muted ? 'warning' : 'success');
864
+ }
865
+ });
866
+
867
+ if (!foundVideoElement) {
868
+ console.log(` - ❌ No video element found for this remote stream`);
869
+ this.addMessage('System', ` Peer ${index + 1} - ❌ No video element displaying this stream`, 'error');
870
+ }
871
+ } else {
872
+ console.log(' - ❌ No remote stream');
873
+ this.addMessage('System', ` Peer ${index + 1} - ❌ No remote stream received`, 'error');
874
+ }
875
+ } else {
876
+ console.log(`❌ No connection object found for peer ${peer.peerId}`);
877
+ this.addMessage('System', `❌ No connection for peer ${index + 1}`, 'error');
878
+ }
879
+ });
880
+
881
+ // Test 1: Audio Context
882
+ if (window.AudioContext || window.webkitAudioContext) {
883
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
884
+ const audioContext = new AudioContext();
885
+ console.log('Audio context state:', audioContext.state);
886
+
887
+ if (audioContext.state === 'suspended') {
888
+ await audioContext.resume();
889
+ console.log('Audio context resumed');
890
+ }
891
+
892
+ // Generate a test tone
893
+ const oscillator = audioContext.createOscillator();
894
+ const gainNode = audioContext.createGain();
895
+
896
+ oscillator.connect(gainNode);
897
+ gainNode.connect(audioContext.destination);
898
+
899
+ oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // A4 note
900
+ gainNode.gain.setValueAtTime(0.1, audioContext.currentTime); // Low volume
901
+
902
+ oscillator.start();
903
+ oscillator.stop(audioContext.currentTime + 0.5); // Play for 0.5 seconds
904
+
905
+ this.addMessage('System', '🔊 Audio test tone played (440Hz for 0.5s)', 'success');
906
+ } else {
907
+ this.addMessage('System', '❌ Audio context not supported', 'error');
908
+ }
909
+
910
+ // Test 2: Check current media streams
911
+ const peers = this.mesh.getPeers();
912
+ console.log('Current peers:', peers.length);
913
+
914
+ peers.forEach(peer => {
915
+ const connection = this.mesh.connectionManager.peers.get(peer.peerId);
916
+ if (connection) {
917
+ const localStream = connection.getLocalStream();
918
+ const remoteStream = connection.getRemoteStream();
919
+
920
+ console.log(`Peer ${peer.peerId.substring(0, 8)}:`);
921
+ if (localStream) {
922
+ const audioTracks = localStream.getAudioTracks();
923
+ console.log(`- Local audio tracks: ${audioTracks.length}`);
924
+ audioTracks.forEach((track, i) => {
925
+ console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
926
+ });
927
+ }
928
+
929
+ if (remoteStream) {
930
+ const audioTracks = remoteStream.getAudioTracks();
931
+ console.log(`- Remote audio tracks: ${audioTracks.length}`);
932
+ audioTracks.forEach((track, i) => {
933
+ console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
934
+ });
935
+
936
+ // Check if there are video elements for this stream
937
+ const videoElements = document.querySelectorAll('video');
938
+ videoElements.forEach(video => {
939
+ if (video.srcObject === remoteStream) {
940
+ console.log(`- Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}`);
941
+ }
942
+ });
943
+ }
944
+ }
945
+ });
946
+
947
+ // Test 3: Check microphone access
948
+ try {
949
+ const testStream = await navigator.mediaDevices.getUserMedia({ audio: true });
950
+ console.log('✅ Microphone access working');
951
+ this.addMessage('System', '✅ Microphone access: OK', 'success');
952
+ testStream.getTracks().forEach(track => track.stop());
953
+ } catch (error) {
954
+ console.log('❌ Microphone access failed:', error);
955
+ this.addMessage('System', `❌ Microphone access failed: ${error.message}`, 'error');
956
+ }
957
+
958
+ } catch (error) {
959
+ console.error('Audio test failed:', error);
960
+ this.addMessage('System', `❌ Audio test failed: ${error.message}`, 'error');
961
+ }
962
+ }
963
+
964
+ handleLocalStreamStarted(data) {
965
+ this.updateMediaButtonStates();
966
+
967
+ // Display local video if video is enabled
968
+ if (data.video) {
969
+ this.displayLocalVideo(data.stream);
970
+ }
971
+
972
+ const mediaTypes = [];
973
+ if (data.video) mediaTypes.push('video');
974
+ if (data.audio) mediaTypes.push('audio');
975
+
976
+ this.addMessage('System', `Local ${mediaTypes.join(' and ')} started`);
977
+ }
978
+
979
+ handleLocalStreamStopped() {
980
+ this.updateMediaButtonStates();
981
+ this.clearLocalVideo();
982
+ this.addMessage('System', 'Local media stopped');
983
+ }
984
+
985
+ displayLocalVideo(stream) {
986
+ const localVideoContainer = document.getElementById('local-video-container');
987
+ if (!localVideoContainer) return;
988
+
989
+ let video = localVideoContainer.querySelector('video');
990
+ if (!video) {
991
+ video = document.createElement('video');
992
+ video.autoplay = true;
993
+ video.muted = true;
994
+ video.playsInline = true;
995
+ video.style.width = '100%';
996
+ video.style.borderRadius = '8px';
997
+ localVideoContainer.appendChild(video);
998
+ }
999
+
1000
+ video.srcObject = stream;
1001
+ }
1002
+
1003
+ clearLocalVideo() {
1004
+ const localVideoContainer = document.getElementById('local-video-container');
1005
+ if (localVideoContainer) {
1006
+ const video = localVideoContainer.querySelector('video');
1007
+ if (video) {
1008
+ video.srcObject = null;
1009
+ video.remove();
1010
+ }
1011
+ }
1012
+ }
1013
+
1014
+ handleRemoteStream(data) {
1015
+ console.log('🎵 Handling remote stream:', data);
1016
+ const { peerId, stream } = data;
1017
+
1018
+ // CRITICAL: Prevent audio loopback - check if this is our own stream
1019
+ if (peerId === this.mesh.peerId) {
1020
+ console.warn('🚨 LOOPBACK DETECTED: Received our own stream as remote! This should not happen.');
1021
+ console.warn('Stream ID:', stream.id);
1022
+ // Still display it but it will be muted by displayRemoteVideo
1023
+ }
1024
+
1025
+ // Detailed audio analysis
1026
+ const audioTracks = stream.getAudioTracks();
1027
+ const videoTracks = stream.getVideoTracks();
1028
+
1029
+ console.log(`Stream from ${peerId.substring(0, 8)}: ${audioTracks.length} audio, ${videoTracks.length} video tracks`);
1030
+
1031
+ audioTracks.forEach((track, i) => {
1032
+ console.log(`🎵 Audio track ${i}:`, {
1033
+ id: track.id,
1034
+ kind: track.kind,
1035
+ enabled: track.enabled,
1036
+ readyState: track.readyState,
1037
+ muted: track.muted,
1038
+ label: track.label
1039
+ });
1040
+
1041
+ // Add track event listeners for state monitoring
1042
+ track.addEventListener('ended', () => {
1043
+ console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} ENDED`);
1044
+ });
1045
+
1046
+ track.addEventListener('mute', () => {
1047
+ console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} MUTED`);
1048
+ });
1049
+
1050
+ track.addEventListener('unmute', () => {
1051
+ console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} UNMUTED`);
1052
+ });
1053
+ });
1054
+
1055
+ this.displayRemoteVideo(peerId, stream);
1056
+
1057
+ // Audio data summary
1058
+ const audioSummary = {
1059
+ peerIdShort: peerId.substring(0, 8),
1060
+ audioTrackCount: audioTracks.length,
1061
+ videoTrackCount: videoTracks.length,
1062
+ audioTracksEnabled: audioTracks.filter(t => t.enabled).length,
1063
+ streamActive: stream.active,
1064
+ streamId: stream.id
1065
+ };
1066
+
1067
+ console.log(`🎵 AUDIO DATA EXPECTATION for peer ${audioSummary.peerIdShort}:`, audioSummary);
1068
+
1069
+ if (audioTracks.length > 0) {
1070
+ console.log(`✅ EXPECTING AUDIO DATA from peer ${audioSummary.peerIdShort} - ${audioSummary.audioTracksEnabled}/${audioSummary.audioTrackCount} tracks enabled`);
1071
+ } else {
1072
+ console.log(`❌ NO AUDIO TRACKS from peer ${audioSummary.peerIdShort} - video only`);
1073
+ }
1074
+
1075
+ this.addMessage('System', `🎵 Remote stream received from ${peerId.substring(0, 8)}... (${audioTracks.length} audio, ${videoTracks.length} video)`);
1076
+ }
1077
+
1078
+ displayRemoteVideo(peerId, stream) {
1079
+ console.log(`Displaying remote video for ${peerId}:`, stream);
1080
+ console.log('Stream tracks:', stream.getTracks().map(t => ({ kind: t.kind, enabled: t.enabled })));
1081
+
1082
+ // CRITICAL: Prevent audio loopback - check if this is our own stream
1083
+ const isOwnStream = peerId === this.mesh.peerId;
1084
+ if (isOwnStream) {
1085
+ console.warn('🚨 LOOPBACK DETECTED: Received our own stream! Muting audio to prevent feedback.');
1086
+ }
1087
+
1088
+ const remoteVideosContainer = document.getElementById('remote-videos-container');
1089
+ if (!remoteVideosContainer) return;
1090
+
1091
+ let remoteVideoItem = remoteVideosContainer.querySelector(`[data-peer-id="${peerId}"]`);
1092
+
1093
+ if (!remoteVideoItem) {
1094
+ remoteVideoItem = document.createElement('div');
1095
+ remoteVideoItem.className = 'remote-video-item';
1096
+ remoteVideoItem.setAttribute('data-peer-id', peerId);
1097
+
1098
+ const title = document.createElement('div');
1099
+ title.className = 'video-title';
1100
+ title.textContent = `Peer ${peerId.substring(0, 8)}...`;
1101
+
1102
+ const video = document.createElement('video');
1103
+ video.autoplay = true;
1104
+ video.playsInline = true;
1105
+ video.controls = true;
1106
+ // CRITICAL: Mute if this is our own stream to prevent audio feedback
1107
+ video.muted = isOwnStream; // Mute our own audio, unmute others
1108
+ video.style.width = '100%';
1109
+ video.style.borderRadius = '8px';
1110
+
1111
+ // Enhanced audio debugging
1112
+ video.addEventListener('loadedmetadata', () => {
1113
+ console.log('Video element loaded metadata:', {
1114
+ duration: video.duration,
1115
+ audioTracks: video.audioTracks?.length || 'N/A',
1116
+ volume: video.volume,
1117
+ muted: video.muted
1118
+ });
1119
+
1120
+ video.play().then(() => {
1121
+ console.log('Video/audio playback started successfully');
1122
+ // Check audio context state
1123
+ if (window.AudioContext || window.webkitAudioContext) {
1124
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
1125
+ const audioContext = new AudioContext();
1126
+ console.log('Audio context state:', audioContext.state);
1127
+ if (audioContext.state === 'suspended') {
1128
+ console.log('Audio context is suspended - may need user interaction');
1129
+ }
1130
+ }
1131
+ // Hide any play button if playback started
1132
+ const playButton = remoteVideoItem.querySelector('.manual-play-button');
1133
+ if (playButton) {
1134
+ playButton.style.display = 'none';
1135
+ }
1136
+ }).catch(error => {
1137
+ console.log('Autoplay failed, user interaction required:', error);
1138
+ // Show a manual play button
1139
+ const playButton = document.createElement('button');
1140
+ playButton.className = 'manual-play-button';
1141
+ playButton.textContent = '▶ Click to Play Audio';
1142
+ playButton.style.cssText = 'position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 10; padding: 10px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;';
1143
+
1144
+ playButton.addEventListener('click', async () => {
1145
+ try {
1146
+ await video.play();
1147
+ playButton.style.display = 'none';
1148
+ console.log('Manual play successful');
1149
+ } catch (e) {
1150
+ console.error('Manual play failed:', e);
1151
+ }
1152
+ });
1153
+
1154
+ remoteVideoItem.style.position = 'relative';
1155
+ remoteVideoItem.appendChild(playButton);
1156
+ });
1157
+ });
1158
+
1159
+ // Add event listeners for audio debugging
1160
+ video.addEventListener('play', () => {
1161
+ console.log('Video element started playing');
1162
+ });
1163
+
1164
+ video.addEventListener('pause', () => {
1165
+ console.log('Video element paused');
1166
+ });
1167
+
1168
+ video.addEventListener('volumechange', () => {
1169
+ console.log('Volume changed:', video.volume, 'Muted:', video.muted);
1170
+ });
1171
+
1172
+ const status = document.createElement('div');
1173
+ status.className = 'video-status';
1174
+
1175
+ remoteVideoItem.appendChild(title);
1176
+ remoteVideoItem.appendChild(video);
1177
+ remoteVideoItem.appendChild(status);
1178
+
1179
+ remoteVideosContainer.appendChild(remoteVideoItem);
1180
+ }
1181
+
1182
+ const video = remoteVideoItem.querySelector('video');
1183
+ const status = remoteVideoItem.querySelector('.video-status');
1184
+
1185
+ video.srcObject = stream;
1186
+
1187
+ // EXPLICIT AUDIO DEBUGGING
1188
+ console.log('🎵 Setting srcObject for video element:', {
1189
+ stream: stream,
1190
+ streamId: stream.id,
1191
+ streamActive: stream.active,
1192
+ videoElement: video,
1193
+ videoMuted: video.muted,
1194
+ videoVolume: video.volume,
1195
+ isOwnStream: isOwnStream
1196
+ });
1197
+
1198
+ const audioTracks = stream.getAudioTracks();
1199
+ const videoTracks = stream.getVideoTracks();
1200
+
1201
+ console.log('🎵 Stream tracks assigned:', {
1202
+ audioTracks: audioTracks.map(t => ({
1203
+ id: t.id,
1204
+ enabled: t.enabled,
1205
+ readyState: t.readyState,
1206
+ muted: t.muted
1207
+ })),
1208
+ videoTracks: videoTracks.map(t => ({
1209
+ id: t.id,
1210
+ enabled: t.enabled,
1211
+ readyState: t.readyState,
1212
+ muted: t.muted
1213
+ }))
1214
+ });
1215
+
1216
+ // CRITICAL: Set audio state based on whether this is our own stream
1217
+ if (isOwnStream) {
1218
+ console.warn('🚨 Muting our own stream to prevent audio feedback');
1219
+ video.muted = true;
1220
+ video.volume = 0;
1221
+ } else {
1222
+ // Only unmute if this is NOT our own stream
1223
+ video.muted = false;
1224
+ video.volume = 1.0;
1225
+
1226
+ // Setup audio playback monitoring for remote streams
1227
+ this.setupAudioPlaybackMonitoring(video, peerId, audioTracks);
1228
+ }
1229
+
1230
+ // Update status based on stream tracks
1231
+ console.log(`Video tracks: ${videoTracks.length}, Audio tracks: ${audioTracks.length}`);
1232
+ audioTracks.forEach((track, i) => {
1233
+ console.log(`Audio track ${i}:`, { enabled: track.enabled, muted: track.muted, label: track.label });
1234
+ });
1235
+
1236
+ // For audio-only streams, ensure the video element is properly configured
1237
+ if (audioTracks.length > 0 && videoTracks.length === 0) {
1238
+ console.log('Audio-only stream detected - configuring for audio playback');
1239
+ video.style.height = '60px'; // Smaller height for audio-only
1240
+ video.style.backgroundColor = '#f0f0f0';
1241
+
1242
+ // Force audio to play by trying to resume audio context
1243
+ if (window.AudioContext || window.webkitAudioContext) {
1244
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
1245
+ try {
1246
+ const audioContext = new AudioContext();
1247
+ if (audioContext.state === 'suspended') {
1248
+ audioContext.resume().then(() => {
1249
+ console.log('Audio context resumed for remote stream');
1250
+ });
1251
+ }
1252
+
1253
+ // Test audio by creating a brief analysis
1254
+ try {
1255
+ const source = audioContext.createMediaStreamSource(stream);
1256
+ const analyser = audioContext.createAnalyser();
1257
+ source.connect(analyser);
1258
+
1259
+ const dataArray = new Uint8Array(analyser.frequencyBinCount);
1260
+ const checkAudio = () => {
1261
+ analyser.getByteFrequencyData(dataArray);
1262
+ const sum = dataArray.reduce((a, b) => a + b, 0);
1263
+ if (sum > 0) {
1264
+ console.log('Remote audio data detected! Sum:', sum);
1265
+ }
1266
+ };
1267
+
1268
+ // Check audio data periodically
1269
+ const audioChecker = setInterval(checkAudio, 1000);
1270
+ setTimeout(() => clearInterval(audioChecker), 10000); // Stop after 10 seconds
1271
+
1272
+ } catch (audioAnalysisError) {
1273
+ console.log('Could not analyze remote audio:', audioAnalysisError);
1274
+ }
1275
+ } catch (e) {
1276
+ console.log('Could not create/resume audio context:', e);
1277
+ }
1278
+ }
1279
+ }
1280
+
1281
+ const statusText = [];
1282
+ if (videoTracks.length > 0) statusText.push('Video');
1283
+ if (audioTracks.length > 0) statusText.push('Audio');
1284
+
1285
+ status.textContent = statusText.length > 0 ? statusText.join(' + ') : 'Audio only';
1286
+ status.style.color = '#28a745';
1287
+
1288
+ this.addMessage('System', `Receiving ${statusText.join(' + ')} from ${peerId.substring(0, 8)}...`);
1289
+ }
1290
+
1291
+ /**
1292
+ * Setup audio playback monitoring for video elements playing remote streams
1293
+ */
1294
+ setupAudioPlaybackMonitoring(videoElement, peerId, audioTracks) {
1295
+ const peerIdShort = peerId.substring(0, 8);
1296
+ console.log(`🎵 Setting up audio playback monitoring for peer ${peerIdShort}`);
1297
+
1298
+ if (audioTracks.length === 0) {
1299
+ console.log(`🎵 No audio tracks to monitor for peer ${peerIdShort}`);
1300
+ return;
1301
+ }
1302
+
1303
+ try {
1304
+ // Monitor video element audio events
1305
+ videoElement.addEventListener('play', () => {
1306
+ console.log(`🎵 Video element started playing for peer ${peerIdShort}`, {
1307
+ muted: videoElement.muted,
1308
+ volume: videoElement.volume,
1309
+ audioTracks: audioTracks.length
1310
+ });
1311
+ });
1312
+
1313
+ videoElement.addEventListener('pause', () => {
1314
+ console.log(`🎵 Video element paused for peer ${peerIdShort}`);
1315
+ });
1316
+
1317
+ videoElement.addEventListener('volumechange', () => {
1318
+ console.log(`🎵 Volume changed for peer ${peerIdShort}:`, {
1319
+ volume: videoElement.volume,
1320
+ muted: videoElement.muted
1321
+ });
1322
+ });
1323
+
1324
+ // Create audio context for monitoring actual audio data playback
1325
+ const AudioContext = window.AudioContext || window.webkitAudioContext;
1326
+ if (!AudioContext) {
1327
+ console.warn('🎵 AudioContext not available - basic monitoring only');
1328
+ return;
1329
+ }
1330
+
1331
+ // Wait for video to load before setting up audio analysis
1332
+ const setupAudioAnalysis = () => {
1333
+ try {
1334
+ const audioContext = new AudioContext();
1335
+ const source = audioContext.createMediaElementSource(videoElement);
1336
+ const analyser = audioContext.createAnalyser();
1337
+ const gainNode = audioContext.createGain();
1338
+
1339
+ analyser.fftSize = 256;
1340
+ const bufferLength = analyser.frequencyBinCount;
1341
+ const dataArray = new Uint8Array(bufferLength);
1342
+
1343
+ // Connect: source -> analyser -> gain -> destination
1344
+ source.connect(analyser);
1345
+ analyser.connect(gainNode);
1346
+ gainNode.connect(audioContext.destination);
1347
+
1348
+ let lastLogTime = 0;
1349
+ let totalSamples = 0;
1350
+ let playbackSamples = 0;
1351
+ let maxPlaybackLevel = 0;
1352
+
1353
+ const monitorPlayback = () => {
1354
+ if (videoElement.paused || videoElement.ended) {
1355
+ return; // Stop monitoring if playback stopped
1356
+ }
1357
+
1358
+ analyser.getByteFrequencyData(dataArray);
1359
+
1360
+ // Calculate playback audio level
1361
+ const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
1362
+ const currentTime = Date.now();
1363
+
1364
+ totalSamples++;
1365
+ if (average > 3) { // Lower threshold for playback detection
1366
+ playbackSamples++;
1367
+ maxPlaybackLevel = Math.max(maxPlaybackLevel, average);
1368
+ }
1369
+
1370
+ // Log every 3 seconds
1371
+ if (currentTime - lastLogTime > 3000) {
1372
+ const playbackActivity = totalSamples > 0 ? (playbackSamples / totalSamples * 100) : 0;
1373
+ console.log(`🔊 Audio PLAYBACK from peer ${peerIdShort}:`, {
1374
+ videoElementMuted: videoElement.muted,
1375
+ videoElementVolume: videoElement.volume,
1376
+ currentPlaybackLevel: Math.round(average),
1377
+ maxPlaybackLevel: Math.round(maxPlaybackLevel),
1378
+ playbackActivityPercent: Math.round(playbackActivity),
1379
+ samplesAnalyzed: totalSamples,
1380
+ audioBeingPlayed: playbackSamples > 0,
1381
+ audioContextState: audioContext.state
1382
+ });
1383
+
1384
+ lastLogTime = currentTime;
1385
+ totalSamples = 0;
1386
+ playbackSamples = 0;
1387
+ maxPlaybackLevel = 0;
1388
+ }
1389
+
1390
+ // Continue monitoring
1391
+ if (!videoElement.paused && !videoElement.ended) {
1392
+ requestAnimationFrame(monitorPlayback);
1393
+ }
1394
+ };
1395
+
1396
+ // Start monitoring when video plays
1397
+ videoElement.addEventListener('play', () => {
1398
+ console.log(`🔊 Starting audio playback monitoring for peer ${peerIdShort}`);
1399
+ if (audioContext.state === 'suspended') {
1400
+ audioContext.resume().then(() => {
1401
+ requestAnimationFrame(monitorPlayback);
1402
+ });
1403
+ } else {
1404
+ requestAnimationFrame(monitorPlayback);
1405
+ }
1406
+ });
1407
+
1408
+ console.log(`🔊 Audio playback analysis setup complete for peer ${peerIdShort}`);
1409
+
1410
+ } catch (error) {
1411
+ console.error(`🔊 Failed to setup audio playback analysis for peer ${peerIdShort}:`, error);
1412
+ }
1413
+ };
1414
+
1415
+ if (videoElement.readyState >= 1) {
1416
+ // Video metadata already loaded
1417
+ setupAudioAnalysis();
1418
+ } else {
1419
+ // Wait for metadata to load
1420
+ videoElement.addEventListener('loadedmetadata', setupAudioAnalysis, { once: true });
1421
+ }
1422
+
1423
+ } catch (error) {
1424
+ console.error(`🎵 Failed to setup audio playback monitoring for peer ${peerIdShort}:`, error);
1425
+ }
1426
+ }
1427
+
1428
+ /**
1429
+ * Diagnostic method to log complete peer connection state
1430
+ */
1431
+ logPeerDiagnostics() {
1432
+ console.log('🔍 PEER DIAGNOSTICS:');
1433
+ const allPeers = this.mesh.getPeers();
1434
+
1435
+ console.log(`📊 Total peers in mesh: ${allPeers.length}`);
1436
+
1437
+ allPeers.forEach((peer, index) => {
1438
+ const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
1439
+
1440
+ console.log(`\n🔍 Peer ${index + 1}: ${peer.peerId.substring(0, 8)}...`);
1441
+ console.log(` Status: ${peer.status}`);
1442
+
1443
+ if (peerConnection) {
1444
+ console.log(` WebRTC Connection State: ${peerConnection.connection?.connectionState || 'none'}`);
1445
+ console.log(` ICE Connection State: ${peerConnection.connection?.iceConnectionState || 'none'}`);
1446
+ console.log(` Data Channel State: ${peerConnection.dataChannel?.readyState || 'none'}`);
1447
+ console.log(` Data Channel Ready: ${peerConnection.dataChannelReady}`);
1448
+ console.log(` Has Local Stream: ${!!peerConnection.localStream}`);
1449
+ console.log(` Has Remote Stream: ${!!peerConnection.remoteStream}`);
1450
+
1451
+ if (peerConnection.localStream) {
1452
+ const audioTracks = peerConnection.localStream.getAudioTracks();
1453
+ const videoTracks = peerConnection.localStream.getVideoTracks();
1454
+ console.log(` Local Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
1455
+ }
1456
+
1457
+ if (peerConnection.remoteStream) {
1458
+ const audioTracks = peerConnection.remoteStream.getAudioTracks();
1459
+ const videoTracks = peerConnection.remoteStream.getVideoTracks();
1460
+ console.log(` Remote Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
1461
+ }
1462
+ } else {
1463
+ console.log(` ❌ No PeerConnection object found`);
1464
+ }
1465
+ });
1466
+
1467
+ console.log('\n🔍 END PEER DIAGNOSTICS\n');
1468
+ }
1469
+
1470
+ // Existing UI methods (keeping the rest of the original functionality)
1471
+ async handleConnect() {
1472
+ const url = document.getElementById('signaling-url').value.trim();
1473
+ if (!url) {
1474
+ this.addMessage('System', 'Please enter a signaling server URL', 'error');
1475
+ return;
1476
+ }
1477
+
1478
+ try {
1479
+ this.updateButtonStates({ connecting: true });
1480
+ await this.mesh.connect(url);
1481
+ } catch (error) {
1482
+ console.error('Connection failed:', error);
1483
+ this.addMessage('System', `Connection failed: ${error.message}`, 'error');
1484
+ this.updateButtonStates({ connecting: false });
1485
+ }
1486
+ }
1487
+
1488
+ async handleDisconnect() {
1489
+ try {
1490
+ this.updateButtonStates({ disconnecting: true });
1491
+ await this.mesh.disconnect();
1492
+ } catch (error) {
1493
+ console.error('Disconnection failed:', error);
1494
+ this.addMessage('System', `Disconnection failed: ${error.message}`, 'error');
1495
+ } finally {
1496
+ this.updateButtonStates({ disconnecting: false });
1497
+ }
1498
+ }
1499
+
1500
+ async handleCleanup() {
1501
+ const now = Date.now();
1502
+ const timeSinceLastCleanup = now - this.lastCleanupTime;
1503
+
1504
+ if (timeSinceLastCleanup < 5000) {
1505
+ const remaining = Math.ceil((5000 - timeSinceLastCleanup) / 1000);
1506
+ this.addMessage('System', `Cleanup on cooldown (${remaining}s remaining)`, 'warning');
1507
+ return;
1508
+ }
1509
+
1510
+ try {
1511
+ this.lastCleanupTime = now;
1512
+ await this.mesh.cleanupSignalingData();
1513
+ this.addMessage('System', 'Signaling data cleanup initiated');
1514
+ } catch (error) {
1515
+ console.error('Cleanup failed:', error);
1516
+ this.addMessage('System', `Cleanup failed: ${error.message}`, 'error');
1517
+ }
1518
+ }
1519
+
1520
+ async handleHealthCheck() {
1521
+ try {
1522
+ const result = await this.mesh.performHealthCheck();
1523
+ if (result.healthy) {
1524
+ this.addMessage('System', 'Health check passed - all systems nominal', 'info');
1525
+ } else {
1526
+ this.addMessage('System', `Health check failed: ${result.issues.join(', ')}`, 'warning');
1527
+ }
1528
+ } catch (error) {
1529
+ console.error('Health check failed:', error);
1530
+ this.addMessage('System', `Health check error: ${error.message}`, 'error');
1531
+ }
1532
+ }
1533
+
1534
+ sendMessage() {
1535
+ const messageInput = document.getElementById('message-input');
1536
+ const dmTargetInput = document.getElementById('dm-target-input');
1537
+ const message = messageInput.value.trim();
1538
+ const dmTarget = dmTargetInput.value.trim();
1539
+
1540
+ if (!message) return;
1541
+
1542
+ try {
1543
+ if (dmTarget) {
1544
+ // Validate peer ID format
1545
+ if (!window.PeerPigeonMesh.validatePeerId(dmTarget)) {
1546
+ this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
1547
+ return;
1548
+ }
1549
+
1550
+ // Send direct message
1551
+ const success = this.mesh.sendDirectMessage(dmTarget, message);
1552
+ if (success) {
1553
+ this.addMessage('You', `(DM to ${dmTarget.substring(0, 8)}...) ${message}`, 'own');
1554
+ } else {
1555
+ this.addMessage('System', `Failed to send direct message to ${dmTarget.substring(0, 8)}...`, 'error');
1556
+ }
1557
+ } else {
1558
+ // Send broadcast message
1559
+ // this.mesh.broadcastMessage(message);
1560
+ this.mesh.sendMessage(message);
1561
+ this.addMessage('You', message, 'own');
1562
+ }
1563
+
1564
+ messageInput.value = '';
1565
+ } catch (error) {
1566
+ console.error('Failed to send message:', error);
1567
+ this.addMessage('System', `Failed to send message: ${error.message}`, 'error');
1568
+ }
1569
+ }
1570
+
1571
+ connectToPeer() {
1572
+ const targetPeerInput = document.getElementById('target-peer');
1573
+ const targetPeerId = targetPeerInput.value.trim();
1574
+
1575
+ if (!targetPeerId) {
1576
+ this.addMessage('System', 'Please enter a peer ID', 'error');
1577
+ return;
1578
+ }
1579
+
1580
+ if (!window.PeerPigeonMesh.validatePeerId(targetPeerId)) {
1581
+ this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
1582
+ return;
1583
+ }
1584
+
1585
+ if (targetPeerId === this.mesh.peerId) {
1586
+ this.addMessage('System', 'Cannot connect to yourself', 'error');
1587
+ return;
1588
+ }
1589
+
1590
+ try {
1591
+ this.mesh.connectToPeer(targetPeerId);
1592
+ this.addMessage('System', `Attempting to connect to ${targetPeerId.substring(0, 8)}...`);
1593
+ targetPeerInput.value = '';
1594
+ } catch (error) {
1595
+ console.error('Failed to initiate connection:', error);
1596
+ this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
1597
+ }
1598
+ }
1599
+
1600
+ /**
1601
+ * Connect to peer from button click (for onclick handlers)
1602
+ */
1603
+ connectToPeerFromButton(button) {
1604
+ const peerId = button.getAttribute('data-peer-id');
1605
+ if (!peerId) {
1606
+ this.addMessage('System', 'Invalid peer ID in button', 'error');
1607
+ return;
1608
+ }
1609
+
1610
+ // Disable button to prevent double-clicks
1611
+ button.disabled = true;
1612
+ button.textContent = 'Connecting...';
1613
+
1614
+ try {
1615
+ this.mesh.connectToPeer(peerId);
1616
+ this.addMessage('System', `Attempting to connect to ${peerId.substring(0, 8)}...`);
1617
+
1618
+ // Re-enable button after a delay
1619
+ setTimeout(() => {
1620
+ button.disabled = false;
1621
+ button.textContent = 'Connect';
1622
+ }, 3000);
1623
+
1624
+ } catch (error) {
1625
+ console.error('Failed to initiate connection:', error);
1626
+ this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
1627
+
1628
+ // Re-enable button immediately on error
1629
+ button.disabled = false;
1630
+ button.textContent = 'Connect';
1631
+ }
1632
+ }
1633
+
1634
+ updateUI() {
1635
+ // Update peer ID display
1636
+ const peerIdElement = document.getElementById('peer-id');
1637
+ if (peerIdElement && this.mesh.peerId) {
1638
+ peerIdElement.textContent = this.mesh.peerId;
1639
+ }
1640
+
1641
+ // Update status
1642
+ this.updateStatus();
1643
+
1644
+ // Update button states
1645
+ this.updateButtonStates();
1646
+
1647
+ // Update peer lists
1648
+ this.updateConnectedPeers();
1649
+ this.updateDiscoveredPeers();
1650
+
1651
+ // Update settings from mesh state
1652
+ this.updateSettings();
1653
+
1654
+ // Update DHT status
1655
+ this.updateDHTStatus();
1656
+ }
1657
+
1658
+ updateStatus() {
1659
+ const statusElement = document.getElementById('status');
1660
+ if (!statusElement) return;
1661
+
1662
+ const status = this.mesh.getStatus();
1663
+ const connectionStatus = status.connected ? 'connected' : 'disconnected';
1664
+ statusElement.textContent = connectionStatus.charAt(0).toUpperCase() + connectionStatus.slice(1);
1665
+ statusElement.className = `status ${connectionStatus.toLowerCase()}`;
1666
+ }
1667
+
1668
+ updateButtonStates(options = {}) {
1669
+ const connectBtn = document.getElementById('connect-btn');
1670
+ const disconnectBtn = document.getElementById('disconnect-btn');
1671
+ const cleanupBtn = document.getElementById('cleanup-btn');
1672
+ const healthCheckBtn = document.getElementById('health-check-btn');
1673
+
1674
+ const isConnected = this.mesh.connected;
1675
+ const isConnecting = options.connecting || false;
1676
+ const isDisconnecting = options.disconnecting || false;
1677
+
1678
+ if (connectBtn) {
1679
+ connectBtn.disabled = isConnected || isConnecting;
1680
+ connectBtn.textContent = isConnecting ? 'Connecting...' : 'Connect';
1681
+ }
1682
+
1683
+ if (disconnectBtn) {
1684
+ disconnectBtn.disabled = !isConnected || isDisconnecting;
1685
+ disconnectBtn.textContent = isDisconnecting ? 'Disconnecting...' : 'Disconnect';
1686
+ }
1687
+
1688
+ if (cleanupBtn) {
1689
+ cleanupBtn.disabled = !isConnected;
1690
+ }
1691
+
1692
+ if (healthCheckBtn) {
1693
+ healthCheckBtn.disabled = !isConnected;
1694
+ }
1695
+ }
1696
+
1697
+ updateConnectedPeers() {
1698
+ const peersList = document.getElementById('peers-list');
1699
+ const connectedPeersCount = document.getElementById('connected-peers-count');
1700
+
1701
+ if (!peersList || !connectedPeersCount) return;
1702
+
1703
+ const peers = this.mesh.getPeers();
1704
+ connectedPeersCount.textContent = peers.length;
1705
+
1706
+ if (peers.length === 0) {
1707
+ peersList.innerHTML = '<p class="empty-state">No peers connected</p>';
1708
+ return;
1709
+ }
1710
+
1711
+ peersList.innerHTML = peers.map(peer => {
1712
+ // peer is a plain object: { peerId, status, isInitiator, connectionStartTime }
1713
+ const statusClass = peer.status === 'connected' ? 'connected' : 'connecting';
1714
+ const connectionTime = ((Date.now() - peer.connectionStartTime) / 1000).toFixed(1);
1715
+
1716
+ return `
1717
+ <div class="peer-item">
1718
+ <div class="peer-info">
1719
+ <span class="peer-id">${peer.peerId.substring(0, 16)}...</span>
1720
+ <span class="peer-status ${statusClass}">${peer.status}</span>
1721
+ </div>
1722
+ <div class="peer-details">
1723
+ <small>Connected: ${connectionTime}s ago</small>
1724
+ <small>Role: ${peer.isInitiator ? 'Initiator' : 'Receiver'}</small>
1725
+ </div>
1726
+ </div>
1727
+ `;
1728
+ }).join('');
1729
+ }
1730
+
1731
+ updateDiscoveredPeers() {
1732
+ const discoveredPeersList = document.getElementById('discovered-peers-list');
1733
+ const discoveredPeersCount = document.getElementById('discovered-peers-count');
1734
+
1735
+ if (!discoveredPeersList || !discoveredPeersCount) return;
1736
+
1737
+ const discoveredPeers = this.mesh.getDiscoveredPeers();
1738
+ const connectedPeerIds = this.mesh.getPeers().map(p => p.peerId);
1739
+
1740
+ // Filter out already connected peers
1741
+ const availablePeers = discoveredPeers.filter(peer =>
1742
+ !connectedPeerIds.includes(peer.peerId) && peer.peerId !== this.mesh.peerId
1743
+ );
1744
+
1745
+ discoveredPeersCount.textContent = availablePeers.length;
1746
+
1747
+ if (availablePeers.length === 0) {
1748
+ discoveredPeersList.innerHTML = '<p class="empty-state">No peers discovered</p>';
1749
+ return;
1750
+ }
1751
+
1752
+ discoveredPeersList.innerHTML = availablePeers.map(peer => {
1753
+ const lastSeen = peer.lastSeen ?
1754
+ `${Math.round((Date.now() - peer.lastSeen) / 1000)}s ago` :
1755
+ 'Unknown';
1756
+
1757
+ return `
1758
+ <div class="peer-item discovered">
1759
+ <div class="peer-info">
1760
+ <span class="peer-id">${peer.peerId.substring(0, 16)}...</span>
1761
+ <button class="btn small" data-peer-id="${peer.peerId}" onclick="window.peerPigeonUI.connectToPeerFromButton(this)">
1762
+ Connect
1763
+ </button>
1764
+ </div>
1765
+ <div class="peer-details">
1766
+ <small>Last seen: ${lastSeen}</small>
1767
+ <small>Distance: ${peer.distance || 'Unknown'}</small>
1768
+ </div>
1769
+ </div>
1770
+ `;
1771
+ }).join('');
1772
+ }
1773
+
1774
+ updateSettings() {
1775
+ // Update form values to match mesh state
1776
+ const minPeersInput = document.getElementById('min-peers');
1777
+ const maxPeersInput = document.getElementById('max-peers');
1778
+ const autoDiscoveryToggle = document.getElementById('auto-discovery-toggle');
1779
+ const evictionStrategyToggle = document.getElementById('eviction-strategy-toggle');
1780
+ const xorRoutingToggle = document.getElementById('xor-routing-toggle');
1781
+ const webdhtToggle = document.getElementById('webdht-toggle');
1782
+
1783
+ if (minPeersInput) minPeersInput.value = this.mesh.minPeers;
1784
+ if (maxPeersInput) maxPeersInput.value = this.mesh.maxPeers;
1785
+ if (autoDiscoveryToggle) autoDiscoveryToggle.checked = this.mesh.autoDiscovery;
1786
+ if (evictionStrategyToggle) evictionStrategyToggle.checked = this.mesh.evictionStrategy;
1787
+ if (xorRoutingToggle) xorRoutingToggle.checked = this.mesh.xorRouting;
1788
+
1789
+ // Update WebDHT status (read-only)
1790
+ if (webdhtToggle) {
1791
+ const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
1792
+ webdhtToggle.checked = isDHTEnabled;
1793
+
1794
+ // Update the visual styling based on status
1795
+ const parent = webdhtToggle.closest('.auto-discovery-control');
1796
+ if (parent) {
1797
+ if (isDHTEnabled) {
1798
+ parent.style.opacity = '1';
1799
+ parent.title = 'WebDHT is enabled and running';
1800
+ } else {
1801
+ parent.style.opacity = '0.6';
1802
+ parent.title = 'WebDHT is disabled (restart required to enable)';
1803
+ }
1804
+ }
1805
+ }
1806
+ }
1807
+
1808
+ /**
1809
+ * Add a message to the UI message log
1810
+ * @param {string} sender - Message sender identifier
1811
+ * @param {string} content - Message content
1812
+ * @param {string} type - Message type ('info', 'error', 'warning', 'own', 'dm')
1813
+ */
1814
+ addMessage(sender, content, type = 'info') {
1815
+ // System messages go to the system-messages container (below connection buttons)
1816
+ // Chat messages go to the messages-log container (at the bottom)
1817
+ if (sender === 'System') {
1818
+ this.addSystemMessage(content, type);
1819
+ } else {
1820
+ this.addChatMessage(sender, content, type);
1821
+ }
1822
+ }
1823
+
1824
+ /**
1825
+ * Add a system message to the system messages container below connection buttons
1826
+ * @param {string} content - Message content
1827
+ * @param {string} type - Message type ('info', 'error', 'warning')
1828
+ */
1829
+ addSystemMessage(content, type = 'info') {
1830
+ const systemMessages = document.getElementById('system-messages');
1831
+ if (!systemMessages) return;
1832
+
1833
+ const messageElement = document.createElement('div');
1834
+ messageElement.className = `system-message ${type}`;
1835
+
1836
+ const timestamp = new Date().toLocaleTimeString();
1837
+
1838
+ messageElement.innerHTML = `
1839
+ <div class="system-message-header">
1840
+ <span class="system-message-time">${timestamp}</span>
1841
+ <span class="system-message-type">${type.toUpperCase()}</span>
1842
+ </div>
1843
+ <div class="system-message-content">${content}</div>
1844
+ `;
1845
+
1846
+ systemMessages.appendChild(messageElement);
1847
+ systemMessages.scrollTop = systemMessages.scrollHeight;
1848
+
1849
+ // Limit message history to prevent memory issues
1850
+ const messages = systemMessages.children;
1851
+ if (messages.length > 50) {
1852
+ systemMessages.removeChild(messages[0]);
1853
+ }
1854
+ }
1855
+
1856
+ /**
1857
+ * Add a chat message to the messages log at the bottom
1858
+ * @param {string} sender - Message sender identifier
1859
+ * @param {string} content - Message content
1860
+ * @param {string} type - Message type ('own', 'dm')
1861
+ */
1862
+ addChatMessage(sender, content, type = 'info') {
1863
+ const messagesLog = document.getElementById('messages-log');
1864
+ if (!messagesLog) return;
1865
+
1866
+ const messageElement = document.createElement('div');
1867
+ messageElement.className = `message-item ${type}`;
1868
+
1869
+ const timestamp = new Date().toLocaleTimeString();
1870
+ const senderDisplay = sender === 'You' ? 'You' : sender.substring(0, 3);
1871
+
1872
+ messageElement.innerHTML = `
1873
+ <div class="avatar">${senderDisplay}</div>
1874
+ <div class="message-body">
1875
+ <div class="message-header">
1876
+ ${sender} • ${timestamp}
1877
+ </div>
1878
+ <div class="message-content">${content}</div>
1879
+ </div>
1880
+ `;
1881
+
1882
+ messagesLog.appendChild(messageElement);
1883
+ messagesLog.scrollTop = messagesLog.scrollHeight;
1884
+
1885
+ // Limit message history to prevent memory issues
1886
+ const messages = messagesLog.children;
1887
+ if (messages.length > 100) {
1888
+ messagesLog.removeChild(messages[0]);
1889
+ }
1890
+ }
1891
+
1892
+ /**
1893
+ * Add an entry to the DHT log
1894
+ * @param {string} message - The log message
1895
+ */
1896
+ addDHTLogEntry(message) {
1897
+ const dhtLog = document.getElementById('dht-log');
1898
+ if (!dhtLog) return;
1899
+
1900
+ const logEntry = document.createElement('div');
1901
+ logEntry.className = 'dht-log-entry';
1902
+
1903
+ const timestamp = new Date().toLocaleTimeString();
1904
+ logEntry.innerHTML = `
1905
+ <span class="dht-log-time">${timestamp}</span>
1906
+ <span class="dht-log-message">${message}</span>
1907
+ `;
1908
+
1909
+ dhtLog.appendChild(logEntry);
1910
+ dhtLog.scrollTop = dhtLog.scrollHeight;
1911
+
1912
+ // Limit log entries to prevent memory issues
1913
+ const entries = dhtLog.children;
1914
+ if (entries.length > 100) {
1915
+ dhtLog.removeChild(entries[0]);
1916
+ }
1917
+ }
1918
+
1919
+ /**
1920
+ * Update the DHT status display
1921
+ */
1922
+ updateDHTStatus() {
1923
+ const dhtStatusElement = document.getElementById('dht-status');
1924
+ if (!dhtStatusElement) return;
1925
+
1926
+ const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
1927
+ dhtStatusElement.textContent = isDHTEnabled ? 'Enabled' : 'Disabled';
1928
+ dhtStatusElement.className = `status ${isDHTEnabled ? 'connected' : 'disconnected'}`;
1929
+ }
1930
+ }