@lethevimlet/sshift 1.5.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2458,6 +2458,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2458
2458
  specialKeysBtn.title = 'Special Keys';
2459
2459
  specialKeysBtn.innerHTML = '<i class="fas fa-keyboard"></i>';
2460
2460
  actions.appendChild(specialKeysBtn);
2461
+
2462
+ const speechToTextBtn = document.createElement('button');
2463
+ speechToTextBtn.className = 'btn btn-sm';
2464
+ speechToTextBtn.id = isSingle ? 'speechToTextBtn' : `${panelId}-speechToTextBtn`;
2465
+ speechToTextBtn.title = 'Speech to Text';
2466
+ speechToTextBtn.innerHTML = '<i class="fas fa-microphone"></i>';
2467
+ actions.appendChild(speechToTextBtn);
2461
2468
 
2462
2469
  container.appendChild(actions);
2463
2470
 
@@ -2507,22 +2514,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2507
2514
  increaseBtn.addEventListener('click', () => this.handleFontSizeChange(panelId, 1));
2508
2515
  }
2509
2516
 
2510
- // Special keys button
2517
+ // Special keys button — touch + click pattern so it works on mobile & desktop
2511
2518
  const specialKeysBtn = document.getElementById(isSingle ? 'specialKeysBtn' : `${panelId}-specialKeysBtn`);
2512
- if (specialKeysBtn) {
2513
- specialKeysBtn.setAttribute('tabindex', '-1');
2514
- specialKeysBtn.addEventListener('focus', () => {
2515
- specialKeysBtn.blur();
2516
- if (this.isMobile) this.focusTerminal();
2517
- });
2518
- specialKeysBtn.addEventListener('touchstart', (e) => {
2519
- if (this.isMobile) e.preventDefault();
2520
- }, { passive: false });
2521
- specialKeysBtn.addEventListener('mousedown', (e) => {
2522
- if (this.isMobile) e.preventDefault();
2523
- });
2524
- specialKeysBtn.addEventListener('click', () => this.handleSpecialKeys(panelId));
2525
- }
2519
+ this._wireActionBtn(specialKeysBtn, () => this.handleSpecialKeys(panelId));
2520
+
2521
+ // Speech-to-text button (terminal tabs only — gating handled in handler)
2522
+ const speechToTextBtn = document.getElementById(isSingle ? 'speechToTextBtn' : `${panelId}-speechToTextBtn`);
2523
+ this._wireActionBtn(speechToTextBtn, () => this.handleSpeechToText(panelId));
2526
2524
 
2527
2525
  // Quick SSH/SFTP buttons in empty state
2528
2526
  const quickSshBtn = document.getElementById(isSingle ? 'quickSshBtn' : `${panelId}-quickSshBtn`);
@@ -2661,6 +2659,348 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2661
2659
  this.openModal('specialKeysModal');
2662
2660
  }
2663
2661
 
