fix: SFU participants, duplicate peers, RC without login, devices, mobile bar (batch75)

#4 Participants list only ever showed "you": in SFU mode meetMakePeer drew a tile but
   NEVER added to meetPeers, so the roster (and the meeting-chat "To" list) was empty.
#5 Same person as several tiles: each tab/reload/reconnect gets a new peerId, leaving
   ghost peers. One uid = one tile now (dropDupPeers keeps the newest).
#1 Remote control needed a login: /share opened top-level (the no-login "Share my
   screen") has the preload bridge RIGHT THERE, but we only postMessage'd to a parent
   frame that doesn't exist — so control never armed. Use the native bridge directly.
#2 Sharer's session bar moved to the shared Lucide icon set (was old inline SVGs).
#3/#6 Device menu: collapse Windows' "Default -"/"Communications -" triplicates into one
   clean list (single "System default" + each real device once), and actually re-apply the
   saved mic/speaker to the room on connect so a picked headset/Bluetooth is used.
#7 Guest "left the meeting" screen rebranded to match the new pre-join.
#9 Tapping a member in group info opens the private conversation with them.
#8a iOS bottom rail: border-box + height incl. the home-indicator inset, px env() fallbacks
   (unitless 0 breaks calc() in Safari), promoted layer so it stops drifting.
#8c/#8e Mobile meeting bar: Mic / Camera / Speaker / End only; screen, record, transcript,
   chat, participants move behind a ⋮ More menu. No mic device dropdown on mobile.
#8d Speaker button reflects the real route: speaker-on / speaker-off (dimmed) / bluetooth
   when a headset is in use; re-detected on devicechange.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-13 15:39:05 +05:30
