import { t, setLanguage, onLanguageChange } from './i18n.js'; // TeamsPeach renderer entry: server connections, core lifecycle, onboarding, connection, self controls and // view routing. // // Several servers can be connected at once (official server connection tabs): one core per connection in // main, one record per connection here (state.js). The viewed connection is what the workspace shows; the // microphone belongs to the input connection (state.inputConnection()), which is chosen explicitly and is // independent of the view. Every core event names its connection; events of closed connections are dropped. import { $, h, icon, setIcon, setText } from './dom.js'; import { S, on, emit, newConnection, viewedConnection, connectionById, connectionList, inputConnection, isAlive, isConnected, ownClient, ownChannel, selectedChannel, } from './state.js'; import { tp, callOn, profileCall, log } from './core.js'; import { errorText, shortUid, stripBBCode } from './text.js'; import { toast } from './toast.js'; import { initTree, renderTree, updateTalking, joinChannel } from './tree.js'; import * as chat from './chat.js'; import * as watch from './watch.js'; import * as voice from './voice.js'; import * as settings from './settings.js'; import { serverBannerUrl, clearMedia, pruneMedia } from './media.js'; import * as servers from './servers.js'; import { initDeviceMenus } from './device-menu.js'; import { initUpdates } from './updates-ui.js'; import { initSidebarLayout } from './sidebar-layout.js'; import { initClientMenu, openClientMenu, syncClientMenu } from './client-menu.js'; import * as broadcast from './broadcast.js'; import * as recording from './recording.js'; import * as notifications from './notifications.js'; import * as osSettings from './os-settings.js'; import { initFiles, renderFiles } from './files.js'; import * as userStyles from './user-styles.js'; import { initConnectionsUi, renderConnections as renderConnectionRows, connectionLabel } from './connections-ui.js'; import { initAdmin, renderChannelInfo } from './admin.js'; import { initWhisper, setWhisperSelection, whisperHistoryButton } from './whisper.js'; import { initKeybinds } from './keybinds.js'; import { focusIdentity } from './identities.js'; import { initSelectControls } from './select-controls.js'; import * as contacts from './contacts.js'; import { syncServerIcons } from './server-icons.js'; let hostBannerKey = null; let adminView = null; function renderConnections() { renderConnectionRows(); contacts.renderContacts(); syncServerIcons(); } /** Server-provided artwork decorates the server card, never a separate tree row. */ function renderHostBanner() { const img = $('#host-banner'); const conn = viewedConnection(); const server = conn?.snap?.server; const key = server?.hostbanner_gfx_url ? `${conn.id}|${server.hostbanner_gfx_url}` : null; if (key === hostBannerKey) return; hostBannerKey = key; img.hidden = true; img.removeAttribute('src'); img.onerror = () => { img.hidden = true; }; if (!key) return; serverBannerUrl(server, conn).then((url) => { if (!url || hostBannerKey !== key) return; img.src = url; img.hidden = false; }); } const VIEWS = ['#boot', '#view-fatal', '#view-onboarding', '#view-app']; let appShown = false; let profileLoading = null; let lastAsyncError = { code: '', at: 0 }; // Official defaultClientSelfProperties: "mute on all servers" also applies to connections opened later. const audioDefaults = { input_muted: false, output_muted: false }; // Connections that had the microphone, most recent last (official restoreMicToPreviousTarget). let inputHistory = []; function showView(id) { for (const v of VIEWS) $(v).hidden = v !== id; } // ---------- prefs ---------- async function savePrefs(partial) { const r = await tp.setPrefs(partial); if (r && r.ok) S.prefs = r.prefs; else toast(() => t('message.setting.not.saved.p0', { p0: r?.message ?? t('ui.error') }), 'error'); if (!Object.hasOwn(partial, 'language')) { renderSessionHead(); servers.renderServers(); } return S.prefs; } // ---------- server connections ---------- /** Main's list of connections (creation order) is authoritative: records are added and closed from it. */ function onConnectionsChanged({ connections: list }) { const ids = new Set(list.map((c) => c.id)); for (const conn of connectionList()) if (!ids.has(conn.id)) closeRecord(conn); for (const info of list) { if (S.connections.has(info.id)) continue; const conn = newConnection(info.id); conn.core = info.core; conn.conn = { state: info.state, address: info.address, reason: null }; conn.identityId = info.identityId ?? null; // The first connection gets the microphone; later ones only when none has it (explicit moves otherwise). conn.inputEnabled = !connectionList().some((c) => c.inputEnabled); S.connections.set(info.id, conn); if (conn.inputEnabled) inputHistory.push(conn.id); } if (!viewedConnection() && S.connections.size) setViewed(connectionList()[0].id); else renderConnections(); } function closeRecord(conn) { const wasViewed = conn.id === S.viewId; const hadMic = conn.inputEnabled; const order = connectionList(); const index = order.indexOf(conn); conn.closed = true; conn.session += 1; S.connections.delete(conn.id); inputHistory = inputHistory.filter((id) => id !== conn.id); watch.onConnectionClosed(conn); broadcast.onConnectionClosed(conn); chat.onConnectionClosed(conn); clearMedia(conn); voice.removeConnection(conn); emit('connection-closed', conn, conn); if (hadMic) restoreMicrophone(); if (wasViewed) { const rest = connectionList(); const next = rest[Math.min(index, rest.length - 1)]; S.viewId = null; if (next) setViewed(next.id); } syncInput(); renderConnections(); } /** Shows another server connection. The microphone stays where it is unless the user enabled moving it. */ function setViewed(id) { const conn = connectionById(id); if (!conn || S.viewId === id) { renderConnections(); return; } S.viewId = id; syncClientMenu(); hostBannerKey = null; emit('view', conn, conn); // Official workflowSettings.autoEnableMicrophone: focusing a server activates its capture device. if (S.prefs?.autoEnableMicrophone && isConnected(conn)) setInputConnection(conn); watch.onViewChanged(); broadcast.onViewChanged(); chat.onViewChanged(); renderServerViews(); renderHostBanner(); renderAll(); if (S.view === 'channel-info') void renderChannelInfo(); if (appShown && S.view === 'main' && !isConnected(conn)) $('#connect-address').value = conn.conn.address || ''; } /** Moves the microphone (official inputHardware / ActivateCaptureDevice): exactly one connection owns it. */ function setInputConnection(target) { if (!isAlive(target) || target.inputEnabled) return; for (const conn of connectionList()) conn.inputEnabled = conn === target; inputHistory = inputHistory.filter((id) => id !== target.id); inputHistory.push(target.id); syncInput(); } /** * The microphone's connection ended (closed, or the server session ended). Official * autoReactivateMicOnPreviousTarget (default on) returns it to the most recent previous holder that is * still connected. */ function restoreMicrophone() { if (!S.prefs?.autoReactivateMicOnPreviousTarget) return; for (let i = inputHistory.length - 1; i >= 0; i -= 1) { const conn = connectionById(inputHistory[i]); if (conn && !conn.inputEnabled && isConnected(conn)) { setInputConnection(conn); return; } } } /** Routes captured audio to the current input connection and starts/stops capture accordingly. */ function syncInput() { void voice.syncInputRoute(); void voice.syncCapture(); emit('input', inputConnection()); renderConnections(); renderSelf(); renderSessionHead(); } async function newConnectionTab() { const r = await tp.createConnection(); if (!r?.ok) { toast(() => (r?.error?.code === 'too_many_connections' ? t('ui.connections.tooMany', { p0: 8 }) : errorText(r?.error)), 'error'); return null; } // Main announced the connection (connections:changed) before answering. const conn = connectionById(r.connection.id); if (conn) setViewed(conn.id); return conn; } async function closeConnectionTab(id) { const conn = connectionById(id); if (!conn) return; const r = await tp.closeConnection(id); if (!r?.ok && r?.error?.code !== 'connection_closed') toast(() => errorText(r?.error), 'error'); } /** Resolves when the connection's core is ready; false if it failed or the connection closed. */ function whenCoreReady(conn, timeoutMs = 20000) { if (conn.core.status === 'ready') return Promise.resolve(true); return new Promise((resolve) => { const done = (value) => { clearTimeout(timer); offStatus(); offClosed(); resolve(value); }; const timer = setTimeout(() => done(false), timeoutMs); const offStatus = on('core-status', (status, c) => { if (c !== conn) return; if (status.status === 'ready') done(true); else if (status.status !== 'starting') done(false); }); const offClosed = on('connection-closed', (c) => { if (c === conn) done(false); }); }); } // ---------- core lifecycle ---------- function onCoreStatus(status) { const conn = connectionById(status.connectionId); if (!conn) return; conn.core = status; emit('core-status', status, conn); switch (status.status) { case 'starting': if (!appShown && !connectionList().some((c) => c.core.status === 'ready')) { setText($('#boot-text'), () => t('ui.starting.core')); showView('#boot'); } break; case 'ready': // A (re)started core transmits directly until told otherwise: apply the chosen mode first; nothing is // forwarded to it before it acknowledges (voice.shouldForward). voice.forgetCoreTransmitMode(conn); void voice.applyVoicePreferences(); applyAudioDefaults(conn); if (!S.profile) loadProfile(); break; case 'missing': showFatal(t('ui.teamspeach.core.not.found'), t('ui.the.core.executable.is.missing.build.it'), status.candidates ?? []); break; case 'stopped': voice.forgetCoreTransmitMode(conn); resetConnection(conn, null); if (!appShown) { setText($('#boot-text'), () => t('ui.restarting.core')); showView('#boot'); } break; default: voice.forgetCoreTransmitMode(conn); resetConnection(conn, null); // Before the app is usable a core failure is fatal; afterwards it affects only that server tab. if (!appShown) showFatal(t('ui.the.core.stopped'), coreStatusText(status), []); else toast(() => `${connectionLabel(conn)}: ${coreStatusText(status)}`, 'error'); } renderConnections(); if (conn.id === S.viewId) renderConnection(); } function coreStatusText(status) { if (status.reason === 'ready_timeout') return t('core.status.readyTimeout'); if (status.reason === 'protocol') return t('core.status.protocol', { protocol: status.protocol }); if (status.reason === 'spawn') return `${t('ui.the.core.stopped')}: ${status.message}`; const code = status.code ?? 'unknown'; return [0, 1, 2, 3].includes(code) ? t(`core.exit.${code}`) : t('core.exit.other', { code }); } function showFatal(title, text, list, { allowImport = false } = {}) { setText($('#fatal-title'), () => title); setText($('#fatal-text'), () => text); $('#fatal-list').replaceChildren(...list.map((item) => h('li', { text: item }))); $('#fatal-import').hidden = !allowImport; $('#fatal-retry').hidden = connectionList().some((c) => c.core.status === 'missing'); showView('#view-fatal'); } /** The profile is shared by all connections; main asks the oldest ready core (profile:request). */ function loadProfile() { profileLoading ??= (async () => { try { S.profile = await profileCall('profile_get'); } catch (err) { if (err.code === 'identity_corrupt' || err.code === 'profile_corrupt') { showFatal(t('ui.profile.corrupted'), t('message.p0.teamspeach.never.replaces.a.corrupted', { p0: errorText(err) }), [], { allowImport: true }); } else { showFatal(t('ui.could.not.read.profile'), errorText(err), []); } return; } finally { profileLoading = null; } if (!S.profile.exists || !S.profile.nickname) showOnboarding(); else showApp(); })(); return profileLoading; } // ---------- onboarding ---------- let onboardingThemeSave = null; let onboardingBusy = false; function syncOnboardingControls() { const busy = onboardingBusy || onboardingThemeSave !== null; $('#onboarding-submit').disabled = busy; $('#onboarding-import').disabled = busy; $('#onboarding-theme').disabled = busy; for (const radio of document.querySelectorAll('input[name="onboarding-theme"]')) radio.checked = radio.value === S.prefs.theme; } function changeOnboardingTheme(theme) { if (appShown || onboardingBusy || onboardingThemeSave || theme === S.prefs.theme) return; const pending = (async () => { try { const result = await tp.setPrefs({ theme }); if (!result?.ok) throw new Error(result?.message || t('ui.error')); S.prefs = result.prefs; setText($('#onboarding-error'), () => ''); return true; } catch (error) { setText($('#onboarding-error'), () => t('message.setting.not.saved.p0', { p0: error.message })); return false; } })(); onboardingThemeSave = pending; $('#onboarding-submit').disabled = true; $('#onboarding-import').disabled = true; $('#onboarding-theme').disabled = true; void pending.finally(() => { onboardingThemeSave = null; syncOnboardingControls(); }); } function showOnboarding() { const existing = $('#onboarding-existing'); existing.hidden = !S.profile.exists; setText(existing, () => S.profile.exists ? t('message.an.identity.already.exists.uid.p0', { p0: S.profile.uid }) : ''); syncOnboardingControls(); showView('#view-onboarding'); $('#onboarding-nick').focus(); } async function submitOnboarding(e) { e.preventDefault(); if (appShown || onboardingBusy) return; if (onboardingThemeSave && !(await onboardingThemeSave)) return; if (appShown || onboardingBusy) return; const input = $('#onboarding-nick'); const error = $('#onboarding-error'); const nickname = input.value.trim(); const len = [...nickname].length; if (len < 3 || len > 30) { input.setAttribute('aria-invalid', 'true'); setText(error, () => t('ui.nickname.must.contain.3.30.characters')); input.focus(); return; } input.removeAttribute('aria-invalid'); setText(error, () => ''); const submit = $('#onboarding-submit'); onboardingBusy = true; syncOnboardingControls(); setText(submit, () => t('ui.creating.identity')); try { S.profile = await profileCall(S.profile.exists ? 'rename' : 'profile_create', { nickname }); showApp(); toast(() => t('message.profile.created.your.uid.p0', { p0: S.profile.uid })); } catch (err) { setText(error, () => errorText(err)); } finally { onboardingBusy = false; syncOnboardingControls(); setText(submit, () => t('ui.continue')); } } // ---------- main shell ---------- function showApp() { appShown = true; showView('#view-app'); voice.startAudio(); renderAll(); if (S.view === 'main' && !isConnected()) $('#connect-address').focus(); } function renderAll() { renderConnections(); renderConnection(); renderTree(); renderSelf(); renderSessionHead(); settings.renderProfile(); renderServerViews(); } /** Server-scoped secondary views follow the viewed connection. */ function renderServerViews() { recording.renderRecording(); renderFiles(); notifications.renderEventLog(); } // Official views: main (server), settings, and the server-scoped recording, file browser and server log pages. // Other modules switch through emit('set-view', name). const SERVER_VIEWS = ['recording', 'files', 'server-log', 'channel-info']; function setView(name) { if (name === S.view || !['main', 'settings', ...SERVER_VIEWS].includes(name)) return; if (S.view === 'settings') void settings.close(); S.view = name; if (name === 'settings') settings.open(); renderConnection(); renderServerViews(); renderSessionHead(); } function renderConnection() { const conn = viewedConnection(); const state = S.conn.state; const coreDown = conn && conn.core.status !== 'ready' && conn.core.status !== 'starting'; const badge = $('#conn-badge'); badge.dataset.state = coreDown ? 'failed' : state; const labels = { connecting: 'ui.connecting', connected: 'ui.connected', disconnecting: 'ui.disconnecting', disconnected: 'ui.not.connected2' }; setText(badge, () => coreDown ? t('ui.connections.coreStopped') : labels[state] ? t(labels[state]) : state); setText($('#server-name'), () => isConnected() ? S.snap.server.name || S.conn.address : S.conn.address && state !== 'disconnected' ? S.conn.address : t('ui.not.connected')); $('#btn-disconnect').hidden = state === 'disconnected'; const inSettings = S.view === 'settings'; // A server-scoped page replaces the session view only while the viewed server is connected. const serverPage = SERVER_VIEWS.includes(S.view) && isConnected() ? S.view : null; $('#settings-view').hidden = !inSettings; const nav = $('#settings-nav'); if (nav) nav.hidden = !inSettings; $('#room-side').hidden = inSettings; $('#connect-view').hidden = inSettings || Boolean(serverPage) || isConnected(); $('#session-view').hidden = inSettings || Boolean(serverPage) || !isConnected(); document.querySelector('.workspace').dataset.view = S.view; for (const [view, id] of [['recording', '#recording-view'], ['files', '#files-view'], ['server-log', '#server-log-view'], ['channel-info', '#channel-info-view']]) { const element = $(id); if (element) element.hidden = serverPage !== view; } const detailVisible = isConnected() && ['main', 'files', 'channel-info'].includes(S.view); $('#detail-header').hidden = !detailVisible; $('#detail-separator').hidden = !detailVisible; for (const [id, mode] of [['#btn-info', 'channel-info'], ['#btn-channel-chat', 'main'], ['#btn-channel-files', 'files']]) $(id).setAttribute('aria-pressed', String(S.view === mode)); servers.renderServers(); const busy = state === 'connecting' || state === 'disconnecting'; $('#connect-submit').disabled = busy; $('#connect-identity-choice').disabled = busy; $('#connect-improve-identity').hidden = !conn?.requiredSecurity; setText($('#connect-status'), () => state === 'connecting' ? t('ui.connecting2') : ''); const identity = servers.connectIdentity(); setText($('#connect-identity'), () => identity ? t('message.you.will.join.as.p0.uid', { p0: identity.nickname || identity.name || '', p1: shortUid(identity.uid) }) : ''); setText($('#connect-error'), () => (coreDown ? coreStatusText(conn.core) : conn?.conn.reason ? errorText(conn.conn.reason) : '')); if (!$('#connect-address').value && S.prefs.lastAddress && connectionList().length === 1) $('#connect-address').value = S.prefs.lastAddress; } function renderSelf() { const p = ownClient() ? { uid: ownClient().uid, nickname: ownClient().nickname } : S.profile; if (!p) return; setText($('#self-nick'), () => p.nickname ?? ''); const ch = ownChannel(); setText($('#self-sub'), () => isConnected() && ch ? ch.name : `UID ${shortUid(p.uid)}`); $('#self-sub').title = `UID ${p.uid}`; // Talking indicator and mute toggles describe the server on screen; the tooltip names the official modifiers. $('#self-dot').dataset.talking = String(Boolean(S.audio.transmitting)); const quick = t('ui.connections.quickTooltip', { alt: navigator.platform.startsWith('Mac') ? 'Option' : 'ALT' }); const mute = $('#btn-mute'); mute.setAttribute('aria-pressed', String(S.audio.input_muted)); setIcon(mute.firstElementChild, S.audio.input_muted ? 'mic-off' : 'mic'); mute.title = `${S.audio.input_muted ? t('ui.unmute.microphone') : t('ui.mute.microphone')}\n${quick}`; mute.setAttribute('aria-label', S.audio.input_muted ? t('ui.microphone.muted') : t('ui.microphone.unmuted')); const deafen = $('#btn-deafen'); deafen.setAttribute('aria-pressed', String(S.audio.output_muted)); setIcon(deafen.firstElementChild, S.audio.output_muted ? 'speaker-off' : 'speaker'); deafen.title = `${S.audio.output_muted ? t('ui.unmute.audio') : t('ui.mute.audio.and.microphone')}\n${quick}`; deafen.setAttribute('aria-label', S.audio.output_muted ? t('ui.audio.muted') : t('ui.audio.unmuted')); } function renderSessionHead() { if (!S.prefs) return; const ch = selectedChannel(); const own = ownChannel(); const conversation = S.view === 'main' ? chat.selectedConversation() : null; const channelView = !conversation || conversation.kind === 'channel'; const browsing = Boolean(channelView && ch && own && ch.id !== own.id); setText($('#channel-title'), () => channelView ? ch?.name ?? '' : conversation.title); setText($('#channel-topic'), () => channelView && ch ? stripBBCode(ch.topic) : ''); setIcon(document.querySelector('.session-icon .icon'), channelView ? 'channel' : conversation.kind === 'client' ? 'avatar' : 'server'); $('#channel-browse').hidden = true; $('#btn-join-channel').hidden = !browsing; $('#btn-info').hidden = !channelView || !isConnected(); $('#btn-channel-files').hidden = !channelView || !isConnected(); const admin = S.view === 'channel-info' && adminView?.connectionId === S.viewId && adminView.kind ? adminView : null; document.querySelector('.session-icon').hidden = admin?.kind === 'client'; if (admin) { setText($('#channel-title'), admin.title); setText($('#channel-topic'), ''); setIcon(document.querySelector('.session-icon .icon'), admin.kind === 'server' ? 'server' : admin.kind === 'client' ? 'avatar' : 'channel'); $('#btn-join-channel').hidden = true; $('#btn-info').hidden = admin.kind !== 'channel'; $('#btn-channel-files').hidden = admin.kind !== 'channel'; } document.querySelector('.workspace').dataset.detailKind = admin?.kind ?? (conversation?.kind === 'client' ? 'client' : 'channel'); $('#admin-mode-info').hidden = !admin?.modes; $('#admin-mode-events').hidden = !admin?.modes?.includes('events'); $('#admin-mode-info').dataset.adminAction = admin?.kind === 'server' ? 'server.info' : 'client.info'; $('#admin-mode-info').setAttribute('aria-pressed', String(Boolean(admin))); delete $('#admin-mode-info').dataset.clientId; if (admin?.kind === 'client') $('#admin-mode-info').dataset.clientId = String(admin.id); $('#btn-channel-chat').hidden = Boolean(admin?.modes ? !admin.modes.includes('chat') : browsing); const privateInfo = document.getElementById('chat-client-info'); if (privateInfo) privateInfo.hidden = Boolean(admin) || conversation?.kind !== 'client'; for (const [id, action] of [['admin-view-back', admin?.backAction], ['admin-view-edit', admin?.editAction]]) { const button = document.getElementById(id); button.hidden = !action; if (action) button.dataset.adminAction = action; else delete button.dataset.adminAction; delete button.dataset.channelId; delete button.dataset.clientId; if (admin?.kind === 'channel') button.dataset.channelId = String(admin.id); if (admin?.kind === 'client') button.dataset.clientId = String(admin.id); } const ptt = S.prefs.pttEnabled; $('#btn-ptt').hidden = !ptt; const notice = $('#session-notice'); const codec = voice.channelCodecProblem(); const mic = inputConnection(); const viewed = viewedConnection(); let text = ''; if (codec) text = t('message.this.channel.uses.a.legacy.codec', { p0: codec }); else if (isConnected() && mic && mic !== viewed) text = t('ui.connections.micElsewhere', { p0: connectionLabel(mic) }); notice.hidden = !text; setText(notice, () => text); } // ---------- connection ---------- function submitConnect(e) { e.preventDefault(); const conn = viewedConnection(); if (conn) connectTo($('#connect-address').value.trim(), { password: $('#connect-password').value, identity_id: $('#connect-identity-choice').value, conn }); } function isPasswordError(err) { const ts = err.ts_error; return Boolean(ts && (ts.id === 1028 || /password/i.test(`${ts.name ?? ''} ${ts.message ?? ''}`))); } function sameAddress(a, b) { return a.trim().toLowerCase() === b.trim().toLowerCase(); } /** * Connects `conn` (default: a server tab chosen for `address`) to `address`. Opening a saved server never * disconnects another one: an existing connection to the same address is shown, an idle viewed tab is used, * otherwise a new server tab is opened (official: connections live side by side). */ async function connectTo(address, { password = '', identity_id = '', conn = null } = {}) { const error = $('#connect-error'); setText(error, () => ''); if (!address) { setText(error, () => t('ui.enter.a.server.address')); $('#connect-address').focus(); return; } if (!conn) { const identityId = identity_id || S.profile?.uid; const existing = connectionList().find((c) => c.conn.state !== 'disconnected' && sameAddress(c.conn.address || '', address) && c.identityId === identityId); if (existing) { setViewed(existing.id); return; } const viewed = viewedConnection(); conn = viewed && viewed.conn.state === 'disconnected' ? viewed : await newConnectionTab(); if (!conn) return; } if (conn.conn.state !== 'disconnected') return; if (conn.id === S.viewId) { $('#connect-address').value = address; servers.selectConnectIdentity(identity_id); } if (!(await whenCoreReady(conn))) { if (isAlive(conn) && conn.id === S.viewId) setText(error, () => coreStatusText(conn.core)); return; } const args = { address }; if (password) args.server_password = password; if (identity_id) args.identity_id = identity_id; const attempt = conn.connectAttempt = (conn.connectAttempt || 0) + 1; conn.requiredSecurity = null; conn.identityId = identity_id || S.profile?.uid || null; conn.conn = { state: 'connecting', address, reason: null }; renderConnections(); if (conn.id === S.viewId) { renderConnection(); renderTree(); } try { await callOn(conn.id, 'connect', args); await savePrefs({ lastAddress: address }); if (conn.id === S.viewId) $('#connect-password').value = ''; } catch (err) { if (err.code === 'already_connected' || !isAlive(conn) || conn.connectAttempt !== attempt) return; if (conn.conn.state === 'connecting') conn.conn = { state: 'disconnected', address, reason: err }; else conn.conn.reason = err; const required = err.detail?.required_security_level; if (Number.isInteger(required) && required > 0) conn.requiredSecurity = { uid: conn.identityId, target: required }; renderConnections(); if (conn.id !== S.viewId) { toast(() => `${address}: ${errorText(err)}`, 'error'); return; } renderConnection(); setText(error, () => isPasswordError(err) ? t('message.p0.enter.the.server.password.and', { p0: errorText(err) }) : errorText(err)); renderTree(); if (isPasswordError(err)) $('#connect-password').focus(); } } async function disconnect(conn = viewedConnection()) { if (!conn) return; try { await callOn(conn.id, 'disconnect', {}); } catch (err) { if (err.code !== 'not_connected' && err.code !== 'connection_closed') toast(() => t('message.disconnect.p0', { p0: errorText(err) }), 'error'); } } /** The connection's server session ended (or its core stopped): every per-session piece is released. */ function resetConnection(conn, reason, reconnecting = false) { const wasConnected = conn.snap !== null; const hadMic = inputConnection() === conn; conn.session += 1; conn.conn = { state: 'disconnected', address: conn.conn.address, reason }; conn.snap = null; conn.talking.clear(); conn.audio = { ...conn.audio, transmitting: false }; conn.welcomeShown = false; conn.lastOwnChannel = null; conn.selectedChannelId = null; watch.onDisconnected(conn); broadcast.onDisconnected(conn); clearMedia(conn); if (conn.id === S.viewId) { syncClientMenu(); hostBannerKey = null; $('#host-banner').hidden = true; $('#host-banner').removeAttribute('src'); } if (hadMic) { voice.setPtt(false, 'reset'); restoreMicrophone(); } syncInput(); if (wasConnected && !reconnecting) { chat.addSystem(conn, 'channel', () => reason ? t('message.disconnected.p0', { p0: errorText(reason) }) : t('ui.disconnected.from.server')); } } function onStateEvent(conn, evt) { const prev = conn.conn.state; if (typeof evt.identity_id === 'string') conn.identityId = evt.identity_id; if (evt.state === 'disconnected') { resetConnection(conn, evt.reason ?? null); } else { if (evt.state === 'connecting' && prev === 'connected') resetConnection(conn, null, true); conn.conn = { state: evt.state, address: evt.address ?? conn.conn.address, reason: null }; if (evt.state === 'connecting' && prev === 'connected') chat.addSystem(conn, 'channel', () => t('ui.connection.lost.reconnecting')); } log('info', `${conn.id} state ${prev} → ${evt.state}`); renderConnections(); if (conn.id === S.viewId) renderAll(); } function onSnapshot(conn, snap) { conn.snap = snap; const viewed = conn.id === S.viewId; if (viewed) syncClientMenu(); pruneMedia(snap, conn); const established = conn.conn.state !== 'connected' && conn.conn.state !== 'disconnecting'; if (established) conn.conn = { ...conn.conn, state: 'connected' }; const present = new Set(snap.clients.map((c) => c.id)); for (const id of Array.from(conn.talking)) if (!present.has(id)) conn.talking.delete(id); if (!conn.welcomeShown) { conn.welcomeShown = true; // Chat keeps history across reconnects; never let its translated label retain the whole snapshot. const serverName = snap.server.name; const serverVersion = snap.server.version; chat.addSystem(conn, 'server', () => t('message.connected.to.p0.p1', { p0: serverName, p1: serverVersion ? ` (${serverVersion})` : '' }), { emphasis: [serverName] }); const welcome = stripBBCode(snap.server.welcome_message).trim(); if (welcome) chat.addSystem(conn, 'server', () => welcome); } if (snap.own_channel_id !== conn.lastOwnChannel) { conn.lastOwnChannel = snap.own_channel_id; // After a join or a server move the workspace shows the channel the user is now in. conn.selectedChannelId = snap.own_channel_id; } if (!snap.channels.some((c) => c.id === conn.selectedChannelId)) conn.selectedChannelId = snap.own_channel_id; chat.onSnapshot(conn); watch.onSnapshot(conn); broadcast.onSnapshot(conn); // A newly established connection takes the microphone when no established connection has it. if (established && !inputConnection()) setInputConnection(conn); else if (established) syncInput(); renderConnections(); if (!viewed) return; renderHostBanner(); renderConnection(); renderTree(); renderSelf(); renderSessionHead(); } function onAsyncError(conn, error) { const code = error?.code; log('warn', `${conn.id} core error ${code}: ${error?.message ?? ''}`); if (code === 'audio_muted' || code === 'not_connected') return; const now = Date.now(); if (lastAsyncError.code === code && now - lastAsyncError.at < 5000) return; lastAsyncError = { code, at: now }; if (code === 'audio_codec_unsupported') { renderSessionHead(); return; } toast(() => (conn.id === S.viewId ? errorText(error) : `${connectionLabel(conn)}: ${errorText(error)}`), 'error'); } function applyAudioState(conn, next) { const wasDeaf = conn.audio.output_muted; const wasTransmitting = conn.audio.transmitting; conn.audio = next; // Core-side confirmation that voice is going out (TEAMSPEACH_LOG=debug only). if (next.transmitting !== wasTransmitting) log('debug', `voice: ${conn.id} core transmitting=${next.transmitting}`); if (next.output_muted && !wasDeaf) voice.onOutputMuted(true, conn); watch.applyVolume(); renderConnections(); if (conn.id !== S.viewId) return; renderSelf(); renderSessionHead(); const self = conn.snap?.own_client_id; if (self !== undefined) updateTalking(self); } function onCoreEvent(evt) { const conn = connectionById(evt.connectionId); if (!conn) return; // closed connection, or a fixture event for an unknown one switch (evt.event) { case 'state': onStateEvent(conn, evt); break; case 'snapshot': onSnapshot(conn, evt); break; case 'audio_state': applyAudioState(conn, { input_muted: Boolean(evt.input_muted), output_muted: Boolean(evt.output_muted), transmitting: Boolean(evt.transmitting) }); break; case 'talking': if (evt.talking) conn.talking.add(evt.client_id); else conn.talking.delete(evt.client_id); if (conn.id === S.viewId) updateTalking(evt.client_id); break; case 'text': chat.onText(evt, conn); renderConnections(); break; case 'stream': watch.onStreamEvent(evt, conn); broadcast.onStreamEvent(evt, conn); break; case 'profile': applyProfile(evt); break; case 'error': onAsyncError(conn, evt.error); break; default: break; } emit(evt.event, evt, conn); } function applyProfile(profile) { if (profile.is_default === false) return; S.profile = { ...profile }; if (!appShown) { if (!profile.exists || !profile.nickname) showOnboarding(); else showApp(); } renderSelf(); renderConnection(); settings.renderProfile(); } // ---------- channel selection ---------- /** Selecting a channel changes only the viewed surface, never the voice channel. */ function selectChannel(cid) { if (!isConnected() || !S.snap.channels.some((c) => c.id === cid)) return; S.selectedChannelId = cid; setWhisperSelection(viewedConnection(), { channel_ids: [cid] }); if (cid === S.snap.own_channel_id) chat.showOwnChannel(); else setView('channel-info'); renderTree(); renderSessionHead(); watch.onSelectionChanged(); if (S.view === 'channel-info') void renderChannelInfo(); } // ---------- self controls ---------- /** * Official toolbar mute (toolbar.toggle.quick.tooltip): click = all servers, Alt+click = current server, * Shift+click = all servers except the current one. The new value is the opposite of the current server's. * "All servers" also becomes the default for connections opened later (defaultClientSelfProperties). */ async function toggleAudio(key, scope = 'all') { const viewed = viewedConnection(); if (!viewed) return; const value = !viewed.audio[key]; const targets = connectionList().filter((c) => c.core.status === 'ready' && (scope === 'all' || (scope === 'current') === (c === viewed))); if (scope === 'all') audioDefaults[key] = value; await setAudio(targets, { [key]: value }); } /** Key bindings update every server and the defaults for connections opened later. */ async function setSelfAudio(key, value) { const next = value === 'toggle' ? !audioDefaults[key] : Boolean(value); audioDefaults[key] = next; await setAudio(connectionList().filter((conn) => conn.core.status === 'ready'), { [key]: next }); } async function setAudio(targets, change) { await Promise.all(targets.map(async (conn) => { try { const result = await callOn(conn.id, 'set_audio', change); if (!isAlive(conn)) return; applyAudioState(conn, { ...conn.audio, input_muted: result.input_muted, output_muted: result.output_muted, transmitting: result.transmitting ?? conn.audio.transmitting }); } catch (err) { if (err.code !== 'connection_closed') toast(() => `${connectionLabel(conn)}: ${errorText(err)}`, 'error'); } })); } /** A (re)started core starts unmuted; "mute on all servers" applies to it too. */ function applyAudioDefaults(conn) { const change = {}; if (audioDefaults.input_muted) change.input_muted = true; if (audioDefaults.output_muted) change.output_muted = true; if (Object.keys(change).length) void setAudio([conn], change); } function muteScope(event) { if (event.altKey) return 'current'; if (event.shiftKey) return 'others'; return 'all'; } function openSettings(panel) { S.view = 'settings'; renderConnection(); settings.open(panel); notifications.renderNotificationSettings(); void osSettings.renderOsSettings(); } async function closeSettings() { await settings.close(); S.view = 'main'; renderConnection(); chat.onViewChanged(); (isConnected() ? $('#chat-input') : $('#connect-address')).focus(); } // ---------- diagnostics for automated smoke runs (read-only) ---------- Object.defineProperty(window, 'teamspeachDiagnostics', { value: Object.freeze({ snapshot: () => ({ core: S.core.status, profile: S.profile ? { uid: S.profile.uid, nickname: S.profile.nickname } : null, conn: S.conn.state, server: S.snap?.server?.name ?? null, ownClientId: S.snap?.own_client_id ?? null, ownChannel: ownChannel()?.name ?? null, selectedChannel: selectedChannel()?.name ?? null, clients: S.snap ? S.snap.clients.map((c) => ({ id: c.id, nickname: c.nickname, channel: c.channel_id, type: c.client_type, inputMuted: c.input_muted })) : [], talking: Array.from(S.talking), audio: { ...S.audio }, voice: { ...voice.voiceStats, forwarding: voice.isForwarding(), capturing: voice.isCapturing(), coreMode: voice.confirmedTransmitMode() }, streams: watch.streamSnapshots(), watchingIds: watch.watchingIds(), watches: watch.watchSnapshots(), fullscreen: document.fullscreenElement?.dataset.streamId ?? null, videoCodecs: settings.videoCodecs(), connections: connectionList().map((c) => ({ id: c.id, core: c.core.status, state: c.conn.state, address: c.conn.address, server: c.snap?.server?.name ?? null, viewed: c.id === S.viewId, inputEnabled: c.inputEnabled, inputMuted: c.audio.input_muted, outputMuted: c.audio.output_muted, transmitting: c.audio.transmitting, unread: chat.unreadCount(c), })), inputConnection: inputConnection()?.id ?? null, }), playback: () => voice.playbackStats(), }), }); // ---------- boot ---------- async function boot() { initSelectControls(); S.prefs = await tp.getPrefs(); initSidebarLayout({ savePrefs }); setLanguage(S.prefs.language); userStyles.initUserStyles(); initConnectionsUi({ view: (id) => setViewed(id), close: (id) => closeConnectionTab(id), create: () => newConnectionTab(), useMicrophone: (id) => setInputConnection(connectionById(id)), unread: (conn) => chat.unreadCount(conn), }); contacts.initContacts({ host: $('#contacts-panel'), view: (id) => setViewed(id), changed: renderTree }); initTree({ savePrefs, contextClient: openClientMenu, openPrivate: (id) => chat.openPrivate(viewedConnection(), id), openSettings, selectChannel, streamsOf: (id) => watch.streamsOf(id), watchingIds: () => watch.watchingIds(), }); chat.initChat(); initClientMenu(); initAdmin(); servers.initServers({ savePrefs, connectTo, onIdentityChanged: () => renderConnection(), }); initDeviceMenus({ openAudioSettings: () => openSettings('audio'), setAudioScope: (key, scope) => toggleAudio(key, scope) }); initUpdates(); watch.initWatch({ onChange: () => renderTree(), savePrefs }); broadcast.initBroadcast(); voice.initVoice({ savePrefs, onOutputChanged: () => watch.applySink(), onPtt: () => renderSessionHead(), onTransmitChanged: () => {}, }); settings.initSettings({ savePrefs, close: closeSettings, onProfile: (p) => { if (p.is_default !== false) S.profile = p; renderSelf(); renderConnection(); settings.renderProfile(); renderTree(); }, }); const connectionStatus = h('button', { id: 'connection-status-btn', class: 'status-btn', type: 'button', 'aria-label': t('clientMenu.connection_info'), title: t('clientMenu.connection_info') }, icon('connection-status')); connectionStatus.addEventListener('click', (event) => { const me = ownClient(); if (me) void openClientMenu(event, me.id, 'connection_info'); }); notifications.initNotifications(); osSettings.initOsSettings(); recording.initRecording(); document.querySelector('.server-status-bar').append(h('div', { class: 'server-informative-buttons' }, whisperHistoryButton(), $('#btn-talk-power'), $('#recording-indicator'), connectionStatus, $('#server-events-btn'))); initFiles(); on('chat-unread', renderConnections); on('chat-selection', renderSessionHead); on('appearance-changed', renderTree); on('admin-view', (view) => { adminView = view; renderSessionHead(); }); on('settings-panel', (name) => settings.showPanel(name)); void initWhisper({ view: (id) => setViewed(id), changed: renderTree }); void initKeybinds({ setSelfAudio, disconnect: (conn) => disconnect(conn) }); on('set-view', (name) => setView(name)); onLanguageChange(() => { renderConnections(); renderSelf(); renderSessionHead(); renderTree(); chat.onViewChanged(); }); $('#onboarding-form').addEventListener('submit', submitOnboarding); for (const radio of document.querySelectorAll('input[name="onboarding-theme"]')) radio.addEventListener('change', () => { if (radio.checked) changeOnboardingTheme(radio.value); }); $('#onboarding-import').addEventListener('click', async () => { if (appShown || onboardingBusy) return; if (onboardingThemeSave && !(await onboardingThemeSave)) return; if (appShown || onboardingBusy) return; onboardingBusy = true; syncOnboardingControls(); try { const r = await tp.importIdentity(); if (r.ok) toast(() => t('message.identity.restored.uid.p0', { p0: r.result?.uid })); else if (!r.canceled) setText($('#onboarding-error'), () => t('message.restore.failed.p0', { p0: errorText(r.error) })); } catch (error) { setText($('#onboarding-error'), () => errorText(error)); } finally { onboardingBusy = false; syncOnboardingControls(); } }); $('#connect-form').addEventListener('submit', submitConnect); $('#connect-identity-choice').addEventListener('change', () => renderConnection()); $('#connect-improve-identity').addEventListener('click', () => { const requirement = viewedConnection()?.requiredSecurity; if (!requirement) return; openSettings('identity'); void focusIdentity(requirement.uid, requirement.target); }); $('#sidebar-search').addEventListener('input', (event) => { S.serverFilter = event.target.value.trim(); renderConnections(); servers.renderServers(); }); $('#sidebar-search').addEventListener('keydown', (event) => { if (event.key !== 'Enter') return; event.preventDefault(); const query = event.currentTarget.value.trim(); if (!query) return; const normalized = query.toLocaleLowerCase(); const conn = connectionList().find((entry) => `${connectionLabel(entry)} ${entry.conn.address}`.toLocaleLowerCase().includes(normalized)); if (conn) { setViewed(conn.id); return; } const bookmark = S.prefs.savedServers.find((entry) => `${entry.name} ${entry.address}`.toLocaleLowerCase().includes(normalized)); void connectTo(bookmark?.address || query, { identity_id: bookmark?.identity_id || '' }); }); $('#btn-disconnect').addEventListener('click', () => disconnect()); $('#server-bookmark').addEventListener('click', () => { if (isConnected()) void servers.saveCurrentServer(); }); $('#server-current-chat').addEventListener('click', () => { const own = ownChannel(); if (own) selectChannel(own.id); }); $('#admin-mode-events').addEventListener('click', () => setView('server-log')); $('#btn-channel-chat').addEventListener('click', () => { if (S.view === 'channel-info' && adminView?.kind === 'client') chat.openPrivate(viewedConnection(), adminView.id); else setView('main'); }); $('#btn-join-channel').addEventListener('click', () => { const ch = selectedChannel(); if (ch) joinChannel(ch.id); }); $('#btn-mute').addEventListener('click', (e) => toggleAudio('input_muted', muteScope(e))); $('#btn-deafen').addEventListener('click', (e) => toggleAudio('output_muted', muteScope(e))); $('#btn-settings').addEventListener('click', () => (S.view === 'settings' ? closeSettings() : openSettings())); $('#fatal-retry').addEventListener('click', () => { for (const conn of connectionList()) if (conn.core.status !== 'ready' && conn.core.status !== 'starting') tp.restartCore(conn.id); }); $('#fatal-import').addEventListener('click', async () => { const r = await tp.importIdentity(); if (!r.ok && !r.canceled) toast(() => t('message.import.failed.p0', { p0: errorText(r.error) }), 'error'); }); $('#fatal-logs').addEventListener('click', () => tp.openLogs()); tp.onConnections(onConnectionsChanged); tp.onEvent(onCoreEvent); tp.onCoreStatus(onCoreStatus); tp.onProfileChanged(applyProfile); const list = await tp.listConnections(); if (list) { onConnectionsChanged(list); for (const info of list.connections) onCoreStatus({ ...info.core, connectionId: info.id }); } } boot().catch((err) => { log('error', `boot failed: ${err.stack || err.message}`); showFatal(t('ui.interface.startup.failed'), String(err.message || err), []); });