@lethevimlet/sshift 1.4.8 → 1.4.9

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.4.8",
3
+ "version": "1.4.9",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -16,6 +16,9 @@
16
16
  "test:integration": "jest --testPathPatterns='src/tests/integration' --forceExit",
17
17
  "test:e2e": "jest --testPathPatterns='src/tests/e2e' --forceExit --runInBand",
18
18
  "test:browser": "jest --testPathPatterns='src/tests/browser' --forceExit --runInBand",
19
+ "test:ssh:up": "docker compose -f docker/test-ssh/docker-compose.yml up -d --build",
20
+ "test:ssh:down": "docker compose -f docker/test-ssh/docker-compose.yml down -v",
21
+ "test:ssh:logs": "docker compose -f docker/test-ssh/docker-compose.yml logs -f",
19
22
  "prepublishOnly": "echo 'Publishing to npm...'",
20
23
  "install:safe": "sfw pnpm install"
21
24
  },
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  const { loadConfig, getStickySetting } = require('../../utils/config');
6
- const { addTab, removeTab, addSocketToTab, removeSocketFromTab } = require('../../utils/tab-manager');
6
+ const { addTab, getTab, removeTab, addSocketToTab, removeSocketFromTab, clearCloseTimer, setCloseTimer } = require('../../utils/tab-manager');
7
7
  const { sftpManager } = require('../../services');
8
8
 
