@lethevimlet/sshift 1.5.1 → 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.
@@ -756,7 +756,7 @@ class SSHIFTClient {
756
756
  // Update active sessions:
757
757
  // 1. Make the moved tab active in the target panel
758
758
  this.switchTab(sessionId, targetPanelId);
759
-
759
+
760
760
  // 2. Activate the first remaining tab in the source panel (if any)
761
761
  if (sourceTabs.length > 0) {
762
762
  const firstRemainingSessionId = sourceTabs[0].dataset.sessionId;
@@ -770,6 +770,38 @@ class SSHIFTClient {
770
770
 
771
771
  // Update server panel map for mobile preservation
772
772
  this._serverPanelMap.set(sessionId, targetPanelId);
773
+
774
+ // After moving the terminal wrapper to a new container, the
775
+ // terminal's internal canvas/renderer dimensions are still tied
776
+ // to the old panel's size. The WebGL atlas has glyphs rasterised
777
+ // for the old cell size. If we fit() immediately the browser
778
+ // hasn't committed the new layout yet, so fit() measures stale
779
+ // dimensions — producing the interlaced/alternating-black-band
780
+ // rendering bug. Fix: double-RAF to let the browser commit the
781
+ // new layout, then fit + clear atlas + force refresh.
782
+ // Also refit ALL terminals (the source panel's remaining tab may
783
+ // have changed container size too).
784
+ const session = this.sessions.get(sessionId);
785
+ if (session && session.terminal && session.fitAddon && session.isController) {
786
+ requestAnimationFrame(() => {
787
+ requestAnimationFrame(() => {
788
+ if (!session.terminal || !session.fitAddon || !session.isController) return;
789
+ // Re-measure char size (font may have loaded differently in
790
+ // the new container) then fit, clear atlas, and refresh.
791
+ const core = session.terminal._core;
792
+ if (core && core._charSizeService && typeof core._charSizeService.measure === 'function') {
793
+ try { core._charSizeService.measure(); } catch (_) {}
794
+ }
795
+ this._fitTerminal(session);
796
+ this._resetWebGLAtlas(session);
797
+ });
798
+ });
799
+ }
800
+
801
+ // Refit ALL visible terminals — the source panel's remaining tab
802
+ // may have a different container width now that the moved tab is
803
+ // gone. Use the existing staggered refit helper.
804
+ this.refitAllTerminals();
773
805
  }
774
806
 
775
807
  // Hide empty state for a specific panel
@@ -2426,6 +2458,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2426
2458
  specialKeysBtn.title = 'Special Keys';
2427
2459
  specialKeysBtn.innerHTML = '<i class="fas fa-keyboard"></i>';
2428
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);
2429
2468
 
2430
2469
  container.appendChild(actions);
2431
2470
 
@@ -2475,22 +2514,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2475
2514
  increaseBtn.addEventListener('click', () => this.handleFontSizeChange(panelId, 1));
2476
2515
  }
2477
2516
 
2478
- // Special keys button
2517
+ // Special keys button — touch + click pattern so it works on mobile & desktop
2479
2518
  const specialKeysBtn = document.getElementById(isSingle ? 'specialKeysBtn' : `${panelId}-specialKeysBtn`);
2480
- if (specialKeysBtn) {
2481
- specialKeysBtn.setAttribute('tabindex', '-1');
2482
- specialKeysBtn.addEventListener('focus', () => {
2483
- specialKeysBtn.blur();
2484
- if (this.isMobile) this.focusTerminal();
2485
- });
2486
- specialKeysBtn.addEventListener('touchstart', (e) => {
2487
- if (this.isMobile) e.preventDefault();
2488
- }, { passive: false });
2489
- specialKeysBtn.addEventListener('mousedown', (e) => {
2490
- if (this.isMobile) e.preventDefault();
2491
- });
2492
- specialKeysBtn.addEventListener('click', () => this.handleSpecialKeys(panelId));
2493
- }
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));
2494
2524
 
2495
2525
  // Quick SSH/SFTP buttons in empty state
2496
2526
  const quickSshBtn = document.getElementById(isSingle ? 'quickSshBtn' : `${panelId}-quickSshBtn`);
@@ -2629,6 +2659,348 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2629
2659
  this.openModal('specialKeysModal');
2630
2660
  }
