@lethevimlet/sshift 1.0.2 → 1.0.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -33,7 +33,7 @@ class SSHManager {
33
33
  const terminal = new Terminal({
34
34
  cols: cols,
35
35
  rows: rows,
36
- scrollback: 5000,
36
+ scrollback: 2000,
37
37
  allowProposedApi: true,
38
38
  logLevel: 'off'
39
39
  });
@@ -59,9 +59,12 @@ class SSHManager {
59
59
  username: options.username,
60
60
  connectedAt: Date.now(),
61
61
  // Data batching state
62
- dataBuffer: '', // Buffer for outgoing data
62
+ dataChunks: [], // Array of chunks for outgoing data (avoids O(n^2) string concat)
63
+ dataBufferSize: 0, // Running total of chunk lengths for fast size checks
63
64
  batchTimer: null, // Timer for batched sends
64
- lastDataTime: 0 // Timestamp of last data received
65
+ lastDataTime: 0, // Timestamp of last data received
66
+ writeQueue: null, // Queue for writes when stream is congested
67
+ drainListener: false // Whether a drain listener is active
65
68
  };
66
69
 
67
70
  const config = {
@@ -149,19 +152,14 @@ class SSHManager {
149
152
  stream.on('data', (data) => {
150
153
  const dataStr = data.toString('utf8');
151
154
 
152
- // Write to headless terminal for state sync (join/resume)
153
- session.terminal.write(dataStr);
154
-
155
- // Buffer data for batched broadcast
155
+ // Buffer data for batched broadcast (headless terminal write
156
+ // is also batched inside bufferData to avoid per-chunk writes)
156
157
  this.bufferData(sessionId, dataStr);
157
158
  });
158
159
 
159
160
  stream.stderr.on('data', (data) => {
160
161
  const dataStr = data.toString('utf8');
161
162
 
162
- // Write to headless terminal for state sync
163
- session.terminal.write(dataStr);
164
-
165
163
  // Buffer data for batched broadcast
166
164
  this.bufferData(sessionId, dataStr);
167
165
  });
@@ -228,15 +226,13 @@ class SSHManager {
228
226
  const session = this.sessions.get(sessionId);
229
227
  if (!session) return;
230
228
 
231
- // Notify plugins about terminal output
232
- pluginManager.onData(sessionId, dataStr);
233
-
234
- // Add data to buffer
235
- session.dataBuffer += dataStr;
229
+ // Add data to chunk array (avoids O(n^2) string concatenation)
230
+ session.dataChunks.push(dataStr);
231
+ session.dataBufferSize += dataStr.length;
236
232
  session.lastDataTime = Date.now();
237
233
 
238
234
  // If buffer exceeds max size, flush immediately
239
- if (session.dataBuffer.length >= this.batchMaxSize) {
235
+ if (session.dataBufferSize >= this.batchMaxSize) {
240
236
  this.flushData(sessionId);
241
237
  return;
242
238
  }
@@ -261,12 +257,23 @@ class SSHManager {
261
257
  }
262
258
 
263
259
  // If there's data to send, broadcast it
264
- if (session.dataBuffer.length > 0) {
260
+ if (session.dataChunks.length > 0) {
261
+ const joinedData = session.dataChunks.join('');
262
+
263
+ // Write to headless terminal for state sync (batched write)
264
+ if (session.terminal) {
265
+ session.terminal.write(joinedData);
266
+ }
267
+
268
+ // Notify plugins about terminal output (batched, not per-chunk)
269
+ pluginManager.onData(sessionId, joinedData);
270
+
265
271
  this.broadcastToSession(sessionId, 'ssh-data', {
266
272
  sessionId,
267
- data: session.dataBuffer
273
+ data: joinedData
268
274
  });
269
- session.dataBuffer = '';
275
+ session.dataChunks = [];
276
+ session.dataBufferSize = 0;
270
277
  }
271
278
  }
272
279
 
@@ -470,7 +477,25 @@ class SSHManager {
470
477
  write(sessionId, data) {
471
478
  const session = this.sessions.get(sessionId);
472
479
  if (session && session.stream) {
473
- session.stream.write(data);
480
+ const canWrite = session.stream.write(data);
481
+ if (!canWrite) {
482
+ // Stream buffer is full — queue write and wait for drain
483
+ if (!session.writeQueue) session.writeQueue = [];
484
+ session.writeQueue.push(data);
485
+ if (!session.drainListener) {
486
+ session.drainListener = true;
487
+ session.stream.once('drain', () => {
488
+ session.drainListener = false;
489
+ if (session.writeQueue && session.writeQueue.length > 0) {
490
+ const queue = session.writeQueue;
491
+ session.writeQueue = [];
492
+ for (const chunk of queue) {
493
+ this.write(sessionId, chunk);
494
+ }
495
+ }
496
+ });
497
+ }
498
+ }
474
499
  }
475
500
  }
476
501
 
@@ -4759,10 +4759,32 @@ body.dragging-tabs .tabs-container {
4759
4759
  /* Mobile context menu adjustments */
4760
4760
  .mobile-context-menu {
4761
4761
  max-width: calc(100vw - 32px);
4762
+ padding: 4px;
4763
+ border-radius: 6px;
4762
4764
  }
4763
4765
 
4766
+ .mobile-menu-drag-handle {
4767
+ padding: 3px 0;
4768
+ }
4769
+
4770
+ .mobile-menu-drag-handle i {
4771
+ font-size: 10px;
4772
+ }
4773
+
4764
4774
  .mobile-menu-btn {
4765
- min-height: 36px; /* Compact touch target matching button size */
4775
+ padding: 5px 8px;
4776
+ font-size: 12px;
4777
+ min-width: 39px;
4778
+ min-height: 47px;
4779
+ gap: 2px;
4780
+ }
4781
+
4782
+ .mobile-menu-btn i {
4783
+ font-size: 16px;
4784
+ }
4785
+
4786
+ .mobile-menu-btn span {
4787
+ font-size: 10px;
4766
4788
  }
4767
4789
  }
4768
4790
 
@@ -802,6 +802,63 @@ class SSHIFTClient {
802
802
  });
803
803
  }
804
804
 
805
+ sendChunkedInput(sessionId, data, chunkSize = 2048) {
806
+ if (!data || !this.sessions.has(sessionId)) return;
807
+ const session = this.sessions.get(sessionId);
808
+ if (!session || !session.connected) return;
809
+
810
+ // Terminal emulators convert \n to \r before sending to the PTY.
811
+ // Clipboard text contains \n line endings, but PTY input expects \r
812
+ // as the "Enter" character. Without this conversion, programs like
813
+ // nano interpret \n as a raw newline that doesn't trigger line actions.
814
+ data = data.replace(/\r\n/g, '\r').replace(/\n/g, '\r');
815
+
816
+ // Wrap in bracketed paste sequences so the remote shell treats this as
817
+ // a single paste rather than individual keystrokes.
818
+ const BP_START = '\x1b[200~';
819
+ const BP_END = '\x1b[201~';
820
+
821
+ const wrapped = BP_START + data + BP_END;
822
+
823
+ if (wrapped.length <= chunkSize) {
824
+ this.socket.emit('ssh-data', { sessionId, data: wrapped });
825
+ return;
826
+ }
827
+
828
+ // For large pastes, send the start bracket, then chunk the content,
829
+ // then send the end bracket. This keeps bracketed paste mode intact
830
+ // across all chunks.
831
+ let offset = 0;
832
+ let isFirst = true;
833
+ const sendNext = () => {
834
+ if (offset >= data.length) {
835
+ this.socket.emit('ssh-data', { sessionId, data: BP_END });
836
+ return;
837
+ }
838
+ let end = Math.min(offset + chunkSize, data.length);
839
+ if (end < data.length) {
840
+ // Split at the last \r to keep line boundaries intact
841
+ const lastCr = data.lastIndexOf('\r', end);
842
+ if (lastCr > offset) {
843
+ end = lastCr + 1;
844
+ }
845
+ }
846
+ let chunk = data.substring(offset, end);
847
+ if (isFirst) {
848
+ chunk = BP_START + chunk;
849
+ isFirst = false;
850
+ }
851
+ offset = end;
852
+ this.socket.emit('ssh-data', { sessionId, data: chunk });
853
+ if (offset < data.length) {
854
+ setTimeout(sendNext, 5);
855
+ } else {
856
+ this.socket.emit('ssh-data', { sessionId, data: BP_END });
857
+ }
858
+ };
859
+ sendNext();
860
+ }
861
+
805
862
  // Legacy method for backwards compatibility
806
863
  saveStickySessions() {
807
864
  this.saveTabs();
@@ -5884,8 +5941,11 @@ const wheelHandler = (e) => {
5884
5941
  syncing: false, // Flag to prevent data writes during screen sync
5885
5942
  fontSize: this.terminalFontSize, // Initialize with default font size
5886
5943
  mobileHandler: null, // Mobile terminal handler for touch interactions
5887
- writeBuffer: '', // Buffer for batching terminal writes
5888
- writeRAF: null // requestAnimationFrame ID for write flush
5944
+ writeChunks: [], // Array of chunks for batching terminal writes (avoids O(n^2) string concat)
5945
+ writeRAF: null, // requestAnimationFrame ID for write flush
5946
+ flushRemaining: null, // Remaining data from a frame that exceeded the write cap
5947
+ originalScrollback: null, // Stores original scrollback before dynamic reduction
5948
+ scrollbackRestoreTimer: null
5889
5949
  });
5890
5950
 
5891
5951
  // Switch to the new tab FIRST to make the container visible
@@ -6255,7 +6315,7 @@ const wheelHandler = (e) => {
6255
6315
  lineHeight: 1.0,
6256
6316
  cursorBlink: false,
6257
6317
  cursorStyle: 'block',
6258
- scrollback: 5000,
6318
+ scrollback: 2000,
6259
6319
  allowProposedApi: true,
6260
6320
  convertEol: true,
6261
6321
  allowTransparency: false,
@@ -6402,11 +6462,9 @@ const wheelHandler = (e) => {
6402
6462
  // Handle terminal input
6403
6463
  terminal.onData((data) => {
6404
6464
  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
6465
 
6407
6466
  // Only allow input if this client is the controller
6408
6467
  if (sess && !sess.isController) {
6409
- console.log('[SSHIFT] Ignoring input - not in control of session');
6410
6468
  return;
6411
6469
  }
6412
6470
 
@@ -6432,7 +6490,6 @@ const wheelHandler = (e) => {
6432
6490
  };
6433
6491
  const sequence = ctrlSequences[char];
6434
6492
  if (sequence) {
6435
- console.log('[SSHIFT] Mobile Ctrl+' + char + ' via onData, sending:', sequence.charCodeAt(0));
6436
6493
  this.socket.emit('ssh-data', { sessionId, data: sequence });
6437
6494
  // Reset Ctrl after use
6438
6495
  this.ctrlPressed = false;
@@ -6442,7 +6499,6 @@ const wheelHandler = (e) => {
6442
6499
  }
6443
6500
  } else if (this.altPressed) {
6444
6501
  // Send ESC + key for Alt
6445
- console.log('[SSHIFT] Mobile Alt+' + char + ' via onData');
6446
6502
  this.socket.emit('ssh-data', { sessionId, data: '\x1b' + data });
6447
6503
  // Reset Alt after use
6448
6504
  this.altPressed = false;
@@ -6453,11 +6509,9 @@ const wheelHandler = (e) => {
6453
6509
  }
6454
6510
  }
6455
6511
 
6456
- console.log('[SSHIFT] Sending input to server, sessionId:', sessionId);
6457
6512
  this.socket.emit('ssh-data', { sessionId, data });
6458
6513
  } else if (sess && sess.connecting) {
6459
6514
  // Buffer input while connecting (optional)
6460
- console.log('[SSHIFT] Input received while connecting, ignoring');
6461
6515
  } else {
6462
6516
  console.warn('[SSHIFT] Input received but session not connected! Session:', sess);
6463
6517
  }
@@ -6490,15 +6544,12 @@ const wheelHandler = (e) => {
6490
6544
 
6491
6545
  // Handle copy/paste keyboard shortcuts
6492
6546
  terminal.attachCustomKeyEventHandler((event) => {
6493
- console.log('[SSHIFT] Key event:', event.type, event.key, 'ctrl:', event.ctrlKey, 'shift:', event.shiftKey, 'hasSelection:', terminal.hasSelection());
6494
-
6495
6547
  // Handle mobile Ctrl modifier - apply to physical keyboard input
6496
6548
  // When mobile Ctrl is active and user types a key, send Ctrl+key
6497
6549
  if (event.type === 'keydown' && this.ctrlPressed && !event.ctrlKey) {
6498
6550
  const key = event.key.toLowerCase();
6499
6551
  // Only apply Ctrl to single character keys (letters, numbers)
6500
6552
  if (key.length === 1 && /[a-z0-9]/.test(key)) {
6501
- console.log('[SSHIFT] Mobile Ctrl active, sending Ctrl+' + key);
6502
6553
  // Send Ctrl+key sequence
6503
6554
  const ctrlSequences = {
6504
6555
  'a': '\x01', 'b': '\x02', 'c': '\x03', 'd': '\x04', 'e': '\x05',
@@ -6512,7 +6563,6 @@ const wheelHandler = (e) => {
6512
6563
  const sess = this.sessions.get(sessionId);
6513
6564
  if (sequence && sess && sess.connected) {
6514
6565
  this.socket.emit('ssh-data', { sessionId, data: sequence });
6515
- console.log('[SSHIFT] Sent Ctrl+' + key + ' sequence');
6516
6566
  }
6517
6567
  // Reset Ctrl after use
6518
6568
  this.ctrlPressed = false;
@@ -6527,12 +6577,10 @@ const wheelHandler = (e) => {
6527
6577
  const key = event.key;
6528
6578
  // Only apply Alt to single character keys
6529
6579
  if (key.length === 1) {
6530
- console.log('[SSHIFT] Mobile Alt active, sending Alt+' + key);
6531
6580
  // Send ESC + key for Alt
6532
6581
  const sess = this.sessions.get(sessionId);
6533
6582
  if (sess && sess.connected) {
6534
6583
  this.socket.emit('ssh-data', { sessionId, data: '\x1b' + key });
6535
- console.log('[SSHIFT] Sent Alt+' + key + ' sequence');
6536
6584
  }
6537
6585
  // Reset Alt after use
6538
6586
  this.altPressed = false;
@@ -6561,13 +6609,11 @@ const wheelHandler = (e) => {
6561
6609
 
6562
6610
  // Ctrl+V - Paste
6563
6611
  if (event.ctrlKey && event.key === 'v' && event.type === 'keydown') {
6564
- console.log('[SSHIFT] Paste shortcut triggered');
6565
6612
  this.readFromClipboard().then(text => {
6566
- console.log('[SSHIFT] Clipboard content:', text ? 'found' : 'empty');
6567
6613
  if (text) {
6568
6614
  const sess = this.sessions.get(sessionId);
6569
6615
  if (sess && sess.connected) {
6570
- this.socket.emit('ssh-data', { sessionId, data: text });
6616
+ this.sendChunkedInput(sessionId, text);
6571
6617
  this.showToast('Pasted from clipboard', 'success');
6572
6618
  }
6573
6619
  } else {
@@ -6596,12 +6642,11 @@ const wheelHandler = (e) => {
6596
6642
 
6597
6643
  // Ctrl+Shift+V - Force paste
6598
6644
  if (event.ctrlKey && event.shiftKey && event.key === 'V') {
6599
- console.log('[SSHIFT] Force paste shortcut triggered');
6600
6645
  this.readFromClipboard().then(text => {
6601
6646
  if (text) {
6602
6647
  const sess = this.sessions.get(sessionId);
6603
6648
  if (sess && sess.connected) {
6604
- this.socket.emit('ssh-data', { sessionId, data: text });
6649
+ this.sendChunkedInput(sessionId, text);
6605
6650
  this.showToast('Pasted from clipboard', 'success');
6606
6651
  }
6607
6652
  } else {
@@ -6642,7 +6687,6 @@ const wheelHandler = (e) => {
6642
6687
  }
6643
6688
  } catch (err) {
6644
6689
  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
6690
  }
6647
6691
 
6648
6692
  // Show terminal context menu
@@ -6664,7 +6708,7 @@ const wheelHandler = (e) => {
6664
6708
  console.log('[SSHIFT] Pasted text length:', pastedText.length);
6665
6709
  const sess = this.sessions.get(sessionId);
6666
6710
  if (sess && sess.connected) {
6667
- this.socket.emit('ssh-data', { sessionId, data: pastedText });
6711
+ this.sendChunkedInput(sessionId, pastedText);
6668
6712
  this.showToast('Pasted from clipboard', 'success');
6669
6713
  }
6670
6714
  } else {
@@ -6678,13 +6722,8 @@ const wheelHandler = (e) => {
6678
6722
  this.updateViewportBackground(session);
6679
6723
 
6680
6724
  // 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
- }
6725
+ if (session.writeChunks.length > 0 || session.flushRemaining) {
6726
+ this._flushWriteChunks(sessionId);
6688
6727
  }
6689
6728
 
6690
6729
  // Initialize mobile terminal handler for touch interactions
@@ -6810,17 +6849,11 @@ const wheelHandler = (e) => {
6810
6849
  }
6811
6850
 
6812
6851
  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;
6852
+ session.writeChunks.push(data.data);
6816
6853
 
6817
6854
  if (!session.writeRAF) {
6818
6855
  session.writeRAF = requestAnimationFrame(() => {
6819
- if (session.terminal && session.writeBuffer) {
6820
- session.terminal.write(session.writeBuffer);
6821
- session.writeBuffer = '';
6822
- }
6823
- session.writeRAF = null;
6856
+ this._flushWriteChunks(data.sessionId);
6824
6857
  });
6825
6858
  }
6826
6859
 
@@ -6842,6 +6875,86 @@ const wheelHandler = (e) => {
6842
6875
  }
6843
6876
  }
6844
6877
 
6878
+ _flushWriteChunks(sessionId) {
6879
+ const session = this.sessions.get(sessionId);
6880
+ if (!session || !session.terminal) {
6881
+ if (session) session.writeRAF = null;
6882
+ return;
6883
+ }
6884
+
6885
+ session.writeRAF = null;
6886
+
6887
+ // Combine any remaining data from last frame with new chunks
6888
+ let combined;
6889
+ if (session.writeChunks.length > 0) {
6890
+ const chunks = session.writeChunks;
6891
+ session.writeChunks = [];
6892
+ combined = chunks.length === 1 ? chunks[0] : chunks.join('');
6893
+ if (session.flushRemaining) {
6894
+ combined = session.flushRemaining + combined;
6895
+ session.flushRemaining = null;
6896
+ }
6897
+ } else if (session.flushRemaining) {
6898
+ combined = session.flushRemaining;
6899
+ session.flushRemaining = null;
6900
+ } else {
6901
+ return;
6902
+ }
6903
+
6904
+ const terminal = session.terminal;
6905
+
6906
+ // When the buffer grows large, reduce scrollback to keep write() fast.
6907
+ // terminal.write() cost is proportional to buffer size because adding lines
6908
+ // that overflow the viewport triggers O(buffer_length) buffer maintenance.
6909
+ // Dynamically lowering scrollback during heavy output limits the max buffer
6910
+ // size, keeping each write() consistently fast. It's restored after output
6911
+ // settles. We do NOT use terminal.clear() because that wipes visible content.
6912
+ const bufferLen = terminal.buffer.active.length;
6913
+ const rows = terminal.rows || 24;
6914
+ const highWatermark = rows + 200;
6915
+ const lowWatermark = rows + 100;
6916
+
6917
+ if (bufferLen > highWatermark) {
6918
+ // Buffer is large — reduce scrollback to cap the max buffer size
6919
+ const currentScrollback = terminal.options.scrollback;
6920
+ if (currentScrollback > 200 || !session.originalScrollback) {
6921
+ if (!session.originalScrollback) {
6922
+ session.originalScrollback = currentScrollback;
6923
+ }
6924
+ terminal.options.scrollback = 200;
6925
+ }
6926
+ // Cancel any pending restore since we're still in heavy output
6927
+ clearTimeout(session.scrollbackRestoreTimer);
6928
+ session.scrollbackRestoreTimer = null;
6929
+ } else if (session.originalScrollback) {
6930
+ // Schedule scrollback restoration — use a timer so it also restores
6931
+ // if the buffer stays between low and high watermarks (output stopped
6932
+ // but buffer didn't drain below lowWatermark)
6933
+ clearTimeout(session.scrollbackRestoreTimer);
6934
+ session.scrollbackRestoreTimer = setTimeout(() => {
6935
+ if (session.terminal && session.originalScrollback) {
6936
+ session.terminal.options.scrollback = session.originalScrollback;
6937
+ session.originalScrollback = null;
6938
+ }
6939
+ session.scrollbackRestoreTimer = null;
6940
+ }, 3000);
6941
+ }
6942
+
6943
+ // Cap write size per frame. terminal.write() is synchronous and blocks
6944
+ // the main thread. We spill overflow to the next frame via flushRemaining.
6945
+ const MAX_WRITE_PER_FRAME = 32768;
6946
+
6947
+ if (combined.length > MAX_WRITE_PER_FRAME) {
6948
+ terminal.write(combined.substring(0, MAX_WRITE_PER_FRAME));
6949
+ session.flushRemaining = combined.substring(MAX_WRITE_PER_FRAME);
6950
+ session.writeRAF = requestAnimationFrame(() => {
6951
+ this._flushWriteChunks(sessionId);
6952
+ });
6953
+ } else {
6954
+ terminal.write(combined);
6955
+ }
6956
+ }
6957
+
6845
6958
  // SFTP Session Management
6846
6959
  createSFTPTab(name, connectionData, restoreSessionId = null) {
6847
6960
  const sessionId = restoreSessionId || 'sftp-' + Date.now();
@@ -7423,6 +7536,15 @@ const wheelHandler = (e) => {
7423
7536
  cancelAnimationFrame(session.writeRAF);
7424
7537
  session.writeRAF = null;
7425
7538
  }
7539
+ // Clean up scrollback restore timer
7540
+ if (session.scrollbackRestoreTimer) {
7541
+ clearTimeout(session.scrollbackRestoreTimer);
7542
+ session.scrollbackRestoreTimer = null;
7543
+ }
7544
+ // Restore scrollback if it was dynamically reduced
7545
+ if (session.originalScrollback && session.terminal) {
7546
+ session.terminal.options.scrollback = session.originalScrollback;
7547
+ }
7426
7548
  // Clean up mobile handler
7427
7549
  if (session.mobileHandler) {
7428
7550
  session.mobileHandler.destroy();
@@ -7531,6 +7653,15 @@ const wheelHandler = (e) => {
7531
7653
 
7532
7654
  // Clean up the session locally (don't emit tab-close again)
7533
7655
  if (session.type === 'ssh') {
7656
+ if (session.writeRAF) {
7657
+ cancelAnimationFrame(session.writeRAF);
7658
+ }
7659
+ if (session.scrollbackRestoreTimer) {
7660
+ clearTimeout(session.scrollbackRestoreTimer);
7661
+ }
7662
+ if (session.originalScrollback && session.terminal) {
7663
+ session.terminal.options.scrollback = session.originalScrollback;
7664
+ }
7534
7665
  if (session.wheelHandler && session.wheelElement) {
7535
7666
  session.wheelElement.removeEventListener('wheel', session.wheelHandler);
7536
7667
  }
@@ -8643,11 +8774,9 @@ async syncTabsFromServer(tabs) {
8643
8774
  if (clipboardContent) {
8644
8775
  // We have clipboard content, paste it
8645
8776
  const sess = this.sessions.get(sessionId);
8646
- console.log('[SSHIFT] Session found:', !!sess, 'connected:', sess?.connected);
8647
8777
  if (sess && sess.connected) {
8648
- this.socket.emit('ssh-data', { sessionId, data: clipboardContent });
8778
+ this.sendChunkedInput(sessionId, clipboardContent);
8649
8779
  this.showToast('Pasted from clipboard', 'success');
8650
- console.log('[SSHIFT] Paste successful');
8651
8780
  // Focus terminal after paste
8652
8781
  if (this.isMobile && sess.mobileHandler && sess.mobileHandler.hiddenTextarea) {
8653
8782
  sess.mobileHandler._focusHiddenTextarea();
@@ -8760,7 +8889,7 @@ async syncTabsFromServer(tabs) {
8760
8889
  if (text) {
8761
8890
  const sess = this.sessions.get(sessionId);
8762
8891
  if (sess && sess.connected) {
8763
- this.socket.emit('ssh-data', { sessionId, data: text });
8892
+ this.sendChunkedInput(sessionId, text);
8764
8893
  this.showToast('Pasted from clipboard', 'success');
8765
8894
  // Focus terminal after paste
8766
8895
  if (sess.terminal) {
@@ -1143,16 +1143,11 @@ class MobileTerminalHandler {
1143
1143
  _pasteText(text) {
1144
1144
  if (!text) return;
1145
1145
 
1146
- // Send paste to server
1147
1146
  const session = this.app.sessions.get(this.sessionId);
1148
- if (session && session.socket && session.connected) {
1149
- session.socket.emit('terminal:input', {
1150
- sessionId: this.sessionId,
1151
- data: text
1152
- });
1147
+ if (session && session.connected) {
1148
+ this.app.sendChunkedInput(this.sessionId, text);
1149
+ this.app.showToast('Pasted', 'success');
1153
1150
  }
1154
-
1155
- this.app.showToast('Pasted', 'success');
1156
1151
  }
1157
1152
 
1158
1153
  /**
@@ -1271,11 +1266,8 @@ class MobileTerminalHandler {
1271
1266
  */
1272
1267
  _sendToTerminal(text) {
1273
1268
  const session = this.app.sessions.get(this.sessionId);
1274
- if (session && session.socket && session.connected && session.isController) {
1275
- session.socket.emit('terminal:input', {
1276
- sessionId: this.sessionId,
1277
- data: text
1278
- });
1269
+ if (session && session.connected && session.isController) {
1270
+ this.app.socket.emit('ssh-data', { sessionId: this.sessionId, data: text });
1279
1271
  }
1280
1272
  }
1281
1273
 
@@ -26,7 +26,8 @@ let config = {
26
26
 
27
27
  function createSessionState(sessionId) {
28
28
  return {
29
- buffer: '',
29
+ chunks: [],
30
+ bufferSize: 0,
30
31
  timerActive: false,
31
32
  paused: false,
32
33
  totalBytesReceived: 0,
@@ -49,26 +50,42 @@ function flushChunks(sessionId) {
49
50
  return;
50
51
  }
51
52
 
52
- if (session.buffer.length === 0) {
53
+ if (session.chunks.length === 0) {
53
54
  session.timerActive = false;
54
55
  return;
55
56
  }
56
57
 
57
58
  // Take up to chunkSize bytes from the buffer
58
- const chunk = session.buffer.substring(0, config.chunkSize);
59
- session.buffer = session.buffer.substring(config.chunkSize);
59
+ let sentSize = 0;
60
+ const sendChunks = [];
61
+ while (session.chunks.length > 0 && sentSize < config.chunkSize) {
62
+ const chunk = session.chunks.shift();
63
+ if (sentSize + chunk.length <= config.chunkSize) {
64
+ sendChunks.push(chunk);
65
+ sentSize += chunk.length;
66
+ } else {
67
+ const remaining = config.chunkSize - sentSize;
68
+ sendChunks.push(chunk.substring(0, remaining));
69
+ session.chunks.unshift(chunk.substring(remaining));
70
+ session.bufferSize -= remaining;
71
+ sentSize = config.chunkSize;
72
+ break;
73
+ }
74
+ }
75
+ session.bufferSize -= sentSize;
60
76
 
61
- session.totalBytesSent += chunk.length;
77
+ const data = sendChunks.join('');
78
+ session.totalBytesSent += data.length;
62
79
  session.chunksSent++;
63
80
 
64
81
  self.postMessage({
65
82
  type: 'data',
66
83
  sessionId: sessionId,
67
- data: chunk
84
+ data: data
68
85
  });
69
86
 
70
87
  // If there's more data to send, schedule next chunk
71
- if (session.buffer.length > 0) {
88
+ if (session.chunks.length > 0) {
72
89
  setTimeout(() => flushChunks(sessionId), config.flushInterval);
73
90
  } else {
74
91
  session.timerActive = false;
@@ -98,25 +115,30 @@ self.onmessage = function(e) {
98
115
  if (!sessionId) break;
99
116
 
100
117
  const session = getOrCreateSession(sessionId);
101
- session.totalBytesReceived += (msg.data || '').length;
118
+ const dataLen = (msg.data || '').length;
119
+ session.totalBytesReceived += dataLen;
102
120
 
103
121
  // Drop data if buffer is overwhelmed (prevents memory explosion)
104
- if (session.buffer.length + (msg.data || '').length > MAX_BUFFER_SIZE) {
122
+ if (session.bufferSize + dataLen > MAX_BUFFER_SIZE) {
105
123
  // Emergency: flush entire buffer immediately in one go
106
124
  // Better than dropping data silently
107
- if (session.buffer.length > 0) {
125
+ if (session.chunks.length > 0) {
108
126
  self.postMessage({
109
127
  type: 'data',
110
128
  sessionId: sessionId,
111
- data: session.buffer
129
+ data: session.chunks.join('')
112
130
  });
113
- session.totalBytesSent += session.buffer.length;
131
+ session.totalBytesSent += session.bufferSize;
114
132
  session.chunksSent++;
115
- session.buffer = '';
133
+ session.chunks = [];
134
+ session.bufferSize = 0;
116
135
  }
117
136
  }
118
137
 
119
- session.buffer += msg.data || '';
138
+ if (msg.data) {
139
+ session.chunks.push(msg.data);
140
+ session.bufferSize += dataLen;
141
+ }
120
142
  scheduleFlush(sessionId);
121
143
  break;
122
144
  }
@@ -127,16 +149,17 @@ self.onmessage = function(e) {
127
149
  if (!sessionId) break;
128
150
 
129
151
  const session = sessions.get(sessionId);
130
- if (!session || session.buffer.length === 0) break;
152
+ if (!session || session.chunks.length === 0) break;
131
153
 
132
154
  self.postMessage({
133
155
  type: 'data',
134
156
  sessionId: sessionId,
135
- data: session.buffer
157
+ data: session.chunks.join('')
136
158
  });
137
- session.totalBytesSent += session.buffer.length;
159
+ session.totalBytesSent += session.bufferSize;
138
160
  session.chunksSent++;
139
- session.buffer = '';
161
+ session.chunks = [];
162
+ session.bufferSize = 0;
140
163
  session.timerActive = false;
141
164
  break;
142
165
  }
@@ -155,7 +178,7 @@ self.onmessage = function(e) {
155
178
  const session = sessions.get(sessionId);
156
179
  if (session) {
157
180
  session.paused = false;
158
- if (session.buffer.length > 0) {
181
+ if (session.chunks.length > 0) {
159
182
  scheduleFlush(sessionId);
160
183
  }
161
184
  }
@@ -166,11 +189,11 @@ self.onmessage = function(e) {
166
189
  const sessionId = msg.sessionId;
167
190
  if (!sessionId) break;
168
191
  const session = sessions.get(sessionId);
169
- if (session && session.buffer.length > 0) {
192
+ if (session && session.chunks.length > 0) {
170
193
  self.postMessage({
171
194
  type: 'data',
172
195
  sessionId: sessionId,
173
- data: session.buffer
196
+ data: session.chunks.join('')
174
197
  });
175
198
  }
176
199
  sessions.delete(sessionId);
@@ -179,11 +202,11 @@ self.onmessage = function(e) {
179
202
 
180
203
  case 'destroy-all': {
181
204
  for (const [sessionId, session] of sessions) {
182
- if (session.buffer.length > 0) {
205
+ if (session.chunks.length > 0) {
183
206
  self.postMessage({
184
207
  type: 'data',
185
208
  sessionId: sessionId,
186
- data: session.buffer
209
+ data: session.chunks.join('')
187
210
  });
188
211
  }
189
212
  }
@@ -198,7 +221,7 @@ self.onmessage = function(e) {
198
221
  type: 'stats',
199
222
  sessionId: sessionId,
200
223
  stats: session ? {
201
- bufferLength: session.buffer.length,
224
+ bufferLength: session.bufferSize,
202
225
  totalBytesReceived: session.totalBytesReceived,
203
226
  totalBytesSent: session.totalBytesSent,
204
227
  chunksSent: session.chunksSent,