2662
+ handleSpeechToText(panelId) {
2663
+ console.log('[SSHIFT] Open speech-to-text for panel:', panelId);
2664
+
2665
+ const activeSessionId = this.activeSessionsByPanel.get(panelId);
2666
+
2667
+ if (!activeSessionId) {
2668
+ this.showToast('No active session in this panel', 'warning');
2669
+ return;
2670
+ }
2671
+
2672
+ const session = this.sessions.get(activeSessionId);
2673
+ if (!session || session.type !== 'ssh') {
2674
+ this.showToast('Speech to text only works in SSH sessions', 'warning');
2675
+ return;
2676
+ }
2677
+
2678
+ // Set this as the active session so Send writes to the right terminal
2679
+ this.activeSessionId = activeSessionId;
2680
+
2681
+ // Reset transcript + record button state for a fresh session
2682
+ const transcript = document.getElementById('sttTranscript');
2683
+ if (transcript) transcript.value = '';
2684
+ this._resetSttRecordButton();
2685
+
2686
+ // Open the speech-to-text modal (TTS/record/wand logic comes later)
2687
+ this.openModal('speechToTextModal');
2688
+ }
2689
+
2690
+ // Wire a tab-action button (keyboard, mic, etc.) with the standard
2691
+ // touch+click pattern used throughout the app. On touch devices, the
2692
+ // action fires from touchend (with a dedupe flag so the synthetic
2693
+ // click doesn't double-fire). On non-touch devices, the action fires
2694
+ // from click. The focus handler keeps focus on the terminal so the
2695
+ // virtual keyboard never pops up when the user taps a tab-action button.
2696
+ _wireActionBtn(btn, action) {
2697
+ if (!btn) return;
2698
+ btn.setAttribute('tabindex', '-1');
2699
+ btn.addEventListener('focus', () => {
2700
+ btn.blur();
2701
+ if (this.isMobile) this.focusTerminal();
2702
+ });
2703
+ let touchHandled = false;
2704
+ btn.addEventListener('touchstart', (e) => {
2705
+ if (this.isMobile) e.preventDefault();
2706
+ touchHandled = true;
2707
+ }, { passive: false });
2708
+ btn.addEventListener('touchend', (e) => {
2709
+ e.preventDefault();
2710
+ touchHandled = true;
2711
+ action();
2712
+ }, { passive: false });
2713
+ btn.addEventListener('mousedown', (e) => {
2714
+ if (this.isMobile) e.preventDefault();
2715
+ });
2716
+ btn.addEventListener('click', () => {
2717
+ if (touchHandled) { touchHandled = false; return; }
2718
+ action();
2719
+ });
2720
+ }
2721
+
2722
+ // Cycle the merged Record/Pause button. Solving for the cleanest UX:
2723
+ // idle (label "Record") —— click ——> recording (label "Pause", red pulse)
2724
+ // recording —— click ——> stop & transcribe ——> back to idle
2725
+ // "Pause" therefore really means "stop+transcribe", with the next Record
2726
+ // appending additional speech to the same transcript. This avoids a 4-state
2727
+ // cycle (record/pause/resume/stop) and matches the spec of "the same button
2728
+ // for record and pause depending on state" — when not recording it's Record,
2729
+ // when recording it's Pause.
2730
+ async _toggleSttRecord() {
2731
+ const btn = document.getElementById('sttRecordBtn');
2732
+ if (!btn) return;
2733
+ const labelEl = btn.querySelector('.stt-btn-label');
2734
+ const iconEl = btn.querySelector('i');
2735
+
2736
+ if (btn.classList.contains('recording')) {
2737
+ // recording -> stop & transcribe
2738
+ btn.classList.remove('recording');
2739
+ if (iconEl) iconEl.className = 'fas fa-microphone';
2740
+ if (labelEl) labelEl.textContent = 'Record';
2741
+ btn.title = 'Start / Pause / Resume recording';
2742
+ btn.disabled = true;
2743
+ try {
2744
+ await this._sttStopAndTranscribe();
2745
+ } finally {
2746
+ btn.disabled = false;
2747
+ }
2748
+ return;
2749
+ }
2750
+
2751
+ // idle -> recording
2752
+ try {
2753
+ await this._startSttRecording();
2754
+ btn.classList.add('recording');
2755
+ if (iconEl) iconEl.className = 'fas fa-pause';
2756
+ if (labelEl) labelEl.textContent = 'Pause';
2757
+ btn.title = 'Stop recording and transcribe';
2758
+ } catch (err) {
2759
+ console.error('[SSHIFT] STT start failed:', err);
2760
+ this.showToast('Could not start recording: ' + (err.message || err), 'error');
2761
+ this._resetSttRecordButton();
2762
+ }
2763
+ }
2764
+
2765
+ // Stop the recorder (without resetting the button UI) and return the
2766
+ // resulting audio Blob. Resolves to null if nothing was recorded.
2767
+ _stopSttRecording() {
2768
+ return new Promise((resolve) => {
2769
+ const rec = this._sttRecorder;
2770
+ if (!rec || rec.state === 'inactive') {
2771
+ resolve(null);
2772
+ return;
2773
+ }
2774
+ const chunks = this._sttChunks || [];
2775
+ const finish = () => {
2776
+ try {
2777
+ const type = rec.mimeType || 'audio/webm';
2778
+ resolve(new Blob(chunks, { type }));
2779
+ } catch (e) {
2780
+ resolve(null);
2781
+ }
2782
+ };
2783
+ rec.addEventListener('stop', finish, { once: true });
2784
+ try { rec.requestData(); } catch (_) {}
2785
+ try { rec.stop(); } catch (_) { resolve(null); }
2786
+ if (this._sttStream) {
2787
+ this._sttStream.getTracks().forEach(t => { try { t.stop(); } catch (_) {} });
2788
+ this._sttStream = null;
2789
+ }
2790
+ });
2791
+ }
2792
+
2793
+ async _startSttRecording() {
2794
+ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
2795
+ throw new Error('Microphone access is not available in this browser');
2796
+ }
2797
+
2798
+ // Tear down any previous session first.
2799
+ this._cleanupSttRecording();
2800
+
2801
+ const stream = await navigator.mediaDevices.getUserMedia({
2802
+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
2803
+ video: false
2804
+ });
2805
+ this._sttStream = stream;
2806
+ this._sttChunks = [];
2807
+
2808
+ // Pick a supported mime type: webm/opus first (Chrome), then ogg, then
2809
+ // whatever the browser offers. DeepInfra's whisper endpoint accepts the
2810
+ // common container formats.
2811
+ const candidates = [
2812
+ 'audio/webm;codecs=opus',
2813
+ 'audio/webm',
2814
+ 'audio/ogg;codecs=opus',
2815
+ 'audio/ogg',
2816
+ 'audio/mp4'
2817
+ ];
2818
+ const mimeType = candidates.find(c => window.MediaRecorder && MediaRecorder.isTypeSupported(c)) || '';
2819
+
2820
+ const recorder = mimeType
2821
+ ? new MediaRecorder(stream, { mimeType })
2822
+ : new MediaRecorder(stream);
2823
+ this._sttRecorder = recorder;
2824
+ this._sttRecorderMime = mimeType || recorder.mimeType || 'audio/webm';
2825
+
2826
+ recorder.addEventListener('dataavailable', (e) => {
2827
+ if (e.data && e.data.size > 0) this._sttChunks.push(e.data);
2828
+ });
2829
+
2830
+ recorder.start(1000); // collect data in 1s chunks so stop() is fast
2831
+ }
2832
+
2833
+ _cleanupSttRecording() {
2834
+ try {
2835
+ if (this._sttRecorder && this._sttRecorder.state !== 'inactive') {
2836
+ this._sttRecorder.stop();
2837
+ }
2838
+ } catch (_) {}
2839
+ if (this._sttStream) {
2840
+ this._sttStream.getTracks().forEach(t => { try { t.stop(); } catch (_) {} });
2841
+ this._sttStream = null;
2842
+ }
2843
+ this._sttRecorder = null;
2844
+ this._sttChunks = null;
2845
+ }
2846
+
2847
+ // Transcribe whatever is currently recorded by sending it to the STT
2848
+ // proxy. Appends the returned text to the transcript textarea.
2849
+ async _sttStopAndTranscribe() {
2850
+ const transcript = document.getElementById('sttTranscript');
2851
+ const blob = await this._stopSttRecording();
2852
+ this._resetSttRecordButton();
2853
+ if (!blob || blob.size === 0) {
2854
+ this.showToast('No audio to transcribe', 'warning');
2855
+ return;
2856
+ }
2857
+ const ext = (this._sttRecorderMime || 'audio/webm').includes('mp4') ? 'm4a'
2858
+ : (this._sttRecorderMime || '').includes('ogg') ? 'ogg'
2859
+ : 'webm';
2860
+ const filename = `sshift-recording-${Date.now()}.${ext}`;
2861
+ // Show an inline spinner + "Transcribing…" label in the modal controls
2862
+ // row instead of a toast, so the user sees feedback right where they
2863
+ // clicked. Also disable the Record/Wand buttons while in flight.
2864
+ const setStatus = (visible, label) => {
2865
+ const s = document.getElementById('sttStatus');
2866
+ if (s) {
2867
+ s.hidden = !visible;
2868
+ const l = s.querySelector('.stt-status-label');
2869
+ if (l && label) l.textContent = label;
2870
+ }
2871
+ const recBtn = document.getElementById('sttRecordBtn');
2872
+ const wandBtn = document.getElementById('sttWandBtn');
2873
+ if (recBtn) recBtn.disabled = visible;
2874
+ if (wandBtn) wandBtn.disabled = visible;
2875
+ };
2876
+ try {
2877
+ setStatus(true, 'Transcribing…');
2878
+ const res = await fetch('/api/speech-ai/stt', {
2879
+ method: 'POST',
2880
+ headers: {
2881
+ 'Content-Type': this._sttRecorderMime || 'audio/webm',
2882
+ 'X-Audio-Filename': filename
2883
+ },
2884
+ body: blob
2885
+ });
2886
+ if (!res.ok) {
2887
+ const txt = await res.text().catch(() => '');
2888
+ throw new Error(`HTTP ${res.status} ${txt}`);
2889
+ }
2890
+ const data = await res.json();
2891
+ const text = (data.text || '').trim();
2892
+ if (!text) {
2893
+ this.showToast('No speech detected', 'warning');
2894
+ return;
2895
+ }
2896
+ if (transcript) {
2897
+ const prev = transcript.value.trim();
2898
+ transcript.value = prev ? (prev + ' ' + text) : text;
2899
+ transcript.scrollTop = transcript.scrollHeight;
2900
+ }
2901
+ } catch (err) {
2902
+ console.error('[SSHIFT] STT transcription failed:', err);
2903
+ this.showToast('Transcription failed: ' + (err.message || err), 'error');
2904
+ } finally {
2905
+ setStatus(false, 'Transcribing…');
2906
+ }
2907
+ }
2908
+
2909
+ // Send the transcript to the Wand proxy and replace the textarea with the
2910
+ // cleaned version returned by the LLM.
2911
+ async _sttRunWand() {
2912
+ const transcript = document.getElementById('sttTranscript');
2913
+ if (!transcript) return;
2914
+ const text = transcript.value.trim();
2915
+ if (!text) {
2916
+ this.showToast('Nothing to clean up yet', 'warning');
2917
+ return;
2918
+ }
2919
+ const wandBtn = document.getElementById('sttWandBtn');
2920
+ const setBusy = (busy) => {
2921
+ if (!wandBtn) return;
2922
+ wandBtn.disabled = busy;
2923
+ wandBtn.style.opacity = busy ? '0.6' : '';
2924
+ const iconEl = wandBtn.querySelector('i');
2925
+ const labelEl = wandBtn.querySelector('.stt-btn-label');
2926
+ if (busy) {
2927
+ wandBtn.dataset.origIcon = iconEl ? iconEl.className : '';
2928
+ if (iconEl) iconEl.className = 'fas fa-spinner fa-spin';
2929
+ if (labelEl) labelEl.textContent = 'Cleaning…';
2930
+ } else {
2931
+ if (iconEl && wandBtn.dataset.origIcon) iconEl.className = wandBtn.dataset.origIcon;
2932
+ if (labelEl) labelEl.textContent = 'Wand';
2933
+ }
2934
+ };
2935
+ setBusy(true);
2936
+ try {
2937
+ const res = await fetch('/api/speech-ai/wand', {
2938
+ method: 'POST',
2939
+ headers: { 'Content-Type': 'application/json' },
2940
+ body: JSON.stringify({ text })
2941
+ });
2942
+ if (!res.ok) {
2943
+ const txt = await res.text().catch(() => '');
2944
+ throw new Error(`HTTP ${res.status} ${txt}`);
2945
+ }
2946
+ const data = await res.json();
2947
+ const cleaned = (data.text || '').trim();
2948
+ if (cleaned) {
2949
+ transcript.value = cleaned;
2950
+ transcript.scrollTop = transcript.scrollHeight;
2951
+ this.showToast('Cleaned up', 'success');
2952
+ } else {
2953
+ this.showToast('Wand returned nothing', 'warning');
2954
+ }
2955
+ } catch (err) {
2956
+ console.error('[SSHIFT] Wand failed:', err);
2957
+ this.showToast('Wand failed: ' + (err.message || err), 'error');
2958
+ } finally {
2959
+ setBusy(false);
2960
+ }
2961
+ }
2962
+
2963
+ // Reset the Record/Pause button to its idle state and stop any active
2964
+ // mic stream. Used when the modal closes.
2965
+ _resetSttRecordButton() {
2966
+ this._cleanupSttRecording();
2967
+ const btn = document.getElementById('sttRecordBtn');
2968
+ if (!btn) return;
2969
+ btn.classList.remove('recording', 'paused');
2970
+ btn.disabled = false;
2971
+ const labelEl = btn.querySelector('.stt-btn-label');
2972
+ const iconEl = btn.querySelector('i');
2973
+ if (iconEl) iconEl.className = 'fas fa-microphone';
2974
+ if (labelEl) labelEl.textContent = 'Record';
2975
+ btn.title = 'Start / Pause / Resume recording';
2976
+ }
2977
+
2978
+ // Enable/disable terminal-only tab action buttons (keyboard + mic) based
2979
+ // on the active session type for the given panel. SFTP tabs disable them.
2980
+ updateTabActionButtons(panelId) {
2981
+ const isSingle = panelId === 'panel-0';
2982
+ const keysBtnId = isSingle ? 'specialKeysBtn' : `${panelId}-specialKeysBtn`;
2983
+ const micBtnId = isSingle ? 'speechToTextBtn' : `${panelId}-speechToTextBtn`;
2984
+
2985
+ const keysBtn = document.getElementById(keysBtnId);
2986
+ const micBtn = document.getElementById(micBtnId);
2987
+
2988
+ const activeSessionId = this.activeSessionsByPanel.get(panelId);
2989
+ const session = activeSessionId ? this.sessions.get(activeSessionId) : null;
2990
+ const enabled = !!(session && session.type === 'ssh');
2991
+
2992
+ [keysBtn, micBtn].forEach(btn => {
2993
+ if (!btn) return;
2994
+ if (enabled) {
2995
+ btn.removeAttribute('disabled');
2996
+ btn.classList.remove('disabled');
2997
+ } else {
2998
+ btn.setAttribute('disabled', 'disabled');
2999
+ btn.classList.add('disabled');
3000
+ }
3001
+ });
3002
+ }
3003
+
2664
3004
  async initLayoutSystem() {
2665
3005
  console.log('[SSHIFT] Initializing layout system...');
2666
3006
 
@@ -5105,22 +5445,138 @@ const wheelHandler = (e) => {
5105
5445
  });