2631
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
+
2632
3004
  async initLayoutSystem() {
2633
3005
  console.log('[SSHIFT] Initializing layout system...');
2634
3006
 
@@ -2928,20 +3300,59 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2928
3300
  element.addEventListener('touchmove', (e) => {
2929
3301
  if (e.touches.length === 1 && session.isScrolling) {
2930
3302
  e.preventDefault();
2931
-
3303
+
2932
3304
  const currentTouchY = e.touches[0].clientY;
2933
3305
  const touchDiff = session.lastTouchY - currentTouchY;
2934
3306
  session.lastTouchY = currentTouchY;
2935
3307
  session.touchAccumulator += touchDiff;
2936
-
3308
+
2937
3309
  const lineHeight = terminal._core?._renderService?.dimensions?.css?.cell?.height || 20;
2938
3310
  const lineH = Math.max(lineHeight, 14);
2939
-
2940
- const linesToScroll = Math.trunc(Math.abs(session.touchAccumulator) / lineH);
2941
- if (linesToScroll > 0) {
2942
- const direction = session.touchAccumulator > 0 ? 1 : -1;
2943
- terminal.scrollLines(direction * linesToScroll);
2944
- session.touchAccumulator -= direction * linesToScroll * lineH;
3311
+
3312
+ // When a TUI app has mouse tracking enabled (DECSET
3313
+ // 1000/1002/1003), scrolling should send mouse wheel
3314
+ // escape sequences directly to the PTY. Instead of
3315
+ // dispatching synthetic WheelEvents (which xterm's own
3316
+ // document-level touch handler can interfere with), we
3317
+ // generate the SGR mouse format ourselves and emit it via
3318
+ // ssh-data. SGR format: \x1b[<button;col;row;M
3319
+ // Wheel up = button 64, wheel down = button 65.
3320
+ const mouseProtocol = terminal._core?.coreMouseService?.activeProtocol;
3321
+ const tuiMouseActive = mouseProtocol && mouseProtocol !== 'NONE';
3322
+
3323
+ if (tuiMouseActive) {
3324
+ if (Math.abs(session.touchAccumulator) >= lineH) {
3325
+ // Compute the terminal cell under the touch point.
3326
+ const screenEl = terminal.element?.querySelector('.xterm-screen');
3327
+ if (screenEl) {
3328
+ const rect = screenEl.getBoundingClientRect();
3329
+ const cellW = terminal._core?._renderService?.dimensions?.css?.cell?.width || 8;
3330
+ const cellH = lineHeight;
3331
+ const touchX = e.touches[0].clientX - rect.left;
3332
+ const touchY = e.touches[0].clientY - rect.top;
3333
+ const col = Math.max(1, Math.min(terminal.cols, Math.floor(touchX / cellW) + 1));
3334
+ const row = Math.max(1, Math.min(terminal.rows, Math.floor(touchY / cellH) + 1));
3335
+
3336
+ const scrollLines = Math.trunc(Math.abs(session.touchAccumulator) / lineH);
3337
+ const direction = session.touchAccumulator > 0 ? 1 : -1; // 1 = scroll down, -1 = scroll up
3338
+ for (let i = 0; i < scrollLines; i++) {
3339
+ // button 64 = wheel up, 65 = wheel down
3340
+ const button = direction > 0 ? 65 : 64;
3341
+ const seq = `\x1b[<${button};${col};${row}M`;
3342
+ if (session.connected && session.isController) {
3343
+ this.socket.emit('ssh-data', { sessionId, data: seq });
3344
+ }
3345
+ }
3346
+ session.touchAccumulator = 0;
3347
+ }
3348
+ }
3349
+ } else {
3350
+ const linesToScroll = Math.trunc(Math.abs(session.touchAccumulator) / lineH);
3351
+ if (linesToScroll > 0) {
3352
+ const direction = session.touchAccumulator > 0 ? 1 : -1;
3353
+ terminal.scrollLines(direction * linesToScroll);
3354
+ session.touchAccumulator -= direction * linesToScroll * lineH;
3355
+ }
2945
3356
  }
2946
3357
  } else if (e.touches.length === 2 && session.isPinching) {
2947
3358
  e.preventDefault();
@@ -3026,16 +3437,24 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3026
3437
 
3027
3438
  const wheelHandler = (e) => {
3028
3439
  if (e.deltaY === 0) return;
3029
-
3440
+
3030
3441
  // If the event target is inside the custom scrollbar,
3031
3442
  // let xterm's ScrollableElement handle it to avoid double-scroll
3032
3443
  const target = e.target;
3033
3444
  if (target && target.closest && target.closest('.xterm-scrollable-element')) {
3034
3445
  return;
3035
3446
  }
3036
-
3447
+
3448
+ // When a TUI app has mouse tracking enabled, let xterm's own
3449
+ // wheel handler process the event so it translates to mouse
3450
+ // tracking escape sequences sent to the PTY. Don't intercept.
3451
+ const mouseProtocol = terminal._core?.coreMouseService?.activeProtocol;
3452
+ if (mouseProtocol && mouseProtocol !== 'NONE') {
3453
+ return;
3454
+ }
3455
+
3037
3456
  e.preventDefault();
3038
-
3457
+
3039
3458
  let lines = 1;
3040
3459
  if (e.deltaMode === 1) {
3041
3460
  lines = Math.abs(e.deltaY);
@@ -3045,14 +3464,14 @@ const wheelHandler = (e) => {
3045
3464
  } else {
3046
3465
  lines = Math.abs(e.deltaY) * terminal.rows;
3047
3466
  }
3048
-
3467
+
3049
3468
  const fastScrollModifier = terminal.options.fastScrollModifier;
3050
3469
  if (fastScrollModifier === 'alt' && e.altKey ||
3051
3470
  fastScrollModifier === 'ctrl' && e.ctrlKey ||
3052
3471
  fastScrollModifier === 'shift' && e.shiftKey) {
3053
3472
  lines *= (terminal.options.fastScrollSensitivity || 5);
3054
3473
  }
3055
-
3474
+
3056
3475
  terminal.scrollLines((e.deltaY > 0 ? 1 : -1) * lines);
3057
3476
  };
3058
3477
 
@@ -4474,11 +4893,11 @@ const wheelHandler = (e) => {
4474
4893
  }
4475
4894
  } else if (data.advisory) {
4476
4895
  // Advisory errors (rate-limit, invalid payload, bufferFull, etc.)
4477
- // are non-fatal — warn via toast but DO NOT close the tab. Closing
4478
- // the tab on every rate-limited ssh-request-sync would kill the
4479
- // very session the user was trying to refresh / switch to.
4896
+ // are operational warnings — log them but do NOT show a toast.
4897
+ // Showing toasts for every rate-limited sync or buffer-full event
4898
+ // is extremely annoying during normal usage like scrolling in a
4899
+ // TUI app.
4480
4900
  console.warn('[SSHIFT] Advisory ssh-error (tab kept open):', data.message);
4481
- this.showToast(data.message, 'warning');
4482
4901
  } else {
4483
4902
  this.showToast(data.message, 'error');
4484
4903
  }
@@ -5026,22 +5445,138 @@ const wheelHandler = (e) => {
5026
5445
  });
5027
5446
  });
5028
5447
 
5029
- // 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).
5030
5450
  const specialKeysBtnEl = document.getElementById('specialKeysBtn');
5031
- specialKeysBtnEl.setAttribute('tabindex', '-1');
5032
- specialKeysBtnEl.addEventListener('focus', () => {
5033
- specialKeysBtnEl.blur();
5034
- if (this.isMobile) this.focusTerminal();
5035
- });
5036
- specialKeysBtnEl.addEventListener('touchstart', (e) => {
5037
- if (this.isMobile) e.preventDefault();
5038
- }, { passive: false });
5039
- specialKeysBtnEl.addEventListener('mousedown', (e) => {
5040
- if (this.isMobile) e.preventDefault();
5041
- });
5042
- specialKeysBtnEl.addEventListener('click', () => {
5043
- this.handleSpecialKeys('panel-0');
5044
- });
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
+ }
5045
5580
 
5046
5581
  const closeSpecialKeysBtn = document.getElementById('closeSpecialKeysModal');
5047
5582
  closeSpecialKeysBtn.setAttribute('tabindex', '-1');
@@ -5065,6 +5600,42 @@ const wheelHandler = (e) => {
5065
5600
  this.focusTerminal();
5066
5601
  });
