@lethevimlet/sshift 1.0.2 → 1.0.4

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.
@@ -33,6 +33,7 @@ class SSHIFTClient {
33
33
  this.isSyncingTabs = false; // Flag to prevent saveTabs emission during tabs-sync
34
34
  this.sftpClipboard = null; // For cut/copy/paste: { action: 'cut'|'copy', path: string, name: string, sessionId: string }
35
35
  this.terminalClipboardContent = null; // Pre-read clipboard content for context menu paste
36
+ this.osc52Buffer = null; // Buffered OSC 52 clipboard content pending write
36
37
  this.terminalColorOverride = true; // Default to true, will be loaded in initThemeAndAccent
37
38
  this.terminalBgColor = '#0d1117';
38
39
  this.terminalFgColor = '#e6edf3';
@@ -71,7 +72,7 @@ class SSHIFTClient {
71
72
  };
72
73
 
73
74
  // Terminal font size (for pinch-to-zoom on mobile)
74
- this.terminalFontSize = 14; // Default font size
75
+ this.terminalFontSize = window.innerWidth <= 768 ? 11 : 14;
75
76
  this.minFontSize = 8; // Minimum font size
76
77
  this.maxFontSize = 32; // Maximum font size
77
78
 
@@ -713,28 +714,37 @@ class SSHIFTClient {
713
714
 
714
715
  // Helper method to copy text to clipboard with fallback
715
716
  async copyToClipboard(text) {
716
- try {
717
- // Try modern clipboard API first
718
- if (navigator.clipboard && navigator.clipboard.writeText) {
717
+ // Try modern clipboard API first (requires secure context + user gesture)
718
+ if (navigator.clipboard && navigator.clipboard.writeText) {
719
+ try {
719
720
  await navigator.clipboard.writeText(text);
721
+ console.log('[SSHIFT] Clipboard API write succeeded, length:', text.length);
720
722
  return true;
723
+ } catch (err) {
724
+ console.warn('[SSHIFT] Clipboard API write failed:', err.name, err.message);
721
725
  }
722
- } catch (err) {
723
- console.warn('[SSHIFT] Modern clipboard API failed, trying fallback:', err);
726
+ } else {
727
+ console.warn('[SSHIFT] Clipboard API not available');
724
728
  }
725
729
 
726
- // Fallback to execCommand
730
+ // Fallback to execCommand (also requires user gesture in modern browsers)
727
731
  try {
728
732
  const textarea = document.createElement('textarea');
729
733
  textarea.value = text;
730
734
  textarea.style.position = 'fixed';
731
735
  textarea.style.left = '-9999px';
732
736
  textarea.style.top = '-9999px';
737
+ textarea.style.opacity = '0';
733
738
  document.body.appendChild(textarea);
734
739
  textarea.focus();
735
740
  textarea.select();
736
741
  const success = document.execCommand('copy');
737
742
  document.body.removeChild(textarea);
743
+ if (success) {
744
+ console.log('[SSHIFT] execCommand copy succeeded, length:', text.length);
745
+ } else {
746
+ console.warn('[SSHIFT] execCommand copy returned false');
747
+ }
738
748
  return success;
739
749
  } catch (err) {
740
750
  console.error('[SSHIFT] Fallback clipboard copy failed:', err);
@@ -802,6 +812,63 @@ class SSHIFTClient {
802
812
  });
803
813
  }
804
814
 
815
+ sendChunkedInput(sessionId, data, chunkSize = 2048) {
816
+ if (!data || !this.sessions.has(sessionId)) return;
817
+ const session = this.sessions.get(sessionId);
818
+ if (!session || !session.connected) return;
819
+
820
+ // Terminal emulators convert \n to \r before sending to the PTY.
821
+ // Clipboard text contains \n line endings, but PTY input expects \r
822
+ // as the "Enter" character. Without this conversion, programs like
823
+ // nano interpret \n as a raw newline that doesn't trigger line actions.
824
+ data = data.replace(/\r\n/g, '\r').replace(/\n/g, '\r');
825
+
826
+ // Wrap in bracketed paste sequences so the remote shell treats this as
827
+ // a single paste rather than individual keystrokes.
828
+ const BP_START = '\x1b[200~';
829
+ const BP_END = '\x1b[201~';
830
+
831
+ const wrapped = BP_START + data + BP_END;
832
+
833
+ if (wrapped.length <= chunkSize) {
834
+ this.socket.emit('ssh-data', { sessionId, data: wrapped });
835
+ return;
836
+ }
837
+
838
+ // For large pastes, send the start bracket, then chunk the content,
839
+ // then send the end bracket. This keeps bracketed paste mode intact
840
+ // across all chunks.
841
+ let offset = 0;
842
+ let isFirst = true;
843
+ const sendNext = () => {
844
+ if (offset >= data.length) {
845
+ this.socket.emit('ssh-data', { sessionId, data: BP_END });
846
+ return;
847
+ }
848
+ let end = Math.min(offset + chunkSize, data.length);
849
+ if (end < data.length) {
850
+ // Split at the last \r to keep line boundaries intact
851
+ const lastCr = data.lastIndexOf('\r', end);
852
+ if (lastCr > offset) {
853
+ end = lastCr + 1;
854
+ }
855
+ }
856
+ let chunk = data.substring(offset, end);
857
+ if (isFirst) {
858
+ chunk = BP_START + chunk;
859
+ isFirst = false;
860
+ }
861
+ offset = end;
862
+ this.socket.emit('ssh-data', { sessionId, data: chunk });
863
+ if (offset < data.length) {
864
+ setTimeout(sendNext, 5);
865
+ } else {
866
+ this.socket.emit('ssh-data', { sessionId, data: BP_END });
867
+ }
868
+ };
869
+ sendNext();
870
+ }
871
+
805
872
  // Legacy method for backwards compatibility
806
873
  saveStickySessions() {
807
874
  this.saveTabs();
@@ -846,7 +913,7 @@ class SSHIFTClient {
846
913
  // Terminal Font Size Management (for pinch-to-zoom and buttons)
847
914
  loadTerminalFontSize() {
848
915
  // Don't persist - always start with default
849
- return 14; // Default font size
916
+ return window.innerWidth <= 768 ? 11 : 14;
850
917
  }
851
918
 
852
919
  saveTerminalFontSize(size) {
@@ -2380,6 +2447,8 @@ class SSHIFTClient {
2380
2447
  // If we switched between mobile and desktop, re-apply the layout
2381
2448
  if (wasMobile !== this.isMobile && this.currentLayout) {
2382
2449
  console.log('[SSHIFT] Viewport changed, re-applying layout for', this.isMobile ? 'mobile' : 'desktop');
2450
+ this.terminalFontSize = this.isMobile ? 11 : 14;
2451
+ this.setTerminalFontSize(this.terminalFontSize);
2383
2452
  this.applyLayout(this.currentLayout);
2384
2453
  this.updateMobileTabsDropdown();
2385
2454
  }
@@ -2587,7 +2656,7 @@ const wheelHandler = (e) => {
2587
2656
  // ydisp is the current scroll position (number of lines scrolled back from bottom)
2588
2657
  // The terminal is at bottom if ydisp is 0 or very close to 0
2589
2658
  const maxYDisp = buffer.length - terminal.rows;
2590
- const currentYDisp = terminal.buffer.ydisp;
2659
+ const currentYDisp = terminal.buffer.active.viewportY;
2591
2660
 
2592
2661
  // We're at the bottom if we're within 2 lines of the bottom
2593
2662
  const isAtBottom = currentYDisp >= maxYDisp - 2;
@@ -2611,7 +2680,7 @@ const wheelHandler = (e) => {
2611
2680
  // ydisp = 0 means we're at the bottom (most recent content)
2612
2681
  // ydisp > 0 means we've scrolled up into the scrollback buffer (older content)
2613
2682
  const buffer = terminal.buffer.active;
2614
- const scrollTop = buffer.ydisp;
2683
+ const scrollTop = buffer.viewportY;
2615
2684
 
2616
2685
  // Get scroll direction
2617
2686
  const scrollDiff = scrollTop - session.lastScrollTop;
@@ -4152,6 +4221,9 @@ const wheelHandler = (e) => {
4152
4221
  // Initialize password toggle
4153
4222
  this.initPasswordToggle();
4154
4223
 
4224
+ // Initialize debug info dialog
4225
+ this.initDebugInfoDialog();
4226
+
4155
4227
  // Initialize sessions modal handlers
4156
4228
  this.initSessionsModalHandlers();
4157
4229
 
@@ -4749,8 +4821,24 @@ const wheelHandler = (e) => {
4749
4821
  }
4750
4822
 
4751
4823
  const downloadCertBtn = document.getElementById('downloadCertBtn');
4824
+ const customCertWarning = document.getElementById('customCertWarning');
4825
+
4826
+ fetch('/api/security-info').then(r => r.json()).then(info => {
4827
+ if (info.usesCustomCert) {
4828
+ if (downloadCertBtn) {
4829
+ downloadCertBtn.disabled = true;
4830
+ downloadCertBtn.style.opacity = '0.5';
4831
+ downloadCertBtn.style.cursor = 'not-allowed';
4832
+ }
4833
+ if (customCertWarning) {
4834
+ customCertWarning.style.display = 'flex';
4835
+ }
4836
+ }
4837
+ }).catch(() => {});
4838
+
4752
4839
  if (downloadCertBtn) {
4753
4840
  downloadCertBtn.addEventListener('click', () => {
4841
+ if (downloadCertBtn.disabled) return;
4754
4842
  window.open('/api/cert', '_blank');
4755
4843
  });
4756
4844
  }
@@ -4782,26 +4870,69 @@ const wheelHandler = (e) => {
4782
4870
  }
4783
4871
 
4784
4872
  openSecurityInfoDialog() {
4873
+ const swStatusIcon = document.getElementById('swStatusIcon');
4874
+ const swStatusTitle = document.getElementById('swStatusTitle');
4785
4875
  const swStatusText = document.getElementById('swStatusText');
4786
- // Re-check actual SW state from navigator API
4876
+ const swStatusContainer = document.getElementById('swStatusContainer');
4877
+
4787
4878
  let swStatus = window._swStatus;
4788
4879
  if (navigator.serviceWorker && navigator.serviceWorker.controller) {
4789
4880
  swStatus = 'active';
4790
4881
  window._swStatus = 'active';
4791
4882
  }
4792
4883
 
4793
- if (swStatusText) {
4884
+ if (swStatusIcon && swStatusTitle && swStatusText && swStatusContainer) {
4885
+ swStatusContainer.classList.remove('sw-status-active', 'sw-status-failed', 'sw-status-unsupported');
4886
+
4794
4887
  if (swStatus === 'active') {
4795
- swStatusText.innerHTML = '<i class="fas fa-check-circle" style="color: var(--accent-success, #4caf50);"></i> Service Worker is <strong>active</strong>. Offline caching is available.';
4888
+ swStatusContainer.classList.add('sw-status-active');
4889
+ swStatusIcon.innerHTML = '<i class="fas fa-check-circle"></i>';
4890
+ swStatusTitle.textContent = 'Connected';
4891
+ swStatusText.innerHTML =
4892
+ '<ul class="sw-feature-list">' +
4893
+ '<li><i class="fas fa-check"></i> No browser security warnings</li>' +
4894
+ '<li><i class="fas fa-check"></i> Installable as app (PWA)</li>' +
4895
+ '<li><i class="fas fa-check"></i> Clipboard API access</li>' +
4896
+ '</ul>';
4796
4897
  } else if (swStatus === 'failed') {
4797
- swStatusText.innerHTML = '<i class="fas fa-exclamation-triangle" style="color: var(--accent-danger, #f44336);"></i> Service Worker <strong>failed to register</strong>: ' + (window._swError || 'Unknown error') + '. This is usually caused by an untrusted HTTPS certificate. Download and install the certificate below to fix this, then reload the page.';
4898
+ swStatusContainer.classList.add('sw-status-failed');
4899
+ swStatusIcon.innerHTML = '<i class="fas fa-exclamation-triangle"></i>';
4900
+ swStatusTitle.textContent = 'Connection Failed';
4901
+ swStatusText.innerHTML =
4902
+ '<p>' + (window._swError || 'Unknown error') + '</p>' +
4903
+ '<ul class="sw-feature-list">' +
4904
+ '<li><i class="fas fa-times"></i> No browser security warnings</li>' +
4905
+ '<li><i class="fas fa-times"></i> Installable as app (PWA)</li>' +
4906
+ '<li><i class="fas fa-times"></i> Clipboard API access</li>' +
4907
+ '</ul>' +
4908
+ '<p class="sw-hint">Trust the HTTPS certificate to enable all features.</p>';
4798
4909
  } else if (swStatus === 'redundant') {
4799
- swStatusText.innerHTML = '<i class="fas fa-exclamation-triangle" style="color: var(--accent-danger, #f44336);"></i> Service Worker became <strong>redundant</strong>. ' + (window._swError || 'The HTTPS certificate may not be trusted.') + ' Download and install the certificate below, then reload the page.';
4910
+ swStatusContainer.classList.add('sw-status-failed');
4911
+ swStatusIcon.innerHTML = '<i class="fas fa-exclamation-triangle"></i>';
4912
+ swStatusTitle.textContent = 'Connection Failed';
4913
+ swStatusText.innerHTML =
4914
+ '<p>' + (window._swError || 'The HTTPS certificate may not be trusted.') + '</p>' +
4915
+ '<ul class="sw-feature-list">' +
4916
+ '<li><i class="fas fa-times"></i> No browser security warnings</li>' +
4917
+ '<li><i class="fas fa-times"></i> Installable as app (PWA)</li>' +
4918
+ '<li><i class="fas fa-times"></i> Clipboard API access</li>' +
4919
+ '</ul>' +
4920
+ '<p class="sw-hint">Trust the HTTPS certificate to enable all features.</p>';
4800
4921
  } else if (swStatus === 'unsupported') {
4801
- swStatusText.innerHTML = '<i class="fas fa-info-circle" style="color: var(--accent-warning, #ff9800);"></i> Service Workers are <strong>not supported</strong> in this browser.';
4922
+ swStatusContainer.classList.add('sw-status-unsupported');
4923
+ swStatusIcon.innerHTML = '<i class="fas fa-info-circle"></i>';
4924
+ swStatusTitle.textContent = 'Not Supported';
4925
+ swStatusText.innerHTML =
4926
+ '<p>Service Workers are not available in this browser.</p>' +
4927
+ '<ul class="sw-feature-list">' +
4928
+ '<li><i class="fas fa-times"></i> No browser security warnings</li>' +
4929
+ '<li><i class="fas fa-times"></i> Installable as app (PWA)</li>' +
4930
+ '<li><i class="fas fa-times"></i> Clipboard API access</li>' +
4931
+ '</ul>';
4802
4932
  } else {
4803
- // Still loading, retry
4804
- swStatusText.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Checking...';
4933
+ swStatusIcon.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
4934
+ swStatusTitle.textContent = 'Checking...';
4935
+ swStatusText.textContent = 'Detecting service worker status';
4805
4936
  setTimeout(() => this.openSecurityInfoDialog(), 500);
4806
4937
  return;
4807
4938
  }
@@ -4810,6 +4941,63 @@ const wheelHandler = (e) => {
4810
4941
  this.openModal('securityInfoModal');
4811
4942
  }
4812
4943
 
4944
+ // Debug Info Dialog
4945
+ initDebugInfoDialog() {
4946
+ const showBtn = document.getElementById('showDebugInfoBtn');
4947
+ if (showBtn) {
4948
+ showBtn.addEventListener('click', () => {
4949
+ this.openDebugInfoDialog();
4950
+ });
4951
+ }
4952
+
4953
+ const closeBtn = document.getElementById('closeDebugInfoModal');
4954
+ if (closeBtn) {
4955
+ closeBtn.addEventListener('click', () => {
4956
+ this.closeModal('debugInfoModal');
4957
+ });
4958
+ }
4959
+
4960
+ const closeBtn2 = document.getElementById('closeDebugInfoBtn');
4961
+ if (closeBtn2) {
4962
+ closeBtn2.addEventListener('click', () => {
4963
+ this.closeModal('debugInfoModal');
4964
+ });
4965
+ }
4966
+
4967
+ const modal = document.getElementById('debugInfoModal');
4968
+ if (modal) {
4969
+ modal.addEventListener('click', (e) => {
4970
+ if (e.target === modal) {
4971
+ this.closeModal('debugInfoModal');
4972
+ }
4973
+ });
4974
+ }
4975
+ }
4976
+
4977
+ openDebugInfoDialog() {
4978
+ fetch('/api/debug-info').then(r => r.json()).then(info => {
4979
+ const configPathEl = document.getElementById('debugConfigPath');
4980
+ const dataDirEl = document.getElementById('debugDataDir');
4981
+ const certPathEl = document.getElementById('debugCertPath');
4982
+ const keyPathEl = document.getElementById('debugKeyPath');
4983
+ const certTypeEl = document.getElementById('debugCertType');
4984
+
4985
+ if (configPathEl) configPathEl.textContent = info.configPath || 'N/A';
4986
+ if (dataDirEl) dataDirEl.textContent = info.dataDir || 'N/A';
4987
+ if (certPathEl) certPathEl.textContent = info.certPath || 'N/A';
4988
+ if (keyPathEl) keyPathEl.textContent = info.keyPath || 'N/A';
4989
+ if (certTypeEl) certTypeEl.textContent = info.usesCustomCert ? 'Custom' : 'Self-signed';
4990
+ }).catch(() => {
4991
+ const ids = ['debugConfigPath', 'debugDataDir', 'debugCertPath', 'debugKeyPath', 'debugCertType'];
4992
+ ids.forEach(id => {
4993
+ const el = document.getElementById(id);
4994
+ if (el) el.textContent = 'Error loading';
4995
+ });
4996
+ });
4997
+
4998
+ this.openModal('debugInfoModal');
4999
+ }
5000
+
4813
5001
  // Sessions Modal
4814
5002
  async openSessionsModal() {
4815
5003
  this.openModal('manageSessionsModal');
@@ -5884,8 +6072,11 @@ const wheelHandler = (e) => {
5884
6072
  syncing: false, // Flag to prevent data writes during screen sync
5885
6073
  fontSize: this.terminalFontSize, // Initialize with default font size
5886
6074
  mobileHandler: null, // Mobile terminal handler for touch interactions
5887
- writeBuffer: '', // Buffer for batching terminal writes
5888
- writeRAF: null // requestAnimationFrame ID for write flush
6075
+ writeChunks: [], // Array of chunks for batching terminal writes (avoids O(n^2) string concat)
6076
+ writeRAF: null, // requestAnimationFrame ID for write flush
6077
+ flushRemaining: null, // Remaining data from a frame that exceeded the write cap
6078
+ originalScrollback: null, // Stores original scrollback before dynamic reduction
6079
+ scrollbackRestoreTimer: null
5889
6080
  });
5890
6081
 
5891
6082
  // Switch to the new tab FIRST to make the container visible
@@ -6255,7 +6446,7 @@ const wheelHandler = (e) => {
6255
6446
  lineHeight: 1.0,
6256
6447
  cursorBlink: false,
6257
6448
  cursorStyle: 'block',
6258
- scrollback: 5000,
6449
+ scrollback: 2000,
6259
6450
  allowProposedApi: true,
6260
6451
  convertEol: true,
6261
6452
  allowTransparency: false,
@@ -6355,6 +6546,70 @@ const wheelHandler = (e) => {
6355
6546
  console.log('[SSHIFT] Image addon disabled in settings');
6356
6547
  }
6357
6548
 
6549
+ // Register OSC 52 handler for clipboard operations from remote terminals
6550
+ // This allows programs like opencode, tmux, vim, etc. to set the clipboard
6551
+ // via the OSC 52 escape sequence: \e]52;c;<base64-text>\007
6552
+ //
6553
+ // Browser Clipboard API requires a user gesture, but OSC 52 data arrives
6554
+ // asynchronously from the SSH stream. We buffer the content synchronously
6555
+ // and flush it on the next user interaction (click, keydown, touchstart).
6556
+ // Immediate writes are also attempted but may fail without a user gesture.
6557
+ try {
6558
+ const flushOsc52Buffer = () => {
6559
+ if (this.osc52Buffer !== null && this.osc52Buffer !== undefined) {
6560
+ const text = this.osc52Buffer;
6561
+ this.osc52Buffer = null;
6562
+ console.log('[SSHIFT] Flushing OSC 52 clipboard buffer, length:', text.length);
6563
+ this.copyToClipboard(text).then(success => {
6564
+ if (success) {
6565
+ console.log('[SSHIFT] OSC 52 clipboard write succeeded (flushed on user gesture)');
6566
+ this.showToast('Copied to clipboard', 'success');
6567
+ } else {
6568
+ console.warn('[SSHIFT] OSC 52 clipboard write failed after flush, re-buffering');
6569
+ this.osc52Buffer = text;
6570
+ }
6571
+ }).catch(err => {
6572
+ console.warn('[SSHIFT] OSC 52 clipboard write failed:', err);
6573
+ this.osc52Buffer = text;
6574
+ });
6575
+ }
6576
+ };
6577
+ document.addEventListener('click', flushOsc52Buffer, true);
6578
+ document.addEventListener('keydown', flushOsc52Buffer, true);
6579
+ document.addEventListener('touchstart', flushOsc52Buffer, true);
6580
+
6581
+ // Store for cleanup when the session is closed
6582
+ const sess = this.sessions.get(sessionId);
6583
+ if (sess) sess.osc52FlushListener = flushOsc52Buffer;
6584
+
6585
+ // Also register as fallback with xterm.js's OSC handler in case any
6586
+ // OSC 52 sequences slip through the data stream interceptor (e.g. from
6587
+ // screen sync restoration). The data stream interceptor is the primary handler.
6588
+ terminal.registerOscHandler(52, (data) => {
6589
+ console.log('[SSHIFT] OSC 52 handler fallback triggered (should be handled by stream interceptor)');
6590
+ const semicolonIndex = data.indexOf(';');
6591
+ if (semicolonIndex === -1) return true;
6592
+ const content = data.substring(semicolonIndex + 1);
6593
+ if (!content) {
6594
+ this.osc52Buffer = '';
6595
+ return true;
6596
+ }
6597
+ try {
6598
+ const decoded = atob(content);
6599
+ this.osc52Buffer = decoded;
6600
+ this.copyToClipboard(decoded).then(success => {
6601
+ if (success) this.osc52Buffer = null;
6602
+ }).catch(() => {});
6603
+ } catch (e) {
6604
+ console.warn('[SSHIFT] OSC 52 base64 decode failed:', e);
6605
+ }
6606
+ return true;
6607
+ });
6608
+ console.log('[SSHIFT] OSC 52 clipboard handler registered');
6609
+ } catch (e) {
6610
+ console.warn('[SSHIFT] Failed to register OSC 52 handler:', e.message);
6611
+ }
6612
+
6358
6613
  // Enable cursor blink after addons are loaded to avoid
6359
6614
  // repaint interference during initial render
6360
6615
  terminal.options.cursorBlink = true;
@@ -6402,11 +6657,9 @@ const wheelHandler = (e) => {
6402
6657
  // Handle terminal input
6403
6658
  terminal.onData((data) => {
6404
6659
  const sess = this.sessions.get(sessionId);
6405
- console.log('[SSHIFT] Terminal input received, session:', sessionId, 'connected:', sess?.connected, 'connecting:', sess?.connecting, 'data:', JSON.stringify(data), 'ctrlPressed:', this.ctrlPressed, 'altPressed:', this.altPressed);
6406
6660
 
6407
6661
  // Only allow input if this client is the controller
6408
6662
  if (sess && !sess.isController) {
6409
- console.log('[SSHIFT] Ignoring input - not in control of session');
6410
6663
  return;
6411
6664
  }
6412
6665
 
@@ -6432,7 +6685,6 @@ const wheelHandler = (e) => {
6432
6685
  };
6433
6686
  const sequence = ctrlSequences[char];
6434
6687
  if (sequence) {
6435
- console.log('[SSHIFT] Mobile Ctrl+' + char + ' via onData, sending:', sequence.charCodeAt(0));
6436
6688
  this.socket.emit('ssh-data', { sessionId, data: sequence });
6437
6689
  // Reset Ctrl after use
6438
6690
  this.ctrlPressed = false;
@@ -6442,7 +6694,6 @@ const wheelHandler = (e) => {
6442
6694
  }
6443
6695
  } else if (this.altPressed) {
6444
6696
  // Send ESC + key for Alt
6445
- console.log('[SSHIFT] Mobile Alt+' + char + ' via onData');
6446
6697
  this.socket.emit('ssh-data', { sessionId, data: '\x1b' + data });
6447
6698
  // Reset Alt after use
6448
6699
  this.altPressed = false;
@@ -6453,11 +6704,9 @@ const wheelHandler = (e) => {
6453
6704
  }
6454
6705
  }
6455
6706
 
6456
- console.log('[SSHIFT] Sending input to server, sessionId:', sessionId);
6457
6707
  this.socket.emit('ssh-data', { sessionId, data });
6458
6708
  } else if (sess && sess.connecting) {
6459
6709
  // Buffer input while connecting (optional)
6460
- console.log('[SSHIFT] Input received while connecting, ignoring');
6461
6710
  } else {
6462
6711
  console.warn('[SSHIFT] Input received but session not connected! Session:', sess);
6463
6712
  }
@@ -6490,15 +6739,12 @@ const wheelHandler = (e) => {
6490
6739
 
6491
6740
  // Handle copy/paste keyboard shortcuts
6492
6741
  terminal.attachCustomKeyEventHandler((event) => {
6493
- console.log('[SSHIFT] Key event:', event.type, event.key, 'ctrl:', event.ctrlKey, 'shift:', event.shiftKey, 'hasSelection:', terminal.hasSelection());
6494
-
6495
6742
  // Handle mobile Ctrl modifier - apply to physical keyboard input
6496
6743
  // When mobile Ctrl is active and user types a key, send Ctrl+key
6497
6744
  if (event.type === 'keydown' && this.ctrlPressed && !event.ctrlKey) {
6498
6745
  const key = event.key.toLowerCase();
6499
6746
  // Only apply Ctrl to single character keys (letters, numbers)
6500
6747
  if (key.length === 1 && /[a-z0-9]/.test(key)) {
6501
- console.log('[SSHIFT] Mobile Ctrl active, sending Ctrl+' + key);
6502
6748
  // Send Ctrl+key sequence
6503
6749
  const ctrlSequences = {
6504
6750
  'a': '\x01', 'b': '\x02', 'c': '\x03', 'd': '\x04', 'e': '\x05',
@@ -6512,7 +6758,6 @@ const wheelHandler = (e) => {
6512
6758
  const sess = this.sessions.get(sessionId);
6513
6759
  if (sequence && sess && sess.connected) {
6514
6760
  this.socket.emit('ssh-data', { sessionId, data: sequence });
6515
- console.log('[SSHIFT] Sent Ctrl+' + key + ' sequence');
6516
6761
  }
6517
6762
  // Reset Ctrl after use
6518
6763
  this.ctrlPressed = false;
@@ -6527,12 +6772,10 @@ const wheelHandler = (e) => {
6527
6772
  const key = event.key;
6528
6773
  // Only apply Alt to single character keys
6529
6774
  if (key.length === 1) {
6530
- console.log('[SSHIFT] Mobile Alt active, sending Alt+' + key);
6531
6775
  // Send ESC + key for Alt
6532
6776
  const sess = this.sessions.get(sessionId);
6533
6777
  if (sess && sess.connected) {
6534
6778
  this.socket.emit('ssh-data', { sessionId, data: '\x1b' + key });
6535
- console.log('[SSHIFT] Sent Alt+' + key + ' sequence');
6536
6779
  }
6537
6780
  // Reset Alt after use
6538
6781
  this.altPressed = false;
@@ -6561,20 +6804,19 @@ const wheelHandler = (e) => {
6561
6804
 
6562
6805
  // Ctrl+V - Paste
6563
6806
  if (event.ctrlKey && event.key === 'v' && event.type === 'keydown') {
6564
- console.log('[SSHIFT] Paste shortcut triggered');
6807
+ event.preventDefault(); // Prevent browser paste event to avoid double-paste
6565
6808
  this.readFromClipboard().then(text => {
6566
- console.log('[SSHIFT] Clipboard content:', text ? 'found' : 'empty');
6567
6809
  if (text) {
6568
6810
  const sess = this.sessions.get(sessionId);
6569
6811
  if (sess && sess.connected) {
6570
- this.socket.emit('ssh-data', { sessionId, data: text });
6812
+ this.sendChunkedInput(sessionId, text);
6571
6813
  this.showToast('Pasted from clipboard', 'success');
6572
6814
  }
6573
6815
  } else {
6574
6816
  this.showToast('Clipboard is empty', 'info');
6575
6817
  }
6576
6818
  });
6577
- return false; // Prevent default behavior
6819
+ return false; // Prevent xterm key handling
6578
6820
  }
6579
6821
 
6580
6822
  // Ctrl+Shift+C - Force copy
@@ -6596,12 +6838,12 @@ const wheelHandler = (e) => {
6596
6838
 
6597
6839
  // Ctrl+Shift+V - Force paste
6598
6840
  if (event.ctrlKey && event.shiftKey && event.key === 'V') {
6599
- console.log('[SSHIFT] Force paste shortcut triggered');
6841
+ event.preventDefault(); // Prevent browser paste event to avoid double-paste
6600
6842
  this.readFromClipboard().then(text => {
6601
6843
  if (text) {
6602
6844
  const sess = this.sessions.get(sessionId);
6603
6845
  if (sess && sess.connected) {
6604
- this.socket.emit('ssh-data', { sessionId, data: text });
6846
+ this.sendChunkedInput(sessionId, text);
6605
6847
  this.showToast('Pasted from clipboard', 'success');
6606
6848
  }
6607
6849
  } else {
@@ -6642,49 +6884,20 @@ const wheelHandler = (e) => {
6642
6884
  }
6643
6885
  } catch (err) {
6644
6886
  console.warn('[SSHIFT] Could not pre-read clipboard:', err.name, err.message);
6645
- // Clipboard API failed, but we'll try fallback when user clicks paste
6646
6887
  }
6647
6888
 
6648
6889
  // Show terminal context menu
6649
6890
  this.showTerminalContextMenu(sessionId, terminal, e);
6650
6891
  });
6651
6892
 
6652
- // Handle native paste event from browser
6653
- container.addEventListener('paste', (e) => {
6654
- console.log('[SSHIFT] Native paste event triggered');
6655
- e.preventDefault();
6656
-
6657
- // Get pasted data from clipboard
6658
- let pastedText = '';
6659
- if (e.clipboardData && e.clipboardData.getData) {
6660
- pastedText = e.clipboardData.getData('text/plain');
6661
- }
6662
-
6663
- if (pastedText) {
6664
- console.log('[SSHIFT] Pasted text length:', pastedText.length);
6665
- const sess = this.sessions.get(sessionId);
6666
- if (sess && sess.connected) {
6667
- this.socket.emit('ssh-data', { sessionId, data: pastedText });
6668
- this.showToast('Pasted from clipboard', 'success');
6669
- }
6670
- } else {
6671
- this.showToast('Clipboard is empty', 'info');
6672
- }
6673
- });
6674
-
6675
6893
  session.terminal = terminal;
6676
6894
  session.fitAddon = fitAddon;
6677
6895
 
6678
6896
  this.updateViewportBackground(session);
6679
6897
 
6680
6898
  // Flush any data that was buffered before the terminal was ready
6681
- if (session.writeBuffer) {
6682
- terminal.write(session.writeBuffer);
6683
- session.writeBuffer = '';
6684
- if (session.writeRAF) {
6685
- cancelAnimationFrame(session.writeRAF);
6686
- session.writeRAF = null;
6687
- }
6899
+ if (session.writeChunks.length > 0 || session.flushRemaining) {
6900
+ this._flushWriteChunks(sessionId);
6688
6901
  }
6689
6902
 
6690
6903
  // Initialize mobile terminal handler for touch interactions
@@ -6810,17 +7023,11 @@ const wheelHandler = (e) => {
6810
7023
  }
6811
7024
 
6812
7025
  try {
6813
- // Buffer data and flush once per animation frame to prevent
6814
- // render queue backup during high-throughput output (e.g. video)
6815
- session.writeBuffer += data.data;
7026
+ session.writeChunks.push(data.data);
6816
7027
 
6817
7028
  if (!session.writeRAF) {
6818
7029
  session.writeRAF = requestAnimationFrame(() => {
6819
- if (session.terminal && session.writeBuffer) {
6820
- session.terminal.write(session.writeBuffer);
6821
- session.writeBuffer = '';
6822
- }
6823
- session.writeRAF = null;
7030
+ this._flushWriteChunks(data.sessionId);
6824
7031
  });
6825
7032
  }
6826
7033
 
@@ -6842,6 +7049,204 @@ const wheelHandler = (e) => {
6842
7049
  }
6843
7050
  }
6844
7051
 
7052
+ // Parse and handle OSC 52 clipboard sequences from terminal data stream.
7053
+ // Extracts clipboard content, writes it to browser clipboard, and safely
7054
+ // handles sequences that span across data chunks.
7055
+ // Also handles tmux DCS passthrough: \x1bPtmux;\x1b\x1b]52;c;...\x07\x1b\\
7056
+ _handleOsc52(data) {
7057
+ if (!data || data.indexOf('52;') === -1) return data;
7058
+
7059
+ let result = data;
7060
+
7061
+ // Handle tmux/screen DCS passthrough wrapper:
7062
+ // \x1bPtmux;\x1b wraps an inner escape sequence, terminated by \x1b\\
7063
+ // \x1bP\x1b (screen) similarly
7064
+ // We unwrap these by extracting the inner OSC 52 sequence.
7065
+ while (true) {
7066
+ const tmuxStart = result.indexOf('\x1bPtmux;\x1b');
7067
+ const screenStart = result.indexOf('\x1bP\x1b');
7068
+ let dcsStart = -1;
7069
+ let dcsPrefixLen = 0;
7070
+
7071
+ if (tmuxStart !== -1 && (screenStart === -1 || tmuxStart < screenStart)) {
7072
+ dcsStart = tmuxStart;
7073
+ dcsPrefixLen = '\x1bPtmux;\x1b'.length;
7074
+ } else if (screenStart !== -1) {
7075
+ dcsStart = screenStart;
7076
+ dcsPrefixLen = '\x1bP\x1b'.length;
7077
+ }
7078
+
7079
+ if (dcsStart !== -1) {
7080
+ // Find the DCS terminator: \x1b\\ (ST)
7081
+ const dcsEnd = result.indexOf('\x1b\\', dcsStart + dcsPrefixLen);
7082
+ if (dcsEnd !== -1) {
7083
+ // Extract the inner sequence and replace the whole DCS block with just the inner sequence
7084
+ const inner = result.substring(dcsStart + dcsPrefixLen, dcsEnd);
7085
+ result = result.substring(0, dcsStart) + inner + result.substring(dcsEnd + 2);
7086
+ } else {
7087
+ break; // Incomplete DCS, leave for next chunk
7088
+ }
7089
+ } else {
7090
+ break;
7091
+ }
7092
+ }
7093
+
7094
+ // Now process plain OSC 52 sequences
7095
+ if (result.indexOf('\x1b]52;') === -1) return result;
7096
+
7097
+ let searchFrom = 0;
7098
+
7099
+ while (true) {
7100
+ const startIdx = result.indexOf('\x1b]52;', searchFrom);
7101
+ if (startIdx === -1) break;
7102
+
7103
+ // Find end of OSC sequence: BEL (\x07) or ST (\x1b\\)
7104
+ let endIdx = -1;
7105
+ let endLen = 1;
7106
+ const belIdx = result.indexOf('\x07', startIdx + 5);
7107
+ const stIdx = result.indexOf('\x1b\\', startIdx + 5);
7108
+
7109
+ if (belIdx !== -1 && (stIdx === -1 || belIdx < stIdx)) {
7110
+ endIdx = belIdx;
7111
+ endLen = 1;
7112
+ } else if (stIdx !== -1) {
7113
+ endIdx = stIdx;
7114
+ endLen = 2;
7115
+ }
7116
+
7117
+ if (endIdx === -1) {
7118
+ break;
7119
+ }
7120
+
7121
+ // Extract the payload: everything between "ESC]52;" and the terminator
7122
+ const payloadStart = startIdx + 5; // skip \x1b]52;
7123
+ const payload = result.substring(payloadStart, endIdx);
7124
+ console.log('[SSHIFT] OSC 52 intercepted from stream, payload length:', payload.length);
7125
+
7126
+ // Parse: <target>;<base64>
7127
+ const semiIdx = payload.indexOf(';');
7128
+ if (semiIdx !== -1) {
7129
+ const clipboardTarget = payload.substring(0, semiIdx);
7130
+ const content = payload.substring(semiIdx + 1);
7131
+ if (content) {
7132
+ try {
7133
+ const decoded = atob(content);
7134
+ console.log('[SSHIFT] OSC 52 decoded, target:', clipboardTarget, 'length:', decoded.length, 'preview:', decoded.substring(0, 60));
7135
+ // Buffer synchronously, then try immediate write
7136
+ this.osc52Buffer = decoded;
7137
+ this.copyToClipboard(decoded).then(success => {
7138
+ if (success) {
7139
+ this.osc52Buffer = null;
7140
+ console.log('[SSHIFT] OSC 52 immediate clipboard write succeeded');
7141
+ } else {
7142
+ console.log('[SSHIFT] OSC 52 immediate write failed, will flush on next user gesture');
7143
+ }
7144
+ }).catch(() => {
7145
+ console.log('[SSHIFT] OSC 52 immediate write rejected, will flush on next user gesture');
7146
+ });
7147
+ } catch (e) {
7148
+ console.warn('[SSHIFT] OSC 52 base64 decode failed:', e);
7149
+ }
7150
+ } else {
7151
+ // Clear clipboard request
7152
+ this.osc52Buffer = '';
7153
+ navigator.clipboard.writeText('').catch(() => {});
7154
+ }
7155
+ }
7156
+
7157
+ // Remove the OSC 52 sequence from the data so xterm.js doesn't render garbage
7158
+ result = result.substring(0, startIdx) + result.substring(endIdx + endLen);
7159
+ searchFrom = startIdx;
7160
+ }
7161
+
7162
+ return result;
7163
+ }
7164
+
7165
+ _flushWriteChunks(sessionId) {
7166
+ const session = this.sessions.get(sessionId);
7167
+ if (!session || !session.terminal) {
7168
+ if (session) session.writeRAF = null;
7169
+ return;
7170
+ }
7171
+
7172
+ session.writeRAF = null;
7173
+
7174
+ // Combine any remaining data from last frame with new chunks
7175
+ let combined;
7176
+ if (session.writeChunks.length > 0) {
7177
+ const chunks = session.writeChunks;
7178
+ session.writeChunks = [];
7179
+ combined = chunks.length === 1 ? chunks[0] : chunks.join('');
7180
+ if (session.flushRemaining) {
7181
+ combined = session.flushRemaining + combined;
7182
+ session.flushRemaining = null;
7183
+ }
7184
+ } else if (session.flushRemaining) {
7185
+ combined = session.flushRemaining;
7186
+ session.flushRemaining = null;
7187
+ } else {
7188
+ return;
7189
+ }
7190
+
7191
+ const terminal = session.terminal;
7192
+
7193
+ // When the buffer grows large, reduce scrollback to keep write() fast.
7194
+ // terminal.write() cost is proportional to buffer size because adding lines
7195
+ // that overflow the viewport triggers O(buffer_length) buffer maintenance.
7196
+ // Dynamically lowering scrollback during heavy output limits the max buffer
7197
+ // size, keeping each write() consistently fast. It's restored after output
7198
+ // settles. We do NOT use terminal.clear() because that wipes visible content.
7199
+ const bufferLen = terminal.buffer.active.length;
7200
+ const rows = terminal.rows || 24;
7201
+ const highWatermark = rows + 200;
7202
+ const lowWatermark = rows + 100;
7203
+
7204
+ if (bufferLen > highWatermark) {
7205
+ // Buffer is large — reduce scrollback to cap the max buffer size
7206
+ const currentScrollback = terminal.options.scrollback;
7207
+ if (currentScrollback > 200 || !session.originalScrollback) {
7208
+ if (!session.originalScrollback) {
7209
+ session.originalScrollback = currentScrollback;
7210
+ }
7211
+ terminal.options.scrollback = 200;
7212
+ }
7213
+ // Cancel any pending restore since we're still in heavy output
7214
+ clearTimeout(session.scrollbackRestoreTimer);
7215
+ session.scrollbackRestoreTimer = null;
7216
+ } else if (session.originalScrollback) {
7217
+ // Schedule scrollback restoration — use a timer so it also restores
7218
+ // if the buffer stays between low and high watermarks (output stopped
7219
+ // but buffer didn't drain below lowWatermark)
7220
+ clearTimeout(session.scrollbackRestoreTimer);
7221
+ session.scrollbackRestoreTimer = setTimeout(() => {
7222
+ if (session.terminal && session.originalScrollback) {
7223
+ session.terminal.options.scrollback = session.originalScrollback;
7224
+ session.originalScrollback = null;
7225
+ }
7226
+ session.scrollbackRestoreTimer = null;
7227
+ }, 3000);
7228
+ }
7229
+
7230
+ // Intercept OSC 52 clipboard sequences before writing to terminal.
7231
+ // OSC 52 format: ESC ] 52 ; <target> ; <base64> (BEL or ST)
7232
+ // This is more reliable than registerOscHandler which may not fire.
7233
+ combined = this._handleOsc52(combined);
7234
+
7235
+ // Cap write size per frame. terminal.write() is synchronous and blocks
7236
+ // the main thread. We spill overflow to the next frame via flushRemaining.
7237
+ const MAX_WRITE_PER_FRAME = 32768;
7238
+
7239
+ if (combined.length > MAX_WRITE_PER_FRAME) {
7240
+ terminal.write(combined.substring(0, MAX_WRITE_PER_FRAME));
7241
+ session.flushRemaining = combined.substring(MAX_WRITE_PER_FRAME);
7242
+ session.writeRAF = requestAnimationFrame(() => {
7243
+ this._flushWriteChunks(sessionId);
7244
+ });
7245
+ } else {
7246
+ terminal.write(combined);
7247
+ }
7248
+ }
7249
+
6845
7250
  // SFTP Session Management
6846
7251
  createSFTPTab(name, connectionData, restoreSessionId = null) {
6847
7252
  const sessionId = restoreSessionId || 'sftp-' + Date.now();
@@ -7423,6 +7828,15 @@ const wheelHandler = (e) => {
7423
7828
  cancelAnimationFrame(session.writeRAF);
7424
7829
  session.writeRAF = null;
7425
7830
  }
7831
+ // Clean up scrollback restore timer
7832
+ if (session.scrollbackRestoreTimer) {
7833
+ clearTimeout(session.scrollbackRestoreTimer);
7834
+ session.scrollbackRestoreTimer = null;
7835
+ }
7836
+ // Restore scrollback if it was dynamically reduced
7837
+ if (session.originalScrollback && session.terminal) {
7838
+ session.terminal.options.scrollback = session.originalScrollback;
7839
+ }
7426
7840
  // Clean up mobile handler
7427
7841
  if (session.mobileHandler) {
7428
7842
  session.mobileHandler.destroy();
@@ -7434,6 +7848,13 @@ const wheelHandler = (e) => {
7434
7848
  session.wheelHandler = null;
7435
7849
  session.wheelElement = null;
7436
7850
  }
7851
+ // Clean up OSC 52 clipboard flush listeners
7852
+ if (session.osc52FlushListener) {
7853
+ document.removeEventListener('click', session.osc52FlushListener, true);
7854
+ document.removeEventListener('keydown', session.osc52FlushListener, true);
7855
+ document.removeEventListener('touchstart', session.osc52FlushListener, true);
7856
+ session.osc52FlushListener = null;
7857
+ }
7437
7858
  if (session.terminal) {
7438
7859
  session.terminal.dispose();
7439
7860
  }
@@ -7531,9 +7952,24 @@ const wheelHandler = (e) => {
7531
7952
 
7532
7953
  // Clean up the session locally (don't emit tab-close again)
7533
7954
  if (session.type === 'ssh') {
7955
+ if (session.writeRAF) {
7956
+ cancelAnimationFrame(session.writeRAF);
7957
+ }
7958
+ if (session.scrollbackRestoreTimer) {
7959
+ clearTimeout(session.scrollbackRestoreTimer);
7960
+ }
7961
+ if (session.originalScrollback && session.terminal) {
7962
+ session.terminal.options.scrollback = session.originalScrollback;
7963
+ }
7534
7964
  if (session.wheelHandler && session.wheelElement) {
7535
7965
  session.wheelElement.removeEventListener('wheel', session.wheelHandler);
7536
7966
  }
7967
+ if (session.osc52FlushListener) {
7968
+ document.removeEventListener('click', session.osc52FlushListener, true);
7969
+ document.removeEventListener('keydown', session.osc52FlushListener, true);
7970
+ document.removeEventListener('touchstart', session.osc52FlushListener, true);
7971
+ session.osc52FlushListener = null;
7972
+ }
7537
7973
  if (session.terminal) {
7538
7974
  session.terminal.dispose();
7539
7975
  }
@@ -8643,11 +9079,9 @@ async syncTabsFromServer(tabs) {
8643
9079
  if (clipboardContent) {
8644
9080
  // We have clipboard content, paste it
8645
9081
  const sess = this.sessions.get(sessionId);
8646
- console.log('[SSHIFT] Session found:', !!sess, 'connected:', sess?.connected);
8647
9082
  if (sess && sess.connected) {
8648
- this.socket.emit('ssh-data', { sessionId, data: clipboardContent });
9083
+ this.sendChunkedInput(sessionId, clipboardContent);
8649
9084
  this.showToast('Pasted from clipboard', 'success');
8650
- console.log('[SSHIFT] Paste successful');
8651
9085
  // Focus terminal after paste
8652
9086
  if (this.isMobile && sess.mobileHandler && sess.mobileHandler.hiddenTextarea) {
8653
9087
  sess.mobileHandler._focusHiddenTextarea();
@@ -8760,7 +9194,7 @@ async syncTabsFromServer(tabs) {
8760
9194
  if (text) {
8761
9195
  const sess = this.sessions.get(sessionId);
8762
9196
  if (sess && sess.connected) {
8763
- this.socket.emit('ssh-data', { sessionId, data: text });
9197
+ this.sendChunkedInput(sessionId, text);
8764
9198
  this.showToast('Pasted from clipboard', 'success');
8765
9199
  // Focus terminal after paste
8766
9200
  if (sess.terminal) {
@@ -9991,6 +10425,12 @@ async syncTabsFromServer(tabs) {
9991
10425
 
9992
10426
  const data = await response.json();
9993
10427
 
10428
+ // Check for update error from server
10429
+ if (data.updateError) {
10430
+ this.handleUpdateError(data.updateError);
10431
+ return;
10432
+ }
10433
+
9994
10434
  // Update progress based on status
9995
10435
  if (data.updating) {
9996
10436
  // Still updating
@@ -10028,23 +10468,25 @@ async syncTabsFromServer(tabs) {
10028
10468
  window.location.reload();
10029
10469
  }, 1000);
10030
10470
  } else if (data.ready && data.version === oldVersion) {
10031
- // Server restarted but version is the same
10032
- // This might mean the update failed or we need to wait longer
10033
- if (attempts < maxAttempts) {
10034
- const progress = Math.min(90, 70 + (attempts * 0.5));
10035
- if (progressBar) {
10036
- progressBar.style.width = `${progress}%`;
10037
- }
10038
-
10039
- if (statusEl) {
10040
- statusEl.textContent = `Waiting for new version... (${attempts}/${maxAttempts})`;
10041
- }
10042
-
10043
- setTimeout(poll, 1000);
10044
- } else {
10045
- // Same version after timeout - might be an error
10046
- this.handleUpdateError('Server restarted but version unchanged. Please check the update manually.');
10471
+ // Server is back and ready. Same version could mean:
10472
+ // 1. Already at the latest version (npm install succeeded but no newer version exists)
10473
+ // 2. Update failed silently
10474
+ // Either way, the server is back and functional — just reload.
10475
+ if (progressBar) {
10476
+ progressBar.style.width = '100%';
10477
+ }
10478
+
10479
+ if (messageEl) {
10480
+ messageEl.textContent = 'Server restarted. Reloading page...';
10047
10481
  }
10482
+
10483
+ if (statusEl) {
10484
+ statusEl.textContent = `Current version: ${data.version}`;
10485
+ }
10486
+
10487
+ setTimeout(() => {
10488
+ window.location.reload();
10489
+ }, 1000);
10048
10490
  } else {
10049
10491
  // Unexpected state
10050
10492
  if (attempts < maxAttempts) {