9
9
  /**
@@ -44,13 +44,13 @@ function registerSFTPHandlers(socket, io) {
44
44
  sticky: sticky
45
45
  });
46
46
 
47
- io.emit('tab-opened', {
47
+ socket.broadcast.emit('tab-opened', {
48
48
  sessionId,
49
49
  name: data.name || 'SFTP',
50
50
  type: 'sftp',
51
51
  connectionData: data
52
52
  });
53
-
53
+
54
54
  io.emit('sessions-updated');
55
55
 
56
56
  socket.emit('sftp-connected', { sessionId });
@@ -274,14 +274,50 @@ function registerSFTPHandlers(socket, io) {
274
274
  }
275
275
  });
276
276
 
277
- // SFTP disconnect
277
+ // SFTP disconnect — mirror the ssh-disconnect viewer/sticky-aware teardown
278
+ // so the closing client's view is removed without tearing down the
279
+ // underlying SFTP stream for other viewers or non-sticky-none-viewers.
278
280
  socket.on('sftp-disconnect', (data) => {
281
+ console.log('[SFTP] sftp-disconnect event received for', data.sessionId, 'from socket', socket.id);
282
+
283
+ const tab = getTab(data.sessionId);
284
+ if (tab) {
285
+ removeSocketFromTab(data.sessionId, socket.id);
286
+
287
+ if (tab.activeSockets.size > 0) {
288
+ console.log('[SFTP] sftp-disconnect from', socket.id, 'but', tab.activeSockets.size, 'viewer(s) remain; keeping:', data.sessionId);
289
+ io.emit('sessions-updated');
290
+ return;
291
+ }
292
+
293
+ // No remaining viewers. Honor sticky flag (same semantics as ssh).
294
+ clearCloseTimer(data.sessionId);
295
+ if (tab.sticky) {
296
+ console.log('[SFTP] Sticky session remains open on server (no viewers):', data.sessionId);
297
+ io.emit('sessions-updated');
298
+ return;
299
+ }
300
+
301
+ console.log('[SFTP] Non-sticky session, scheduling close after grace:', data.sessionId);
302
+ const gracePeriod = 5000;
303
+ setCloseTimer(data.sessionId, setTimeout(() => {
304
+ const currentTab = getTab(data.sessionId);
305
+ if (currentTab && currentTab.activeSockets.size === 0) {
306
+ console.log('[SFTP] Grace expired, closing session:', data.sessionId);
307
+ sftpManager.disconnect(data.sessionId);
308
+ removeTab(data.sessionId);
309
+ io.emit('tab-closed', { sessionId: data.sessionId });
310
+ io.emit('sessions-updated');
311
+ } else {
312
+ console.log('[SFTP] Session has new sockets, canceling close:', data.sessionId);
313
+ }
314
+ }, gracePeriod));
315
+ return;
316
+ }
317
+
318
+ // No tab record — broadcast close so stale client UIs clear it.
279
319
  sftpManager.disconnect(data.sessionId);
280
-
281
- // Remove from open tabs
282
320
  removeTab(data.sessionId);
283
-
284
- // Broadcast to all clients that tab was closed
285
321
  io.emit('tab-closed', { sessionId: data.sessionId });
286
322
  io.emit('sessions-updated');
287
323
  });
@@ -6,6 +6,20 @@ const { loadConfig, getStickySetting, getScrollback } = require('../../utils/con
6
6
  const { addTab, getTab, addSocketToTab, removeSocketFromTab, removeTab, getTabOrder, setCloseTimer, clearCloseTimer, getCloseTimer } = require('../../utils/tab-manager');
7
7
  const { sshManager } = require('../../services');
8
8
 
9
+ // Per-session rate limiting for ssh-request-sync. A non-controller could
10
+ // otherwise trigger a 1MB serialization + base64 + emit on every
11
+ // keystroke, easily saturating the server's main thread and bandwidth.
12
+ // Allow at most one request per session every 2 seconds.
13
+ const _syncLastSent = new Map(); // sessionId -> last sync emit timestamp (ms)
14
+ const SYNC_RATE_LIMIT_MS = 2000;
15
+
16
+ // Acceptable client-supplied terminal dimensions. Guards against
17
+ // malformed clients passing 0 or huge values that would crash the
18
+ // headless xterm.js terminal.resize() or the remote PTY.
19
+ const MIN_DIM = 1;
20
+ const MAX_COLS = 400;
21
+ const MAX_ROWS = 200;
22
+
9
23
  /**
10
24
  * Register SSH WebSocket handlers
11
25
  * @param {Object} socket - Socket.IO socket
@@ -53,13 +67,16 @@ function registerSSHHandlers(socket, io) {
53
67
  sticky: sticky
54
68
  });
55
69
 
56
- io.emit('tab-opened', {
70
+ // Use socket.broadcast.emit so the originator doesn't receive its own
71
+ // tab-opened echo. The originator already created the tab locally via
72
+ // createSSHTab, so relying on a client-side guard was fragile.
73
+ socket.broadcast.emit('tab-opened', {
57
74
  sessionId,
58
75
  name: data.name || 'SSH',
59
76
  type: 'ssh',
60
77
  connectionData: data
61
78
  });
62
-
79
+
63
80
  io.emit('sessions-updated');
64
81
 
65
82
  socket.emit('ssh-connected', { sessionId });
@@ -85,6 +102,19 @@ function registerSSHHandlers(socket, io) {
85
102
  // SSH request screen sync (for manual refresh or reconnection)
86
103
  socket.on('ssh-request-sync', (data) => {
87
104
  console.log('[SSH] ssh-request-sync event received for session:', data.sessionId);
105
+
106
+ // Rate-limit per session to prevent abuse / accidental DoS.
107
+ const now = Date.now();
108
+ const last = _syncLastSent.get(data.sessionId) || 0;
109
+ if ((now - last) < SYNC_RATE_LIMIT_MS) {
110
+ socket.emit('ssh-error', {
111
+ sessionId: data.sessionId,
112
+ message: 'Sync rate limit reached, please wait'
113
+ });
114
+ return;
115
+ }
116
+ _syncLastSent.set(data.sessionId, now);
117
+
88
118
  const state = sshManager.getTerminalState(data.sessionId);
89
119
  if (state) {
90
120
  // Base64 encode to avoid Socket.IO binary detection issues
@@ -109,7 +139,25 @@ function registerSSHHandlers(socket, io) {
109
139
  console.log(`[SSH] Ignoring input from non-controller socket ${socket.id}`);
110
140
  return;
111
141
  }
112
- sshManager.write(data.sessionId, data.data);
142
+ // Validate payload type — a non-string `data.data` would throw deep
143
+ // inside the ssh2 stream.write and crash the socket handler.
144
+ if (typeof data.data !== 'string') {
145
+ console.warn(`[SSH] ssh-data: invalid payload type from socket ${socket.id}`);
146
+ socket.emit('ssh-error', {
147
+ sessionId: data.sessionId,
148
+ message: 'Invalid input payload'
149
+ });
150
+ return;
151
+ }
152
+ try {
153
+ sshManager.write(data.sessionId, data.data);
154
+ } catch (err) {
155
+ console.error(`[SSH] ssh-data: write failed for ${data.sessionId}:`, err.message);
156
+ socket.emit('ssh-error', {
157
+ sessionId: data.sessionId,
158
+ message: 'Failed to write input: ' + err.message
159
+ });
160
+ }
113
161
  });
114
162
 
115
163
  // SSH take control
@@ -145,24 +193,93 @@ function registerSSHHandlers(socket, io) {
145
193
  console.log(`[SSH] Ignoring resize from non-controller socket ${socket.id}`);
146
194
  return;
147
195
  }
148
- sshManager.resize(data.sessionId, data.cols, data.rows);
149
-
196
+ // Validate dimensions. cols=0/rows=0 (or NaN, negative, huge) would
197
+ // crash headless terminal.resize() inside the SSH manager.
198
+ const cols = Number(data.cols);
199
+ const rows = Number(data.rows);
200
+ if (!Number.isFinite(cols) || !Number.isFinite(rows) ||
201
+ cols < MIN_DIM || rows < MIN_DIM ||
202
+ cols > MAX_COLS || rows > MAX_ROWS) {
203
+ console.warn(`[SSH] ssh-resize: invalid dimensions (${data.cols}x${data.rows}) from socket ${socket.id}`);
204
+ socket.emit('ssh-error', {
205
+ sessionId: data.sessionId,
206
+ message: `Invalid terminal dimensions: ${data.cols}x${data.rows}`
207
+ });
208
+ return;
209
+ }
210
+ try {
211
+ sshManager.resize(data.sessionId, cols, rows);
212
+ } catch (err) {
213
+ console.error(`[SSH] ssh-resize: resize failed for ${data.sessionId}:`, err.message);
214
+ socket.emit('ssh-error', {
215
+ sessionId: data.sessionId,
216
+ message: 'Failed to resize: ' + err.message
217
+ });
218
+ return;
219
+ }
220
+
150
221
  // Broadcast resize to all other clients in the session
151
222
  // This ensures all clients stay in sync with the server terminal size
152
223
  socket.to(`session-${data.sessionId}`).emit('ssh-resize-sync', {
153
224
  sessionId: data.sessionId,
154
- cols: data.cols,
155
- rows: data.rows
225
+ cols,
226
+ rows
156
227
  });
157
228
  });
158
229
 
159
- // SSH disconnect
230
+ // SSH disconnect — historically meant "I'm done with this session locally".
231
+ // Treat it identically to tab-close: viewer-aware + sticky-aware teardown.
232
+ // Only destroy the underlying SSH stream when no other clients remain AND
233
+ // the session is non-sticky. This lets the orchestrator close their view
234
+ // without yanking the session out from under sticky observers (or shedding
235
+ // a session the user wants to rejoin from the Sessions modal).
160
236
  socket.on('ssh-disconnect', (data) => {
237
+ console.log('[SSH] ssh-disconnect event received for', data.sessionId, 'from socket', socket.id);
238
+
239
+ // Remove this socket from the SSH session room and reassign control if needed.
240
+ sshManager.leaveSession(socket, data.sessionId);
241
+
242
+ // Also remove from the tab's active-socket set so viewer counting
243
+ // reflects reality.
244
+ const tab = getTab(data.sessionId);
245
+ if (tab) {
246
+ removeSocketFromTab(data.sessionId, socket.id);
247
+
248
+ if (tab.activeSockets.size > 0) {
249
+ // Other viewers still active — keep the session alive for them.
250
+ console.log('[SSH] ssh-disconnect from', socket.id, 'but', tab.activeSockets.size, 'viewer(s) remain; keeping:', data.sessionId);
251
+ io.emit('sessions-updated');
252
+ return;
253
+ }
254
+
255
+ // No remaining viewers. Honor sticky flag.
256
+ clearCloseTimer(data.sessionId);
257
+ if (tab.sticky) {
258
+ console.log('[SSH] Sticky session remains open on server (no viewers):', data.sessionId);
259
+ io.emit('sessions-updated');
260
+ return;
261
+ }
262
+
263
+ console.log('[SSH] Non-sticky session, scheduling close after grace:', data.sessionId);
264
+ const gracePeriod = 5000;
265
+ setCloseTimer(data.sessionId, setTimeout(() => {
266
+ const currentTab = getTab(data.sessionId);
267
+ if (currentTab && currentTab.activeSockets.size === 0) {
268
+ console.log('[SSH] Grace expired, closing session:', data.sessionId);
269
+ sshManager.disconnect(data.sessionId);
270
+ removeTab(data.sessionId);
271
+ io.emit('tab-closed', { sessionId: data.sessionId });
272
+ io.emit('sessions-updated');
273
+ } else {
274
+ console.log('[SSH] Session has new sockets, canceling close:', data.sessionId);
275
+ }
276
+ }, gracePeriod));
277
+ return;
278
+ }
279
+
280
+ // No tab record — broadcast close so stale client UIs clear it.
161
281
  sshManager.disconnect(data.sessionId);
162
-
163
- // Remove from open tabs and order
164
282
  removeTab(data.sessionId);
165
-
166
283
  io.emit('tab-closed', { sessionId: data.sessionId });
167
284
  io.emit('sessions-updated');
168
285
  });
@@ -32,34 +32,64 @@ function registerTabHandlers(socket, io) {
32
32
  // Tab close event (client-side tab close, not full disconnect)
33
33
  socket.on('tab-close', (data) => {
34
34
  console.log('[TAB] Tab closed:', data.sessionId, 'by socket:', socket.id);
35
-
35
+
36
36
  // Remove this socket from the tab's active sockets
37
37
  const tab = getTab(data.sessionId);
38
38
  if (tab) {
39
39
  removeSocketFromTab(data.sessionId, socket.id);
40
-
41
- // When user explicitly closes a tab, close the session immediately
42
- // regardless of sticky setting (user intent is to close)
43
- if (tab.activeSockets.size === 0) {
44
- // Clear any existing close timer
45
- clearCloseTimer(data.sessionId);
46
-
47
- console.log('[TAB] Tab explicitly closed by user, closing session:', data.sessionId);
48
-
49
- // Close the session immediately
40
+
41
+ // If other sockets are still viewing this tab, the originating
42
+ // client's close must NOT tear down the session for them.
43
+ // Just notify remaining viewers to refresh their sessions list.
44
+ // The originating client already removed the tab locally via
45
+ // closeTab() (app.js), so it does NOT need a tab-closed echo.
46
+ if (tab.activeSockets.size > 0) {
47
+ console.log('[TAB] Tab closed by', socket.id, 'but', tab.activeSockets.size, 'viewer(s) remain; keeping session:', data.sessionId);
48
+ // SSH: drop this socket from the session room so it stops
49
+ // receiving broadcasts from this session.
50
50
  if (tab.type === 'ssh') {
51
- sshManager.disconnect(data.sessionId);
52
- } else if (tab.type === 'sftp') {
53
- sftpManager.disconnect(data.sessionId);
51
+ sshManager.leaveSession(socket, data.sessionId);
54
52
  }
55
- removeTab(data.sessionId);
56
-
57
- // Broadcast to all clients that tab was closed
58
- io.emit('tab-closed', { sessionId: data.sessionId });
53
+ // Tell remaining clients to refresh any open "manage sessions"
54
+ // modal — they may want to reflect the new viewer count.
59
55
  io.emit('sessions-updated');
56
+ return;
60
57
  }
58
+
59
+ // No more viewers left after this close. Honor the sticky flag:
60
+ // sticky sessions stay alive on the server indefinitely (until
61
+ // explicitly killed by another path or server restart). Non-
62
+ // sticky sessions get the same 5s grace path used by
63
+ // handleTabDisconnect, so a transient close-then-reopen round-
64
+ // trip (e.g. closing and reloading a devtools session) doesn't
65
+ // yank the SSH connection out from under the user.
66
+ clearCloseTimer(data.sessionId);
67
+ if (tab.sticky) {
68
+ console.log('[TAB] Sticky session remains open on server (no viewers):', data.sessionId);
69
+ io.emit('sessions-updated');
70
+ return;
71
+ }
72
+
73
+ console.log('[TAB] Non-sticky session, scheduling close after grace period:', data.sessionId);
74
+ const gracePeriod = 5000;
75
+ setCloseTimer(data.sessionId, setTimeout(() => {
76
+ const currentTab = getTab(data.sessionId);
77
+ if (currentTab && currentTab.activeSockets.size === 0) {
78
+ console.log('[TAB] Grace period expired, closing session:', data.sessionId);
79
+ if (currentTab.type === 'ssh') {
80
+ sshManager.disconnect(data.sessionId);
81
+ } else if (currentTab.type === 'sftp') {
82
+ sftpManager.disconnect(data.sessionId);
83
+ }
84
+ removeTab(data.sessionId);
85
+ io.emit('tab-closed', { sessionId: data.sessionId });
86
+ io.emit('sessions-updated');
87
+ } else {
88
+ console.log('[TAB] Session has new sockets, canceling close:', data.sessionId);
89
+ }
90
+ }, gracePeriod));
61
91
  } else {
62
- // Broadcast to all clients that tab was closed
92
+ // No tab record — broadcast close so stale client UIs clear it.
63
93
  io.emit('tab-closed', { sessionId: data.sessionId });
64
94
  io.emit('sessions-updated');
65
95
  }
@@ -189,6 +189,10 @@ class SSHManager {
189
189
 
190
190
  stream.on('close', () => {
191
191
  console.log(`[SSH] Stream closed: ${sessionId}`);
192
+ if (session.exitTimer) {
193
+ clearTimeout(session.exitTimer);
194
+ session.exitTimer = null;
195
+ }
192
196
  this.flushData(sessionId);
193
197
  this.broadcastToSession(sessionId, 'ssh-disconnected', { sessionId });
194
198
  this.disconnect(sessionId);
@@ -202,6 +206,21 @@ class SSHManager {
202
206
  stream.on('exit', (code, signal) => {
203
207
  console.log(`[SSH] Stream exit: ${sessionId}, code: ${code}, signal: ${signal}`);
204
208
  this.broadcastToSession(sessionId, 'ssh-exit', { sessionId, code, signal });
209
+ // Remote process exited. The ssh2 channel normally fires
210
+ // `close` shortly after, but if it doesn't (network drop,
211
+ // half-open socket) the session would linger in the map
212
+ // forever, freezing sticky clients that reattach to it.
213
+ // Arm a 500ms safety timer to force teardown if `close`
214
+ // doesn't fire.
215
+ if (session.exitTimer) clearTimeout(session.exitTimer);
216
+ session.exitTimer = setTimeout(() => {
217
+ console.warn(`[SSH] Stream close did not fire after exit; forcing disconnect for ${sessionId}`);
218
+ this.disconnect(sessionId);
219
+ if (this.io) {
220
+ this.io.emit('tab-closed', { sessionId });
221
+ this.io.emit('sessions-updated');
222
+ }
223
+ }, 500);
205
224
  });
206
225
 
207
226
  stream.on('error', (err) => {
@@ -544,8 +563,22 @@ class SSHManager {
544
563
  if (session && session.stream) {
545
564
  const canWrite = session.stream.write(data);
546
565
  if (!canWrite) {
547
- // Stream buffer is full — queue write and wait for drain
566
+ // Stream buffer is full — queue write and wait for drain.
567
+ // Cap the queue to avoid OOM on a slow/half-open remote;
568
+ // 64 chunks is enough headroom for normal paste flows
569
+ // while bounding memory in pathological cases.
548
570
  if (!session.writeQueue) session.writeQueue = [];
571
+ if (session.writeQueue.length >= 64) {
572
+ console.warn(`[SSH] writeQueue overflow for ${sessionId}; dropping ${session.writeQueue.length} queued chunks`);
573
+ session.writeQueue = [];
574
+ if (this.io) {
575
+ this.io.to(`session-${sessionId}`).emit('ssh-error', {
576
+ sessionId,
577
+ message: 'bufferFull'
578
+ });
579
+ }
580
+ return;
581
+ }
549
582
  session.writeQueue.push(data);
550
583
  if (!session.drainListener) {
551
584
  session.drainListener = true;
@@ -567,13 +600,23 @@ class SSHManager {
567
600
  resize(sessionId, cols, rows) {
568
601
  const session = this.sessions.get(sessionId);
569
602
  if (session && session.stream) {
570
- session.stream.setWindow(rows, cols);
603
+ try {
604
+ session.stream.setWindow(rows, cols);
605
+ } catch (err) {
606
+ console.error(`[SSH] stream.setWindow failed for ${sessionId}:`, err.message);
607
+ }
571
608
  session.cols = cols;
572
609
  session.rows = rows;
573
-
574
- // Also resize the headless terminal
610
+
611
+ // Also resize the headless terminal. xterm.js v6 throws on
612
+ // resize(0, 0) or out-of-range values — wrap so a malformed
613
+ // payload doesn't tear down the entire session.
575
614
  if (session.terminal) {
576
- session.terminal.resize(cols, rows);
615
+ try {
616
+ session.terminal.resize(cols, rows);
617
+ } catch (err) {
618
+ console.error(`[SSH] headless terminal.resize failed for ${sessionId}:`, err.message);
619
+ }
577
620
  }
578
621
  }
579
622
  }
@@ -619,6 +662,11 @@ class SSHManager {
619
662
  clearTimeout(session.batchTimer);
620
663
  session.batchTimer = null;
621
664
  }
665
+ // Clear any pending exit-safety timer
666
+ if (session.exitTimer) {
667
+ clearTimeout(session.exitTimer);
668
+ session.exitTimer = null;
669
+ }
622
670
  // Flush any remaining incomplete UTF-8 bytes from the streaming
623
671
  // decoder. Passing { stream: false } (or no option) signals the
624
672
  // decoder that the stream has ended, emitting any buffered bytes
@@ -626,10 +674,15 @@ class SSHManager {
626
674
  // disconnect, but this prevents a memory leak.
627
675
  try { session.decoder.decode(new Uint8Array(0)); } catch (_) {}
628
676
  if (session.stream) {
629
- session.stream.end();
677
+ try { session.stream.end(); } catch (_) {}
678
+ // Also call destroy() to force teardown of half-open sockets.
679
+ // end() only signals EOF and waits for the peer to acknowledge;
680
+ // if the remote is unreachable, end() alone can leave a
681
+ // half-open socket pinning the session in the map until GC.
682
+ try { session.stream.destroy(); } catch (_) {}
630
683
  }
631
684
  if (session.conn) {
632
- session.conn.end();
685
+ try { session.conn.end(); } catch (_) {}
633
686
  }
634
687
  // Dispose of the headless terminal
635
688
  if (session.terminal) {
@@ -41,6 +41,11 @@ class SSHIFTClient {
41
41
  this._serverLayout = null; // Layout from server (preserved for mobile saves)
42
42
  this._initialSyncDone = false; // Whether initial open-tabs sync from server has completed
43
43
  this._serverSyncTimeout = null; // Timeout for fallback to localStorage restore
44
+ // saveTabs dedup/debounce state — prevents redundant localStorage writes
45
+ // and tabs-save broadcasts when called rapidly (e.g. on every tab move,
46
+ // rename, switch, distribute) with the same payload.
47
+ this._saveTabsTimer = null;
48
+ this._saveTabsSignature = null;
44
49
  this.sftpClipboard = null; // For cut/copy/paste: { action: 'cut'|'copy', path: string, name: string, sessionId: string }
45
50
  this.terminalClipboardContent = null; // Pre-read clipboard content for context menu paste
46
51
  this.osc52Buffer = null; // Buffered OSC 52 clipboard content pending write
@@ -447,23 +452,23 @@ class SSHIFTClient {
447
452
  this.clearTabs();
448
453
  return;
449
454
  }
450
-
455
+
451
456
  const tabs = [];
452
-
457
+
453
458
  // Get tabs from all panels
454
459
  const panels = this.getAllPanels();
455
-
460
+
456
461
  panels.forEach(panelId => {
457
462
  const tabsContainer = this.getTabsContainer(panelId);
458
463
  if (!tabsContainer) return;
459
-
464
+
460
465
  const tabElements = Array.from(tabsContainer.children);
461
466
  const activeInThisPanel = this.activeSessionsByPanel.get(panelId);
462
-
467
+
463
468
  tabElements.forEach(tabElement => {
464
469
  const sessionId = tabElement.dataset.sessionId;
465
470
  const session = this.sessions.get(sessionId) || this.sftpSessions.get(sessionId);
466
-
471
+
467
472
  if (session) {
468
473
  // On mobile (single panel), preserve the server-assigned panel instead of panel-0
469
474
  const effectivePanelId = this.isMobile
@@ -482,7 +487,7 @@ class SSHIFTClient {
482
487
  }
483
488
  });
484
489
  });
485
-
490
+
486
491
  // Save tabs with current layout (mobile saves server layout, not 'single')
487
492
  const savedLayout = this.isMobile
488
493
  ? (this._serverLayout || 'single')
@@ -491,15 +496,30 @@ class SSHIFTClient {
491
496
  tabs,
492
497
  layout: savedLayout
493
498
  };
494
-
495
- localStorage.setItem('openTabs', JSON.stringify(tabsData));
496
- console.log('[SSHIFT] Saved tabs:', tabs.length, 'layout:', tabsData.layout);
497
-
498
- // Sync to server for cross-tab sync
499
- // Don't emit if we're currently syncing from another client to prevent loops
500
- if (this.socket && this.socket.connected && !this.isSyncingTabs) {
501
- this.socket.emit('tabs-save', tabsData);
502
- }
499
+
500
+ // Debounce + dedup: collapse rapid-fire saveTabs calls into one
501
+ // tabs-save broadcast. Many call sites (switchTab, distributeTabs,
502
+ // drag-end, handleTabClosed, createSSHTab/SFTPTab, distribution)
503
+ // fire saveTabs in tight succession with identical payloads; that
504
+ // amplified duplicates across clients and spammed the server.
505
+ const signature = JSON.stringify(tabsData);
506
+ if (this._saveTabsTimer) clearTimeout(this._saveTabsTimer);
507
+ this._saveTabsTimer = setTimeout(() => {
508
+ this._saveTabsTimer = null;
509
+ // Only persist + broadcast if payload actually changed since the
510
+ // last write (signature dedup suppresses no-op re-exports).
511
+ if (this._saveTabsSignature === signature) return;
512
+ this._saveTabsSignature = signature;
513
+
514
+ localStorage.setItem('openTabs', signature);
515
+ console.log('[SSHIFT] Saved tabs:', tabs.length, 'layout:', tabsData.layout);
516
+
517
+ // Sync to server for cross-tab sync
518
+ // Don't emit if we're currently syncing from another client to prevent loops
519
+ if (this.socket && this.socket.connected && !this.isSyncingTabs) {
520
+ this.socket.emit('tabs-save', tabsData);
521
+ }
522
+ }, 150);
503
523
  }
504
524
 
505
525
  loadTabs() {
@@ -713,17 +733,13 @@ class SSHIFTClient {
713
733
  if (!sourceTabsContainer || !targetTabsContainer) return;
714
734
  if (!sourceTerminalsContainer || !targetTerminalsContainer) return;
715
735
 
716
- // Move tab element
717
- const tabElement = sourceTabsContainer.querySelector(`[data-session-id="${sessionId}"]`);
718
- if (tabElement) {
719
- targetTabsContainer.appendChild(tabElement);
720
- }
721
-
722
- // Move terminal element
723
- const terminalElement = sourceTerminalsContainer.querySelector(`[data-session-id="${sessionId}"]`);
724
- if (terminalElement) {
725
- targetTerminalsContainer.appendChild(terminalElement);
726
- }
736
+ // Move ALL tab elements matching this session (defensive against duplicates)
737
+ const tabElements = sourceTabsContainer.querySelectorAll(`[data-session-id="${sessionId}"]`);
738
+ tabElements.forEach(el => targetTabsContainer.appendChild(el));
739
+
740
+ // Move terminal element(s)
741
+ const terminalElements = sourceTerminalsContainer.querySelectorAll(`[data-session-id="${sessionId}"]`);
742
+ terminalElements.forEach(el => targetTerminalsContainer.appendChild(el));
727
743
 
728
744
  // Hide empty state in target panel if it has tabs now
729
745
  const targetTabs = targetTabsContainer.children;
@@ -1017,7 +1033,11 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1017
1033
  if (!this.webglRenderer || typeof window.WebglAddon !== 'function') return false;
1018
1034
 
1019
1035
  if ((session.webglContextLossCount || 0) >= 3) {
1020
- console.warn('[SSHIFT] Too many WebGL context losses for session, staying on canvas renderer');
1036
+ // xterm v6 does NOT ship a built-in canvas renderer — without
1037
+ // @xterm/addon-caddon-canvas packaged, the post-WebGL fallback
1038
+ // is the default DOM renderer, which is slower but functional.
1039
+ // Log explicitly so the degraded state is observable.
1040
+ console.warn('[SSHIFT] Too many WebGL context losses for session — staying on the default DOM renderer (slower than WebGL/canvas). Consider restarting the tab if rendering feels sluggish.');
1021
1041
  return false;
1022
1042
  }
1023
1043
 
@@ -1060,6 +1080,15 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1060
1080
  if (session.fitAddon && !document.hidden) {
1061
1081
  try { session.fitAddon.fit(); } catch (_) {}
1062
1082
  }
1083
+ // After context loss the local terminal's rasterised
1084
+ // cells may have been cleared; reconcile with the
1085
+ // server's headless terminal state to avoid divergence.
1086
+ // Only do this if the session is connected (a connecting
1087
+ // session hasn't received its first sync yet).
1088
+ const sid = session.id;
1089
+ if (sid && session.connected) {
1090
+ try { this.requestScreenSync(sid); } catch (_) {}
1091
+ }
1063
1092
  }
1064
1093
  });
1065
1094
  } else {
@@ -1709,7 +1738,18 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1709
1738
  this.saveAccent(accent);
1710
1739
  this.updateAccentPreview(accent);
1711
1740
  this.updateAccentActiveState(accent);
1712
-
1741
+
1742
+ // Repaint existing terminals so the new accent's color is reflected
1743
+ // immediately. Previously terminals only picked up the accent at
1744
+ // construction time, so live accent changes left existing tabs with
1745
+ // the stale accent until reload.
1746
+ try {
1747
+ const currentTheme = this.loadTheme();
1748
+ this.updateTerminalThemes(currentTheme);
1749
+ } catch (e) {
1750
+ console.warn('[SSHIFT] Failed to re-apply terminal themes after accent change:', e.message);
1751
+ }
1752
+
1713
1753
  // Sync accent to server for cross-device sync
1714
1754
  if (this.socket && this.socket.connected) {
1715
1755
  this.socket.emit('accent-change', { accent: accent });
@@ -2889,13 +2929,18 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2889
2929
  const fontSizeChange = distanceDiff * 0.1;
2890
2930
 
2891
2931
  if (Math.abs(fontSizeChange) >= 0.5) {
2892
- const newFontSize = Math.round(this.terminalFontSize + fontSizeChange);
2893
-
2894
- if (newFontSize !== this.terminalFontSize) {
2895
- this.setTerminalFontSize(newFontSize);
2932
+ // Per-session font sizing: use setSessionFontSize so we
2933
+ // don't clobber other sessions' personalised font sizes
2934
+ // when pinch-zooming. (The legacy setTerminalFontSize()
2935
+ // would force every terminal to the same value.)
2936
+ const currentSessionSize = session.fontSize || this.terminalFontSize;
2937
+ const newFontSize = Math.round(currentSessionSize + fontSizeChange);
2938
+
2939
+ if (newFontSize !== currentSessionSize) {
2940
+ this.setSessionFontSize(session.id, newFontSize);
2896
2941
  }
2897
2942
  }
2898
-
2943
+
2899
2944
  session.lastPinchDistance = currentDistance;
2900
2945
  }
2901
2946
  }, { passive: false });
@@ -3640,8 +3685,12 @@ const wheelHandler = (e) => {
3640
3685
  });
3641
3686
  }
3642
3687
 
3643
- let activeSessionId = null;
3644
-
3688
+ // Map old savedTab.sessionId -> freshly-created sessionId so the active
3689
+ // highlight resolves against the new session id (not the pre-restart id
3690
+ // which no longer exists on the server).
3691
+ const savedToFresh = new Map();
3692
+ let activeSavedId = null;
3693
+
3645
3694
  // Restore each session
3646
3695
  for (const savedTab of savedTabs) {
3647
3696
  // Stop restoring if server tabs have been synced (open-tabs arrived while we were restoring)
@@ -3651,37 +3700,42 @@ const wheelHandler = (e) => {
3651
3700
  }
3652
3701
 
3653
3702
  console.log('[SSHIFT] Restoring tab:', savedTab.name, savedTab.type);
3654
-
3655
- let sessionId;
3656
-
3703
+
3704
+ let freshSessionId = null;
3657
3705
  // restoreTabs() is only called when the server has no active sessions
3658
3706
  // (e.g. server restart), so we must create new connections, not join.
3659
3707
  const restoreSessionId = null;
3660
-
3708
+
3661
3709
  if (savedTab.type === 'ssh') {
3662
- sessionId = this.createSSHTab(savedTab.name, savedTab.connectionData, restoreSessionId);
3710
+ freshSessionId = this.createSSHTab(savedTab.name, savedTab.connectionData, restoreSessionId);
3663
3711
  } else if (savedTab.type === 'sftp') {
3664
- sessionId = this.createSFTPTab(savedTab.name, savedTab.connectionData, restoreSessionId);
3712
+ freshSessionId = this.createSFTPTab(savedTab.name, savedTab.connectionData, restoreSessionId);
3665
3713
  }
3666
-
3667
- // Track the active session
3714
+
3715
+ if (freshSessionId) {
3716
+ savedToFresh.set(savedTab.sessionId, freshSessionId);
3717
+ }
3718
+
3719
+ // Track the active saved id; resolve to the fresh id below
3668
3720
  if (savedTab.active) {
3669
- activeSessionId = savedTab.sessionId;
3721
+ activeSavedId = savedTab.sessionId;
3670
3722
  }
3671
-
3723
+
3672
3724
  // Small delay between sessions
3673
3725
  await new Promise(resolve => setTimeout(resolve, 100));
3674
3726
  }
3675
-
3676
- // Restore active session after all sessions are created
3677
- if (activeSessionId) {
3678
- setTimeout(() => {
3679
- console.log('[SSHIFT] Restoring active session:', activeSessionId);
3680
- // Find the panelId for this session from savedTabs
3681
- const savedTab = savedTabs.find(t => t.sessionId === activeSessionId);
3682
- const panelId = savedTab?.panelId || this.getPanelForSession(activeSessionId);
3683
- this.switchTab(activeSessionId, panelId);
3684
- }, 500);
3727
+
3728
+ // Restore active session using the freshly-minted sessionId
3729
+ if (activeSavedId) {
3730
+ const freshActiveId = savedToFresh.get(activeSavedId);
3731
+ if (freshActiveId) {
3732
+ setTimeout(() => {
3733
+ console.log('[SSHIFT] Restoring active session (fresh id):', freshActiveId);
3734
+ const savedTab = savedTabs.find(t => t.sessionId === activeSavedId);
3735
+ const panelId = savedTab?.panelId || this.getPanelForSession(freshActiveId);
3736
+ this.switchTab(freshActiveId, panelId);
3737
+ }, 500);
3738
+ }
3685
3739
  }
3686
3740
 
3687
3741
  // Restore layout if saved, or use current layout
@@ -4083,10 +4137,17 @@ const wheelHandler = (e) => {
4083
4137
  // This includes all escape sequences to reconstruct the screen
4084
4138
  session.terminal.write(state, () => {
4085
4139
  console.log('[SSHIFT] Terminal state synchronized, partial:', data.partial);
4086
-
4140
+
4087
4141
  // Clear syncing flag after sync is complete
4088
4142
  session.syncing = false;
4089
-
4143
+ // Sync succeeded — reset the retry counter used by the
4144
+ // requestScreenSync safety timeout.
4145
+ session._syncRetries = 0;
4146
+ if (session.syncTimeout) {
4147
+ clearTimeout(session.syncTimeout);
4148
+ session.syncTimeout = null;
4149
+ }
4150
+
4090
4151
  // If full scrollback was restored, scroll to bottom to show latest output
4091
4152
  if (!data.partial) {
4092
4153
  session.terminal.scrollToBottom();
@@ -4365,17 +4426,31 @@ const wheelHandler = (e) => {
4365
4426
  clearTimeout(session.syncTimeout);
4366
4427
  }
4367
4428
 
4368
- // Set syncing flag to prevent data from being written during sync
4369
- session.syncing = true;
4370
-
4371
- // Safety timeout: clear syncing flag after 5 seconds if ssh-screen-sync never arrives
4372
- session.syncTimeout = setTimeout(() => {
4373
- console.warn('[SSHIFT] Sync timeout, clearing syncing flag for session:', sessionId);
4374
- session.syncing = false;
4375
- }, 5000);
4376
-
4377
- console.log('[SSHIFT] Requesting screen sync for session:', sessionId);
4378
- this.socket.emit('ssh-request-sync', { sessionId });
4429
+ // Set syncing flag to prevent data from being written during sync
4430
+ session.syncing = true;
4431
+
4432
+ // Safety timeout: if ssh-screen-sync never arrives within 5s the
4433
+ // terminal would otherwise be stuck silently dropping all output.
4434
+ // Clear the flag AND request a fresh sync. After 2 failed attempts
4435
+ // we give up to avoid hammering the server when the session is
4436
+ // actually gone.
4437
+ session._syncRetries = (session._syncRetries || 0);
4438
+ session.syncTimeout = setTimeout(() => {
4439
+ console.warn('[SSHIFT] Sync timeout for session:', sessionId, 'retries:', session._syncRetries);
4440
+ session.syncing = false;
4441
+ if (session._syncRetries < 2 && session.connected) {
4442
+ session._syncRetries += 1;
4443
+ // Re-arm by calling ourselves once more. We pass a flag via the
4444
+ // session so we don't recurse infinitely (the new timeout will
4445
+ // run with retries incremented and bail at the cap above).
4446
+ this.requestScreenSync(sessionId);
4447
+ } else {
4448
+ session._syncRetries = 0;
4449
+ }
4450
+ }, 5000);
4451
+
4452
+ console.log('[SSHIFT] Requesting screen sync for session:', sessionId);
4453
+ this.socket.emit('ssh-request-sync', { sessionId });
4379
4454
  };
4380
4455
 
4381
4456
  this.socket.on('ssh-data', (data) => {
@@ -6818,6 +6893,23 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
6818
6893
  // SSH Session Management
6819
6894
  createSSHTab(name, connectionData, restoreSessionId = null) {
6820
6895
  const sessionId = restoreSessionId || 'ssh-' + Date.now();
6896
+
6897
+ // Idempotency: if a tab for this sessionId already exists (DOM +
6898
+ // session map), return the existing id rather than creating a
6899
+ // duplicate. Guards against duplicate tab-opened echoes and any
6900
+ // future regressions of the mobile tab-count bug.
6901
+ const existingDomTab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
6902
+ if (existingDomTab && this.sessions.has(sessionId)) {
6903
+ console.log('[SSHIFT] createSSHTab: session already exists, returning existing id:', sessionId);
6904
+ return sessionId;
6905
+ }
6906
+ if (existingDomTab) {
6907
+ // Stale DOM tab without a session entry — remove it before re-creating.
6908
+ existingDomTab.remove();
6909
+ const existingWrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
6910
+ if (existingWrapper) existingWrapper.remove();
6911
+ }
6912
+
6821
6913
  console.log('[SSHIFT] createSSHTab called:', {
6822
6914
  name,
6823
6915
  sessionId,
@@ -6868,7 +6960,10 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
6868
6960
  writeRAF: null,
6869
6961
  flushRemaining: null,
6870
6962
  originalScrollback: null,
6871
- scrollbackRestoreTimer: null
6963
+ scrollbackRestoreTimer: null,
6964
+ // Per-session buffer for OSC 52 / DCS sequences that arrive split
6965
+ // across two write-chunk frames (see _handleOsc52).
6966
+ pendingOsc52: null
6872
6967
  });
6873
6968
 
6874
6969
  // Switch to the new tab FIRST to make the container visible
@@ -6892,15 +6987,25 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
6892
6987
  const session = this.sessions.get(restoreSessionId);
6893
6988
  if (session) {
6894
6989
  session.syncing = true;
6895
-
6896
- // Safety timeout: clear syncing flag after 5 seconds if ssh-screen-sync never arrives
6897
- // This prevents the terminal from being stuck in syncing state
6990
+ session._syncRetries = 0;
6991
+
6992
+ // Safety timeout: if sync never arrives within 5s the
6993
+ // terminal would be stuck silently dropping all output.
6994
+ // Clear the flag AND request a fresh sync (up to 2 retries)
6995
+ // so a slow/lost ssh-screen-sync doesn't permanently lose
6996
+ // output for this client.
6898
6997
  session.syncTimeout = setTimeout(() => {
6899
- console.warn('[SSHIFT] Sync timeout, clearing syncing flag for session:', restoreSessionId);
6998
+ console.warn('[SSHIFT] Sync timeout for session:', restoreSessionId, 'retries:', session._syncRetries);
6900
6999
  session.syncing = false;
7000
+ if (session._syncRetries < 2 && session.connected) {
7001
+ session._syncRetries += 1;
7002
+ this.requestScreenSync(restoreSessionId);
7003
+ } else {
7004
+ session._syncRetries = 0;
7005
+ }
6901
7006
  }, 5000);
6902
7007
  }
6903
-
7008
+
6904
7009
  this.socket.emit('ssh-join', { sessionId: restoreSessionId });
6905
7010
  } else {
6906
7011
  // Show connecting message only for new connections
@@ -7945,14 +8050,79 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7945
8050
  }
7946
8051
  }
7947
8052
 
8053
+ // Pure helper used by _flushWriteChunks to pick a frame-write split point
8054
+ // that doesn't bisect a UTF-16 surrogate pair or an ANSI escape sequence.
8055
+ // Exposed as a static method so it can be unit-tested without a Terminal.
8056
+ static findSafeWriteSplitPoint(combined, maxLen, scanWindow = 4096) {
8057
+ if (typeof combined !== 'string' || combined.length <= maxLen) return combined ? combined.length : 0;
8058
+ let splitAt = maxLen;
8059
+ const startScan = Math.max(0, maxLen - scanWindow);
8060
+ for (let i = maxLen - 1; i > startScan && i > 0; i--) {
8061
+ const code = combined.charCodeAt(i);
8062
+ // ESC (\x1b) always begins a new control sequence — safe to split before it.
8063
+ if (code === 0x1b) {
8064
+ splitAt = i;
8065
+ break;
8066
+ }
8067
+ // Don't split inside a UTF-16 surrogate pair. Two arrangements
8068
+ // need to back off:
8069
+ // (a) i is a TRAIL surrogate (0xDC00-0xDFFF) and i-1 is its
8070
+ // LEAD partner (0xD800-0xDBFF). Splitting at i would leave
8071
+ // the lone lead at the end of chunk-1 — and the lone trail
8072
+ // at the start of chunk-2 — both halves rendering as
8073
+ // U+FFFD. Move split back to before the LEAD.
8074
+ // (b) i is itself a LEAD surrogate (0xD800-0xDBFF) whose TRAIL
8075
+ // partner is at i+1. Splitting at i would put the LEAD at
8076
+ // the END of chunk-1 with no partner. Split at i instead
8077
+ // moves the entire pair into chunk-2.
8078
+ if (code >= 0xDC00 && code <= 0xDFFF) {
8079
+ if (i > 0) {
8080
+ const prev = combined.charCodeAt(i - 1);
8081
+ if (prev >= 0xD800 && prev <= 0xDBFF) {
8082
+ splitAt = i - 1;
8083
+ break;
8084
+ }
8085
+ }
8086
+ splitAt = i;
8087
+ break;
8088
+ }
8089
+ if (code >= 0xD800 && code <= 0xDBFF) {
8090
+ splitAt = i;
8091
+ break;
8092
+ }
8093
+ }
8094
+ return splitAt;
8095
+ }
8096
+
7948
8097
  // Parse and handle OSC 52 clipboard sequences from terminal data stream.
7949
8098
  // Extracts clipboard content, writes it to browser clipboard, and safely
7950
8099
  // handles sequences that span across data chunks.
7951
8100
  // Also handles tmux DCS passthrough: \x1bPtmux;\x1b\x1b]52;c;...\x07\x1b\\
7952
- _handleOsc52(data) {
7953
- if (!data || data.indexOf('52;') === -1) return data;
8101
+ //
8102
+ // Cross-chunk handling: an OSC 52 sequence may arrive split across two
8103
+ // `_flushWriteChunks` calls (e.g. `\x1b]52;c;` in one frame and the
8104
+ // base64 + BEL in the next). When we detect an incomplete sequence we
8105
+ // stash the partial bytes on `session.pendingOsc52` and strip them
8106
+ // from the data sent to xterm.js; the next call prepends that buffer
8107
+ // and processes the whole sequence as one.
8108
+ _handleOsc52(session, data) {
8109
+ if (!data) return data;
7954
8110
 
7955
- let result = data;
8111
+ // If a previous frame left a pending partial OSC 52 / DCS sequence,
8112
+ // prepend it so the now-complete sequence can be processed as a unit.
8113
+ let working = data;
8114
+ if (session.pendingOsc52) {
8115
+ working = session.pendingOsc52 + working;
8116
+ session.pendingOsc52 = null;
8117
+ }
8118
+
8119
+ // Fast path: nothing OSC-52-shaped in the payload (and no pending
8120
+ // partial). Skip the heavy reshaping work below.
8121
+ if (working.indexOf('52;') === -1 && working.indexOf('\x1bPtmux;') === -1 && working.indexOf('\x1bP\x1b') === -1) {
8122
+ return working;
8123
+ }
8124
+
8125
+ let result = working;
7956
8126
 
7957
8127
  // Handle tmux/screen DCS passthrough wrapper:
7958
8128
  // \x1bPtmux;\x1b wraps an inner escape sequence, terminated by \x1b\\
@@ -7980,7 +8150,13 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7980
8150
  const inner = result.substring(dcsStart + dcsPrefixLen, dcsEnd);
7981
8151
  result = result.substring(0, dcsStart) + inner + result.substring(dcsEnd + 2);
7982
8152
  } else {
7983
- break; // Incomplete DCS, leave for next chunk
8153
+ // Incomplete DCS — save the tail (from dcsStart onward) onto
8154
+ // pendingOsc52 so the next frame can finish processing it.
8155
+ // Strip it from `result` so xterm doesn't buffer the partial
8156
+ // DCS itself.
8157
+ session.pendingOsc52 = result.substring(dcsStart);
8158
+ result = result.substring(0, dcsStart);
8159
+ break;
7984
8160
  }
7985
8161
  } else {
7986
8162
  break;
@@ -8011,6 +8187,14 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8011
8187
  }
8012
8188
 
8013
8189
  if (endIdx === -1) {
8190
+ // Incomplete OSC 52 — save the tail (from startIdx onward) onto
8191
+ // pendingOsc52 so the next frame can finish processing it.
8192
+ // Strip it from `result` so xterm doesn't buffer the partial
8193
+ // OSC sequence itself (which would cause the eventual clipboard
8194
+ // payload to leak through to xterm.js as soon as the rest of
8195
+ // the sequence arrives in the next frame).
8196
+ session.pendingOsc52 = result.substring(startIdx);
8197
+ result = result.substring(0, startIdx);
8014
8198
  break;
8015
8199
  }
8016
8200
 
@@ -8126,32 +8310,16 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8126
8310
  // Intercept OSC 52 clipboard sequences before writing to terminal.
8127
8311
  // OSC 52 format: ESC ] 52 ; <target> ; <base64> (BEL or ST)
8128
8312
  // This is more reliable than registerOscHandler which may not fire.
8129
- combined = this._handleOsc52(combined);
8313
+ combined = this._handleOsc52(session, combined);
8130
8314
 
8131
8315
  // Cap write size per frame. terminal.write() is synchronous and blocks
8132
8316
  // the main thread. We spill overflow to the next frame via flushRemaining.
8133
8317
  const MAX_WRITE_PER_FRAME = 32768;
8134
8318
 
8135
8319
  if (combined.length > MAX_WRITE_PER_FRAME) {
8136
- // Find a safe split point that doesn't break in the middle of an
8137
- // escape sequence. Scan backwards from the cap limit for a character
8138
- // that is NOT part of a multi-byte UTF-16 surrogate or an escape
8139
- // sequence body. A bare ESC (\x1b) or CSI introducer (\x1b[)
8140
- // always starts a new sequence, so splitting just before ESC is safe.
8141
- let splitAt = MAX_WRITE_PER_FRAME;
8142
- for (let i = MAX_WRITE_PER_FRAME - 1; i > MAX_WRITE_PER_FRAME - 4096 && i > 0; i--) {
8143
- const code = combined.charCodeAt(i);
8144
- // ESC (\x1b) always begins a new control sequence
8145
- if (code === 0x1b) {
8146
- splitAt = i;
8147
- break;
8148
- }
8149
- // Don't split inside a UTF-16 surrogate pair
8150
- if (code >= 0xDC00 && code <= 0xDFFF) {
8151
- splitAt = i;
8152
- break;
8153
- }
8154
- }
8320
+ // Find a safe split point using the static helper so the logic is
8321
+ // unit-testable without an xterm.js terminal instance.
8322
+ const splitAt = SSHIFTClient.findSafeWriteSplitPoint(combined, MAX_WRITE_PER_FRAME);
8155
8323
  terminal.write(combined.substring(0, splitAt));
8156
8324
  session.flushRemaining = combined.substring(splitAt);
8157
8325
  session.writeRAF = requestAnimationFrame(() => {
@@ -8165,6 +8333,19 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8165
8333
  // SFTP Session Management
8166
8334
  createSFTPTab(name, connectionData, restoreSessionId = null) {
8167
8335
  const sessionId = restoreSessionId || 'sftp-' + Date.now();
8336
+
8337
+ // Idempotency: bail out if this session is already in the DOM + map.
8338
+ const existingDomTab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
8339
+ if (existingDomTab && this.sftpSessions.has(sessionId)) {
8340
+ console.log('[SSHIFT] createSFTPTab: session already exists, returning existing id:', sessionId);
8341
+ return sessionId;
8342
+ }
8343
+ if (existingDomTab) {
8344
+ existingDomTab.remove();
8345
+ const existingWrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
8346
+ if (existingWrapper) existingWrapper.remove();
8347
+ }
8348
+
8168
8349
  console.log('[SSHIFT] Creating SFTP tab with sessionId:', sessionId);
8169
8350
 
8170
8351
  const tab = this.createTabElement(sessionId, name, 'sftp');
@@ -9058,11 +9239,10 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9058
9239
  this.sftpSessions.delete(sessionId);
9059
9240
  }
9060
9241
 
9061
- // Remove from DOM
9062
- const tab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
9242
+ // Remove from DOM (use querySelectorAll to catch any duplicates)
9243
+ const tabs = document.querySelectorAll(`.tab[data-session-id="${sessionId}"]`);
9063
9244
  const wrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
9064
-
9065
- if (tab) tab.remove();
9245
+ tabs.forEach(t => t.remove());
9066
9246
  if (wrapper) wrapper.remove();
9067
9247
 
9068
9248
  // Update scroll arrows visibility
@@ -9157,10 +9337,10 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9157
9337
  this.sftpSessions.delete(sessionId);
9158
9338
  }
9159
9339
 
9160
- // Remove from DOM
9161
- const tab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
9340
+ // Remove from DOM (use querySelectorAll to catch any duplicates)
9341
+ const tabs = document.querySelectorAll(`.tab[data-session-id="${sessionId}"]`);
9162
9342
  const wrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
9163
- if (tab) tab.remove();
9343
+ tabs.forEach(t => t.remove());
9164
9344
  if (wrapper) wrapper.remove();
9165
9345
 
9166
9346
  // Update scroll arrows
@@ -9204,20 +9384,19 @@ handleTabOpened(data) {
9204
9384
  this._serverPanelMap.set(data.sessionId, data.panelId);
9205
9385
  }
9206
9386
 
9207
- // Create the tab without connecting (we'll join the existing session)
9208
- if (data.type === 'ssh') {
9209
- this.createSSHTab(data.name, data.connectionData, data.sessionId);
9210
- } else if (data.type === 'sftp') {
9211
- this.createSFTPTab(data.name, data.connectionData, data.sessionId);
9212
- }
9213
-
9214
- console.log('[SSHIFT] Creating tab for session from another client:', data.sessionId);
9215
-
9216
- // Create the tab without connecting (we'll join the existing session)
9217
- if (data.type === 'ssh') {
9218
- this.createSSHTab(data.name, data.connectionData, data.sessionId);
9219
- } else if (data.type === 'sftp') {
9220
- this.createSFTPTab(data.name, data.connectionData, data.sessionId);
9387
+ // Create the tab without connecting (we'll join the existing session).
9388
+ // Defensive dedupe: only create if no DOM tab exists yet for this session.
9389
+ const existingTabNodes = document.querySelectorAll(
9390
+ `.tab[data-session-id="${data.sessionId}"]`
9391
+ );
9392
+ if (existingTabNodes.length === 0) {
9393
+ if (data.type === 'ssh') {
9394
+ this.createSSHTab(data.name, data.connectionData, data.sessionId);
9395
+ } else if (data.type === 'sftp') {
9396
+ this.createSFTPTab(data.name, data.connectionData, data.sessionId);
9397
+ }
9398
+ } else {
9399
+ console.log('[SSHIFT] Tab DOM already exists for session, skipping:', data.sessionId);
9221
9400
  }
9222
9401
 
9223
9402
  // Update mobile tabs dropdown
@@ -9267,11 +9446,10 @@ handleTabOpened(data) {
9267
9446
  this.sftpSessions.delete(sessionId);
9268
9447
  }
9269
9448
 
9270
- // Remove from DOM
9271
- const tab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
9449
+ // Remove from DOM (querySelectorAll to handle any duplicates)
9450
+ const tabs = document.querySelectorAll(`.tab[data-session-id="${sessionId}"]`);
9272
9451
  const wrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
9273
-
9274
- if (tab) tab.remove();
9452
+ tabs.forEach(t => t.remove());
9275
9453
  if (wrapper) wrapper.remove();
9276
9454
 
9277
9455
  // Check if there are remaining tabs in the panel
@@ -9325,6 +9503,7 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null)
9325
9503
  // Suppress switchTab during creation so we can activate the correct tab at the end
9326
9504
  this._suppressTabSwitch = true;
9327
9505
 
9506
+ try {
9328
9507
  // On initial sync, remove any client-side tabs that don't exist on the server.
9329
9508
  // This ensures the server is the single source of truth and prevents duplicates
9330
9509
  // from stale localStorage caches (e.g. when switching between devices).
@@ -9393,9 +9572,13 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null)
9393
9572
 
9394
9573
  // Apply any flash states that arrived before DOM elements existed
9395
9574
  this.applyFlashStates();
9396
-
9397
- this.isRestoring = false;
9398
- this._suppressTabSwitch = false;
9575
+ } finally {
9576
+ // Guarantee the sync flags clear even if a throw happens mid-sync.
9577
+ // Without this the UI would dead-lock (switchTab suppressed forever
9578
+ // and restoreTabs blocked waiting on isRestoring).
9579
+ this.isRestoring = false;
9580
+ this._suppressTabSwitch = false;
9581
+ }
9399
9582
 
9400
9583
  // Activate the correct tab per panel based on server state
9401
9584
  if (activeTabsByPanel && !this.isMobile) {
@@ -110,6 +110,29 @@ self.onmessage = function(e) {
110
110
  break;
111
111
  }
112
112
 
113
+ case 'init': {
114
+ // Explicitly register a session ahead of the first data frame.
115
+ // Optional — `data` will lazily create the session state via
116
+ // getOrCreateSession(). `init` exists so callers can pre-warm the
117
+ // worker and verify the round-trip with an ack.
118
+ const sessionId = msg.sessionId;
119
+ if (!sessionId) break;
120
+ getOrCreateSession(sessionId);
121
+ self.postMessage({
122
+ type: 'ready',
123
+ sessionId: sessionId,
124
+ cols: msg.cols || 80,
125
+ rows: msg.rows || 24
126
+ });
127
+ break;
128
+ }
129
+
130
+ case 'ping': {
131
+ // Liveness probe — used by tests and health checks.
132
+ self.postMessage({ type: 'pong', sessionId: msg.sessionId });
133
+ break;
134
+ }
135
+
113
136
  case 'data': {
114
137
  const sessionId = msg.sessionId;
115
138
  if (!sessionId) break;
@@ -230,5 +253,18 @@ self.onmessage = function(e) {
230
253
  });
231
254
  break;
232
255
  }
256
+
257
+ default: {
258
+ // Unknown message types are explicitly rejected so callers can
259
+ // detect protocol drift rather than observing silent no-ops.
260
+ console.warn('[terminal-worker] Unknown message type:', msg.type);
261
+ self.postMessage({
262
+ type: 'error',
263
+ error: 'unknownMessage',
264
+ messageType: msg.type,
265
+ sessionId: msg.sessionId
266
+ });
267
+ break;
268
+ }
233
269
  }
234
270
  };