5106
5446
  });
5107
5447
 
5108
- // Special keys modal
5448
+ // Special keys modal — panel-0 static instance uses the shared tap wiring
5449
+ // so it behaves identically on mobile and desktop (same as mic button).
5109
5450
  const specialKeysBtnEl = document.getElementById('specialKeysBtn');
5110
- specialKeysBtnEl.setAttribute('tabindex', '-1');
5111
- specialKeysBtnEl.addEventListener('focus', () => {
5112
- specialKeysBtnEl.blur();
5113
- if (this.isMobile) this.focusTerminal();
5114
- });
5115
- specialKeysBtnEl.addEventListener('touchstart', (e) => {
5116
- if (this.isMobile) e.preventDefault();
5117
- }, { passive: false });
5118
- specialKeysBtnEl.addEventListener('mousedown', (e) => {
5119
- if (this.isMobile) e.preventDefault();
5120
- });
5121
- specialKeysBtnEl.addEventListener('click', () => {
5122
- this.handleSpecialKeys('panel-0');
5123
- });
5451
+ this._wireActionBtn(specialKeysBtnEl, () => this.handleSpecialKeys('panel-0'));
5452
+
5453
+ // Speech-to-text button (panel-0 static instance) — wired the same way
5454
+ // as the keyboard button so both behave the same on mobile & desktop.
5455
+ const speechToTextBtnEl = document.getElementById('speechToTextBtn');
5456
+ this._wireActionBtn(speechToTextBtnEl, () => this.handleSpeechToText('panel-0'));
5457
+
5458
+ // Speech-to-text modal close / cancel / send / record / wand handlers
5459
+ const closeSttBtn = document.getElementById('closeSpeechToTextModal');
5460
+ const sttCancelBtn = document.getElementById('sttCancelBtn');
5461
+ const sttSendBtn = document.getElementById('sttSendBtn');
5462
+ const sttRecordBtn = document.getElementById('sttRecordBtn');
5463
+ const sttWandBtn = document.getElementById('sttWandBtn');
5464
+
5465
+ const closeSpeechToTextModal = () => {
5466
+ this.closeModal('speechToTextModal');
5467
+ const transcript = document.getElementById('sttTranscript');
5468
+ if (transcript) transcript.value = '';
5469
+ const status = document.getElementById('sttStatus');
5470
+ if (status) status.hidden = true;
5471
+ this._resetSttRecordButton();
5472
+ // Always return focus to the terminal (desktop + mobile) so the user
5473
+ // can keep typing/backspacing immediately after Send/Cancel/Close.
5474
+ this.focusTerminal();
5475
+ };
5476
+
5477
+ const attachSttClose = (btn) => {
5478
+ if (!btn) return;
5479
+ btn.setAttribute('tabindex', '-1');
5480
+ btn.addEventListener('focus', () => {
5481
+ btn.blur();
5482
+ if (this.isMobile) this.focusTerminal();
5483
+ });
5484
+ btn.addEventListener('touchstart', (e) => {
5485
+ e.preventDefault();
5486
+ }, { passive: false });
5487
+ btn.addEventListener('mousedown', (e) => {
5488
+ e.preventDefault();
5489
+ });
5490
+ btn.addEventListener('click', closeSpeechToTextModal);
5491
+ btn.addEventListener('touchend', (e) => {
5492
+ e.preventDefault();
5493
+ closeSpeechToTextModal();
5494
+ }, { passive: false });
5495
+ };
5496
+
5497
+ attachSttClose(closeSttBtn);
5498
+ attachSttClose(sttCancelBtn);
5499
+
5500
+ // Record / Pause / Resume toggle (STT endpoint wiring comes later).
5501
+ // Uses a basic touch+click handler — no focus stealing since the modal
5502
+ // is the topmost layer and we don't want to yank focus to the terminal.
5503
+ const attachSttAction = (btn, action) => {
5504
+ if (!btn) return;
5505
+ btn.setAttribute('tabindex', '-1');
5506
+ let touchHandled = false;
5507
+ btn.addEventListener('touchstart', (e) => {
5508
+ if (this.isMobile) e.preventDefault();
5509
+ touchHandled = true;
5510
+ }, { passive: false });
5511
+ btn.addEventListener('touchend', (e) => {
5512
+ e.preventDefault();
5513
+ touchHandled = true;
5514
+ action();
5515
+ }, { passive: false });
5516
+ btn.addEventListener('mousedown', (e) => {
5517
+ if (this.isMobile) e.preventDefault();
5518
+ });
5519
+ btn.addEventListener('click', () => {
5520
+ if (touchHandled) { touchHandled = false; return; }
5521
+ action();
5522
+ });
5523
+ };
5524
+
5525
+ attachSttAction(sttRecordBtn, () => this._toggleSttRecord());
5526
+ // Wand: pipe transcript through LLM proxy and replace text in place.
5527
+ attachSttAction(sttWandBtn, () => this._sttRunWand());
5528
+
5529
+ if (sttSendBtn) {
5530
+ sttSendBtn.setAttribute('tabindex', '-1');
5531
+ const sendStt = async () => {
5532
+ // If still recording/paused, stop the mic first (any pending audio
5533
+ // that hasn't been transcribed yet is discarded — Send sends what's
5534
+ // currently in the textarea).
5535
+ if (this._sttRecorder && this._sttRecorder.state !== 'inactive') {
5536
+ try { this._sttRecorder.stop(); } catch (_) {}
5537
+ this._cleanupSttRecording();
5538
+ this._resetSttRecordButton();
5539
+ }
5540
+ const transcript = document.getElementById('sttTranscript');
5541
+ const text = transcript ? transcript.value : '';
5542
+ if (text) {
5543
+ const session = this.sessions.get(this.activeSessionId);
5544
+ // Pipe text to the remote shell via the SSH socket channel so the
5545
+ // shell actually receives it as input. terminal.write() would only
5546
+ // paint pixels locally and the keystrokes would never reach the
5547
+ // server (backspace/enter had no effect because the shell never
5548
+ // saw the input).
5549
+ if (session && session.type === 'ssh' && session.id && session.connected && session.isController) {
5550
+ this.socket.emit('ssh-data', { sessionId: session.id, data: text });
5551
+ } else if (session && session.type === 'ssh' && session.terminal) {
5552
+ // Fallback (non-controller or disconnected): at least render
5553
+ // locally so the user sees what would have been sent.
5554
+ session.terminal.write(text);
5555
+ this.showToast('Not connected as controller — text not sent', 'warning');
5556
+ } else if (session && session.terminal) {
5557
+ session.terminal.write(text);
5558
+ }
5559
+ }
5560
+ closeSpeechToTextModal();
5561
+ };
5562
+ let sendTouchHandled = false;
5563
+ sttSendBtn.addEventListener('touchstart', (e) => {
5564
+ if (this.isMobile) e.preventDefault();
5565
+ sendTouchHandled = true;
5566
+ }, { passive: false });
5567
+ sttSendBtn.addEventListener('touchend', (e) => {
5568
+ e.preventDefault();
5569
+ sendTouchHandled = true;
5570
+ sendStt();
5571
+ }, { passive: false });
5572
+ sttSendBtn.addEventListener('mousedown', (e) => {
5573
+ if (this.isMobile) e.preventDefault();
5574
+ });
5575
+ sttSendBtn.addEventListener('click', () => {
5576
+ if (sendTouchHandled) { sendTouchHandled = false; return; }
5577
+ sendStt();
5578
+ });
5579
+ }
5124
5580
 