5067
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
+
5068
5639
  // Special key buttons
5069
5640
  const specialKeysModal = document.getElementById('specialKeysModal');
5070
5641
  document.querySelectorAll('.key-btn').forEach(btn => {
@@ -5110,6 +5681,10 @@ const wheelHandler = (e) => {
5110
5681
  this.handleFontSizeChange('panel-0', -1);
5111
5682
  });
5112
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
+
5113
5688
  // SFTP modal - now handled via tabs, keeping for backward compatibility
5114
5689
  // These event listeners are no longer needed but kept for reference
5115
5690
  // SFTP is now opened in tabs instead of modal
@@ -5324,13 +5899,101 @@ const wheelHandler = (e) => {
5324
5899
 
5325
5900
  // Load plugins
5326
5901
  this.loadPlugins();
5327
-
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
+
5328
5910
  // Reset to first category
5329
5911
  this.switchSettingsCategory('sessions');
5330
5912
 
5331
5913
  this.openModal('settingsModal');
5332
5914
  }
5333
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
+
5334
5997
  initSettingsModalHandlers() {
5335
5998
  // Settings category navigation (sidebar + mobile dropdown)
5336
5999
  const navItems = document.querySelectorAll('.settings-nav-item');
@@ -5463,6 +6126,14 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
5463
6126
 
5464
6127
  // Save all settings to config
5465
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
+
5466
6137
  console.log('[SSHIFT] Settings saved - sticky:', this.sticky,
5467
6138
  'takeControlDefault:', this.takeControlDefault,
5468
6139
  'keepaliveInterval:', this.sshKeepaliveInterval,
@@ -7334,7 +8005,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7334
8005
  fastScrollModifier: 'alt',
7335
8006
  fastScrollSensitivity: 5,
7336
8007
  smoothScrollDuration: 80,
7337
- overviewRuler: { width: 14 },
8008
+ overviewRuler: { width: 0 },
7338
8009
  customGlyphs: true
7339
8010
  });
7340
8011
 
@@ -7843,40 +8514,35 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7843
8514
  }
