yum-slop/TaSTT

Free self-hosted STT for VRChat.

git clone https://git.yummers.dev/yum-slop/TaSTT

yumRedact usernames from console output672d0a5

v1.0.0-beta02
19.2 KiB534 linesraw
1// Import configuration schema
2const CONFIG_FIELDS = window.CONFIG_SCHEMA;
3
4// Process state tracking
5let isProcessRunning = false;
6let buttonManager;
7let loadingOverlay;
8
9// Auto-save functionality with debouncing
10let saveTimeout;
11const SAVE_DELAY = 500;
12let isSettingValues = false;
13
14// Console management
15const consoleContent = document.getElementById('console-content');
16const MAX_CONSOLE_LINES = 512;
17let consoleLineCount = 0;
18
19// Button management system
20class ButtonManager {
21    constructor() {
22        this.buttons = {
23            start: document.getElementById('start-process'),
24            stop: document.getElementById('stop-process'),
25            setupVenv: document.getElementById('setup-venv'),
26            resetVenv: document.getElementById('reset-venv'),
27            refreshMicrophones: document.getElementById('refresh-microphones')
28        };
29
30        // Initialize button states - process is not running at startup
31        this.setProcessStopped();
32    }
33
34    setState(buttonName, disabled) {
35        const button = this.buttons[buttonName];
36        if (!button) return;
37
38        button.disabled = disabled;
39    }
40
41    setProcessRunning() {
42        this.setState('start', true);
43        this.setState('stop', false);
44        isProcessRunning = true;
45    }
46
47    setProcessStopped() {
48        this.setState('start', false);
49        this.setState('stop', true);
50        isProcessRunning = false;
51    }
52
53    async withButtonLoading(buttonName, asyncFn) {
54        this.setState(buttonName, true);
55        try {
56            return await asyncFn();
57        } finally {
58            this.setState(buttonName, false);
59        }
60    }
61}
62
63// Add loading overlay management
64class LoadingOverlay {
65    constructor() {
66        this.overlay = document.getElementById('loading-overlay');
67        this.form = document.getElementById('config-form');
68        this.messageElement = this.overlay.querySelector('p');
69        this.defaultMessage = 'Environment setup underway - please wait.';
70        this.originalStates = new Map(); // Track original disabled states
71    }
72
73    show(message = null) {
74        this.messageElement.textContent = message || this.defaultMessage;
75        this.overlay.classList.remove('hidden');
76        // Disable all form inputs and buttons in the entire left panel
77        const leftPanel = this.overlay.parentElement;
78        const inputs = leftPanel.querySelectorAll('input, select, textarea, button');
79        inputs.forEach(input => {
80            // Store original disabled state before disabling
81            this.originalStates.set(input, input.disabled);
82            input.disabled = true;
83            input.classList.add('opacity-50');
84        });
85    }
86
87    hide() {
88        this.overlay.classList.add('hidden');
89        // Restore original states of form inputs and buttons
90        const leftPanel = this.overlay.parentElement;
91        const inputs = leftPanel.querySelectorAll('input, select, textarea, button');
92        inputs.forEach(input => {
93            // Restore original disabled state
94            input.disabled = this.originalStates.get(input) || false;
95            input.classList.remove('opacity-50');
96        });
97        // Clear the stored states
98        this.originalStates.clear();
99        // Reset to default message
100        this.messageElement.textContent = this.defaultMessage;
101    }
102}
103
104// Handle status messages with better color management
105function showStatus(message, type = 'info') {
106    const statusEl = document.getElementById('status-message');
107    statusEl.textContent = message;
108
109    // Remove all status classes
110    const statusClasses = ['hidden', 'bg-green-100', 'bg-red-100', 'bg-blue-100', 'text-green-800', 'text-red-800', 'text-blue-800'];
111    statusEl.classList.remove(...statusClasses);
112
113    // Add appropriate classes based on type
114    const typeMap = {
115        success: ['bg-green-100', 'text-green-800'],
116        error: ['bg-red-100', 'text-red-800'],
117        info: ['bg-blue-100', 'text-blue-800']
118    };
119
120    statusEl.classList.add(...(typeMap[type] || typeMap.info));
121
122    // Also log to console
123    appendToConsole(message, type === 'error' ? 'stderr' : 'info');
124
125    setTimeout(() => statusEl.classList.add('hidden'), 5000);
126}
127
128// Get form values using field mappings
129function getFormValues() {
130    const config = {};
131
132    for (const [fieldName, fieldConfig] of Object.entries(CONFIG_FIELDS)) {
133        const element = document.getElementById(fieldName);
134        if (!element) continue;
135
136        switch (fieldConfig.type) {
137            case 'boolean':
138                config[fieldName] = element.checked ? 1 : 0;
139                break;
140            case 'number':
141                const numValue = parseInt(element.value);
142                config[fieldName] = isNaN(numValue) ? fieldConfig.default : numValue;
143                break;
144            case 'text':
145                config[fieldName] = element.value || fieldConfig.default;
146                break;
147            default:
148                config[fieldName] = element.value || fieldConfig.default;
149        }
150    }
151
152    return config;
153}
154
155// Set form values using field mappings
156function setFormValues(config) {
157    isSettingValues = true; // Disable auto-save temporarily
158
159    for (const [fieldName, fieldConfig] of Object.entries(CONFIG_FIELDS)) {
160        const element = document.getElementById(fieldName);
161        if (!element) continue;
162
163        const value = config[fieldName] ?? fieldConfig.default;
164
165        switch (fieldConfig.type) {
166            case 'boolean':
167                element.checked = value === 1;
168                break;
169            case 'text':
170                element.value = value || '';
171                break;
172            default:
173                element.value = value;
174        }
175    }
176
177    // Handle use_builtin toggle state
178    const useBuiltin = config.use_builtin === 1;
179    const customChatboxInputs = ['block_width', 'num_blocks', 'rows', 'cols'];
180    customChatboxInputs.forEach(inputId => {
181        const input = document.getElementById(inputId);
182        if (input) {
183            input.disabled = useBuiltin;
184            if (useBuiltin) {
185                input.classList.add('opacity-50', 'cursor-not-allowed');
186            } else {
187                input.classList.remove('opacity-50', 'cursor-not-allowed');
188            }
189        }
190    });
191
192    // Update volume display
193    if (config.volume !== undefined) {
194        const volumePercent = Math.round(config.volume);
195        document.getElementById('volume-display').textContent = `${volumePercent}%`;
196    }
197
198    isSettingValues = false; // Re-enable auto-save
199}
200
201function appendToConsole(message, type = 'stdout') {
202    const timestamp = new Date().toLocaleTimeString();
203    const timestampSpan = document.createElement('span');
204    timestampSpan.className = 'console-timestamp';
205    timestampSpan.textContent = `[${timestamp}] `;
206
207    const messageSpan = document.createElement('span');
208    messageSpan.className = `console-${type}`;
209
210    // Redact usernames from paths.
211    const redactedMessage = message.replace(/([A-Za-z]:[\/\\]Users[\/\\])([^\/\\]+)/g, '$1*****');
212    messageSpan.textContent = redactedMessage;
213
214    const lineDiv = document.createElement('div');
215    lineDiv.appendChild(timestampSpan);
216    lineDiv.appendChild(messageSpan);
217
218    consoleContent.appendChild(lineDiv);
219    consoleLineCount++;
220
221    // Remove old lines if we exceed the limit
222    if (consoleLineCount > MAX_CONSOLE_LINES) {
223        // Calculate how many lines to remove (remove 10% to avoid frequent trimming)
224        const linesToRemove = Math.floor(MAX_CONSOLE_LINES * 0.1);
225
226        // Remove the oldest lines
227        for (let i = 0; i < linesToRemove; i++) {
228            if (consoleContent.firstChild) {
229                consoleContent.removeChild(consoleContent.firstChild);
230            }
231        }
232
233        consoleLineCount -= linesToRemove;
234
235        // Add a notice that lines were trimmed
236        const trimNotice = document.createElement('div');
237        trimNotice.className = 'console-info';
238        trimNotice.innerHTML = '<span class="console-timestamp">[System] </span><span class="console-info">... older lines removed to maintain performance ...</span>';
239        consoleContent.insertBefore(trimNotice, consoleContent.firstChild);
240    }
241
242    // Auto-scroll to bottom
243    const pythonConsole = document.getElementById('python-console');
244    pythonConsole.scrollTop = pythonConsole.scrollHeight;
245}
246
247// Async action handler with better error handling
248async function handleAsyncAction(actionName, actionFn) {
249    try {
250        const result = await actionFn();
251        if (result?.message) {
252            showStatus(result.message, 'success');
253        }
254        return result;
255    } catch (error) {
256        showStatus(`${actionName} failed: ${error.message}`, 'error');
257        throw error;
258    }
259}
260
261async function autoSaveConfig() {
262    if (isSettingValues) return;
263
264    clearTimeout(saveTimeout);
265    saveTimeout = setTimeout(async () => {
266        try {
267            const config = getFormValues();
268            await window.electronAPI.saveConfig(config);
269            showStatus('Configuration saved', 'success');
270
271            // Restart process if running
272            if (isProcessRunning) {
273                appendToConsole('Restarting process with new configuration...', 'info');
274
275                try {
276                    await window.electronAPI.stopProcess();
277                    await new Promise(resolve => setTimeout(resolve, 1000));
278                    await window.electronAPI.startProcess();
279                    buttonManager.setProcessRunning();
280                    appendToConsole('Process restarted with new configuration', 'info');
281                } catch (error) {
282                    appendToConsole(`Failed to restart process: ${error.message}`, 'stderr');
283                    buttonManager.setProcessStopped();
284                }
285            }
286        } catch (error) {
287            showStatus(`Failed to save configuration: ${error.message}`, 'error');
288        }
289    }, SAVE_DELAY);
290}
291
292// Auto-save setup
293function setupAutoSave() {
294    const form = document.getElementById('config-form');
295    const inputs = form.querySelectorAll('input, select, textarea');
296
297    inputs.forEach(input => {
298        const eventType = input.type === 'checkbox' ? 'change' :
299                         (input.type === 'number' || input.type === 'text' || input.tagName === 'TEXTAREA') ? 'input' : 'change';
300        input.addEventListener(eventType, autoSaveConfig);
301    });
302}
303
304// Microphone loading
305async function loadMicrophones() {
306    const microphoneSelect = document.getElementById('microphone');
307
308    try {
309        // Check/install requirements during startup
310        appendToConsole('Checking virtual environment and requirements...', 'info');
311        loadingOverlay.show('Setting up environment - this can take several minutes.');
312        try {
313            await handleAsyncAction('Install requirements', () => window.electronAPI.installRequirements());
314        } finally {
315            loadingOverlay.hide(); // Always hide overlay when done
316        }
317
318        appendToConsole('Loading available microphones...', 'info');
319        const microphones = await window.electronAPI.getMicrophones();
320
321        microphoneSelect.innerHTML = '';
322
323        if (microphones.length === 0) {
324            microphoneSelect.innerHTML = '<option value="" disabled>No microphones found</option>';
325            appendToConsole('No microphones found', 'stderr');
326            return;
327        }
328
329        appendToConsole(`Found ${microphones.length} microphone(s)`, 'info');
330        microphones.forEach(mic => {
331            const option = document.createElement('option');
332            option.value = mic.index.toString();
333            option.textContent = mic.name;
334            microphoneSelect.appendChild(option);
335            appendToConsole(`  - ${mic.name} (Device ${mic.index})`, 'stdout');
336        });
337
338        // Restore previously selected microphone
339        try {
340            const config = await window.electronAPI.loadConfig();
341            if (config.microphone) {
342                microphoneSelect.value = config.microphone;
343            }
344        } catch (error) {
345            // Ignore config load errors here
346        }
347
348    } catch (error) {
349        appendToConsole(`Failed to load microphones: ${error.message}`, 'stderr');
350        microphoneSelect.innerHTML = '<option value="" disabled>Error loading microphones</option>';
351    }
352}
353
354// Event handlers setup
355function setupEventHandlers() {
356    // Advanced settings toggle
357    document.getElementById('toggle-advanced').addEventListener('click', () => {
358        const advancedSettings = document.getElementById('advanced-settings');
359        const chevron = document.getElementById('chevron');
360
361        if (advancedSettings.classList.contains('hidden')) {
362            advancedSettings.classList.remove('hidden');
363            chevron.classList.add('rotate-90');
364        } else {
365            advancedSettings.classList.add('hidden');
366            chevron.classList.remove('rotate-90');
367        }
368    });
369
370    // Use builtin chatbox toggle
371    document.getElementById('use_builtin').addEventListener('change', (e) => {
372        const customChatboxInputs = ['block_width', 'num_blocks', 'rows', 'cols'];
373        const isBuiltin = e.target.checked;
374
375        customChatboxInputs.forEach(inputId => {
376            const input = document.getElementById(inputId);
377            if (input) {
378                input.disabled = isBuiltin;
379                if (isBuiltin) {
380                    input.classList.add('opacity-50', 'cursor-not-allowed');
381                } else {
382                    input.classList.remove('opacity-50', 'cursor-not-allowed');
383                }
384            }
385        });
386    });
387
388    // Volume slider update
389    document.getElementById('volume').addEventListener('input', (e) => {
390        const volumePercent = Math.round(e.target.value);
391        document.getElementById('volume-display').textContent = `${volumePercent}%`;
392    });
393
394    // Setup virtual environment
395    document.getElementById('setup-venv').addEventListener('click', async () => {
396        loadingOverlay.show('Setting up virtual environment - please wait...'); // Show overlay with custom message
397        try {
398            await buttonManager.withButtonLoading('setupVenv', async () => {
399                await window.electronAPI.deleteVenvIndicatorFile();
400                await handleAsyncAction('Install requirements', () => window.electronAPI.installRequirements());
401            });
402        } finally {
403            loadingOverlay.hide(); // Always hide overlay when done
404        }
405    });
406
407    // Reset virtual environment
408    document.getElementById('reset-venv').addEventListener('click', async () => {
409        loadingOverlay.show('Resetting virtual environment - please wait...'); // Show overlay with custom message
410        try {
411            await buttonManager.withButtonLoading('resetVenv', async () => {
412                await handleAsyncAction('Reset virtual environment', () => window.electronAPI.resetVenv());
413            });
414        } finally {
415            loadingOverlay.hide(); // Always hide overlay when done
416        }
417    });
418
419    // Reset configuration
420    document.getElementById('reset-config').addEventListener('click', async () => {
421        const confirmReset = confirm('Are you sure you want to reset all settings to defaults? This cannot be undone.');
422        if (!confirmReset) return;
423
424        try {
425            // Stop process if running
426            const wasRunning = isProcessRunning;
427            if (wasRunning) {
428                appendToConsole('Stopping process before resetting configuration...', 'info');
429                await window.electronAPI.stopProcess();
430                buttonManager.setProcessStopped();
431                await new Promise(resolve => setTimeout(resolve, 500));
432            }
433
434            // Reset configuration
435            appendToConsole('Resetting configuration to defaults...', 'info');
436            const result = await window.electronAPI.resetConfig();
437
438            // Reload configuration with defaults
439            const config = await window.electronAPI.loadConfig();
440            setFormValues(config);
441
442            showStatus(result.message, 'success');
443            appendToConsole('Configuration reset successfully', 'info');
444
445            // Restart process if it was running
446            if (wasRunning) {
447                appendToConsole('Restarting process with default configuration...', 'info');
448                await window.electronAPI.startProcess();
449                buttonManager.setProcessRunning();
450                appendToConsole('Process restarted with default configuration', 'info');
451            }
452        } catch (error) {
453            showStatus(`Failed to reset configuration: ${error.message}`, 'error');
454            appendToConsole(`Failed to reset configuration: ${error.message}`, 'stderr');
455        }
456    });
457
458    // Refresh microphones
459    document.getElementById('refresh-microphones').addEventListener('click', async () => {
460        await buttonManager.withButtonLoading('refreshMicrophones', async () => {
461            await loadMicrophones();
462        });
463    });
464
465    // Start process
466    document.getElementById('start-process').addEventListener('click', async () => {
467        buttonManager.setState('start', true);
468
469        try {
470            // The installRequirements function will now check if venv is set up.
471            loadingOverlay.show('Verifying environment setup - please wait...'); // Show overlay with custom message
472            try {
473                await window.electronAPI.installRequirements();
474                appendToConsole('Virtual environment setup checked/completed', 'info');
475            } finally {
476                loadingOverlay.hide(); // Always hide overlay when done
477            }
478
479            await window.electronAPI.startProcess();
480            buttonManager.setProcessRunning();
481            appendToConsole('Process started successfully', 'info');
482        } catch (error) {
483            appendToConsole(`Failed to start process: ${error.message}`, 'stderr');
484            buttonManager.setState('start', false);
485        }
486    });
487
488    // Stop process
489    document.getElementById('stop-process').addEventListener('click', async () => {
490        buttonManager.setState('stop', true);
491
492        try {
493            await window.electronAPI.stopProcess();
494            appendToConsole('Process stop initiated', 'info');
495        } catch (error) {
496            appendToConsole(`Failed to stop process: ${error.message}`, 'stderr');
497            buttonManager.setState('stop', false);
498        }
499    });
500
501    // Listen for process stopped event
502    window.electronAPI.onProcessStopped(() => {
503        buttonManager.setProcessStopped();
504    });
505}
506
507// Initialize application
508window.addEventListener('load', async () => {
509    appendToConsole('TaSTT Configuration UI initialized', 'info');
510
511    loadingOverlay = new LoadingOverlay();
512    buttonManager = new ButtonManager();
513
514    // Set up Python output listener first so we capture all output
515    window.electronAPI.onPythonOutput((data) => {
516        appendToConsole(data.message, data.type);
517    });
518
519    // Load configuration
520    try {
521        const config = await window.electronAPI.loadConfig();
522        setFormValues(config);
523        appendToConsole('Configuration loaded', 'info');
524    } catch (error) {
525        appendToConsole(`Failed to load configuration: ${error.message}`, 'stderr');
526    }
527
528    // Load microphones
529    await loadMicrophones();
530
531    // Setup event handlers and auto-save
532    setupEventHandlers();
533    setupAutoSave();
534});