Upload files to "kronic-chat/js"

This commit is contained in:
2026-11-25 20:26:26 -06:00
parent 597639ee34
commit 9ad6c44a84
5 changed files with 2647 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+116
View File
@@ -0,0 +1,116 @@
/*
* RNNoise AudioWorklet Processor
* Handles frame chunking (480 samples / 10ms frame size required by RNNoise)
* and bridges PCM audio buffers with the WebAssembly RNNoise engine.
*/
class RNNoiseWorkletProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.FRAME_SIZE = 480; // 10ms at 48kHz
this.inputBuffer = new Float32Array(0);
this.outputBuffer = new Float32Array(0);
this.isWasmReady = false;
// Listen for WASM binary or module initialization from the main thread
this.port.onmessage = (event) => {
if (event.data.type === 'INIT_WASM') {
this.initWasm(event.data.wasmBytes);
}
};
}
initWasm(wasmBytes) {
// Instantiate WASM module directly inside the AudioWorklet scope
WebAssembly.instantiate(wasmBytes, {
env: {
memory: new WebAssembly.Memory({ initial: 256 }),
abort: () => console.error('RNNoise WASM Aborted')
}
}).then(result => {
this.wasmInstance = result.instance;
this.denoiseState = this.wasmInstance.exports.rnnoise_create(null);
this.wasmInputPtr = this.wasmInstance.exports.malloc(this.FRAME_SIZE * 4);
this.wasmOutputPtr = this.wasmInstance.exports.malloc(this.FRAME_SIZE * 4);
this.isWasmReady = true;
}).catch(err => {
console.error('Failed to initialize RNNoise WASM in AudioWorklet:', err);
});
}
process(inputs, outputs, parameters) {
const input = inputs[0];
const output = outputs[0];
if (!input || !input[0]) return true;
const inputChannel = input[0];
const outputChannel = output[0];
// Append incoming Web Audio rendering quantum (typically 128 samples) to buffer
this.inputBuffer = this.concatFloat32(this.inputBuffer, inputChannel);
// Process full 480-sample frames when available
while (this.inputBuffer.length >= this.FRAME_SIZE) {
const frame = this.inputBuffer.subarray(0, this.FRAME_SIZE);
this.inputBuffer = this.inputBuffer.subarray(this.FRAME_SIZE);
if (this.isWasmReady && this.denoiseState) {
// Copy frame to WASM heap
const heapF32 = new Float32Array(
this.wasmInstance.exports.memory.buffer,
this.wasmInputPtr,
this.FRAME_SIZE
);
heapF32.set(frame);
// Run RNNoise frame processing
this.wasmInstance.exports.rnnoise_process_frame(
this.denoiseState,
this.wasmOutputPtr,
this.wasmInputPtr
);
// Extract processed frame from WASM heap
const processedFrame = new Float32Array(
this.wasmInstance.exports.memory.buffer,
this.wasmOutputPtr,
this.FRAME_SIZE
);
this.outputBuffer = this.concatFloat32(this.outputBuffer, processedFrame);
} else {
// Pass-through fallback until WASM module is fully loaded
this.outputBuffer = this.concatFloat32(this.outputBuffer, frame);
}
}
// Deliver processed audio back to Web Audio graph (128 samples at a time)
if (this.outputBuffer.length >= outputChannel.length) {
outputChannel.set(this.outputBuffer.subarray(0, outputChannel.length));
this.outputBuffer = this.outputBuffer.subarray(outputChannel.length);
} else {
// Silence padding if buffer is temporarily underrun
outputChannel.fill(0);
}
return true;
}
concatFloat32(a, b) {
const c = new Float32Array(a.length + b.length);
c.set(a, 0);
c.set(b, a.length);
return c;
}
destroy() {
if (this.isWasmReady && this.wasmInstance) {
this.wasmInstance.exports.rnnoise_destroy(this.denoiseState);
this.wasmInstance.exports.free(this.wasmInputPtr);
this.wasmInstance.exports.free(this.wasmOutputPtr);
}
}
}
registerProcessor('rnnoise-worklet', RNNoiseWorkletProcessor);
+721
View File
@@ -0,0 +1,721 @@
// room-auth.js
window.Kronick =
window.Kronick || {};
Kronick.roomAuth = {
status:
null,
checkedRoomName:
'',
pendingResolve:
null,
pendingReject:
null,
statusTimer:
null
};
Kronick.normalizeRoomName =
function normalizeRoomName(value) {
return String(
value || ''
)
.trim()
.toLowerCase();
};
Kronick.getOwnerTokenStorageKey =
function getOwnerTokenStorageKey(
roomName
) {
return (
'kronickRoomOwner:'
+ Kronick.normalizeRoomName(
roomName
)
);
};
Kronick.getStoredRoomOwnerToken =
function getStoredRoomOwnerToken(
roomName
) {
return localStorage.getItem(
Kronick.getOwnerTokenStorageKey(
roomName
)
) || '';
};
Kronick.saveRoomOwnerToken =
function saveRoomOwnerToken(
roomName,
ownerToken
) {
if (
!roomName
|| !ownerToken
) {
return;
}
localStorage.setItem(
Kronick.getOwnerTokenStorageKey(
roomName
),
ownerToken
);
};
Kronick.removeRoomOwnerToken =
function removeRoomOwnerToken(
roomName
) {
localStorage.removeItem(
Kronick.getOwnerTokenStorageKey(
roomName
)
);
};
Kronick.formatCooldownTime =
function formatCooldownTime(seconds) {
const remaining =
Math.max(
0,
Number(seconds || 0)
);
const hours =
Math.floor(
remaining / 3600
);
const minutes =
Math.ceil(
(
remaining % 3600
) / 60
);
if (hours > 0) {
return (
`${hours}h ${minutes}m`
);
}
return `${minutes}m`;
};
Kronick.checkRoomStatus =
async function checkRoomStatus(
roomName
) {
const normalizedRoom =
Kronick.normalizeRoomName(
roomName
);
const statusElement =
document.getElementById(
'roomAvailabilityStatus'
);
if (
normalizedRoom.length < 3
) {
Kronick.roomAuth.status =
null;
Kronick.roomAuth
.checkedRoomName =
'';
if (statusElement) {
statusElement.textContent =
'Enter at least 3 characters.';
}
return null;
}
if (statusElement) {
statusElement.textContent =
'Checking room...';
}
try {
const response =
await fetch(
'/api/rooms/'
+ encodeURIComponent(
normalizedRoom
)
+ '/status',
{
cache:
'no-store'
}
);
const data =
await response.json();
if (!response.ok) {
throw new Error(
typeof data.detail
=== 'string'
? data.detail
: 'Could not check room.'
);
}
Kronick.roomAuth.status =
data;
Kronick.roomAuth
.checkedRoomName =
normalizedRoom;
if (statusElement) {
if (data.exists) {
statusElement.textContent =
'Room exists — enter its password.';
} else if (data.cooldown) {
statusElement.textContent =
'Room name unavailable for '
+ Kronick.formatCooldownTime(
data
.cooldownSecondsRemaining
)
+ '.';
} else {
statusElement.textContent =
'Room is available — you will create it.';
}
}
return data;
} catch (error) {
console.error(
'Room status check failed:',
error
);
Kronick.roomAuth.status =
null;
if (statusElement) {
statusElement.textContent =
'Could not check room status.';
}
return null;
}
};
Kronick.ensureCurrentRoomStatus =
async function ensureCurrentRoomStatus() {
const roomInput =
document.getElementById(
'roomName'
);
const roomName =
Kronick.normalizeRoomName(
roomInput?.value
);
if (!roomName) {
throw new Error(
'Enter a room name.'
);
}
if (
Kronick.roomAuth
.checkedRoomName
=== roomName
&& Kronick.roomAuth.status
) {
return Kronick.roomAuth.status;
}
const status =
await Kronick.checkRoomStatus(
roomName
);
if (!status) {
throw new Error(
'Room status could not be determined.'
);
}
return status;
};
Kronick.openRoomAuthModal =
async function openRoomAuthModal() {
const roomInput =
document.getElementById(
'roomName'
);
const roomName =
Kronick.normalizeRoomName(
roomInput?.value
);
const status =
await Kronick
.ensureCurrentRoomStatus();
if (status.cooldown) {
throw new Error(
'That room name is unavailable for '
+ Kronick.formatCooldownTime(
status
.cooldownSecondsRemaining
)
+ '.'
);
}
const modal =
document.getElementById(
'roomAuthModal'
);
const title =
document.getElementById(
'roomAuthTitle'
);
const message =
document.getElementById(
'roomAuthMessage'
);
const passwordInput =
document.getElementById(
'roomAuthPassword'
);
const confirmationInput =
document.getElementById(
'roomAuthPasswordConfirm'
);
const confirmationGroup =
document.getElementById(
'roomAuthConfirmGroup'
);
const submitButton =
document.getElementById(
'roomAuthSubmitBtn'
);
const error =
document.getElementById(
'roomAuthError'
);
if (
!modal
|| !title
|| !message
|| !passwordInput
|| !confirmationInput
|| !confirmationGroup
|| !submitButton
|| !error
) {
throw new Error(
'Room authentication modal is incomplete.'
);
}
passwordInput.value =
'';
confirmationInput.value =
'';
error.hidden =
true;
error.textContent =
'';
if (status.exists) {
title.textContent =
'Join Room';
message.textContent =
`Enter the password for "${roomName}".`;
confirmationGroup.hidden =
true;
submitButton.textContent =
'Join Room';
} else {
title.textContent =
'Create Room';
message.textContent =
`The room "${roomName}" does not exist. `
+ 'Choose its permanent entry password.';
confirmationGroup.hidden =
false;
submitButton.textContent =
'Create Room';
}
modal.hidden =
false;
requestAnimationFrame(
() => {
passwordInput.focus();
}
);
return new Promise(
(
resolve,
reject
) => {
Kronick.roomAuth
.pendingResolve =
resolve;
Kronick.roomAuth
.pendingReject =
reject;
}
);
};
Kronick.closeRoomAuthModal =
function closeRoomAuthModal() {
const modal =
document.getElementById(
'roomAuthModal'
);
if (modal) {
modal.hidden =
true;
}
if (
Kronick.roomAuth
.pendingReject
) {
Kronick.roomAuth
.pendingReject(
new Error(
'Room authentication cancelled.'
)
);
}
Kronick.roomAuth
.pendingResolve =
null;
Kronick.roomAuth
.pendingReject =
null;
};
Kronick.submitRoomAuthentication =
function submitRoomAuthentication() {
const status =
Kronick.roomAuth.status;
const modal =
document.getElementById(
'roomAuthModal'
);
const passwordInput =
document.getElementById(
'roomAuthPassword'
);
const confirmationInput =
document.getElementById(
'roomAuthPasswordConfirm'
);
const error =
document.getElementById(
'roomAuthError'
);
const password =
passwordInput?.value || '';
const confirmation =
confirmationInput?.value || '';
if (!password) {
error.textContent =
'Enter a room password.';
error.hidden =
false;
return;
}
if (
!status?.exists
&& password.length < 8
) {
error.textContent =
'New passwords must contain at least 8 characters.';
error.hidden =
false;
return;
}
if (
!status?.exists
&& password !== confirmation
) {
error.textContent =
'The passwords do not match.';
error.hidden =
false;
return;
}
const resolve =
Kronick.roomAuth
.pendingResolve;
Kronick.roomAuth
.pendingResolve =
null;
Kronick.roomAuth
.pendingReject =
null;
if (modal) {
modal.hidden =
true;
}
resolve?.({
password,
creating:
!status.exists
});
};
Kronick.updateDeleteRoomButton =
function updateDeleteRoomButton(
roomName,
isOwner
) {
const button =
document.getElementById(
'deleteRoomBtn'
);
if (!button) {
return;
}
const ownerToken =
Kronick
.getStoredRoomOwnerToken(
roomName
);
button.hidden =
!isOwner
|| !ownerToken;
};
Kronick.requestDeleteCurrentRoom =
async function requestDeleteCurrentRoom() {
const roomName =
Kronick.normalizeRoomName(
Kronick.state
.currentRoomName
);
const ownerToken =
Kronick
.getStoredRoomOwnerToken(
roomName
);
if (
!roomName
|| !ownerToken
) {
alert(
'Room-owner authorization is unavailable.'
);
return;
}
const confirmed =
window.confirm(
`Delete "${roomName}" permanently?\n\n`
+ 'Everyone will be disconnected and '
+ 'the room name will be locked for 24 hours.'
);
if (!confirmed) {
return;
}
const response =
await fetch(
'/api/rooms/'
+ encodeURIComponent(
roomName
),
{
method:
'DELETE',
headers: {
Authorization:
`Bearer ${ownerToken}`
}
}
);
const data =
await response.json();
if (!response.ok) {
const detail =
typeof data.detail
=== 'string'
? data.detail
: data.detail?.message
|| 'Room deletion failed.';
alert(detail);
return;
}
Kronick.removeRoomOwnerToken(
roomName
);
Kronick.disconnect();
await Kronick.checkRoomStatus(
roomName
);
alert(
'Room deleted. Its name is reserved for 24 hours.'
);
};
window.closeRoomAuthModal =
function closeRoomAuthModal() {
return Kronick
.closeRoomAuthModal();
};
window.submitRoomAuthentication =
function submitRoomAuthentication() {
return Kronick
.submitRoomAuthentication();
};
window.requestDeleteCurrentRoom =
function requestDeleteCurrentRoom() {
return Kronick
.requestDeleteCurrentRoom();
};
window.addEventListener(
'DOMContentLoaded',
() => {
const roomInput =
document.getElementById(
'roomName'
);
roomInput?.addEventListener(
'input',
() => {
clearTimeout(
Kronick.roomAuth
.statusTimer
);
Kronick.roomAuth
.statusTimer =
setTimeout(
() => {
Kronick.checkRoomStatus(
roomInput.value
);
},
450
);
}
);
document
.querySelectorAll(
'[data-room-auth-close]'
)
.forEach(element => {
element.addEventListener(
'click',
() => {
Kronick
.closeRoomAuthModal();
}
);
});
}
);
+80
View File
@@ -0,0 +1,80 @@
/* Kronic compact room layout. Retain every existing audio control and listener. */
(() => {
function init() {
const sidebar = document.getElementById('connectionPanel');
const header = document.querySelector('.topbar');
if (!sidebar || !header || document.getElementById('kronicVoiceTop')) return;
const connection = sidebar.querySelector('.panel-section:not(.audio-settings-section)');
const top = document.createElement('div');
top.id = 'kronicVoiceTop';
top.className = 'kronic-voice-top';
header.insertBefore(top, header.querySelector('.topbar-tools') || null);
if (connection) top.append(connection);
// Three independent popups use the original details elements, not clones.
const names = ['voice', 'noise', 'spatial'];
const groups = [...sidebar.querySelectorAll('.audio-setting-group.audio-collapsible')];
const popups = {};
for (let i = 0; i < names.length; i++) {
const panel = document.createElement('section');
panel.className = 'kronic-audio-popup';
panel.dataset.audioPopup = names[i];
panel.hidden = true;
panel.setAttribute('role', 'dialog');
panel.setAttribute('aria-label', names[i] + ' audio settings');
const close = document.createElement('button');
close.className = 'kronic-audio-close';
close.type = 'button';
close.textContent = '×';
close.setAttribute('aria-label', 'Close audio settings');
close.addEventListener('click', () => hideAll());
panel.append(close);
if (groups[i]) {
groups[i].open = true;
panel.append(groups[i]);
}
// Noise suppression has Apply and restart-hint elements in the same source section.
if (names[i] === 'noise') {
const section = sidebar.querySelector('.audio-settings-section');
// Keep external controls that are siblings of the noise group near their original section.
// Existing handlers remain attached to the original DOM nodes.
}
document.body.append(panel);
popups[names[i]] = panel;
}
sidebar.classList.add('kronic-parked-sidebar');
document.body.append(sidebar);
function hideAll() {
Object.values(popups).forEach(panel => panel.hidden = true);
window.parent?.postMessage({type:'KRONIC_ROOM_UI_PANEL', action:'closed'}, location.origin);
}
window.addEventListener('message', event => {
if (event.origin !== location.origin || event.source !== window.parent) return;
const message = event.data;
if (message?.type !== 'KRONIC_ROOM_UI') return;
if (message.action === 'close-audio') hideAll();
else if (typeof message.action === 'string' && message.action.startsWith('open-audio-')) {
const target = message.action.slice('open-audio-'.length);
Object.entries(popups).forEach(([name,panel]) => panel.hidden = name !== target);
if (popups[target]) popups[target].scrollTop = 0;
} else if (message.action === 'mute') {
document.getElementById('muteBtn')?.click();
} else if (message.action === 'leave') {
document.getElementById('leaveBtn')?.click();
}
});
document.addEventListener('keydown', event => { if (event.key === 'Escape') hideAll(); });
const state = document.getElementById('statusBar');
const publish = () => {
if (window.parent !== window) window.parent.postMessage({
type:'KRONIC_ROOM_UI_STATUS',label:state?.textContent?.trim() || 'Not connected'
},location.origin);
};
if (state) new MutationObserver(publish).observe(state, {childList:true,subtree:true,characterData:true});
publish();
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init, {once:true});
else init();
})();
+55
View File
@@ -0,0 +1,55 @@
/* Kronic room playback bridge: LiveKit is the ONLY transport between peers.
* Parent and embedded Chat share the same origin through /borg-chat/app.
* No URLs, passwords, or media bytes are sent to other participants.
*/
(() => {
'use strict';
const PREFIX = 'KRONIC_ROOM_SYNC';
const TOPIC = 'kronic-room-playback-v1';
const VALID_KINDS = new Set(['library', 'youtube', 'twitch', 'music', 'iptv']);
const VALID_ACTIONS = new Set(['open', 'play', 'pause', 'seek']);
let sequence = 0;
const parentIsSameOrigin = () => window.parent !== window && (() => {
try { return window.parent.location.origin === location.origin; }
catch { return false; }
})();
function valid(message) {
if (!message || message.v !== 1 || !VALID_KINDS.has(message.kind) || !VALID_ACTIONS.has(message.action)) return false;
if (message.kind === 'library' || message.kind === 'music') {
if (!Number.isSafeInteger(Number(message.id)) || Number(message.id) <= 0) return false;
} else if (typeof message.id !== 'string' || message.id.length < 1 || message.id.length > 100 || !/^[\w-]+$/.test(message.id)) return false;
if (message.title !== undefined && (typeof message.title !== 'string' || message.title.length > 240)) return false;
if (message.position !== undefined && (!Number.isFinite(message.position) || message.position < 0 || message.position > 864000)) return false;
return true;
}
function toParent(payload) {
if (parentIsSameOrigin()) window.parent.postMessage({type: PREFIX + '_INCOMING', payload}, location.origin);
}
// Do not use the legacy "media" URL player: these messages target Media's native players.
window.Kronick = window.Kronick || {};
Kronick.handleNativeRoomPlayback = function (payload, participant) {
if (!participant || !valid(payload)) return;
toParent(payload);
};
window.addEventListener('message', (event) => {
if (!parentIsSameOrigin() || event.origin !== location.origin || event.source !== window.parent) return;
const message = event.data;
if (message?.type !== PREFIX + '_OUTGOING' || !valid(message.payload)) return;
const room = Kronick.state?.room;
if (!room?.localParticipant || room.state !== 'connected') {
window.parent.postMessage({type: PREFIX + '_STATUS', connected: false}, location.origin);
return;
}
const payload = {...message.payload, v: 1, seq: ++sequence};
room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(payload)), {
reliable: true, topic: TOPIC,
}).catch(error => console.warn('[Kronic room sync] LiveKit publish failed:', error));
});
Kronick.roomPlaybackTopic = TOPIC;
})();