Files
Kronic-Krusaders/JS/balroc.js
T
2026-11-25 20:21:57 -06:00

352 lines
30 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
(() => {
const $ = id => document.getElementById(id);
const win=$('balrocWindow'), log=$('balrocMessages'), input=$('balrocInput');
const status=$('balrocStatus'), mic=$('balrocMic'), send=$('balrocSend');
// Live destination selector: Kronic is ALWAYS default, other targets require approval.
const destinationSelect=document.createElement('select');
destinationSelect.id='aiCommandDestination';destinationSelect.add(new Option('Kronic (this window)','kronic'));
destinationSelect.title='Playback destination';
destinationSelect.setAttribute('aria-label','Playback destination');
destinationSelect.style.cssText='background:#142237;color:#e8efff;border:1px solid #456084;border-radius:6px;padding:7px;flex:1;min-width:170px';
const destinationRow=document.createElement('div');
destinationRow.style.cssText='display:flex;align-items:center;gap:7px;padding:6px 9px;flex-wrap:wrap';
const destinationLabel=document.createElement('label');
destinationLabel.textContent='Player:';
destinationLabel.setAttribute('for','aiCommandDestination');
destinationLabel.style.cssText='font-size:12px';
const refreshPlayers=document.createElement('button');
refreshPlayers.type='button';refreshPlayers.textContent='Refresh players';
refreshPlayers.style.cssText='padding:6px 8px;border:1px solid #456084;border-radius:5px';
const approvePlayer=document.createElement('button');
approvePlayer.type='button';approvePlayer.textContent='Approve player';
approvePlayer.title='Platform administrators can approve selected Jellyfin clients';
approvePlayer.style.cssText='padding:6px 9px;border:1px solid #54769b;border-radius:6px;background:#294365;color:#fff;cursor:pointer';
approvePlayer.hidden=true;
destinationRow.append(destinationLabel,destinationSelect,refreshPlayers,approvePlayer);
const aiForm=$('balrocForm');
// kronic-ai-players-v6: controls above messages, chat composer stays pinned at bottom.
destinationRow.classList.add('ai-command-player-toolbar');
destinationRow.style.cssText='display:flex;align-items:center;gap:8px;padding:10px 12px;flex-wrap:wrap;background:#16263b;border-bottom:1px solid #30455f';
if(win && log)win.insertBefore(destinationRow,log);
let aiClientList=[];let canApproveAiPlayers=false;let playersLoading=false;
function updateApproveButton(){
const c=aiClientList.find(x=>x.device_id===destinationSelect.value);
approvePlayer.hidden=!canApproveAiPlayers || !c || !!c.approved || !c.controllable;
approvePlayer.disabled=!c || !c.controllable;
}
destinationSelect.addEventListener('change',()=>{updateApproveButton();renderPlayback();});
approvePlayer.addEventListener('click',async()=>{
const c=aiClientList.find(x=>x.device_id===destinationSelect.value);
if(!c || !c.controllable || c.approved)return;
if(!confirm('Approve remote playback control for '+c.device+' ('+c.client+')?'))return;
approvePlayer.disabled=true;
try{
const response=await fetch('/api/balroc/approve-client',{method:'POST',headers:{'Content-Type':'application/json','X-Kronic-Room':document.body.dataset.roomId},credentials:'same-origin',body:JSON.stringify({device_id:c.device_id})});
const data=await response.json().catch(()=>({}));
if(!response.ok)throw new Error(data.error||data.detail||'HTTP '+response.status);
await refreshAiPlayers();
}catch(error){alert('Player approval failed: '+error.message);updateApproveButton();}
});
async function refreshAiPlayers(){
const previous=destinationSelect.value;
if(playersLoading)return;playersLoading=true;
try{
const response=await fetch('/api/balroc/clients',{credentials:'same-origin',cache:'no-store',headers:{'X-Kronic-Room':document.body.dataset.roomId}});
if(!response.ok)throw Error('HTTP '+response.status);
const data=await response.json();
const selected=destinationSelect.value||previous;
destinationSelect.replaceChildren(new Option('Kronic (this window)','kronic'));
aiClientList=Array.isArray(data.clients)?data.clients:[];
canApproveAiPlayers=!!data.can_approve;
for(const c of aiClientList){
if(!c.device_id||!c.device)continue;
const allowed=!!c.approved && !!c.controllable;
const option=new Option(String(c.device)+' · '+String(c.client||'Jellyfin')+(c.approved?'':' (approval required)')+(!c.controllable?' (not controllable)':''),String(c.device_id));
option.disabled=!c.controllable;
destinationSelect.add(option);
}
if(selected && ![...destinationSelect.options].some(o=>o.value===selected)){destinationSelect.add(new Option('Previously selected player (offline)',selected));}
if(selected)destinationSelect.value=selected;
refreshPlayers.title='Live Jellyfin clients refreshed';
updateApproveButton();
}catch(error){refreshPlayers.title='Client list failed: '+error.message;approvePlayer.hidden=true;aiClientList=[];}finally{playersLoading=false;renderPlayback();}
}
refreshPlayers.addEventListener('click',()=>{void refreshAiPlayers();});
$('balrocOpen')?.addEventListener('click',()=>{void refreshAiPlayers();});
let session='',busy=false,recorder=null,stream=null,chunks=[];
const windowId = (globalThis.crypto?.randomUUID?.() || 'win_'+Math.random().toString(36).slice(2)+Date.now().toString(36)).replace(/[^A-Za-z0-9_-]/g,'');
async function navigateMedia(kind){
// The Borg navigator opens the FLOATING media window and loads its content.
// showYouTubeLibrary()/showMusicLibrary()/showIptvLibrary() alone only render hidden content.
const expected={youtube:'youtubeSearchInput',music:'musicFilterInput',iptv:'iptvChannelSearch'}[kind];
if(!expected)throw Error('Unknown media destination');
await new Promise((resolve,reject)=>{
let complete=false;
const timeout=setTimeout(()=>{if(complete)return;complete=true;reject(Error('Media window navigation timed out'));},15000);
const finish=(err)=>{if(complete)return;complete=true;clearTimeout(timeout);if(err)reject(Error(String(err.message||err)));else resolve();};
window.dispatchEvent(new CustomEvent('kronic:ai-media-navigate',{detail:{kind,finish}}));
});
const wrap=document.getElementById('borgWindowWrap');
const field=document.getElementById(expected);
if(!wrap||wrap.hidden||!field)throw Error('The '+kind+' media window did not open (check library access permissions)');
return field;
}
async function navigateMediaTree(kind,action){
await navigateMediaV3(kind);
if(!action || !Number.isSafeInteger(Number(action.source_id)) || Number(action.source_id)<=0)return;
await new Promise((resolve,reject)=>{
let done=false;
const finish=error=>{if(done)return;done=true;clearTimeout(timer);error?reject(Error(String(error.message||error))):resolve();};
const timer=setTimeout(()=>finish(Error('Kronic library navigation timed out')),15000);
window.dispatchEvent(new CustomEvent('kronic:ai-open-library',{detail:{source_id:Number(action.source_id),kind,show_name:action.show_name||'',season:action.season,finish}}));
});
}
async function navigateMediaV3(kind){
if(!['movies','shows','twitch'].includes(kind))throw Error('Unsupported media category');
await new Promise((resolve,reject)=>{
let done=false;
const finish=error=>{if(done)return;done=true;clearTimeout(timer);error?reject(Error(String(error.message||error))):resolve();};
const timer=setTimeout(()=>finish(new Error('Kronic media navigation timed out')),15000);
window.dispatchEvent(new CustomEvent('kronic:ai-media-navigate',{detail:{kind,finish}}));
});
const wrap=document.getElementById('borgWindowWrap');
if(!wrap||wrap.hidden)throw Error('Kronic media window did not open');
}
async function runUiAction(action){
if(!action||!action.type)return;
if(action.type==='kronic_video_play'){
const kind=action.kind==='shows'?'shows':'movies';
await navigateMediaTree(kind,action);
const id=Number(action.media_id);
if(!Number.isSafeInteger(id)||id<=0)throw Error('Invalid Kronic media ID');
if(typeof api!=='function'||typeof openPlayer!=='function')throw Error('Kronic video player is unavailable');
const item=(await api('/api/media')).find(x=>Number(x.id)===id);
if(!item)throw Error('Media is no longer available to this user');
await openPlayer(id,String(action.title||item.effective_title||item.title||'Media'));
return;
}
if(action.type==='kronic_video_browse'){
await navigateMediaTree(action.kind==='shows'?'shows':'movies',action);
return;
}
if(action.type==='twitch_search'||action.type==='twitch_play'){
await navigateMediaV3('twitch');
if(action.type==='twitch_play'){
if(typeof api!=='function'||typeof openTwitchPlayer!=='function')throw Error('Kronic Twitch player unavailable');
const data=await api('/api/twitch/overview');
const channel=(data.channels||[]).find(c=>String(c.id)===String(action.channel_id));
if(!channel)throw Error('Twitch channel is not accessible to this account');
await openTwitchPlayer(channel);
}
return;
}
if(action.type==='tube_search'){
const inp=await navigateMedia('youtube');
inp.value=String(action.query||'');
if(typeof searchYouTube!=='function')throw Error('Kronic Tube search function is unavailable');
await searchYouTube(inp.value);
}else if(action.type==='tube_play'){
const inp=await navigateMedia('youtube');
inp.value=String(action.query||'');
if(typeof searchYouTube!=='function'||typeof openYouTubePlayer!=='function')throw Error('Kronic Tube playback is unavailable');
await searchYouTube(inp.value);
const targetId=String(action.video_id||'');
if(!targetId)throw Error('No matching YouTube video ID was provided');
// Use the exact result that the authenticated server matched, not the first search card.
let item=(typeof youtubeItemRegistry!=='undefined'&&youtubeItemRegistry.get(targetId))||null;
if(!item&&action.item&&String(action.item.id)===targetId){
item={...action.item,id:targetId};
}
if(!item)throw Error('Selected video is no longer available; choose a search result');
await openYouTubePlayer(item);
if(!document.getElementById('youtubePlayerWindow')||!document.getElementById('youtubeVideoElement')){
throw Error('Kronic Tube player failed to open');
}
}else if(action.type==='music_search'||action.type==='music_play'){
const inp=await navigateMedia('music');
inp.value=String(action.query||'');
if(typeof loadMusicTracks!=='function')throw Error('Kronic music search function is unavailable');
await loadMusicTracks(inp.value);
if(action.type==='music_play'){
if(typeof musicTrackRegistry==='undefined'||typeof playMusicTrack!=='function')throw Error('Kronic music playback is unavailable');
const item=musicTrackRegistry.get(String(action.track_id));
if(!item)throw Error('Music track no longer available');
await playMusicTrack(item);
}
}else if(action.type==='iptv_search'||action.type==='iptv_play'){
const inp=await navigateMedia('iptv');
inp.value=String(action.query||'');
inp.dispatchEvent(new Event('input',{bubbles:true}));
if(action.type==='iptv_play'){
if(typeof api!=='function'||typeof openIptvChannel!=='function')throw Error('Kronic IPTV player is unavailable');
const overview=await api('/api/iptv/overview');
const item=(overview.channels||[]).find(x=>Number(x.id)===Number(action.channel_id));
if(!item)throw Error('IPTV channel is not accessible');
await openIptvChannel(item);
}
}
}
// Inline search previews use the authenticated resolver's actual result IDs.
const searchTypes=new Set(['tube_search','music_search','iptv_search','twitch_search','kronic_video_browse']);
let pendingSearch=null, resultActionBusy=false;
function resultKind(action){return ({tube_search:'youtube',music_search:'music',iptv_search:'iptv',twitch_search:'twitch'})[action.type] || (action.kind==='shows'?'shows':'movies');}
function resultRow(item,action,index){
const kind=resultKind(action), row=document.createElement('button');row.type='button';row.className='balroc-result-row';
const thumb=document.createElement('span');thumb.className='balroc-result-thumb';thumb.textContent=kind==='music'?'♪':kind==='iptv'?'TV':'▶';
const id=String(item.id||item.video_id||'');
const raw=kind==='movies'||kind==='shows'?`/thumbnail/${encodeURIComponent(id)}`:kind==='iptv'?`/api/iptv/channels/${encodeURIComponent(id)}/snapshot`:item.thumbnail||item.thumbnail_url;
if(raw){try{const url=new URL(raw,location.origin);if(['https:','http:'].includes(url.protocol)){const img=document.createElement('img');img.alt='';img.loading='lazy';img.referrerPolicy='no-referrer';img.onerror=()=>img.remove();img.src=roomMediaUrl(url.href);thumb.append(img);}}catch(e){}}
const words=document.createElement('span');words.className='balroc-result-text';const title=document.createElement('strong');title.textContent=item.title||item.name||id;words.append(title);
const subtitle=document.createElement('small');subtitle.textContent=item.artist||item.subtitle||({movies:'Movie',shows:'TV episode',iptv:'Live TV',twitch:'Twitch',youtube:'Tube',music:'Music'})[kind];words.append(subtitle);
const arrow=document.createElement('span');arrow.textContent='›';arrow.setAttribute('aria-hidden','true');row.append(thumb,words,arrow);
row.onclick=()=>void resultTask(async()=>{
// Preview cards are Kronic-local; never silently retarget a remote player.
if(destinationSelect.value!=='kronic')throw Error('Select Kronic (this window) to play this local result.');
const rights=await api('/api/auth/media-context');const key=({youtube:'tube',shows:'tv'})[kind]||kind;if(rights.allowedLibraries?.[key]!==true)throw Error('Library access denied');
if(kind==='youtube'){await openYouTubePlayer({...item,id});}
else if(kind==='movies'||kind==='shows'){const fresh=(await api('/api/media')).find(x=>String(x.id)===id);if(!fresh)throw Error('Media no longer accessible');await openPlayer(Number(id),title.textContent);}
else if(kind==='iptv'){const d=await api('/api/iptv/overview');const fresh=(d.channels||[]).find(x=>String(x.id)===id);if(!fresh)throw Error('Channel no longer accessible');await openIptvChannel(fresh);}
else if(kind==='twitch'){const d=await api('/api/twitch/overview');const fresh=(d.channels||[]).find(x=>String(x.id)===id);if(!fresh)throw Error('Channel no longer accessible');await openTwitchPlayer(fresh);}
else if(kind==='music'){const d=await api(`/api/music/overview?limit=2000&q=${encodeURIComponent(action.query||'')}`);const fresh=(d.tracks||[]).find(x=>String(x.id)===id);if(!fresh)throw Error('Track no longer accessible');await playMusicTrack(fresh);}
renderPlayback();
});return row;
}
async function resultTask(fn){if(resultActionBusy||busy||voicePhase!=='idle'||!toolsAllowed)return;resultActionBusy=true;try{await fn();}catch(e){append('assistant','Media: '+e.message);if(win.hidden)alert('Media: '+e.message);}finally{resultActionBusy=false;}}
async function showFullResults(search){
const {action,items}=search,kind=resultKind(action);
if(kind==='youtube'){const inp=await navigateMedia('youtube');inp.value=action.query||'';await searchYouTube(inp.value,items);$('youtubeSearchArea')?.scrollIntoView({block:'start'});}
else{
if(['music','iptv'].includes(kind))await navigateMedia(kind);else await navigateMediaV3(kind);
// Preserve the native library beneath the exact matched results.
const area=$('content');if(!area)throw Error('Media view unavailable');$('aiFullSearchResults')?.remove();
const section=document.createElement('section');section.id='aiFullSearchResults';section.className='balroc-full-results';const heading=document.createElement('h2');heading.textContent=`Search results · ${action.query||kind} (${items.length})`;section.append(heading);
for(const [i,item] of items.entries())section.append(resultRow(item,action,i));area.prepend(section);section.scrollIntoView({block:'start'});
}
if(pendingSearch===search)pendingSearch=null;
}
function inlineSearch(reply,action,items){
const valid=items.filter(x=>x&&String(x.id||x.video_id||''));
const search={action,items:valid};pendingSearch=search;
reply.textContent=valid.length?`${valid.length} matching result${valid.length===1?'':'s'}. Choose one to play.`:'No matching results.';
if(!valid.length){pendingSearch=null;return;}
reply.classList.add('balroc-result-message');const list=document.createElement('div');list.className='balroc-result-list';
valid.slice(0,5).forEach((item,i)=>list.append(resultRow(item,action,i)));reply.append(list);
const full=document.createElement('button');full.type='button';full.className='balroc-view-results';full.textContent=`Media · View all ${valid.length} results ›`;full.onclick=()=>void resultTask(()=>showFullResults(search));reply.append(full);log.scrollTop=reply.offsetTop-log.offsetTop;
}
// On mobile, tapping Media directly after a Find also opens its exact result list.
document.addEventListener('click',e=>{if(!pendingSearch||!document.body.classList.contains('kronic-mobile')||document.body.dataset.mobileTab!=='ai'||!e.target.closest('#mobileNav [data-tab="media"]'))return;if(busy||resultActionBusy||voicePhase!=='idle')return;e.preventDefault();e.stopImmediatePropagation();const search=pendingSearch;void resultTask(()=>showFullResults(search));},true);
let aiAllowed=false, toolsAllowed=false;
async function checkAccess(){
try{
const response=await fetch('/api/balroc/access',{credentials:'same-origin',cache:'no-store',headers:{'X-Kronic-Room':document.body.dataset.roomId}});
if(!response.ok)throw Error('Access denied');
const rights=await response.json();
aiAllowed=!!rights.can_chat;toolsAllowed=!!rights.can_use_tools;
}catch(e){aiAllowed=false;}
const launcher=$('balrocOpen');if(launcher){launcher.hidden=!aiAllowed;launcher.style.display=aiAllowed?'':'none';}
if(!aiAllowed)win.hidden=true;else void refreshAiPlayers();
}
void checkAccess();
function append(role,text){const e=document.createElement('div');e.className='balroc-message '+role;e.textContent=text;log.appendChild(e);log.scrollTop=log.scrollHeight;return e;}
function open(){if(!aiAllowed)return;win.hidden=false;renderPlayback();}
$('balrocOpen')?.addEventListener('click',open);
$('balrocClose')?.addEventListener('click',()=>{win.hidden=true;});
async function post(url,data){const response=await fetch(url,{method:'POST',headers:{'Content-Type':'application/json','X-Kronic-Room':document.body.dataset.roomId},credentials:'same-origin',body:JSON.stringify(data)});const json=await response.json().catch(()=>({}));if(!response.ok)throw Error(json.error||json.detail||`HTTP ${response.status}`);return json;}
async function submit(text,destination=destinationSelect.value,fromVoice=false){if(!aiAllowed||busy||resultActionBusy||(!fromVoice&&voicePhase!=='idle')||!String(text||'').trim())return;busy=true;send.disabled=true;input.value='';append('user',text);const reply=append('assistant','Working…');status.textContent='Thinking';renderPlayback();try{const data=await post('/api/balroc/chat',{message:text,window_id:windowId,destination:destination});if(data.session_id)session=data.session_id;reply.textContent=data.reply||data.error||'Balroc returned no reply'; if(data.reply){reply.textContent=reply.textContent.replace(/\s*\(device ID [a-z0-9_-]+\)/gi,'');if(reply.textContent!==data.reply){const detail=document.createElement('details');const summary=document.createElement('summary');summary.textContent='Execution details';detail.append(summary,document.createTextNode(data.reply));reply.append(detail);}}if(data.ui_action)try{if(destination==='kronic'&&searchTypes.has(data.ui_action.type)&&Array.isArray(data.results)){inlineSearch(reply,data.ui_action,data.results);}else{pendingSearch=null;await runUiAction(data.ui_action);}}catch(uiErr){reply.append(document.createTextNode('\nWindow action failed: '+uiErr.message));}status.textContent='Ready';}catch(e){reply.textContent=`Error: ${e.message}`;status.textContent='Error';}finally{busy=false;send.disabled=false;renderPlayback();void refreshAiPlayers();}}
$('balrocForm')?.addEventListener('submit',e=>{e.preventDefault();submit(input.value);});
input?.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();submit(input.value);}});
function bytes64(bytes){let out='';for(let i=0;i<bytes.length;i+=0x8000)out+=String.fromCharCode(...bytes.subarray(i,i+0x8000));return btoa(out);}
function stopTracks(){if(stream){stream.getTracks().forEach(t=>t.stop());stream=null;}}
// Hold-to-speak: one recording per physical hold, including delayed permission prompts.
let voicePhase='idle', held=false, discard=false, holdDestination='', holdStart=0, voiceTimer=null, activePointer=null;
const voiceBox=document.createElement('div');voiceBox.className='balroc-voice';
mic.textContent='🎙';mic.title='Hold to speak; release to send';mic.setAttribute('aria-label',mic.title);mic.setAttribute('aria-pressed','false');
const voiceLabel=document.createElement('span');voiceLabel.textContent='Hold to speak';voiceLabel.className='balroc-voice-label';voiceLabel.setAttribute('aria-live','polite');
voiceBox.append(mic,voiceLabel);win.insertBefore(voiceBox,aiForm);
if($('balrocHint'))$('balrocHint').textContent='Hold microphone to speak, release to send. Or type a command.';
function voiceReset(){clearTimeout(voiceTimer);stopTracks();recorder=null;held=false;activePointer=null;voicePhase='idle';mic.disabled=false;mic.setAttribute('aria-pressed','false');voiceLabel.textContent='Hold to speak';renderPlayback();}
async function startHold(){
if(busy||resultActionBusy||voicePhase!=='idle'||!aiAllowed)return;
if(!navigator.mediaDevices?.getUserMedia||!window.MediaRecorder){append('assistant','Microphone recording is not supported here. Use HTTPS or localhost.');return;}
held=true;discard=false;voicePhase='starting';holdDestination=destinationSelect.value;voiceLabel.textContent='Opening microphone…';status.textContent='Opening microphone';renderPlayback();
try{
stream=await navigator.mediaDevices.getUserMedia({audio:true});
if(!held||discard){voiceReset();status.textContent='Hold again to speak';return;}
chunks=[];const mime=['audio/webm;codecs=opus','audio/webm','audio/ogg;codecs=opus','audio/mp4'].find(t=>MediaRecorder.isTypeSupported(t));
const active=new MediaRecorder(stream,mime?{mimeType:mime}:{});recorder=active;
active.ondataavailable=e=>{if(e.data.size)chunks.push(e.data);};
active.onerror=()=>{discard=true;finishHold(true);};
active.onstop=async()=>{
clearTimeout(voiceTimer);stopTracks();mic.setAttribute('aria-pressed','false');
if(discard||performance.now()-holdStart<250||!chunks.length){voiceReset();status.textContent='Ready';return;}
voicePhase='transcribing';mic.disabled=true;voiceLabel.textContent='Transcribing…';status.textContent='Transcribing';
try{const blob=new Blob(chunks,{type:active.mimeType});const audio=new Uint8Array(await blob.arrayBuffer());
const result=await post('/api/balroc/transcribe',{audio_base64:bytes64(audio),mime_type:blob.type});
if(!discard&&String(result.text||'').trim())await submit(result.text,holdDestination,true);
}catch(e){append('assistant',`Whisper: ${e.message}`);status.textContent='Error';}finally{voiceReset();}
};
active.start();holdStart=performance.now();voicePhase='recording';mic.setAttribute('aria-pressed','true');voiceLabel.textContent='Recording — release to send';status.textContent='Recording';voiceTimer=setTimeout(()=>finishHold(false),60000);
}catch(e){voiceReset();status.textContent='Error';append('assistant',`Microphone: ${e.message}`);}
}
function finishHold(cancel=false){held=false;if(cancel)discard=true;if(voicePhase==='recording'&&recorder?.state==='recording'){voicePhase='stopping';recorder.stop();} }
// Track the original contact until release, even if capture is lost.
mic.addEventListener('pointerdown',e=>{
if(e.button!==0||!e.isPrimary)return;e.preventDefault();
if(voicePhase!=='idle'||busy||resultActionBusy||!aiAllowed)return;
activePointer=e.pointerId;
try{mic.setPointerCapture(e.pointerId);}catch(_){}
void startHold();
});
window.addEventListener('pointerup',e=>{if(e.pointerId!==activePointer)return;activePointer=null;finishHold();},true);
window.addEventListener('pointercancel',e=>{if(e.pointerId!==activePointer)return;activePointer=null;finishHold(true);},true);
// A capture change is not a physical release; window listeners remain active.
mic.addEventListener('contextmenu',e=>e.preventDefault());
mic.addEventListener('keydown',e=>{if(e.code==='Space'||e.code==='Enter'){e.preventDefault();if(!e.repeat)void startHold();}});
mic.addEventListener('keyup',e=>{if(e.code==='Space'||e.code==='Enter'){e.preventDefault();finishHold();}});
window.addEventListener('blur',()=>{if(held)finishHold(true);});
document.addEventListener('visibilitychange',()=>{if(document.hidden&&held)finishHold(true);});
new MutationObserver(()=>{if(win.hidden&&held)finishHold(true);}).observe(win,{attributes:true,attributeFilter:['hidden']});
// Live playback panel. Remote metadata is optional; never invent a title or position.
const playback=document.createElement('section');playback.className='balroc-playback';
playback.innerHTML='<div class="balroc-now"><img alt="" hidden><div><small>NOW PLAYING</small><strong></strong><span></span></div></div><progress max="1" value="0" hidden></progress><div class="balroc-time"></div><div class="balroc-transport"></div>';
win.insertBefore(playback,log);
const controls=[['previous','⏮','Previous'],['rewind','⏪','Back 10 seconds'],['toggle','▶','Play / pause'],['forward','⏩','Forward 10 seconds'],['next','⏭','Next'],['stop','■','Stop']];
const transport=playback.querySelector('.balroc-transport');
for(const [key,icon,label] of controls){const btn=document.createElement('button');btn.type='button';btn.dataset.action=key;btn.textContent=icon;btn.title=label;btn.setAttribute('aria-label',label);btn.onclick=()=>void transportAction(key);transport.append(btn);}
function localPlayback(){
const music=$('musicAudio'), video=typeof mediaPlayer!=='undefined'?mediaPlayer:null, tube=$('youtubeVideoElement'), twitch=$('twitchVideoElement');
const candidates=[{el:video,title:$('playerTitle')?.textContent,stop:()=>closePlayer(),kind:'video'},{el:tube,title:$('youtubePlayerTitle')?.textContent,stop:()=>closeYouTubePlayer(),kind:'tube'},{el:twitch,title:$('twitchPlayerTitle')?.textContent,stop:()=>closeTwitchPlayer(),kind:'twitch'},{el:music,title:$('musicPlayerTitle')?.textContent,artist:$('musicPlayerArtist')?.textContent,cover:$('musicPlayerCover')?.getAttribute('src'),stop:()=>$('musicClose')?.click(),kind:'music'}].filter(x=>x.el?.getAttribute('src'));
return candidates.find(x=>!x.el.paused&&!x.el.ended)||candidates[0];
}
function remotePlayback(){const c=aiClientList.find(x=>String(x.device_id)===destinationSelect.value);const item=c?.now_playing_item||c?.NowPlayingItem||c?.now_playing;const state=c?.play_state||c?.PlayState||{};return {c,title:typeof item==='string'?item:item?.Name||item?.name||item?.title,pos:Number(state.PositionTicks??state.position_ticks??c?.position_ticks)/1e7,duration:Number(item?.RunTimeTicks??item?.run_time_ticks??c?.duration_ticks)/1e7,paused:state.IsPaused??state.is_paused??c?.is_paused};}
function fmtTime(n){n=Math.max(0,Math.floor(n));return `${Math.floor(n/60)}:${String(n%60).padStart(2,'0')}`;}
function renderPlayback(){
const local=destinationSelect.value==='kronic', x=local?localPlayback():remotePlayback(), el=x?.el;
const name=local?'Kronic':x?.c?.device||'Selected player';
playback.querySelector('strong').textContent=x?.title||(local?'Nothing playing':'Playback status unavailable');
playback.querySelector('.balroc-now span').textContent=local?(x?.artist||name):name+(x?.title?(x.paused===true?' · Paused':x.paused===false?' · Playing':''):'');
const cover=playback.querySelector('img');if(local&&x?.cover){if(cover.getAttribute('src')!==x.cover)cover.src=x.cover;cover.hidden=false;}else{cover.hidden=true;cover.removeAttribute('src');}
const pos=el?.currentTime??x?.pos,dur=el?.duration??x?.duration,progress=playback.querySelector('progress');const valid=Number.isFinite(pos)&&Number.isFinite(dur)&&dur>0;progress.hidden=!valid;if(valid){progress.max=dur;progress.value=Math.min(pos,dur);}playback.querySelector('.balroc-time').textContent=valid?`${fmtTime(pos)} / ${fmtTime(dur)}`:'';
for(const btn of transport.children){const k=btn.dataset.action;btn.disabled=!toolsAllowed||busy||voicePhase!=='idle'||(local?(!el||(['previous','next'].includes(k)&&x.kind!=='music')||(['rewind','forward'].includes(k)&&(!Number.isFinite(el.duration)||(x.kind==='video'&&typeof playbackSeekMode!=='undefined'&&playbackSeekMode==='server')))):(!x?.c?.approved||!x?.c?.controllable));if(k==='toggle'){btn.textContent=(local?el&&!el.paused:x?.paused===false)?'❚❚':'▶';}}
}
async function transportAction(key){
if(!toolsAllowed||busy||voicePhase!=='idle')return;
if(destinationSelect.value!=='kronic'){const x=remotePlayback();if(!x.c?.approved||!x.c?.controllable)return;const command={previous:'Play previous item',rewind:'Seek backward 10 seconds',toggle:x.paused===true?'Resume playback':x.paused===false?'Pause playback':'Toggle play pause',forward:'Seek forward 10 seconds',next:'Play next item',stop:'Stop playback'}[key];await submit(command);return;}
const x=localPlayback(),el=x?.el;if(!el)return;
try{if(key==='toggle'){if(el.paused)await el.play();else el.pause();}else if(key==='stop')await x.stop();else if(key==='previous'||key==='next'){if(x.kind==='music')$(key==='previous'?'musicPrev':'musicNext')?.click();}else if(Number.isFinite(el.duration)&&!(x.kind==='video'&&typeof playbackSeekMode!=='undefined'&&playbackSeekMode==='server')){el.currentTime=Math.max(0,Math.min(el.duration,el.currentTime+(key==='rewind'?-10:10)));}}catch(e){append('assistant','Playback: '+e.message);}renderPlayback();
}
setInterval(()=>{if(!win.hidden)renderPlayback();},1000);
setInterval(()=>{if(!win.hidden&&aiAllowed&&destinationSelect.value!=='kronic'&&!busy&&voicePhase==='idle')void refreshAiPlayers();},15000);
renderPlayback();
let drag=null;
$('balrocHeader')?.addEventListener('pointerdown',e=>{if(e.target.closest('button'))return;const r=win.getBoundingClientRect();drag={x:e.clientX,y:e.clientY,left:r.left,top:r.top};$('balrocHeader').setPointerCapture(e.pointerId);});
$('balrocHeader')?.addEventListener('pointermove',e=>{if(!drag)return;win.style.left=Math.max(0,Math.min(window.innerWidth-120,drag.left+e.clientX-drag.x))+'px';win.style.top=Math.max(0,Math.min(window.innerHeight-80,drag.top+e.clientY-drag.y))+'px';win.style.right='auto';});
$('balrocHeader')?.addEventListener('pointerup',()=>{drag=null;});
})();