@lethevimlet/sshift 1.5.2 → 1.6.1

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.
@@ -1043,6 +1043,34 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1043
1043
  session.terminal.refresh(0, session.terminal.rows - 1);
1044
1044
  }
1045
1045
 
1046
+ // Synchronously commit the renderer's cell dimensions after a font-size
1047
+ // (or font-family) option change, then clear the glyph atlas.
1048
+ //
1049
+ // xterm.js v6 invalidates _renderService.dimensions ASYNCHRONOUSLY when an
1050
+ // option like fontSize is set: the CharSizeService only re-measures on the
1051
+ // next change tick. If fitAddon.fit() runs in the same synchronous frame
1052
+ // it reads the STALE (pre-invalidation) cell height/width, so cols/rows are
1053
+ // computed for one cell size while the renderer later paints at another.
1054
+ // That mismatch paints every other row as an empty black band — the
1055
+ // "interlace" bug (see comments at the Terminal construction path and at
1056
+ // _fitTerminal). Calling _charSizeService.measure() fires
1057
+ // onCharSizeChange synchronously, which the RenderService forwards to the
1058
+ // renderer's handleCharSizeChanged so _updateDimensions runs BEFORE fit.
1059
+ // This mirrors the proven fix used after document.fonts.ready at
1060
+ // construction time. Without this, switchTab/setSessionFontSize race the
1061
+ // fit and the terminal renders interlaced until a window resize forces a
1062
+ // clean re-fit.
1063
+ _syncCharSizeThenClearAtlas(session) {
1064
+ if (!session || !session.terminal) return;
1065
+ const core = session.terminal._core;
1066
+ if (core && core._charSizeService && typeof core._charSizeService.measure === 'function') {
1067
+ try { core._charSizeService.measure(); } catch (_) {}
1068
+ }
1069
+ if (session.webglAddon) {
1070
+ try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
1071
+ }
1072
+ }
1073
+
1046
1074
  // Sub-pixel seam mitigation is handled by canvas/WebGL renderer +
1047
1075
  // customGlyphs: true, which draws block/box characters as vector fills
1048
1076
  // that meet exactly. letterSpacing nudging doesn't work because xterm.js
@@ -1342,12 +1370,103 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1342
1370
 
1343
1371
  if (!wrapper.classList.contains('active')) {
1344
1372
  this.switchTab(sessionId);
1345
- setTimeout(() => this._fitTerminal(session), 50);
1373
+ setTimeout(() => this.forceResizeLikeRefit(session), 50);
1346
1374
  } else {
1347
- this._fitTerminal(session);
1375
+ // Use the resize-like refit (synchronous reflow + measure + fit +
1376
+ // clearTextureAtlas + refresh) — this is the user-facing "terminal
1377
+ // looks wrong, force a resize" button, so it should do everything a
1378
+ // real window resize does, not just fit().
1379
+ this.forceResizeLikeRefit(session);
1348
1380
  }
1349
1381
  }
1350
1382
 
1383
+ // Force a refit that behaves like a real window resize for one session.
1384
+ //
1385
+ // A real browser resize reliably clears the interlace ("black band")
1386
+ // rendering artefact because it:
1387
+ // 1. forces the browser to COMMIT any pending layout synchronously before
1388
+ // any handler reads dimensions, and
1389
+ // 2. fires the terminal's ResizeObserver + the global `resize` event.
1390
+ //
1391
+ // The existing safety refits (setTimeout/requestAnimationFrame in switchTab
1392
+ // and the take-control paths) can run BEFORE the browser has committed the
1393
+ // post-visibility / post-font-swap layout, so _fitTerminal measures a
1394
+ // transient container size and the WebGL atlas ends up rasterising glyphs
1395
+ // at a cell pitch that no longer matches the committed cell layout → bands.
1396
+ //
1397
+ // This helper replicates the two guarantees of a real resize, in order:
1398
+ // a) read offsetWidth/offsetHeight on the wrapper AND container — a
1399
+ // synchronous reflow that forces layout to commit NOW,
1400
+ // b) synchronously commit the renderer's cell metrics (measure()) so
1401
+ // fit() reads the current cell size, not a stale one,
1402
+ // c) fitAddon.fit() (which internally calls resize() / onResize),
1403
+ // d) clearTextureAtlas() + refresh() so the WebGL glyph cache is rebuilt
1404
+ // at the committed cell pitch (this is what actually kills the bands),
1405
+ // e) notify the remote PTY of the corrected cols/rows if this is a
1406
+ // connected controller session.
1407
+ //
1408
+ // Returns true on success, false if the session/container isn't usable.
1409
+ forceResizeLikeRefit(session, { emit = true } = {}) {
1410
+ if (!session || !session.terminal || !session.fitAddon) return false;
1411
+ const wrapper = document.getElementById(`terminal-wrapper-${session.id}`);
1412
+ const container = document.getElementById(`terminal-${session.id}`);
1413
+ if (!wrapper || !container) return false;
1414
+
1415
+ // (a) Synchronous reflow — force the browser to commit layout NOW.
1416
+ // This is what a real window resize does implicitly before handlers
1417
+ // run, and what setTimeout-based refits cannot guarantee.
1418
+ void wrapper.offsetWidth;
1419
+ void wrapper.offsetHeight;
1420
+ void container.offsetWidth;
1421
+ void container.offsetHeight;
1422
+
1423
+ // (b) Commit the renderer's cell metrics before fit reads them.
1424
+ this._syncCharSizeThenClearAtlas(session);
1425
+
1426
+ // (c) Fit (resize the terminal buffer to the now-committed container).
1427
+ let ok = false;
1428
+ try {
1429
+ session.fitAddon.fit();
1430
+ ok = true;
1431
+ } catch (e) {
1432
+ console.warn('[SSHIFT] forceResizeLikeRefit: fit failed:', e.message);
1433
+ }
1434
+
1435
+ // (d) Rebuild the WebGL glyph atlas at the committed cell pitch + repaint.
1436
+ // This is the step that actually clears the interlace bands: a stale
1437
+ // atlas rasters glyphs at the old (smaller) row pitch and the renderer
1438
+ // paints them at the new (taller) pitch, leaving every other row dark.
1439
+ if (session.terminal) {
1440
+ if (session.webglAddon) {
1441
+ try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
1442
+ }
1443
+ try { session.terminal.refresh(0, session.terminal.rows - 1); } catch (_) {}
1444
+ }
1445
+
1446
+ // (e) Notify the remote PTY of the corrected dimensions. Mirror the
1447
+ // debounced onResize handler but fire immediately so the server's
1448
+ // PTY matches our terminal within this frame. Only emit for a
1449
+ // connected controller SSH/SFTP session (non-controllers get the
1450
+ // resize via the sticky sync).
1451
+ if (emit && ok && session.connected && session.isController && session.terminal) {
1452
+ const sid = session.id;
1453
+ const cols = session.terminal.cols;
1454
+ const rows = session.terminal.rows;
1455
+ if (cols && rows) {
1456
+ try {
1457
+ if (session.resizeTimeout) {
1458
+ clearTimeout(session.resizeTimeout);
1459
+ session.resizeTimeout = null;
1460
+ }
1461
+ // Emit synchronously (we already debounced upstream by only calling
1462
+ // this on discrete events: take-control / panel grab settlement).
1463
+ this.socket.emit('ssh-resize', { sessionId: sid, cols, rows });
1464
+ } catch (_) {}
1465
+ }
1466
+ }
1467
+ return ok;
1468
+ }
1469
+
1351
1470
  // Set font size for a specific session