5125
5581
  const closeSpecialKeysBtn = document.getElementById('closeSpecialKeysModal');
5126
5582
  closeSpecialKeysBtn.setAttribute('tabindex', '-1');
@@ -5144,6 +5600,42 @@ const wheelHandler = (e) => {
5144
5600
  this.focusTerminal();
5145
5601
  });
5146
5602
 
5603
+ // Speech & AI settings — show/hide auth key toggles + Reset wand prompt
5604
+ const toggleSttAuth = document.getElementById('toggleSttAuthKey');
5605
+ if (toggleSttAuth) {
5606
+ toggleSttAuth.addEventListener('click', () => {
5607
+ const input = document.getElementById('sttAuthKey');
5608
+ const icon = toggleSttAuth.querySelector('i');
5609
+ if (!input) return;
5610
+ if (input.type === 'password') {
5611
+ input.type = 'text';
5612
+ if (icon) icon.classList.replace('fa-eye', 'fa-eye-slash');
5613
+ } else {
5614
+ input.type = 'password';
5615
+ if (icon) icon.classList.replace('fa-eye-slash', 'fa-eye');
5616
+ }
5617
+ });
5618
+ }
5619
+ const toggleLlmAuth = document.getElementById('toggleLlmAuthKey');
5620
+ if (toggleLlmAuth) {
5621
+ toggleLlmAuth.addEventListener('click', () => {
5622
+ const input = document.getElementById('llmAuthKey');
5623
+ const icon = toggleLlmAuth.querySelector('i');
5624
+ if (!input) return;
5625
+ if (input.type === 'password') {
5626
+ input.type = 'text';
5627
+ if (icon) icon.classList.replace('fa-eye', 'fa-eye-slash');
5628
+ } else {
5629
+ input.type = 'password';
5630
+ if (icon) icon.classList.replace('fa-eye-slash', 'fa-eye');
5631
+ }
5632
+ });
5633
+ }
5634
+ const resetWandBtn = document.getElementById('resetWandPromptBtn');
5635
+ if (resetWandBtn) {
5636
+ resetWandBtn.addEventListener('click', () => this.resetWandPromptToDefault());
5637
+ }
5638
+
5147
5639
  // Special key buttons