parent 94b8fac32f
commit 48b6a4050a
4 changed files with 165 additions and 44 deletions
+137 -35
View File
@@ -167,7 +167,7 @@
.ptr-ind.spin .ptr-g{animation:ptrspin .7s linear infinite;}
@keyframes ptrspin{to{transform:rotate(360deg);}}
/* Enable-notifications prompt (esp. iOS PWA) */
.notif-prompt{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(74px + env(safe-area-inset-bottom,0));z-index:2000;display:flex;align-items:center;gap:.7rem;width:max-content;max-width:min(460px,94vw);background:var(--blue);color:#fff;padding:.6rem .7rem .6rem 1rem;border-radius:12px;box-shadow:0 10px 30px rgba(20,30,60,.32);font-size:.86rem;}
.notif-prompt{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(74px + env(safe-area-inset-bottom,0px));z-index:2000;display:flex;align-items:center;gap:.7rem;width:max-content;max-width:min(460px,94vw);background:var(--blue);color:#fff;padding:.6rem .7rem .6rem 1rem;border-radius:12px;box-shadow:0 10px 30px rgba(20,30,60,.32);font-size:.86rem;}
.notif-prompt .np-actions{display:flex;align-items:center;gap:.4rem;margin-left:auto;flex:0 0 auto;}
.notif-prompt .btn.sm{background:#fff;color:var(--blue);}
.notif-prompt .np-x{background:transparent;border:none;color:#fff;opacity:.85;cursor:pointer;display:grid;place-items:center;padding:.2rem;}
@@ -608,11 +608,10 @@
.guest-prejoin .gp-join{width:100%;margin-top:.75rem;border:none;border-radius:11px;background:var(--blue);color:#fff;font:inherit;font-size:.95rem;font-weight:600;padding:.75rem;cursor:pointer;}
.guest-prejoin .gp-join:hover{filter:brightness(1.08);}
.guest-prejoin .gp-note{display:flex;align-items:center;justify-content:center;gap:.3rem;margin-top:.7rem;font-size:.74rem;color:var(--muted);}
.guest-left{position:fixed;inset:0;background:#1F3B73;display:flex;align-items:center;justify-content:center;z-index:9900;padding:1rem;}
.guest-left .gl-card{background:#fff;border-radius:16px;padding:2rem 1.6rem;text-align:center;max-width:360px;width:100%;box-shadow:0 18px 44px rgba(0,0,0,.3);}
.guest-left .gl-card h2{margin:.2rem 0 .3rem;font-size:1.15rem;color:var(--ink);}
.guest-left .gl-card p{margin:0 0 1.1rem;color:var(--muted);font-size:.9rem;}
.guest-left .gl-card .bzc-ok{width:100%;justify-content:center;}
/* Guest "left the meeting" — same brand language as the pre-join card. */
.guest-left{position:fixed;inset:0;z-index:9900;display:flex;align-items:center;justify-content:center;padding:1rem;
background:radial-gradient(1200px 600px at 50% -10%, #2b4f96 0%, #1F3B73 55%, #16294f 100%);}
.guest-left .gl-tick{width:64px;height:64px;margin:.4rem auto .8rem;border-radius:50%;background:#dcfce7;color:#15803d;display:grid;place-items:center;}
.modal-ov{position:fixed;inset:0;background:rgba(15,23,42,.45);display:flex;align-items:center;justify-content:center;z-index:9800;padding:1rem;}
.modal{background:#fff;border-radius:16px;padding:1.4rem;max-width:380px;width:100%;box-shadow:0 18px 44px rgba(0,0,0,.3);max-height:calc(100vh - 2rem);max-height:calc(100dvh - 2rem);overflow-y:auto;}
.modal h3{margin:0 0 .8rem;color:var(--blue);}
@@ -691,6 +690,18 @@
.meet-bar .mic-grp{position:relative;display:inline-flex;align-items:center;}
.meet-bar .mic-caret{position:absolute;right:-2px;bottom:-2px;width:20px;height:20px;border-radius:50%;border:2px solid var(--card,#fff);background:var(--blue);color:#fff;display:grid;place-items:center;cursor:pointer;padding:0;z-index:2;}
.meet-bar .mic-caret:hover{filter:brightness(1.12);}
.meet-bar .more-btn{display:none;} /* desktop: everything is on the bar */
.meet-bar .meet-ic.off{background:#e2e8f0;color:#94a3b8;} /* speaker off → lite colour (#8d) */
.gi-list .mrow.dm-able{cursor:pointer;border-radius:9px;}
.gi-list .mrow.dm-able:hover{background:var(--blue-soft);}
.spk-menu .mm-opt{display:flex;align-items:center;gap:.55rem;}
.spk-menu .mm-opt svg{flex:0 0 auto;color:var(--blue);}
/* ---- Mobile meeting bar (#8c/#8e): only Mic / Camera / Speaker / End; the rest behind ⋮ More ---- */
@media (max-width:640px){
.meet-bar .mic-caret{display:none;} /* #8c: no device dropdown on mobile — plain on/off */
.meet-bar .sec-btn{display:none;} /* screen, record, transcript, chat, participants → ⋮ */
.meet-bar .more-btn{display:inline-flex;}
}
.call-invite .ci-ico{width:38px;height:38px;border-radius:50%;background:#dcfce7;color:#15803d;display:grid;place-items:center;flex:0 0 auto;}
.call-invite .ci-txt{font-size:.88rem;color:var(--ink);line-height:1.25;}
.call-invite .ci-join{border:none;background:#15803d;color:#fff;border-radius:9px;padding:.45rem .7rem;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:.3rem;flex:0 0 auto;}
@@ -897,14 +908,22 @@
relocated into the chat-list header (see placeHdrRight). The shell is pushed below the
device status bar so no view overlaps it. */
header{display:none;}
.shell{padding-top:env(safe-area-inset-top,0);}
.shell{padding-top:env(safe-area-inset-top,0px);}
.side-title{gap:.5rem;}
.side-title h2{flex:1;}
.side-title #hdrRight{display:flex;align-items:center;gap:.4rem;flex:0 0 auto;}
.brand{font-size:.98rem;}
.navtoggle{display:none;} .rail-backdrop{display:none!important;} /* bottom nav replaces the drawer */
/* App-style bottom navigation bar */
.rail{position:fixed;left:0;right:0;bottom:0;top:auto;width:auto;height:60px;flex-direction:row;justify-content:space-around;align-items:center;gap:0;padding:0 .3rem env(safe-area-inset-bottom,0) .3rem;border-right:none;border-top:1px solid var(--line);box-shadow:0 -3px 14px rgba(20,30,60,.08);transform:none!important;z-index:1200;}
/* iOS: the 60px height had the home-indicator inset padded INSIDE it, so the bar sat under the
indicator and drifted with the URL bar. Use border-box + a height that INCLUDES the inset, pin it
with a promoted layer, and use px-unit env() fallbacks (unitless 0 breaks calc() on Safari). */
.rail{position:fixed;left:0;right:0;bottom:0;top:auto;width:auto;box-sizing:border-box;
height:calc(60px + env(safe-area-inset-bottom,0px));
padding:0 .3rem env(safe-area-inset-bottom,0px) .3rem;
flex-direction:row;justify-content:space-around;align-items:center;gap:0;
border-right:none;border-top:1px solid var(--line);box-shadow:0 -3px 14px rgba(20,30,60,.08);
transform:translateZ(0)!important;-webkit-transform:translateZ(0)!important;z-index:1200;background:var(--card);}
.rail .rail-spacer{display:none;}
.railbtn{display:flex;flex-direction:column;justify-content:center;gap:2px;width:62px;height:50px;border-radius:12px;}
.railbtn .rlabel{display:block;font-size:.66rem;font-weight:700;line-height:1;}
@@ -915,12 +934,12 @@
/* Meeting room code: always fully visible, full-width, easy to read */
.meet-bar .code{flex:1 1 100%;font-size:.9rem;white-space:normal;word-break:break-word;text-align:center;background:var(--blue-soft);border-radius:8px;padding:.35rem .5rem;}
/* Chat: one pane at a time (list, then the open conversation) */
.chatcol{width:100%;flex:1 1 100%;padding-bottom:calc(60px + env(safe-area-inset-bottom,0));}
.chatcol{width:100%;flex:1 1 100%;padding-bottom:calc(60px + env(safe-area-inset-bottom,0px));}
body.chat-open .chatcol{display:none;}
.content{display:none;}
body.chat-open .content, .shell:not(.is-chat) .content{display:block;}
.shell:not(.is-chat) .chatcol{display:none;}
.content .panel{bottom:calc(60px + env(safe-area-inset-bottom,0));} /* clear the bottom nav + home indicator */
.content .panel{bottom:calc(60px + env(safe-area-inset-bottom,0px));} /* clear the bottom nav + home indicator */
/* Bigger touch targets */
.chat-row{padding:.7rem .85rem;}
.convo-head{padding:.7rem .85rem;}
@@ -938,7 +957,7 @@
.md-actions > .btn{width:100%;justify-content:center;}
.md-join{flex:1 1 100%;}
.call-invite{left:8px;right:8px;max-width:none;bottom:70px;}
.bell-menu{position:fixed;left:8px;right:8px;top:calc(56px + env(safe-area-inset-top,0));width:auto;}
.bell-menu{position:fixed;left:8px;right:8px;top:calc(56px + env(safe-area-inset-top,0px));width:auto;}
#rail .bell-menu,#rail .profile .pmenu{left:auto;} /* desktop rail rule must not leak to the mobile bottom-nav */
/* Touch devices have no hover: keep member-row actions (make-admin / remove) always visible */
.mrow .iconbtn{opacity:1;}
@@ -946,9 +965,9 @@
</style>
</head>
<body>
<script src="/icons.js?v=5"></script>
<script src="/icons.js?v=6"></script>
<script src="https://cdn.jsdelivr.net/npm/@twemoji/api@15.1.0/dist/twemoji.min.js" crossorigin="anonymous"></script>
<script>window.__BUILD='2026-07-11-batch74';console.log('%cBiz Connect','color:#1F3B73;font-weight:bold','build '+window.__BUILD);
<script>window.__BUILD='2026-07-13-batch75';console.log('%cBiz Connect','color:#1F3B73;font-weight:bold','build '+window.__BUILD);
// Render modern (Twemoji) emojis in place of the OS's flat ones. No-op if the CDN didn't load
// (emojis stay as plain Unicode). (#5)
function twemojify(el){ try{ if(el && window.twemoji) window.twemoji.parse(el, { folder:'svg', ext:'.svg' }); }catch(_){} }</script>
@@ -2985,7 +3004,7 @@ async function openGroupInfo(gid){
+ (info.isAdmin?'<label class="gi-setting"><span>'+ic('lock',15)+' Only admins can add or remove people</span><span class="switch"><input type="checkbox" id="giAdminOnly"'+(info.adminOnly?' checked':'')+'><span class="slider"></span></span></label>':'')
+ '<div class="gi-sec-h"><span>Shared</span></div>' + mediaRowHTML()
+ '<div class="gi-sec-h"><span>Members</span>'+(canManage?'<button class="linkbtn" id="giAddToggle">'+ic('userPlus',15)+' Add people</button>':'')+'</div>'
+ '<div class="gi-list">'+info.members.map(m=>'<div class="mrow">'+miniAv(m.name,m.avatar)+'<span class="mn">'+pEsc(m.name)+(m.isMe?' <span class="youtag">you</span>':'')+(m.admin?' <span class="admin-tag">'+ic('crown',11)+' Admin</span>':'')+'</span>'+((info.isAdmin&&!m.isMe)?'<button class="iconbtn role'+(m.admin?' is-admin':'')+'" data-role="'+pEsc(m.id)+'" data-val="'+(m.admin?'0':'1')+'" title="'+(m.admin?'Remove admin':'Make admin')+'">'+ic('crown',15)+'</button>':'')+((canManage&&!m.isMe)?'<button class="iconbtn rm" data-rm="'+pEsc(m.id)+'" title="Remove">'+ic('trash',15)+'</button>':'')+'</div>').join('')+'</div>'
+ '<div class="gi-list">'+info.members.map(m=>'<div class="mrow'+(m.isMe?'':' dm-able')+'"'+(m.isMe?'':' data-dm="'+pEsc(m.id)+'" title="Message '+pEsc(m.name)+'"')+'>'+miniAv(m.name,m.avatar)+'<span class="mn">'+pEsc(m.name)+(m.isMe?' <span class="youtag">you</span>':'')+(m.admin?' <span class="admin-tag">'+ic('crown',11)+' Admin</span>':'')+'</span>'+((info.isAdmin&&!m.isMe)?'<button class="iconbtn role'+(m.admin?' is-admin':'')+'" data-role="'+pEsc(m.id)+'" data-val="'+(m.admin?'0':'1')+'" title="'+(m.admin?'Remove admin':'Make admin')+'">'+ic('crown',15)+'</button>':'')+((canManage&&!m.isMe)?'<button class="iconbtn rm" data-rm="'+pEsc(m.id)+'" title="Remove">'+ic('trash',15)+'</button>':'')+'</div>').join('')+'</div>'
+ '<div class="gi-add hidden" id="giAddWrap">'
+ (addable.length
? ('<div class="gi-search"><input id="giAddSearch" placeholder="Search people…" autocomplete="off"><button class="search-x" id="giAddSearchX" title="Clear" style="display:none">'+ic('x',14)+'</button></div>'
@@ -3021,6 +3040,12 @@ async function openGroupInfo(gid){
}
const addBtn=document.getElementById('giAddBtn'); if(addBtn) addBtn.onclick=async()=>{ const ids=[...ov.querySelectorAll('#giAddWrap input:checked')].map(i=>i.value); if(!ids.length){ toast('Pick members to add'); return; } try{ await postJSON('/api/groups/add',{group:gid,memberIds:ids}); ov.remove(); await refresh(); openGroupInfo(gid); }catch(e){ toast(e.message); } };
const nameOf=(uid)=>{ const mm=info.members.find(x=>x.id===uid); return mm?mm.name:'this person'; };
// #9: tapping a member (not their admin/remove buttons) opens the private conversation with them.
ov.querySelectorAll('.mrow[data-dm]').forEach(row=>row.addEventListener('click',(e)=>{
if(e.target.closest('button')) return; // let the admin / remove buttons do their thing
const id=row.dataset.dm; if(!id) return;
ov.remove(); switchTab('chat'); selectChat('dm', id);
}));
ov.querySelectorAll('[data-rm]').forEach(b=>b.onclick=async()=>{ const nm=nameOf(b.dataset.rm); if(!confirm('Remove '+nm+' from the group?\n\nThey will lose access to this conversation.')) return; try{ await postJSON('/api/groups/remove',{group:gid,userId:b.dataset.rm}); ov.remove(); await refresh(); openGroupInfo(gid); }catch(e){ toast(e.message); } });
ov.querySelectorAll('[data-role]').forEach(b=>b.onclick=async()=>{ const mk=b.dataset.val==='1'; const nm=nameOf(b.dataset.role); if(!confirm(mk?('Make '+nm+' an admin?\n\nThey will be able to add or remove members and manage this group.'):('Remove '+nm+' as an admin?'))) return; try{ await postJSON('/api/groups/admin',{group:gid,userId:b.dataset.role,value:mk}); ov.remove(); await refresh(); openGroupInfo(gid); }catch(e){ toast(e.message); } });
document.getElementById('giLeave').onclick=async()=>{
@@ -3102,6 +3127,10 @@ async function sfuConnect(){
room.on(LK.RoomEvent.TrackSubscribed, (track,pub,participant)=>sfuAttach(pub,track,participant));
room.on(LK.RoomEvent.TrackUnsubscribed, (track,pub,participant)=>sfuDetach(pub,track,participant));
await room.connect(SFU.url, tk.token);
// Re-apply the user's saved mic/speaker choice to this room (#3: a picked headset/Bluetooth device
// must actually be used, not just remembered).
try{ if(meetMicId && room.switchActiveDevice) await room.switchActiveDevice('audioinput', meetMicId); }catch(_){}
try{ if(meetSinkId && room.switchActiveDevice) await room.switchActiveDevice('audiooutput', meetSinkId); }catch(_){}
}
// Per-peer track bookkeeping → one tile stream that prefers the screen track over the camera,
// mirroring the mesh's single-video-per-tile model and driving the existing sharing/stage UI.
@@ -3390,12 +3419,14 @@ function renderCall(){
+ '<span class="mic-grp"><button class="meet-ic'+(meetMic?'':' off')+'" id="meetMicBtn" title="'+(meetMic?'Mute':'Unmute')+'">'+ic(meetMic?'mic':'micOff',20)+'</button>'
+ '<button class="mic-caret" id="meetAudioBtn" title="Audio devices (mic & speaker)">'+ic('chevronUp',12)+'</button></span>'
+ '<button class="meet-ic'+(meetCam?'':' off')+'" id="meetCamBtn" title="'+(meetCam?'Turn camera off':'Turn camera on')+'">'+ic(meetCam?'video':'videoOff',20)+'</button>'
+ '<button class="meet-ic" id="meetScreenBtn" title="Share screen">'+ic('monitor',20)+'</button>'
+ '<button class="meet-ic host-only" id="meetRecBtn" title="Record meeting" style="display:none">'+ic('record',20)+'</button>'
+ ((ME&&ME.guest)?'':'<button class="meet-ic" id="meetTransBtn" title="Live transcript">'+ic('fileText',20)+'</button>') // #12: transcript is a signed-in feature (guests can't download it)
+ '<button class="meet-ic" id="meetChatBtn" title="Chat"><span class="mc-badge" id="meetChatBadge" style="display:none">0</span>'+ic('chat',20)+'</button>'
+ (isMobileUA()?'<button class="meet-ic'+(meetSpeakerOn?'':' off')+'" id="meetSpkBtn" title="Speakerphone">'+ic('headphones',20)+'</button>':'')
+ '<button class="meet-ic" id="meetPplBtn" title="Participants">'+ic('users',20)+'</button>'
// Mobile keeps only Mic / Camera / Speaker / End on the bar (#8e); everything else moves behind ⋮ More.
+ '<button class="meet-ic sec-btn" id="meetScreenBtn" title="Share screen">'+ic('monitor',20)+'</button>'
+ '<button class="meet-ic host-only sec-btn" id="meetRecBtn" title="Record meeting" style="display:none">'+ic('record',20)+'</button>'
+ ((ME&&ME.guest)?'':'<button class="meet-ic sec-btn" id="meetTransBtn" title="Live transcript">'+ic('fileText',20)+'</button>') // #12: transcript is a signed-in feature (guests can't download it)
+ '<button class="meet-ic sec-btn" id="meetChatBtn" title="Chat"><span class="mc-badge" id="meetChatBadge" style="display:none">0</span>'+ic('chat',20)+'</button>'
+ '<button class="meet-ic spk-btn'+(meetSpeakerOn?'':' off')+'" id="meetSpkBtn" title="Speakerphone">'+ic(spkIcon(),20)+'</button>'
+ '<button class="meet-ic sec-btn" id="meetPplBtn" title="Participants">'+ic('users',20)+'</button>'
+ '<button class="meet-ic more-btn" id="meetMoreBtn" title="More">'+ic('moreVertical',20)+'</button>'
+ '<button class="meet-ic leave" id="meetLeaveBtn" title="Leave">'+ic('callEnd',20)+'</button></div></div>';
document.getElementById('meetMicBtn').onclick=toggleMic;
document.getElementById('meetCamBtn').onclick=toggleCam;
@@ -3405,13 +3436,15 @@ function renderCall(){
document.getElementById('meetPplBtn').onclick=toggleMeetPanel;
{ const cb=document.getElementById('meetChatBtn'); if(cb) cb.onclick=toggleMeetChat; }
{ const ab=document.getElementById('meetAudioBtn'); if(ab) ab.onclick=(e)=>{ e.stopPropagation(); openAudioMenu(ab); }; } // desktop: mic ▾ → devices
{ const sb=document.getElementById('meetSpkBtn'); if(sb) sb.onclick=toggleSpeakerphone; } // mobile: speakerphone toggle
{ const sb=document.getElementById('meetSpkBtn'); if(sb) sb.onclick=toggleSpeakerphone; } // speaker / headset toggle
{ const mb=document.getElementById('meetMoreBtn'); if(mb) mb.onclick=(e)=>{ e.stopPropagation(); openMeetMore(mb); }; } // mobile: ⋮ → the rest
document.getElementById('meetLeaveBtn').onclick=leaveMeeting;
updateHostControls();
// Click another shared screen (in the side column) to bring it onto the stage.
const grid=document.getElementById('meetGrid'); if(grid) grid.addEventListener('click', e=>{ if(!grid.classList.contains('sharing-mode')) return; const t=e.target.closest('.meet-tile.sharing'); if(t && !t.classList.contains('stage')){ setStage(t.id.replace('meet-tile-','')); } });
addTile('__local', meetLocalStream, (ME&&ME.name)?ME.name:'You', true);
setTileMute('__local', !meetMic);
detectBtOutput(); // #8d: pick the right speaker/bluetooth glyph for the current route
}
// ---- Audio devices (#3): one menu behind the MIC's ▾ caret, listing Speaker + Microphone (like Teams),
// instead of a separate headphones button. Choosing a speaker applies setSinkId to every meeting media
@@ -3424,6 +3457,42 @@ function applySink(el){ try{ if(el && meetSinkId && typeof el.setSinkId==='funct
function applySinkAll(){ document.querySelectorAll('#meetGrid video').forEach(applySink); }
// Bluetooth/headset devices report themselves in the label — used to pick a sensible icon on mobile.
function isBtLabel(l){ return /bluetooth|airpod|buds|headset|headphone|wh-|wf-/i.test(l||''); }
// #8d: the speaker button's icon reflects the ACTUAL route — bluetooth/headset when one is in use,
// otherwise speaker-on / speaker-off (dimmed when off).
let _btConnected=false;
function spkIcon(){ if(_btConnected && !meetSpeakerOn) return 'bluetooth'; return meetSpeakerOn?'speaker':'speakerOff'; }
function refreshSpkBtn(){
const b=document.getElementById('meetSpkBtn'); if(!b) return;
b.classList.toggle('off', !meetSpeakerOn);
b.innerHTML=ic(spkIcon(),20);
b.title=(_btConnected&&!meetSpeakerOn)?'Using headset / Bluetooth':(meetSpeakerOn?'Speaker on':'Speaker off');
}
// Detect a connected BT/headset output so the icon can switch to the bluetooth glyph.
async function detectBtOutput(){
try{ const d=await navigator.mediaDevices.enumerateDevices(); _btConnected=d.some(x=>x.kind==='audiooutput' && isBtLabel(x.label)); }catch(_){ _btConnected=false; }
refreshSpkBtn();
}
try{ if(navigator.mediaDevices && navigator.mediaDevices.addEventListener) navigator.mediaDevices.addEventListener('devicechange', ()=>{ detectBtOutput(); }); }catch(_){}
// #8e: on mobile the bar keeps only Mic/Camera/Speaker/End — the rest live behind this ⋮ menu.
function openMeetMore(anchor){
document.querySelectorAll('.spk-menu').forEach(x=>x.remove());
const items=[];
items.push({ic:'monitor', label:'Share screen', fn:toggleScreen});
if(meetIsHost) items.push({ic:'record', label:(meetRec?'Stop recording':'Record meeting'), fn:toggleRecord});
if(!(ME&&ME.guest)) items.push({ic:'fileText', label:(meetTranscribe?'Stop transcript':'Live transcript'), fn:toggleTranscribe});
items.push({ic:'chat', label:'Chat'+(meetChatUnread?(' ('+meetChatUnread+')'):''), fn:toggleMeetChat});
items.push({ic:'users', label:'Participants', fn:toggleMeetPanel});
items.push({ic:'headphones', label:'Audio devices', fn:()=>openAudioMenu(anchor)});
const menu=document.createElement('div'); menu.className='spk-menu';
menu.innerHTML=items.map((it,i)=>'<button class="spk-opt mm-opt" data-i="'+i+'">'+ic(it.ic,15)+'<span>'+pEsc(it.label)+'</span></button>').join('');
document.body.appendChild(menu);
const r=anchor.getBoundingClientRect();
menu.style.left=Math.max(8,Math.min(r.left-100, window.innerWidth-menu.offsetWidth-8))+'px';
menu.style.top=Math.max(8,(r.top-menu.offsetHeight-10))+'px';
menu.querySelectorAll('.mm-opt').forEach(b=>b.onclick=()=>{ const it=items[+b.dataset.i]; menu.remove(); try{ it.fn(); }catch(_){} });
const close=(e)=>{ if(!menu.contains(e.target) && !anchor.contains(e.target)){ menu.remove(); document.removeEventListener('mousedown',close); document.removeEventListener('touchstart',close); } };
setTimeout(()=>{ document.addEventListener('mousedown',close); document.addEventListener('touchstart',close); },0);
}
async function setSpeakerDevice(id){
meetSinkId=id||''; try{ localStorage.setItem('bzc_sink', meetSinkId); }catch(_){}
try{ if(SFU.room && SFU.room.switchActiveDevice) await SFU.room.switchActiveDevice('audiooutput', meetSinkId); }catch(_){}
@@ -3443,10 +3512,25 @@ async function setMicDevice(id){
meetPeers.forEach(p=>{ try{ const snd=p.pc.getSenders().find(x=>x.track&&x.track.kind==='audio'); if(snd) snd.replaceTrack(nt); }catch(_){} });
}catch(e){ toast(mediaErrMsg(e,'microphone')); }
}
// Windows lists the same physical device three times ("Default - X", "Communications - X", "X"). Collapse
// that into one clean list: a single "System default" entry plus each real device once (#6).
function cleanDevices(list){
const out=[]; const seen=new Set(); let hasDefault=false;
for(const d of (list||[])){
if(d.deviceId==='communications') continue; // Windows' duplicate "comms" alias
if(d.deviceId==='default'){ hasDefault=true; continue; } // folded into the single entry below
const label=String(d.label||'').replace(/^\s*(Default|Communications)\s*-\s*/i,'').trim();
const key=(d.groupId||d.deviceId||'')+'|'+label.toLowerCase();
if(seen.has(key)) continue; seen.add(key);
out.push({ deviceId:d.deviceId, label: label||'Device' });
}
if(hasDefault) out.unshift({ deviceId:'default', label:'System default' });
return out;
}
async function openAudioMenu(anchor){
document.querySelectorAll('.spk-menu').forEach(x=>x.remove());
let outs=[], ins=[];
try{ const d=await navigator.mediaDevices.enumerateDevices(); outs=d.filter(x=>x.kind==='audiooutput'); ins=d.filter(x=>x.kind==='audioinput'); }catch(_){}
try{ const d=await navigator.mediaDevices.enumerateDevices(); outs=cleanDevices(d.filter(x=>x.kind==='audiooutput')); ins=cleanDevices(d.filter(x=>x.kind==='audioinput')); }catch(_){}
const menu=document.createElement('div'); menu.className='spk-menu';
const sel=(id, cur)=> (id===cur || (!cur && (id==='default'||id===''))) ? ' on' : '';
let html='';
@@ -3477,15 +3561,13 @@ async function toggleSpeakerphone(){
const btn=document.getElementById('meetSpkBtn'); if(!btn) return;
meetSpeakerOn=!meetSpeakerOn; try{ localStorage.setItem('bzc_spk', meetSpeakerOn?'1':'0'); }catch(_){}
let outs=[]; try{ outs=(await navigator.mediaDevices.enumerateDevices()).filter(x=>x.kind==='audiooutput'); }catch(_){}
const bt=outs.find(d=>isBtLabel(d.label));
const bt=outs.find(d=>isBtLabel(d.label)); _btConnected=!!bt;
if(meetSpeakerOn){
const spk=outs.find(d=>/speaker/i.test(d.label)) || outs.find(d=>d.deviceId==='default') || outs[0];
if(spk) await setSpeakerDevice(spk.deviceId);
} else if(bt){ await setSpeakerDevice(bt.deviceId); }
else { await setSpeakerDevice(''); }
btn.classList.toggle('off', !meetSpeakerOn);
btn.innerHTML=ic('headphones',20);
btn.title=meetSpeakerOn?'Speakerphone on':(bt?('Using '+(bt.label||'headset')):'Speakerphone off');
} else if(bt){ await setSpeakerDevice(bt.deviceId); } // speaker off + headset present → route to the headset
else { await setSpeakerDevice(''); } // no headset → back to the system default (earpiece on mobile)
refreshSpkBtn();
toast(meetSpeakerOn?'Speaker on':(bt?'Using headset':'Speaker off'));
}
function addTile(id, stream, label, muted){
@@ -3531,9 +3613,24 @@ function meetWatchStream(id, stream){
}
function meetUnwatch(id){ const r=meetVU.get(id); if(!r) return; try{cancelAnimationFrame(r.raf);}catch(_){} try{r.src.disconnect();}catch(_){} try{r.ctx.close();}catch(_){} meetVU.delete(id); const t=document.getElementById('meet-tile-'+id); if(t) t.classList.remove('speaking'); }
function meetUnwatchAll(){ for(const id of Array.from(meetVU.keys())) meetUnwatch(id); }
// #5: the same person showing up as several tiles. Each browser tab / reload / reconnect gets a NEW
// peerId, so a stale session left a ghost tile behind. One person (uid) = one tile: when a uid reappears
// on a new peerId, drop their older peer entirely.
function dropDupPeers(uid, keepPid){
if(!uid) return;
for(const [pid,u] of [...meetPeerUids]){
if(u!==uid || pid===keepPid) continue;
const p=meetPeers.get(pid); if(p){ try{ p.pc&&p.pc.close(); }catch(_){} meetPeers.delete(pid); }
if(SFU.on){ try{ sfuDropPeer(pid); }catch(_){} }
meetSharers.delete(pid); meetPeerUids.delete(pid); meetNames.delete(pid); meetAvatars.delete(pid);
removeTile(pid);
}
}
function meetMakePeer(peerId, name){
// SFU mode: no P2P peer connection — just show the tile (avatar until LiveKit delivers media).
if(SFU.on){ addTile(peerId, null, meetNames.get(peerId)||name||'Guest', false); return null; }
// SFU mode: no P2P peer connection — but we STILL record the peer, otherwise meetPeers stays empty and
// the Participants list only ever shows "you" (and the meeting-chat "To" list is empty). pc is null;
// every p.pc use is already try/catch-guarded.
if(SFU.on){ meetPeers.set(peerId, { pc:null, name, vsender:null }); addTile(peerId, null, meetNames.get(peerId)||name||'Guest', false); return null; }
const pc=new RTCPeerConnection(MEET_ICE);
const entry={ pc, name, vsender:null }; meetPeers.set(peerId, entry);
addTile(peerId, null, meetNames.get(peerId)||name||'Guest', false); // show the tile right away (avatar)
@@ -3707,7 +3804,7 @@ async function onMeetMsg(e){
meetWatchStream('__local', meetLocalStream); // active-speaker detection on my own mic
// Existing peers OFFER to me (their offers carry their tracks incl. any active screen share);
// I just set up the connections and wait. Avoids the "newcomer can't receive screen" bug.
for(const p of (m.peers||[])){ meetNames.set(p.peerId,p.name); if(p.avatar) meetAvatars.set(p.peerId,p.avatar); if(p.uid){ meetPeerUids.set(p.peerId,p.uid); meetInviteJoined(p.uid); } meetMakePeer(p.peerId,p.name); }
for(const p of (m.peers||[])){ meetNames.set(p.peerId,p.name); if(p.avatar) meetAvatars.set(p.peerId,p.avatar); if(p.uid){ meetPeerUids.set(p.peerId,p.uid); meetInviteJoined(p.uid); dropDupPeers(p.uid, p.peerId); } meetMakePeer(p.peerId,p.name); }
if(_dmCallWaiting && !(m.peers&&m.peers.length)) addWaitingTile(_dmCallWaiting.name, _dmCallWaiting.avatar); // #7: show who we're calling while it rings
// SFU: connect to LiveKit for media once (peer uid→peerId map is populated above). Mic/cam are
// off at join, so nothing publishes yet — toggleMic/toggleCam publish on demand.
@@ -3725,7 +3822,7 @@ async function onMeetMsg(e){
if(m.type==='meeting-ended'){ toast(m.reason==='unanswered'?'No answer':'Call ended'); leaveMeeting(true); return; } // 1:1 hangup / host ended / unanswered
if(m.type==='meeting-peer-joined'){
stopRingback(); removeWaitingTile(); _dmCallWaiting=null; // #17/#7: they answered → stop ring + drop the ringing tile
meetNames.set(m.peerId,m.name); if(m.avatar) meetAvatars.set(m.peerId,m.avatar); if(m.uid){ meetPeerUids.set(m.peerId,m.uid); meetInviteJoined(m.uid); }
meetNames.set(m.peerId,m.name); if(m.avatar) meetAvatars.set(m.peerId,m.avatar); if(m.uid){ meetPeerUids.set(m.peerId,m.uid); meetInviteJoined(m.uid); dropDupPeers(m.uid, m.peerId); }
const pc=meetMakePeer(m.peerId,m.name); // I'm an existing peer → I OFFER to the newcomer (carries my screen)
if(pc){ try{ const offer=await pc.createOffer(); await pc.setLocalDescription(offer); meetSend({type:'meeting-signal',to:m.peerId,data:{sdp:pc.localDescription}}); }catch(_){} } // (SFU: LiveKit handles media, no offer)
meetSend({type:'meeting-state', muted:!meetMic, camOff:!meetCam});
@@ -3828,9 +3925,14 @@ let _guestRoom=null;
function renderGuestLeft(){
document.querySelectorAll('.guest-left').forEach(x=>x.remove());
const el=document.createElement('div'); el.className='guest-left';
el.innerHTML='<div class="gl-card"><img src="/mark-light.png" alt="" style="height:46px;width:auto;object-fit:contain;margin-bottom:.4rem" onerror="this.remove()">'
+'<h2>Youve left the meeting</h2><p>Thanks for joining.</p>'
+(_guestRoom?'<button class="bzc-ok" id="glRejoin">Rejoin meeting</button>':'')+'</div>';
el.innerHTML='<div class="gp-card">'
+'<div class="gp-brand"><img src="/mark-light.png" alt="" onerror="this.remove()"><span>Biz <b>Connect</b></span></div>'
+'<div class="gl-tick">'+ic('check',30)+'</div>'
+'<h2>Youve left the meeting</h2>'
+'<p class="gp-sub">Thanks for joining'+((ME&&ME.name)?(', '+pEsc(firstName(ME.name))):'')+'.</p>'
+(_guestRoom?'<button class="gp-join" id="glRejoin">Rejoin meeting</button>':'')
+'<div class="gp-note">'+ic('info',13)+' You can close this tab safely.</div>'
+'</div>';
document.body.appendChild(el);
const rj=el.querySelector('#glRejoin'); if(rj) rj.onclick=()=>{ location.href='/home?meet='+encodeURIComponent(_guestRoom); };
}