7844
8515
  });
7845
8516
 
7846
- // Defensive activation on user interaction.
8517
+ // Defensive activation: clear stuck `isResyncing` on user interaction.
7847
8518
  // Backgrounded / throttled browser tabs can leave `isResyncing` set
7848
8519
  // (setTimeout was deferred by the browser's power saver) which
7849
- // suppresses onResize emits. Some browsers also move focus to the
7850
- // body when the tab is hidden, and xterm's mouse input + IME only
7851
- // fire while the terminal's element / hidden textarea has focus.
7852
- // Result: after a period of inactivity on a TUI app, mouse clicks
7853
- // and scroll stop working until the user refreshes. Fix: on every
7854
- // mouse / touch / wheel interaction with the terminal, re-focus
7855
- // xterm and clear any stuck isResyncing flag so subsequent resize
7856
- // events (and TUI mouse-tracking escape sequences) flow through.
7857
- const activateSession = () => {
8520
+ // suppresses onResize emits. After inactivity on a TUI app, mouse
8521
+ // clicks and scroll can stop working until the user refreshes.
8522
+ // Fix: on mouse/wheel interaction (desktop), clear the flag AND
8523
+ // re-focus the terminal so xterm's mouse-service fires.
8524
+ // On mobile touch, ONLY clear the flag — do NOT re-focus the
8525
+ // hidden textarea because that would pop the on-screen keyboard
8526
+ // on every scroll drag. The mobile handler manages keyboard
8527
+ // visibility separately.
8528
+ const clearResyncing = () => {
7858
8529
  if (!session) return;
7859
8530
  if (session.isResyncing) {
7860
- // setTimeout was probably deferred by background throttling.
7861
- // Releasing here lets the next user-initiated resize flow.
7862
8531
  session.isResyncing = false;
7863
8532
  }
7864
- // Re-focus the terminal so xterm's mouse-service fires. Use
7865
- // requestAnimationFrame to avoid stealing focus mid-click on
7866
- // the active selection.
8533
+ };
8534
+ const activateAndFocus = () => {
8535
+ clearResyncing();
7867
8536
  requestAnimationFrame(() => {
7868
- if (session.terminal) {
7869
- if (this.isMobile && session.mobileHandler && session.mobileHandler.hiddenTextarea) {
7870
- session.mobileHandler._focusHiddenTextarea();
7871
- } else {
7872
- try { session.terminal.focus(); } catch (_) {}
7873
- }
8537
+ if (session.terminal && !this.isMobile) {
8538
+ try { session.terminal.focus(); } catch (_) {}
7874
8539
  }
7875
8540
  });
7876
8541
  };
7877
- container.addEventListener('mousedown', activateSession, true);
7878
- container.addEventListener('touchstart', activateSession, true);
7879
- container.addEventListener('wheel', activateSession, true);
8542
+ container.addEventListener('mousedown', activateAndFocus, true);
8543
+ container.addEventListener('wheel', clearResyncing, true);
8544
+ // On mobile, only clear isResyncing on touchstart — do NOT focus.
8545
+ container.addEventListener('touchstart', clearResyncing, true);
7880
8546
 
7881
8547
  session.terminal = terminal;
7882
8548
  session.fitAddon = fitAddon;
@@ -7932,11 +8598,75 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7932
8598
  resizeObserver.observe(wrapper);
7933
8599
  session.resizeObserver = resizeObserver;
7934
8600
 
8601
+ // Keep xterm's scrollbar dimensions + slider bg consistent.
8602
+ // xterm sets inline width: 14px and bg: rgb(73,77,83) on the
8603
+ // slider every time it re-renders; a MutationObserver catches
8604
+ // each change and overrides it back.
8605
+ {
8606
+ const targetW = this.isMobile ? '4px' : '8px';
8607
+ const fixScrollbar = () => {
8608
+ const sbs = wrapper.querySelectorAll('.xterm-scrollable-element > .scrollbar.vertical');
8609
+ sbs.forEach(sb => {
8610
+ if (sb.style.width !== targetW) {
8611
+ sb.style.width = targetW;
8612
+ sb.style.minWidth = targetW;
8613
+ sb.style.maxWidth = targetW;
8614
+ }
8615
+ const slider = sb.querySelector('.slider');
8616
+ if (slider) {
8617
+ if (slider.style.width !== targetW) {
8618
+ slider.style.width = targetW;
8619
+ slider.style.minWidth = targetW;
8620
+ slider.style.maxWidth = targetW;
8621
+ }
8622
+ // Override xterm's inline !important bg (lighter shade
8623
+ // that looks like a white line) with a dark thumb color.
8624
+ slider.style.setProperty('background-color', '#3d444d', 'important');
8625
+ }
8626
+ });
8627
+ };
8628
+ requestAnimationFrame(fixScrollbar);
8629
+ const mo = new MutationObserver(fixScrollbar);
8630
+ const scrollableEl = wrapper.querySelector('.xterm-scrollable-element');
8631
+ if (scrollableEl) {
8632
+ mo.observe(scrollableEl, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
8633
+ }
8634
+ session._scrollbarObserver = mo;
8635
+ }
8636
+
7935
8637
  // Setup mobile scroll behavior after terminal is ready
7936
8638
  // Use requestAnimationFrame to ensure terminal.element is available
7937
8639
  requestAnimationFrame(() => {
7938
8640
  this.setupMobileScrollBehavior(sessionId);
7939
8641
  this.setupWheelScroll(sessionId);
8642
+
8643
+ // Force thinner scrollbar on mobile. xterm v6 sets an inline
8644
+ // width: 14px on the vertical scrollbar AND its slider — override
8645
+ // both via inline style since CSS !important on the slider doesn't
8646
+ // always survive against xterm's re-renders.
8647
+ // On desktop, override the slider bg color which xterm sets inline
8648
+ // to rgb(73,77,83) — a lighter shade that looks like a white line
8649
+ // against the dark terminal background.
8650
+ const targetWidth = this.isMobile ? '4px' : '8px';
8651
+ {
8652
+ const scrollbars = wrapper.querySelectorAll('.xterm-scrollable-element > .scrollbar');
8653
+ scrollbars.forEach(sb => {
8654
+ if (sb.classList.contains('vertical')) {
8655
+ sb.style.width = targetWidth;
8656
+ sb.style.minWidth = targetWidth;
8657
+ sb.style.maxWidth = targetWidth;
8658
+ const slider = sb.querySelector('.slider');
8659
+ if (slider) {
8660
+ slider.style.width = targetWidth;
8661
+ slider.style.minWidth = targetWidth;
8662
+ slider.style.maxWidth = targetWidth;
8663
+ // Override xterm's inline !important bg with a dark shade
8664
+ // that's visible but doesn't look like a white line.
8665
+ slider.style.setProperty('background-color', '#3d444d', 'important');
8666
+ }
8667
+ }
8668
+ });
8669
+ }
7940
8670
  });
7941
8671
 
7942
8672
  console.log('[SSHIFT] Terminal initialized for session:', sessionId);
@@ -9173,6 +9903,9 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9173
9903
  // Update mobile tabs dropdown for this panel
9174
9904
  this.updateMobileTabsDropdown(panelId);
9175
9905
 
9906
+ // Enable/disable terminal-only tab actions (keyboard + mic) for this panel
9907
+ this.updateTabActionButtons(panelId);
9908
+
9176
9909
  // Save tabs
9177
9910
  this.saveTabs();
9178
9911
  }
@@ -9203,6 +9936,11 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9203
9936
  clearTimeout(session.resizeTimeout);
9204
9937
  session.resizeTimeout = null;
9205
9938
  }
9939
+ // Clean up scrollbar MutationObserver (mobile-only)
9940
+ if (session._scrollbarObserver) {
9941
+ session._scrollbarObserver.disconnect();
9942
+ session._scrollbarObserver = null;
9943
+ }
9206
9944
  // Clean up write buffer RAF
9207
9945
  if (session.writeRAF) {
9208
9946
  cancelAnimationFrame(session.writeRAF);