1352
1471
  setSessionFontSize(sessionId, size) {
1353
1472
  const session = this.sessions.get(sessionId);
@@ -1362,12 +1481,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1362
1481
  // Update session's font size
1363
1482
  session.fontSize = size;
1364
1483
 
1365
- // Update the terminal
1484
+ // Update the terminal. Setting fontSize async-invalidates the
1485
+ // renderer dimensions; commit the new cell size synchronously
1486
+ // (measure) before fit() reads it, otherwise cols/rows are
1487
+ // computed from a stale cell height and the terminal paints
1488
+ // interlaced black bands (the "interlace" bug).
1366
1489
  session.terminal.options.fontSize = size;
1367
-
1368
- // Font-size changes invalidate the glyph atlas — clear it so
1369
- // glyphs are re-rasterised at the new size.
1370
- this._resetWebGLAtlas(session);
1490
+ this._syncCharSizeThenClearAtlas(session);
1371
1491
 
1372
1492
  if (session.fitAddon && session.isController) {
1373
1493
  this._fitTerminal(session);
@@ -1392,11 +1512,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1392
1512
 
1393
1513
  this.terminalFontSize = size;
1394
1514
 
1395
- // Update all active SSH terminals
1515
+ // Update all active SSH terminals. Commit the new cell size
1516
+ // synchronously (measure) before fit() so it doesn't read the
1517
+ // stale pre-invalidation cell height and paint interlaced bands.
1396
1518
  this.sessions.forEach((session) => {
1397
1519
  if (session.terminal) {
1398
1520
  session.terminal.options.fontSize = size;
1399
- this._resetWebGLAtlas(session);
1521
+ this._syncCharSizeThenClearAtlas(session);
1400
1522
  if (session.fitAddon && session.isController) {
1401
1523
  this._fitTerminal(session);
1402
1524
  }
@@ -1409,7 +1531,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1409
1531
  this.sftpSessions.forEach((session) => {
1410
1532
  if (session.terminal) {
1411
1533
  session.terminal.options.fontSize = size;
1412
- this._resetWebGLAtlas(session);
1534
+ this._syncCharSizeThenClearAtlas(session);
1413
1535
  if (session.fitAddon) {
1414
1536
  this._fitTerminal(session);
1415
1537
  }
@@ -2458,6 +2580,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2458
2580
  specialKeysBtn.title = 'Special Keys';
2459
2581
  specialKeysBtn.innerHTML = '<i class="fas fa-keyboard"></i>';
2460
2582
  actions.appendChild(specialKeysBtn);
2583
+
2584
+ const speechToTextBtn = document.createElement('button');
2585
+ speechToTextBtn.className = 'btn btn-sm';
2586
+ speechToTextBtn.id = isSingle ? 'speechToTextBtn' : `${panelId}-speechToTextBtn`;
2587
+ speechToTextBtn.title = 'Speech to Text';
2588
+ speechToTextBtn.innerHTML = '<i class="fas fa-microphone"></i>';
2589
+ actions.appendChild(speechToTextBtn);
2461
2590
 
2462
2591
  container.appendChild(actions);
2463
2592
 
@@ -2507,22 +2636,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2507
2636
  increaseBtn.addEventListener('click', () => this.handleFontSizeChange(panelId, 1));
2508
2637
  }
2509
2638
 
2510
- // Special keys button
2639
+ // Special keys button — touch + click pattern so it works on mobile & desktop
2511
2640
  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
- }
2641
+ this._wireActionBtn(specialKeysBtn, () => this.handleSpecialKeys(panelId));
2642
+
2643
+ // Speech-to-text button (terminal tabs only — gating handled in handler)
2644
+ const speechToTextBtn = document.getElementById(isSingle ? 'speechToTextBtn' : `${panelId}-speechToTextBtn`);
2645
+ this._wireActionBtn(speechToTextBtn, () => this.handleSpeechToText(panelId));
2526
2646
 
2527
2647
  // Quick SSH/SFTP buttons in empty state
2528
2648
  const quickSshBtn = document.getElementById(isSingle ? 'quickSshBtn' : `${panelId}-quickSshBtn`);
@@ -2621,10 +2741,12 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2621
2741
  const currentSize = sftpSession.fontSize || this.terminalFontSize;
2622
2742
  const newSize = currentSize + delta;
2623
2743
 
2624
- // Set font size for this SFTP session
2744
+ // Set font size for this SFTP session. Commit the new cell size
2745
+ // synchronously (measure) before fit() so it doesn't read a stale
2746
+ // cell height and paint interlaced black bands (the "interlace" bug).
2625
2747
  sftpSession.fontSize = Math.max(this.minFontSize, Math.min(this.maxFontSize, newSize));
2626
2748
  sftpSession.terminal.options.fontSize = sftpSession.fontSize;
2627
- this._resetWebGLAtlas(sftpSession);
2749
+ this._syncCharSizeThenClearAtlas(sftpSession);
2628
2750
 
2629
2751
  if (sftpSession.fitAddon) {
2630
2752
  this._fitTerminal(sftpSession);
@@ -2661,6 +2783,348 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2661
2783
  this.openModal('specialKeysModal');
2662
2784
  }
2663
2785
 
2786
+ handleSpeechToText(panelId) {
2787
+ console.log('[SSHIFT] Open speech-to-text for panel:', panelId);
2788
+
2789
+ const activeSessionId = this.activeSessionsByPanel.get(panelId);
2790
+
2791
+ if (!activeSessionId) {
2792
+ this.showToast('No active session in this panel', 'warning');
2793
+ return;
2794
+ }
2795
+
2796
+ const session = this.sessions.get(activeSessionId);
2797
+ if (!session || session.type !== 'ssh') {
2798
+ this.showToast('Speech to text only works in SSH sessions', 'warning');
2799
+ return;
2800
+ }
2801
+
2802
+ // Set this as the active session so Send writes to the right terminal
2803
+ this.activeSessionId = activeSessionId;
2804
+
2805
+ // Reset transcript + record button state for a fresh session
2806
+ const transcript = document.getElementById('sttTranscript');
2807
+ if (transcript) transcript.value = '';
2808
+ this._resetSttRecordButton();
2809
+
2810
+ // Open the speech-to-text modal (TTS/record/wand logic comes later)
2811
+ this.openModal('speechToTextModal');
2812
+ }
2813
+
2814
+ // Wire a tab-action button (keyboard, mic, etc.) with the standard
2815
+ // touch+click pattern used throughout the app. On touch devices, the
2816
+ // action fires from touchend (with a dedupe flag so the synthetic
2817
+ // click doesn't double-fire). On non-touch devices, the action fires
2818
+ // from click. The focus handler keeps focus on the terminal so the
2819
+ // virtual keyboard never pops up when the user taps a tab-action button.
2820
+ _wireActionBtn(btn, action) {
2821
+ if (!btn) return;
2822
+ btn.setAttribute('tabindex', '-1');
2823
+ btn.addEventListener('focus', () => {
2824
+ btn.blur();
2825
+ if (this.isMobile) this.focusTerminal();
2826
+ });
2827
+ let touchHandled = false;
2828
+ btn.addEventListener('touchstart', (e) => {
2829
+ if (this.isMobile) e.preventDefault();
2830
+ touchHandled = true;
2831
+ }, { passive: false });
2832
+ btn.addEventListener('touchend', (e) => {
2833
+ e.preventDefault();
2834
+ touchHandled = true;
2835
+ action();
2836
+ }, { passive: false });
2837
+ btn.addEventListener('mousedown', (e) => {
2838
+ if (this.isMobile) e.preventDefault();
2839
+ });
2840
+ btn.addEventListener('click', () => {
2841
+ if (touchHandled) { touchHandled = false; return; }
2842
+ action();
2843
+ });
2844
+ }
2845
+
2846
+ // Cycle the merged Record/Pause button. Solving for the cleanest UX:
2847
+ // idle (label "Record") —— click ——> recording (label "Pause", red pulse)
2848
+ // recording —— click ——> stop & transcribe ——> back to idle
2849
+ // "Pause" therefore really means "stop+transcribe", with the next Record
2850
+ // appending additional speech to the same transcript. This avoids a 4-state
2851
+ // cycle (record/pause/resume/stop) and matches the spec of "the same button
2852
+ // for record and pause depending on state" — when not recording it's Record,
2853
+ // when recording it's Pause.
2854
+ async _toggleSttRecord() {
2855
+ const btn = document.getElementById('sttRecordBtn');
2856
+ if (!btn) return;
2857
+ const labelEl = btn.querySelector('.stt-btn-label');
2858
+ const iconEl = btn.querySelector('i');
2859
+
2860
+ if (btn.classList.contains('recording')) {
2861
+ // recording -> stop & transcribe
2862
+ btn.classList.remove('recording');
2863
+ if (iconEl) iconEl.className = 'fas fa-microphone';
2864
+ if (labelEl) labelEl.textContent = 'Record';
2865
+ btn.title = 'Start / Pause / Resume recording';
2866
+ btn.disabled = true;
2867
+ try {
2868
+ await this._sttStopAndTranscribe();
2869
+ } finally {
2870
+ btn.disabled = false;
2871
+ }
2872
+ return;
2873
+ }
2874
+
2875
+ // idle -> recording
2876
+ try {
2877
+ await this._startSttRecording();
2878
+ btn.classList.add('recording');
2879
+ if (iconEl) iconEl.className = 'fas fa-pause';
2880
+ if (labelEl) labelEl.textContent = 'Pause';
2881
+ btn.title = 'Stop recording and transcribe';
2882
+ } catch (err) {
2883
+ console.error('[SSHIFT] STT start failed:', err);
2884
+ this.showToast('Could not start recording: ' + (err.message || err), 'error');
2885
+ this._resetSttRecordButton();
2886
+ }
2887
+ }
2888
+
2889
+ // Stop the recorder (without resetting the button UI) and return the
2890
+ // resulting audio Blob. Resolves to null if nothing was recorded.
2891
+ _stopSttRecording() {
2892
+ return new Promise((resolve) => {
2893
+ const rec = this._sttRecorder;
2894
+ if (!rec || rec.state === 'inactive') {
2895
+ resolve(null);
2896
+ return;
2897
+ }
2898
+ const chunks = this._sttChunks || [];
2899
+ const finish = () => {
2900
+ try {
2901
+ const type = rec.mimeType || 'audio/webm';
2902
+ resolve(new Blob(chunks, { type }));
2903
+ } catch (e) {
2904
+ resolve(null);
2905
+ }
2906
+ };
2907
+ rec.addEventListener('stop', finish, { once: true });
2908
+ try { rec.requestData(); } catch (_) {}
2909
+ try { rec.stop(); } catch (_) { resolve(null); }
2910
+ if (this._sttStream) {
2911
+ this._sttStream.getTracks().forEach(t => { try { t.stop(); } catch (_) {} });
2912
+ this._sttStream = null;
2913
+ }
2914
+ });
2915
+ }
2916
+
2917
+ async _startSttRecording() {
2918
+ if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
2919
+ throw new Error('Microphone access is not available in this browser');
2920
+ }
2921
+
2922
+ // Tear down any previous session first.
2923
+ this._cleanupSttRecording();
2924
+
2925
+ const stream = await navigator.mediaDevices.getUserMedia({
2926
+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
2927
+ video: false
2928
+ });
2929
+ this._sttStream = stream;
2930
+ this._sttChunks = [];
2931
+
2932
+ // Pick a supported mime type: webm/opus first (Chrome), then ogg, then
2933
+ // whatever the browser offers. DeepInfra's whisper endpoint accepts the
2934
+ // common container formats.
2935
+ const candidates = [
2936
+ 'audio/webm;codecs=opus',
2937
+ 'audio/webm',
2938
+ 'audio/ogg;codecs=opus',
2939
+ 'audio/ogg',
2940
+ 'audio/mp4'
2941
+ ];
2942
+ const mimeType = candidates.find(c => window.MediaRecorder && MediaRecorder.isTypeSupported(c)) || '';
2943
+
2944
+ const recorder = mimeType
2945
+ ? new MediaRecorder(stream, { mimeType })
2946
+ : new MediaRecorder(stream);
2947
+ this._sttRecorder = recorder;
2948
+ this._sttRecorderMime = mimeType || recorder.mimeType || 'audio/webm';
2949
+
2950
+ recorder.addEventListener('dataavailable', (e) => {
2951
+ if (e.data && e.data.size > 0) this._sttChunks.push(e.data);
2952
+ });
2953
+
2954
+ recorder.start(1000); // collect data in 1s chunks so stop() is fast
2955
+ }
2956
+
2957
+ _cleanupSttRecording() {
2958
+ try {
2959
+ if (this._sttRecorder && this._sttRecorder.state !== 'inactive') {
2960
+ this._sttRecorder.stop();
2961
+ }
2962
+ } catch (_) {}
2963
+ if (this._sttStream) {
2964
+ this._sttStream.getTracks().forEach(t => { try { t.stop(); } catch (_) {} });
2965
+ this._sttStream = null;
2966
+ }
2967
+ this._sttRecorder = null;
2968
+ this._sttChunks = null;
2969
+ }
2970
+
2971
+ // Transcribe whatever is currently recorded by sending it to the STT
2972
+ // proxy. Appends the returned text to the transcript textarea.
2973
+ async _sttStopAndTranscribe() {
2974
+ const transcript = document.getElementById('sttTranscript');
2975
+ const blob = await this._stopSttRecording();
2976
+ this._resetSttRecordButton();
2977
+ if (!blob || blob.size === 0) {
2978
+ this.showToast('No audio to transcribe', 'warning');
2979
+ return;
2980
+ }
2981
+ const ext = (this._sttRecorderMime || 'audio/webm').includes('mp4') ? 'm4a'
2982
+ : (this._sttRecorderMime || '').includes('ogg') ? 'ogg'
2983
+ : 'webm';
2984
+ const filename = `sshift-recording-${Date.now()}.${ext}`;
2985
+ // Show an inline spinner + "Transcribing…" label in the modal controls
2986
+ // row instead of a toast, so the user sees feedback right where they
2987
+ // clicked. Also disable the Record/Wand buttons while in flight.
2988
+ const setStatus = (visible, label) => {
2989
+ const s = document.getElementById('sttStatus');
2990
+ if (s) {
2991
+ s.hidden = !visible;
2992
+ const l = s.querySelector('.stt-status-label');
2993
+ if (l && label) l.textContent = label;
2994
+ }
2995
+ const recBtn = document.getElementById('sttRecordBtn');
2996
+ const wandBtn = document.getElementById('sttWandBtn');
2997
+ if (recBtn) recBtn.disabled = visible;
2998
+ if (wandBtn) wandBtn.disabled = visible;
2999
+ };
3000
+ try {
3001
+ setStatus(true, 'Transcribing…');
3002
+ const res = await fetch('/api/speech-ai/stt', {
3003
+ method: 'POST',
3004
+ headers: {
3005
+ 'Content-Type': this._sttRecorderMime || 'audio/webm',
3006
+ 'X-Audio-Filename': filename
3007
+ },
3008
+ body: blob
3009
+ });
3010
+ if (!res.ok) {
3011
+ const txt = await res.text().catch(() => '');
3012
+ throw new Error(`HTTP ${res.status} ${txt}`);
3013
+ }
3014
+ const data = await res.json();
3015
+ const text = (data.text || '').trim();
3016
+ if (!text) {
3017
+ this.showToast('No speech detected', 'warning');
3018
+ return;
3019
+ }
3020
+ if (transcript) {
3021
+ const prev = transcript.value.trim();
3022
+ transcript.value = prev ? (prev + ' ' + text) : text;
3023
+ transcript.scrollTop = transcript.scrollHeight;
3024
+ }
3025
+ } catch (err) {
3026
+ console.error('[SSHIFT] STT transcription failed:', err);
3027
+ this.showToast('Transcription failed: ' + (err.message || err), 'error');
3028
+ } finally {
3029
+ setStatus(false, 'Transcribing…');
3030
+ }
3031
+ }
3032
+
3033
+ // Send the transcript to the Wand proxy and replace the textarea with the
3034
+ // cleaned version returned by the LLM.
3035
+ async _sttRunWand() {
3036
+ const transcript = document.getElementById('sttTranscript');
3037
+ if (!transcript) return;
3038
+ const text = transcript.value.trim();
3039
+ if (!text) {
3040
+ this.showToast('Nothing to clean up yet', 'warning');
3041
+ return;
3042
+ }
3043
+ const wandBtn = document.getElementById('sttWandBtn');
3044
+ const setBusy = (busy) => {
3045
+ if (!wandBtn) return;
3046
+ wandBtn.disabled = busy;
3047
+ wandBtn.style.opacity = busy ? '0.6' : '';
3048
+ const iconEl = wandBtn.querySelector('i');
3049
+ const labelEl = wandBtn.querySelector('.stt-btn-label');
3050
+ if (busy) {
3051
+ wandBtn.dataset.origIcon = iconEl ? iconEl.className : '';
3052
+ if (iconEl) iconEl.className = 'fas fa-spinner fa-spin';
3053
+ if (labelEl) labelEl.textContent = 'Cleaning…';
3054
+ } else {
3055
+ if (iconEl && wandBtn.dataset.origIcon) iconEl.className = wandBtn.dataset.origIcon;
3056
+ if (labelEl) labelEl.textContent = 'Wand';
3057
+ }
3058
+ };
3059
+ setBusy(true);
3060
+ try {
3061
+ const res = await fetch('/api/speech-ai/wand', {
3062
+ method: 'POST',
3063
+ headers: { 'Content-Type': 'application/json' },
3064
+ body: JSON.stringify({ text })
3065
+ });
3066
+ if (!res.ok) {
3067
+ const txt = await res.text().catch(() => '');
3068
+ throw new Error(`HTTP ${res.status} ${txt}`);
3069
+ }
3070
+ const data = await res.json();
3071
+ const cleaned = (data.text || '').trim();
3072
+ if (cleaned) {
3073
+ transcript.value = cleaned;
3074
+ transcript.scrollTop = transcript.scrollHeight;
3075
+ this.showToast('Cleaned up', 'success');
3076
+ } else {
3077
+ this.showToast('Wand returned nothing', 'warning');
3078
+ }
3079
+ } catch (err) {
3080
+ console.error('[SSHIFT] Wand failed:', err);
3081
+ this.showToast('Wand failed: ' + (err.message || err), 'error');
3082
+ } finally {
3083
+ setBusy(false);
3084
+ }
3085
+ }
3086
+
3087
+ // Reset the Record/Pause button to its idle state and stop any active
3088
+ // mic stream. Used when the modal closes.
3089
+ _resetSttRecordButton() {
3090
+ this._cleanupSttRecording();
3091
+ const btn = document.getElementById('sttRecordBtn');
3092
+ if (!btn) return;
3093
+ btn.classList.remove('recording', 'paused');
3094
+ btn.disabled = false;
3095
+ const labelEl = btn.querySelector('.stt-btn-label');
3096
+ const iconEl = btn.querySelector('i');
3097
+ if (iconEl) iconEl.className = 'fas fa-microphone';
3098
+ if (labelEl) labelEl.textContent = 'Record';
3099
+ btn.title = 'Start / Pause / Resume recording';
3100
+ }
3101
+
3102
+ // Enable/disable terminal-only tab action buttons (keyboard + mic) based
3103
+ // on the active session type for the given panel. SFTP tabs disable them.
3104
+ updateTabActionButtons(panelId) {
3105
+ const isSingle = panelId === 'panel-0';
3106
+ const keysBtnId = isSingle ? 'specialKeysBtn' : `${panelId}-specialKeysBtn`;
3107
+ const micBtnId = isSingle ? 'speechToTextBtn' : `${panelId}-speechToTextBtn`;
3108
+
3109
+ const keysBtn = document.getElementById(keysBtnId);
3110
+ const micBtn = document.getElementById(micBtnId);
3111
+
3112
+ const activeSessionId = this.activeSessionsByPanel.get(panelId);
3113
+ const session = activeSessionId ? this.sessions.get(activeSessionId) : null;
3114
+ const enabled = !!(session && session.type === 'ssh');
3115
+
3116
+ [keysBtn, micBtn].forEach(btn => {
3117
+ if (!btn) return;
3118
+ if (enabled) {
3119
+ btn.removeAttribute('disabled');
3120
+ btn.classList.remove('disabled');
3121
+ } else {
3122
+ btn.setAttribute('disabled', 'disabled');
3123
+ btn.classList.add('disabled');
3124
+ }
3125
+ });
3126
+ }
3127
+
2664
3128
  async initLayoutSystem() {
2665
3129
  console.log('[SSHIFT] Initializing layout system...');
2666
3130
 
@@ -4327,6 +4791,14 @@ const wheelHandler = (e) => {
4327
4791
 
4328
4792
  setTimeout(() => {
4329
4793
  if (session.terminal && session.connected && session.isController) {
4794
+ // Force a resize-like refit before requesting the screen
4795
+ // sync: clearTextureAtlas()+refresh() at the committed
4796
+ // cell pitch clears the interlace "black band" artefact
4797
+ // that can form when becoming the controller (the take-
4798
+ // control overlay hide is a display change that can
4799
+ // leave the WebGL atlas desynced from the cell layout).
4800
+ console.log('[SSHIFT] Force-resize refit before screen sync after becoming controller');
4801
+ this.forceResizeLikeRefit(session);
4330
4802
  console.log('[SSHIFT] Requesting screen sync after becoming controller to redraw at local dimensions');
4331
4803
  this.requestScreenSync(data.sessionId);
4332
4804
  }
@@ -4424,6 +4896,14 @@ const wheelHandler = (e) => {
4424
4896
 
4425
4897
  setTimeout(() => {
4426
4898
  if (session.terminal && session.connected && session.isController) {
4899
+ // Force a resize-like refit before requesting the screen
4900
+ // sync: clearTextureAtlas()+refresh() at the committed cell
4901
+ // pitch clears the interlace "black band" artefact that can
4902
+ // form on take-control (the control-overlay hide is a
4903
+ // display change that can leave the WebGL atlas desynced
4904
+ // from the cell layout — same family as the panel-grab bug).
4905
+ console.log('[SSHIFT] Force-resize refit before screen sync after taking control');
4906
+ this.forceResizeLikeRefit(session);
4427
4907
  console.log('[SSHIFT] Requesting screen sync after taking control to redraw at local dimensions');
4428
4908
  this.requestScreenSync(data.sessionId);
4429
4909
  }
@@ -5105,22 +5585,138 @@ const wheelHandler = (e) => {
5105
5585
  });
5106
5586
  });
5107
5587
 
5108
- // Special keys modal
5588
+ // Special keys modal — panel-0 static instance uses the shared tap wiring
5589
+ // so it behaves identically on mobile and desktop (same as mic button).
5109
5590
  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
- });
5591
+ this._wireActionBtn(specialKeysBtnEl, () => this.handleSpecialKeys('panel-0'));
5592
+
5593
+ // Speech-to-text button (panel-0 static instance) — wired the same way
5594
+ // as the keyboard button so both behave the same on mobile & desktop.
5595
+ const speechToTextBtnEl = document.getElementById('speechToTextBtn');
5596
+ this._wireActionBtn(speechToTextBtnEl, () => this.handleSpeechToText('panel-0'));
5597
+
5598
+ // Speech-to-text modal close / cancel / send / record / wand handlers
5599
+ const closeSttBtn = document.getElementById('closeSpeechToTextModal');
5600
+ const sttCancelBtn = document.getElementById('sttCancelBtn');
5601
+ const sttSendBtn = document.getElementById('sttSendBtn');
5602
+ const sttRecordBtn = document.getElementById('sttRecordBtn');
5603
+ const sttWandBtn = document.getElementById('sttWandBtn');
5604
+
5605
+ const closeSpeechToTextModal = () => {
5606
+ this.closeModal('speechToTextModal');
5607
+ const transcript = document.getElementById('sttTranscript');
5608
+ if (transcript) transcript.value = '';
5609
+ const status = document.getElementById('sttStatus');
5610
+ if (status) status.hidden = true;
5611
+ this._resetSttRecordButton();
5612
+ // Always return focus to the terminal (desktop + mobile) so the user
5613
+ // can keep typing/backspacing immediately after Send/Cancel/Close.
5614
+ this.focusTerminal();
5615
+ };
5616
+
5617
+ const attachSttClose = (btn) => {
5618
+ if (!btn) return;
5619
+ btn.setAttribute('tabindex', '-1');
5620
+ btn.addEventListener('focus', () => {
5621
+ btn.blur();
5622
+ if (this.isMobile) this.focusTerminal();
5623
+ });
5624
+ btn.addEventListener('touchstart', (e) => {
5625
+ e.preventDefault();
5626
+ }, { passive: false });
5627
+ btn.addEventListener('mousedown', (e) => {
5628
+ e.preventDefault();
5629
+ });
5630
+ btn.addEventListener('click', closeSpeechToTextModal);
5631
+ btn.addEventListener('touchend', (e) => {
5632
+ e.preventDefault();
5633
+ closeSpeechToTextModal();
5634
+ }, { passive: false });
5635
+ };
5636
+
5637
+ attachSttClose(closeSttBtn);
5638
+ attachSttClose(sttCancelBtn);
5639
+
5640
+ // Record / Pause / Resume toggle (STT endpoint wiring comes later).
5641
+ // Uses a basic touch+click handler — no focus stealing since the modal
5642
+ // is the topmost layer and we don't want to yank focus to the terminal.
5643
+ const attachSttAction = (btn, action) => {
5644
+ if (!btn) return;
5645
+ btn.setAttribute('tabindex', '-1');
5646
+ let touchHandled = false;
5647
+ btn.addEventListener('touchstart', (e) => {
5648
+ if (this.isMobile) e.preventDefault();
5649
+ touchHandled = true;
5650
+ }, { passive: false });
5651
+ btn.addEventListener('touchend', (e) => {
5652
+ e.preventDefault();
5653
+ touchHandled = true;
5654
+ action();
5655
+ }, { passive: false });
5656
+ btn.addEventListener('mousedown', (e) => {
5657
+ if (this.isMobile) e.preventDefault();
5658
+ });
5659
+ btn.addEventListener('click', () => {
5660
+ if (touchHandled) { touchHandled = false; return; }
5661
+ action();
5662
+ });
5663
+ };
5664
+
5665
+ attachSttAction(sttRecordBtn, () => this._toggleSttRecord());
5666
+ // Wand: pipe transcript through LLM proxy and replace text in place.
5667
+ attachSttAction(sttWandBtn, () => this._sttRunWand());
5668
+
5669
+ if (sttSendBtn) {
5670
+ sttSendBtn.setAttribute('tabindex', '-1');
5671
+ const sendStt = async () => {
5672
+ // If still recording/paused, stop the mic first (any pending audio
5673
+ // that hasn't been transcribed yet is discarded — Send sends what's
5674
+ // currently in the textarea).
5675
+ if (this._sttRecorder && this._sttRecorder.state !== 'inactive') {
5676
+ try { this._sttRecorder.stop(); } catch (_) {}
5677
+ this._cleanupSttRecording();
5678
+ this._resetSttRecordButton();
5679
+ }
5680
+ const transcript = document.getElementById('sttTranscript');
5681
+ const text = transcript ? transcript.value : '';
5682
+ if (text) {
5683
+ const session = this.sessions.get(this.activeSessionId);
5684
+ // Pipe text to the remote shell via the SSH socket channel so the
5685
+ // shell actually receives it as input. terminal.write() would only
5686
+ // paint pixels locally and the keystrokes would never reach the
5687
+ // server (backspace/enter had no effect because the shell never
5688
+ // saw the input).
5689
+ if (session && session.type === 'ssh' && session.id && session.connected && session.isController) {
5690
+ this.socket.emit('ssh-data', { sessionId: session.id, data: text });
5691
+ } else if (session && session.type === 'ssh' && session.terminal) {
5692
+ // Fallback (non-controller or disconnected): at least render
5693
+ // locally so the user sees what would have been sent.
5694
+ session.terminal.write(text);
5695
+ this.showToast('Not connected as controller — text not sent', 'warning');
5696
+ } else if (session && session.terminal) {
5697
+ session.terminal.write(text);
5698
+ }
5699
+ }
5700
+ closeSpeechToTextModal();
5701
+ };
5702
+ let sendTouchHandled = false;
5703
+ sttSendBtn.addEventListener('touchstart', (e) => {
5704
+ if (this.isMobile) e.preventDefault();
5705
+ sendTouchHandled = true;
5706
+ }, { passive: false });
5707
+ sttSendBtn.addEventListener('touchend', (e) => {
5708
+ e.preventDefault();
5709
+ sendTouchHandled = true;
5710
+ sendStt();
5711
+ }, { passive: false });
5712
+ sttSendBtn.addEventListener('mousedown', (e) => {
5713
+ if (this.isMobile) e.preventDefault();
5714
+ });
5715
+ sttSendBtn.addEventListener('click', () => {
5716
+ if (sendTouchHandled) { sendTouchHandled = false; return; }
5717
+ sendStt();
5718
+ });
5719
+ }
5124
5720
 
5125
5721
  const closeSpecialKeysBtn = document.getElementById('closeSpecialKeysModal');
5126
5722
  closeSpecialKeysBtn.setAttribute('tabindex', '-1');
@@ -5144,6 +5740,42 @@ const wheelHandler = (e) => {
5144
5740
  this.focusTerminal();
5145
5741
  });
5146
5742
 
5743
+ // Speech & AI settings — show/hide auth key toggles + Reset wand prompt
5744
+ const toggleSttAuth = document.getElementById('toggleSttAuthKey');
5745
+ if (toggleSttAuth) {
5746
+ toggleSttAuth.addEventListener('click', () => {
5747
+ const input = document.getElementById('sttAuthKey');
5748
+ const icon = toggleSttAuth.querySelector('i');
5749
+ if (!input) return;
5750
+ if (input.type === 'password') {
5751
+ input.type = 'text';
5752
+ if (icon) icon.classList.replace('fa-eye', 'fa-eye-slash');
5753
+ } else {
5754
+ input.type = 'password';
5755
+ if (icon) icon.classList.replace('fa-eye-slash', 'fa-eye');
5756
+ }
5757
+ });
5758
+ }
5759
+ const toggleLlmAuth = document.getElementById('toggleLlmAuthKey');
5760
+ if (toggleLlmAuth) {
5761
+ toggleLlmAuth.addEventListener('click', () => {
5762
+ const input = document.getElementById('llmAuthKey');
5763
+ const icon = toggleLlmAuth.querySelector('i');
5764
+ if (!input) return;
5765
+ if (input.type === 'password') {
5766
+ input.type = 'text';
5767
+ if (icon) icon.classList.replace('fa-eye', 'fa-eye-slash');
5768
+ } else {
5769
+ input.type = 'password';
5770
+ if (icon) icon.classList.replace('fa-eye-slash', 'fa-eye');
5771
+ }
5772
+ });
5773
+ }
5774
+ const resetWandBtn = document.getElementById('resetWandPromptBtn');
5775
+ if (resetWandBtn) {
5776
+ resetWandBtn.addEventListener('click', () => this.resetWandPromptToDefault());
5777
+ }
5778
+
5147
5779
  // Special key buttons
5148
5780
  const specialKeysModal = document.getElementById('specialKeysModal');
5149
5781
  document.querySelectorAll('.key-btn').forEach(btn => {
@@ -5189,6 +5821,10 @@ const wheelHandler = (e) => {
5189
5821
  this.handleFontSizeChange('panel-0', -1);
5190
5822
  });
5191
5823
 
5824
+ // Initialise terminal-only tab action gating (disabled until an SSH
5825
+ // session becomes active in the panel).
5826
+ this.updateTabActionButtons('panel-0');
5827
+
5192
5828
  // SFTP modal - now handled via tabs, keeping for backward compatibility
5193
5829
  // These event listeners are no longer needed but kept for reference
5194
5830
  // SFTP is now opened in tabs instead of modal
@@ -5403,13 +6039,101 @@ const wheelHandler = (e) => {
5403
6039
 
5404
6040
  // Load plugins
5405
6041
  this.loadPlugins();
5406
-
6042
+
6043
+ // Load Speech & AI config from server (auth keys are redacted by the
6044
+ // server — we only get back a "set" flag and fill the auth inputs with
6045
+ // the sentinel placeholder so unchanged values aren't overwritten on save).
6046
+ this.loadSpeechAiConfig().catch(err => {
6047
+ console.error('[SSHIFT] Failed to load Speech & AI config:', err);
6048
+ });
6049
+
5407
6050
  // Reset to first category
5408
6051
  this.switchSettingsCategory('sessions');
5409
6052
 
5410
6053
  this.openModal('settingsModal');
5411
6054
  }
5412
6055
 
6056
+ // ---- Speech & AI: settings load/save ---------------------------------
6057
+ // Auth keys are never sent back to the client. When the user doesn't type
6058
+ // a new one, we post the "__UNCHANGED__" sentinel so the server preserves
6059
+ // the existing value.
6060
+ async loadSpeechAiConfig() {
6061
+ const res = await fetch('/api/speech-ai/config');
6062
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
6063
+ const cfg = await res.json();
6064
+ this._speechAiConfig = cfg;
6065
+
6066
+ const set = (id, val) => { const el = document.getElementById(id); if (el) el.value = val; };
6067
+ set('sttEndpoint', cfg.sttEndpoint || '');
6068
+ set('sttLanguage', cfg.sttLanguage || '');
6069
+ set('llmEndpoint', cfg.llmEndpoint || '');
6070
+ set('llmModel', cfg.llmModel || '');
6071
+ set('wandSystemPrompt', cfg.wandSystemPrompt || '');
6072
+
6073
+ // Auth keys: redacted. Show a placeholder describing current state and
6074
+ // leave the input blank so a Save without typing keeps the existing key.
6075
+ const sttAuth = document.getElementById('sttAuthKey');
6076
+ if (sttAuth) {
6077
+ sttAuth.value = '';
6078
+ sttAuth.placeholder = cfg.sttAuthKeySet
6079
+ ? 'API key set — leave blank to keep'
6080
+ : 'sk-...';
6081
+ }
6082
+ const llmAuth = document.getElementById('llmAuthKey');
6083
+ if (llmAuth) {
6084
+ llmAuth.value = '';
6085
+ llmAuth.placeholder = cfg.llmAuthKeySet
6086
+ ? 'API key set — leave blank to keep'
6087
+ : 'sk-...';
6088
+ }
6089
+ }
6090
+
6091
+ async saveSpeechAiConfig() {
6092
+ const val = (id) => { const el = document.getElementById(id); return el ? el.value : ''; };
6093
+ const sttAuth = document.getElementById('sttAuthKey');
6094
+ const llmAuth = document.getElementById('llmAuthKey');
6095
+
6096
+ // Sentinel preserves existing keys when the user didn't type a new one.
6097
+ const sttAuthKey = (sttAuth && sttAuth.value.trim()) ? sttAuth.value.trim() : '__UNCHANGED__';
6098
+ const llmAuthKey = (llmAuth && llmAuth.value.trim()) ? llmAuth.value.trim() : '__UNCHANGED__';
6099
+
6100
+ const body = {
6101
+ sttEndpoint: val('sttEndpoint'),
6102
+ sttLanguage: val('sttLanguage'),
6103
+ llmEndpoint: val('llmEndpoint'),
6104
+ llmModel: val('llmModel'),
6105
+ wandSystemPrompt:val('wandSystemPrompt'),
6106
+ sttAuthKey,
6107
+ llmAuthKey
6108
+ };
6109
+
6110
+ const res = await fetch('/api/speech-ai/config', {
6111
+ method: 'POST',
6112
+ headers: { 'Content-Type': 'application/json' },
6113
+ body: JSON.stringify(body)
6114
+ });
6115
+ if (!res.ok) {
6116
+ const txt = await res.text().catch(() => '');
6117
+ throw new Error(`HTTP ${res.status} ${txt}`);
6118
+ }
6119
+ // Reload so the redacted placeholders reflect the new state.
6120
+ return this.loadSpeechAiConfig();
6121
+ }
6122
+
6123
+ async resetWandPromptToDefault() {
6124
+ try {
6125
+ const res = await fetch('/api/speech-ai/wand-default');
6126
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
6127
+ const data = await res.json();
6128
+ const ta = document.getElementById('wandSystemPrompt');
6129
+ if (ta) ta.value = data.prompt || '';
6130
+ this.showToast('Wand prompt reset to default', 'info');
6131
+ } catch (err) {
6132
+ console.error('[SSHIFT] Failed to load default wand prompt:', err);
6133
+ this.showToast('Failed to load default prompt', 'error');
6134
+ }
6135
+ }
6136
+
5413
6137
  initSettingsModalHandlers() {
5414
6138
  // Settings category navigation (sidebar + mobile dropdown)
5415
6139
  const navItems = document.querySelectorAll('.settings-nav-item');
@@ -5542,6 +6266,14 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
5542
6266
 
5543
6267
  // Save all settings to config
5544
6268
  this.saveStickyConfig();
6269
+
6270
+ // Persist Speech & AI settings (server-side, redacted keys preserved
6271
+ // when the user left the auth inputs blank).
6272
+ this.saveSpeechAiConfig().catch(err => {
6273
+ console.error('[SSHIFT] Failed to save Speech & AI config:', err);
6274
+ this.showToast('Speech & AI settings failed to save', 'error');
6275
+ });
6276
+
5545
6277
  console.log('[SSHIFT] Settings saved - sticky:', this.sticky,
5546
6278
  'takeControlDefault:', this.takeControlDefault,
5547
6279
  'keepaliveInterval:', this.sshKeepaliveInterval,
@@ -9225,9 +9957,15 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9225
9957
  // Clearing + refreshing forces a clean redraw at the correct size.
9226
9958
  this._resetWebGLAtlas(session);
9227
9959
 
9228
- // Restore font size for this session
9960
+ // Restore font size for this session. Setting fontSize async-
9961
+ // invalidates _renderService.dimensions; we must commit the new
9962
+ // cell size synchronously (via _charSizeService.measure()) BEFORE
9963
+ // fit() below reads it, otherwise fit computes cols/rows from a
9964
+ // stale cell height and the renderer paints interlaced black bands
9965
+ // (the "interlace" bug — see _syncCharSizeThenClearAtlas).
9229
9966
  if (session.fontSize && session.terminal) {
9230
9967
  session.terminal.options.fontSize = session.fontSize;
9968
+ this._syncCharSizeThenClearAtlas(session);
9231
9969
  console.log('[SSHIFT] Restored font size', session.fontSize, 'for session', sessionId);
9232
9970
  }
9233
9971
 
@@ -9259,11 +9997,19 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9259
9997
  // (e.g. 100×100px) because the browser hasn't fully committed the
9260
9998
  // display:none → display:flex layout change. A delayed refit
9261
9999
  // corrects this once the layout has settled.
10000
+ //
10001
+ // This uses forceResizeLikeRefit (not plain _fitTerminal) because
10002
+ // it replicates what a real window resize does — a synchronous
10003
+ // layout commit via offsetWidth reflow, then measure()+fit()+
10004
+ // clearTextureAtlas() + refresh(). That is exactly what clears
10005
+ // the interlace "black band" artefact after a panel/tab switch
10006
+ // (the artefact self-heals on manual resize; this gives the same
10007
+ // self-heal without requiring the user to resize).
9262
10008
  setTimeout(() => {
9263
10009
  if (!session.terminal || !session.fitAddon || !session.isController) return;
9264
10010
  const wrapper = document.getElementById(`terminal-wrapper-${session.id}`);
9265
10011
  if (wrapper && wrapper.classList.contains('active')) {
9266
- this._fitTerminal(session);
10012
+ this.forceResizeLikeRefit(session);
9267
10013
  }
9268
10014
  }, 150);
9269
10015
 
@@ -9304,13 +10050,16 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9304
10050
  if (sftpSession && sftpSession.terminal) {
9305
10051
  if (sftpSession.fontSize) {
9306
10052
  sftpSession.terminal.options.fontSize = sftpSession.fontSize;
9307
- this._resetWebGLAtlas(sftpSession);
10053
+ this._syncCharSizeThenClearAtlas(sftpSession);
9308
10054
  }
9309
10055
  }
9310
10056
 
9311
10057
  // Update mobile tabs dropdown for this panel
9312
10058
  this.updateMobileTabsDropdown(panelId);
9313
10059
 
10060
+ // Enable/disable terminal-only tab actions (keyboard + mic) for this panel
10061
+ this.updateTabActionButtons(panelId);
10062
+
9314
10063
  // Save tabs
9315
10064
  this.saveTabs();
9316
10065
  }