5148
5640
  const specialKeysModal = document.getElementById('specialKeysModal');
5149
5641
  document.querySelectorAll('.key-btn').forEach(btn => {
@@ -5189,6 +5681,10 @@ const wheelHandler = (e) => {
5189
5681
  this.handleFontSizeChange('panel-0', -1);
5190
5682
  });
5191
5683
 
5684
+ // Initialise terminal-only tab action gating (disabled until an SSH
5685
+ // session becomes active in the panel).
5686
+ this.updateTabActionButtons('panel-0');
5687
+
5192
5688
  // SFTP modal - now handled via tabs, keeping for backward compatibility
5193
5689
  // These event listeners are no longer needed but kept for reference
5194
5690
  // SFTP is now opened in tabs instead of modal
@@ -5403,13 +5899,101 @@ const wheelHandler = (e) => {
5403
5899
 
5404
5900
  // Load plugins
5405
5901
  this.loadPlugins();
5406
-
5902
+
5903
+ // Load Speech & AI config from server (auth keys are redacted by the
5904
+ // server — we only get back a "set" flag and fill the auth inputs with
5905
+ // the sentinel placeholder so unchanged values aren't overwritten on save).
5906
+ this.loadSpeechAiConfig().catch(err => {
5907
+ console.error('[SSHIFT] Failed to load Speech & AI config:', err);
5908
+ });
5909
+
5407
5910
  // Reset to first category
5408
5911
  this.switchSettingsCategory('sessions');
5409
5912
 
5410
5913
  this.openModal('settingsModal');
5411
5914
  }
5412
5915
 
5916
+ // ---- Speech & AI: settings load/save ---------------------------------
5917
+ // Auth keys are never sent back to the client. When the user doesn't type
5918
+ // a new one, we post the "__UNCHANGED__" sentinel so the server preserves
5919
+ // the existing value.
5920
+ async loadSpeechAiConfig() {
5921
+ const res = await fetch('/api/speech-ai/config');
5922
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
5923
+ const cfg = await res.json();
5924
+ this._speechAiConfig = cfg;
5925
+
5926
+ const set = (id, val) => { const el = document.getElementById(id); if (el) el.value = val; };
5927
+ set('sttEndpoint', cfg.sttEndpoint || '');
5928
+ set('sttLanguage', cfg.sttLanguage || '');
5929
+ set('llmEndpoint', cfg.llmEndpoint || '');
5930
+ set('llmModel', cfg.llmModel || '');
5931
+ set('wandSystemPrompt', cfg.wandSystemPrompt || '');
5932
+
5933
+ // Auth keys: redacted. Show a placeholder describing current state and
5934
+ // leave the input blank so a Save without typing keeps the existing key.
5935
+ const sttAuth = document.getElementById('sttAuthKey');
5936
+ if (sttAuth) {
5937
+ sttAuth.value = '';
5938
+ sttAuth.placeholder = cfg.sttAuthKeySet
5939
+ ? 'API key set — leave blank to keep'
5940
+ : 'sk-...';
5941
+ }
5942
+ const llmAuth = document.getElementById('llmAuthKey');
5943
+ if (llmAuth) {
5944
+ llmAuth.value = '';
5945
+ llmAuth.placeholder = cfg.llmAuthKeySet
5946
+ ? 'API key set — leave blank to keep'
5947
+ : 'sk-...';
5948
+ }
5949
+ }
5950
+
5951
+ async saveSpeechAiConfig() {
5952
+ const val = (id) => { const el = document.getElementById(id); return el ? el.value : ''; };
5953
+ const sttAuth = document.getElementById('sttAuthKey');
5954
+ const llmAuth = document.getElementById('llmAuthKey');
5955
+
5956
+ // Sentinel preserves existing keys when the user didn't type a new one.
5957
+ const sttAuthKey = (sttAuth && sttAuth.value.trim()) ? sttAuth.value.trim() : '__UNCHANGED__';
5958
+ const llmAuthKey = (llmAuth && llmAuth.value.trim()) ? llmAuth.value.trim() : '__UNCHANGED__';
5959
+
5960
+ const body = {
5961
+ sttEndpoint: val('sttEndpoint'),
5962
+ sttLanguage: val('sttLanguage'),
5963
+ llmEndpoint: val('llmEndpoint'),
5964
+ llmModel: val('llmModel'),
5965
+ wandSystemPrompt:val('wandSystemPrompt'),
5966
+ sttAuthKey,
5967
+ llmAuthKey
5968
+ };
5969
+
5970
+ const res = await fetch('/api/speech-ai/config', {
5971
+ method: 'POST',
5972
+ headers: { 'Content-Type': 'application/json' },
5973
+ body: JSON.stringify(body)
5974
+ });
5975
+ if (!res.ok) {
5976
+ const txt = await res.text().catch(() => '');
5977
+ throw new Error(`HTTP ${res.status} ${txt}`);
5978
+ }
5979
+ // Reload so the redacted placeholders reflect the new state.
5980
+ return this.loadSpeechAiConfig();
5981
+ }
5982
+
5983
+ async resetWandPromptToDefault() {
5984
+ try {
5985
+ const res = await fetch('/api/speech-ai/wand-default');
5986
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
5987
+ const data = await res.json();
5988
+ const ta = document.getElementById('wandSystemPrompt');
5989
+ if (ta) ta.value = data.prompt || '';
5990
+ this.showToast('Wand prompt reset to default', 'info');
5991
+ } catch (err) {
5992
+ console.error('[SSHIFT] Failed to load default wand prompt:', err);
5993
+ this.showToast('Failed to load default prompt', 'error');
5994
+ }
5995
+ }
5996
+
5413
5997
  initSettingsModalHandlers() {
5414
5998
  // Settings category navigation (sidebar + mobile dropdown)
5415
5999
  const navItems = document.querySelectorAll('.settings-nav-item');
@@ -5542,6 +6126,14 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
5542
6126
 
5543
6127
  // Save all settings to config
5544
6128
  this.saveStickyConfig();
6129
+
6130
+ // Persist Speech & AI settings (server-side, redacted keys preserved
6131
+ // when the user left the auth inputs blank).
6132
+ this.saveSpeechAiConfig().catch(err => {
6133
+ console.error('[SSHIFT] Failed to save Speech & AI config:', err);
6134
+ this.showToast('Speech & AI settings failed to save', 'error');
6135
+ });
6136
+
5545
6137
  console.log('[SSHIFT] Settings saved - sticky:', this.sticky,
5546
6138
  'takeControlDefault:', this.takeControlDefault,
5547
6139
  'keepaliveInterval:', this.sshKeepaliveInterval,
@@ -9311,6 +9903,9 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9311
9903
  // Update mobile tabs dropdown for this panel
9312
9904
  this.updateMobileTabsDropdown(panelId);
9313
9905
 
9906
+ // Enable/disable terminal-only tab actions (keyboard + mic) for this panel
9907
+ this.updateTabActionButtons(panelId);
9908
+
9314
9909
  // Save tabs
9315
9910
  this.saveTabs();
9316
9911
  }