@lethevimlet/sshift 1.4.8 → 1.4.10

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.
@@ -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 });
@@ -2703,13 +2743,30 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2703
2743
  this.updateTerminalColorOverrideUI();
2704
2744
 
2705
2745
  // In sticky mode, the server is the single source of truth for tabs.
2706
- // Wait for the open-tabs event from the server instead of restoring from localStorage.
2707
- // Set a fallback timeout in case the server is unreachable.
2746
+ // We WAIT for the open-tabs event from the server instead of
2747
+ // restoring from localStorage. If the server is unreachable or
2748
+ // reports 0 active tabs (e.g. after a server restart), we treat it
2749
+ // as a fresh slate and DO NOT resurrect stale localStorage tabs —
2750
+ // the SSH sessions those tabs represented are GONE on the server,
2751
+ // so reopening them as fresh connections would silently spawn
2752
+ // duplicate sessions and confuse every other connected client.
2753
+ //
2754
+ // The 3s fallback below used to call restoreTabs() on timeout,
2755
+ // which auto-reconnected to all sessions in localStorage. That
2756
+ // behavior is removed: if the server doesn't respond within 3s we
2757
+ // just clear the stale localStorage cache so the next saveTabs()
2758
+ // doesn't re-broadcast it to other clients.
2708
2759
  if (this.sticky) {
2709
2760
  this._serverSyncTimeout = setTimeout(() => {
2710
2761
  if (!this._initialSyncDone) {
2711
- console.log('[SSHIFT] Server tabs not received within timeout, falling back to localStorage');
2712
- this.restoreTabs();
2762
+ console.warn('[SSHIFT] Server tabs not received within 3s timeout — starting with a fresh slate.');
2763
+ // Clear any stale localStorage tab cache so a future saveTabs
2764
+ // doesn't broadcast dead sessions to other clients.
2765
+ try { this.clearTabs(); } catch (_) {}
2766
+ // Drop the wait flag so any pending syncTabsFromServer busy-wait
2767
+ // doesn't block forever (it watches `this.isRestoring`).
2768
+ this.isRestoring = false;
2769
+ this._initialSyncDone = true;
2713
2770
  }
2714
2771
  }, 3000);
2715
2772
  }
@@ -2755,7 +2812,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2755
2812
  }
2756
2813
  this.syncTabsFromServer(pendingData.tabs, isInitialSync, pendingData.activeTabsByPanel);
2757
2814
  } else {
2758
- this.restoreTabs();
2815
+ // Server has no tabs (e.g. right after restart). Treat it as a
2816
+ // fresh slate: clear stale localStorage and DO NOT resurrect
2817
+ // those sessions — they're gone on the server.
2818
+ if (pendingData.layout && !this.isMobile) {
2819
+ this.setLayoutFromServer(pendingData.layout);
2820
+ }
2821
+ try { this.clearTabs(); } catch (_) {}
2759
2822
  }
2760
2823
  } finally {
2761
2824
  this.isSyncingTabs = wasSyncingTabs;
@@ -2889,13 +2952,18 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2889
2952
  const fontSizeChange = distanceDiff * 0.1;
2890
2953
 
2891
2954
  if (Math.abs(fontSizeChange) >= 0.5) {
2892
- const newFontSize = Math.round(this.terminalFontSize + fontSizeChange);
2893
-
2894
- if (newFontSize !== this.terminalFontSize) {
2895
- this.setTerminalFontSize(newFontSize);
2955
+ // Per-session font sizing: use setSessionFontSize so we
2956
+ // don't clobber other sessions' personalised font sizes
2957
+ // when pinch-zooming. (The legacy setTerminalFontSize()
2958
+ // would force every terminal to the same value.)
2959
+ const currentSessionSize = session.fontSize || this.terminalFontSize;
2960
+ const newFontSize = Math.round(currentSessionSize + fontSizeChange);
2961
+
2962
+ if (newFontSize !== currentSessionSize) {
2963
+ this.setSessionFontSize(session.id, newFontSize);
2896
2964
  }
2897
2965
  }
2898
-
2966
+
2899
2967
  session.lastPinchDistance = currentDistance;
2900
2968
  }
2901
2969
  }, { passive: false });
@@ -3608,104 +3676,30 @@ const wheelHandler = (e) => {
3608
3676
  }
3609
3677
 
3610
3678
  async restoreTabs() {
3611
- // If server tabs have already been synced, skip localStorage restore
3612
- // This prevents duplication when the server responded before the fallback timeout
3613
- if (this._initialSyncDone) {
3614
- console.log('[SSHIFT] Server tabs already synced, skipping localStorage restore');
3615
- return;
3616
- }
3617
-
3618
- const savedData = this.loadTabs();
3619
-
3620
- // Handle both old format (array) and new format (object with tabs and layout)
3621
- const savedTabs = Array.isArray(savedData) ? savedData : (savedData?.tabs || []);
3622
- const savedLayout = !Array.isArray(savedData) ? savedData?.layout : null;
3623
-
3624
- if (!savedTabs || savedTabs.length === 0) {
3625
- console.log('[SSHIFT] No tabs to restore');
3626
- return;
3627
- }
3628
-
3629
- console.log('[SSHIFT] Restoring', savedTabs.length, 'tabs');
3630
- console.log('[SSHIFT] sticky:', this.sticky, 'layout:', savedLayout);
3631
-
3632
- // Set restoring flag to prevent saving during restoration
3633
- this.isRestoring = true;
3634
-
3635
- // Wait for socket to be connected
3636
- if (!this.socket.connected) {
3637
- await new Promise(resolve => {
3638
- this.socket.once('connect', resolve);
3639
- setTimeout(resolve, 1000); // Timeout after 1s
3640
- });
3641
- }
3642
-
3643
- let activeSessionId = null;
3644
-
3645
- // Restore each session
3646
- for (const savedTab of savedTabs) {
3647
- // Stop restoring if server tabs have been synced (open-tabs arrived while we were restoring)
3648
- if (this._initialSyncDone) {
3649
- console.log('[SSHIFT] Server tabs received during restore, stopping localStorage restore');
3650
- break;
3651
- }
3652
-
3653
- console.log('[SSHIFT] Restoring tab:', savedTab.name, savedTab.type);
3654
-
3655
- let sessionId;
3656
-
3657
- // restoreTabs() is only called when the server has no active sessions
3658
- // (e.g. server restart), so we must create new connections, not join.
3659
- const restoreSessionId = null;
3660
-
3661
- if (savedTab.type === 'ssh') {
3662
- sessionId = this.createSSHTab(savedTab.name, savedTab.connectionData, restoreSessionId);
3663
- } else if (savedTab.type === 'sftp') {
3664
- sessionId = this.createSFTPTab(savedTab.name, savedTab.connectionData, restoreSessionId);
3665
- }
3666
-
3667
- // Track the active session
3668
- if (savedTab.active) {
3669
- activeSessionId = savedTab.sessionId;
3670
- }
3671
-
3672
- // Small delay between sessions
3673
- await new Promise(resolve => setTimeout(resolve, 100));
3674
- }
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);
3685
- }
3686
-
3687
- // Restore layout if saved, or use current layout
3688
- if (this.currentLayout) {
3689
- const layoutToApply = (savedLayout && this.layouts)
3690
- ? this.layouts.find(l => l.id === savedLayout) || this.currentLayout
3691
- : this.currentLayout;
3692
-
3693
- console.log('[SSHIFT] Applying layout after restoration:', layoutToApply.id);
3694
- // Pass savedTabs to applyLayout which will handle distribution
3695
- this.applyLayout(layoutToApply, savedTabs);
3696
- }
3697
-
3698
- // Update mobile tabs Dropdown after restoration
3699
- this.updateMobileTabsDropdown();
3700
-
3701
- // Apply any flash states that arrived before DOM elements existed
3702
- this.applyFlashStates();
3703
-
3704
- // Clear restoring flag after restoration is complete
3679
+ /**
3680
+ * DEPRECATED — server restart now produces a fresh slate with
3681
+ * 0 active sessions (no localStorage-based tab reconstruction).
3682
+ *
3683
+ * The previous behavior auto-SSH-connected to every tab the user
3684
+ * had open before the restart. Because the underlying SSH
3685
+ * sessions are GONE on the server, this silently spawned brand-
3686
+ * new SSH connections AND broadcast them to every other client
3687
+ * as if they were the original sessions — confusing sticky
3688
+ * state across devices. The user-visible contract is now: server
3689
+ * restart = blank client.
3690
+ *
3691
+ * Former call sites now invoke clearTabs() to drop the stale
3692
+ * localStorage cache and start empty. This method remains as a
3693
+ * no-op for any external callers (legacy extensions, plugins) so
3694
+ * they don't accidentally resurrect sessions.
3695
+ */
3696
+ console.log('[SSHIFT] restoreTabs() is deprecated — clearing stale localStorage cache.');
3697
+ try { this.clearTabs(); } catch (_) {}
3705
3698
  this.isRestoring = false;
3699
+ this._initialSyncDone = true;
3706
3700
  }
3707
3701
 
3708
- // Legacy method for backwards compatibility
3702
+ // Legacy method for backwards compatibility
3709
3703
  async restoreStickySessions() {
3710
3704
  return this.restoreTabs();
3711
3705
  }
@@ -3834,13 +3828,17 @@ const wheelHandler = (e) => {
3834
3828
  }
3835
3829
  this.syncTabsFromServer(data.tabs, isInitialSync, data.activeTabsByPanel);
3836
3830
  } else if (!this._initialSyncDone) {
3837
- // Server has no tabs and this is the first sync (e.g. server restart).
3838
- // Still apply layout from server even with no tabs.
3831
+ // Server has no tabs and this is the first sync. This is the
3832
+ // post-restart / fresh-install / single-client-with-no-sessions
3833
+ // case. Per the user contract, a server restart = new slate:
3834
+ // we do NOT auto-reconnect stale localStorage tabs (those SSH
3835
+ // sessions are gone on the server, recreating them as new
3836
+ // connections silently spawns duplicates and confuses other
3837
+ // clients). Drop the stale cache and start fresh.
3839
3838
  if (data.layout && !this.isMobile) {
3840
3839
  this.setLayoutFromServer(data.layout);
3841
3840
  }
3842
- // Fall back to localStorage restore to reconnect sessions.
3843
- this.restoreTabs();
3841
+ try { this.clearTabs(); } catch (_) {}
3844
3842
  } else if (data.layout && !this.isMobile) {
3845
3843
  // No tabs change, but layout may have changed
3846
3844
  this.setLayoutFromServer(data.layout);
@@ -4083,10 +4081,17 @@ const wheelHandler = (e) => {
4083
4081
  // This includes all escape sequences to reconstruct the screen
4084
4082
  session.terminal.write(state, () => {
4085
4083
  console.log('[SSHIFT] Terminal state synchronized, partial:', data.partial);
4086
-
4084
+
4087
4085
  // Clear syncing flag after sync is complete
4088
4086
  session.syncing = false;
4089
-
4087
+ // Sync succeeded — reset the retry counter used by the
4088
+ // requestScreenSync safety timeout.
4089
+ session._syncRetries = 0;
4090
+ if (session.syncTimeout) {
4091
+ clearTimeout(session.syncTimeout);
4092
+ session.syncTimeout = null;
4093
+ }
4094
+
4090
4095
  // If full scrollback was restored, scroll to bottom to show latest output
4091
4096
  if (!data.partial) {
4092
4097
  session.terminal.scrollToBottom();
@@ -4365,17 +4370,31 @@ const wheelHandler = (e) => {
4365
4370
  clearTimeout(session.syncTimeout);
4366
4371
  }
4367
4372
 
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 });
4373
+ // Set syncing flag to prevent data from being written during sync
4374
+ session.syncing = true;
4375
+
4376
+ // Safety timeout: if ssh-screen-sync never arrives within 5s the
4377
+ // terminal would otherwise be stuck silently dropping all output.
4378
+ // Clear the flag AND request a fresh sync. After 2 failed attempts
4379
+ // we give up to avoid hammering the server when the session is
4380
+ // actually gone.
4381
+ session._syncRetries = (session._syncRetries || 0);
4382
+ session.syncTimeout = setTimeout(() => {
4383
+ console.warn('[SSHIFT] Sync timeout for session:', sessionId, 'retries:', session._syncRetries);
4384
+ session.syncing = false;
4385
+ if (session._syncRetries < 2 && session.connected) {
4386
+ session._syncRetries += 1;
4387
+ // Re-arm by calling ourselves once more. We pass a flag via the
4388
+ // session so we don't recurse infinitely (the new timeout will
4389
+ // run with retries incremented and bail at the cap above).
4390
+ this.requestScreenSync(sessionId);
4391
+ } else {
4392
+ session._syncRetries = 0;
4393
+ }
4394
+ }, 5000);
4395
+
4396
+ console.log('[SSHIFT] Requesting screen sync for session:', sessionId);
4397
+ this.socket.emit('ssh-request-sync', { sessionId });
4379
4398
  };
4380
4399
 
4381
4400
  this.socket.on('ssh-data', (data) => {
@@ -4441,11 +4460,25 @@ const wheelHandler = (e) => {
4441
4460
  } else {
4442
4461
  this.showToast(data.message, 'error');
4443
4462
  }
4463
+ } else if (data.advisory) {
4464
+ // Advisory errors (rate-limit, invalid payload, bufferFull, etc.)
4465
+ // are non-fatal — warn via toast but DO NOT close the tab. Closing
4466
+ // the tab on every rate-limited ssh-request-sync would kill the
4467
+ // very session the user was trying to refresh / switch to.
4468
+ console.warn('[SSHIFT] Advisory ssh-error (tab kept open):', data.message);
4469
+ this.showToast(data.message, 'warning');
4444
4470
  } else {
4445
4471
  this.showToast(data.message, 'error');
4446
4472
  }
4447
-
4448
- if (data.sessionId && data.message !== 'Session not found') {
4473
+
4474
+ // Only close the tab for hard errors that actually break the session.
4475
+ // `advisory: true` errors (rate-limit, invalid payload, bufferFull) are
4476
+ // operational warnings and must NOT close the tab. Previously a single
4477
+ // mobile dropdown tab switch would close every tab because switchTab
4478
+ // triggers ssh-request-sync, which hit the Phase-3 rate-limit and
4479
+ // emitted an advisory ssh-error; the old closeTab-on-any-error path
4480
+ // then chained the close into server-side teardown cascades.
4481
+ if (data.sessionId && data.message !== 'Session not found' && !data.advisory) {
4449
4482
  this.closeTab(data.sessionId);
4450
4483
  }
4451
4484
  });
@@ -6818,6 +6851,23 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
6818
6851
  // SSH Session Management
6819
6852
  createSSHTab(name, connectionData, restoreSessionId = null) {
6820
6853
  const sessionId = restoreSessionId || 'ssh-' + Date.now();
6854
+
6855
+ // Idempotency: if a tab for this sessionId already exists (DOM +
6856
+ // session map), return the existing id rather than creating a
6857
+ // duplicate. Guards against duplicate tab-opened echoes and any
6858
+ // future regressions of the mobile tab-count bug.
6859
+ const existingDomTab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
6860
+ if (existingDomTab && this.sessions.has(sessionId)) {
6861
+ console.log('[SSHIFT] createSSHTab: session already exists, returning existing id:', sessionId);
6862
+ return sessionId;
6863
+ }
6864
+ if (existingDomTab) {
6865
+ // Stale DOM tab without a session entry — remove it before re-creating.
6866
+ existingDomTab.remove();
6867
+ const existingWrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
6868
+ if (existingWrapper) existingWrapper.remove();
6869
+ }
6870
+
6821
6871
  console.log('[SSHIFT] createSSHTab called:', {
6822
6872
  name,
6823
6873
  sessionId,
@@ -6868,7 +6918,10 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
6868
6918
  writeRAF: null,
6869
6919
  flushRemaining: null,
6870
6920
  originalScrollback: null,
6871
- scrollbackRestoreTimer: null
6921
+ scrollbackRestoreTimer: null,
6922
+ // Per-session buffer for OSC 52 / DCS sequences that arrive split
6923
+ // across two write-chunk frames (see _handleOsc52).
6924
+ pendingOsc52: null
6872
6925
  });
6873
6926
 
6874
6927
  // Switch to the new tab FIRST to make the container visible
@@ -6892,15 +6945,25 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
6892
6945
  const session = this.sessions.get(restoreSessionId);
6893
6946
  if (session) {
6894
6947
  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
6948
+ session._syncRetries = 0;
6949
+
6950
+ // Safety timeout: if sync never arrives within 5s the
6951
+ // terminal would be stuck silently dropping all output.
6952
+ // Clear the flag AND request a fresh sync (up to 2 retries)
6953
+ // so a slow/lost ssh-screen-sync doesn't permanently lose
6954
+ // output for this client.
6898
6955
  session.syncTimeout = setTimeout(() => {
6899
- console.warn('[SSHIFT] Sync timeout, clearing syncing flag for session:', restoreSessionId);
6956
+ console.warn('[SSHIFT] Sync timeout for session:', restoreSessionId, 'retries:', session._syncRetries);
6900
6957
  session.syncing = false;
6958
+ if (session._syncRetries < 2 && session.connected) {
6959
+ session._syncRetries += 1;
6960
+ this.requestScreenSync(restoreSessionId);
6961
+ } else {
6962
+ session._syncRetries = 0;
6963
+ }
6901
6964
  }, 5000);
6902
6965
  }
6903
-
6966
+
6904
6967
  this.socket.emit('ssh-join', { sessionId: restoreSessionId });
6905
6968
  } else {
6906
6969
  // Show connecting message only for new connections
@@ -7945,14 +8008,79 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7945
8008
  }
7946
8009
  }
7947
8010
 
8011
+ // Pure helper used by _flushWriteChunks to pick a frame-write split point
8012
+ // that doesn't bisect a UTF-16 surrogate pair or an ANSI escape sequence.
8013
+ // Exposed as a static method so it can be unit-tested without a Terminal.
8014
+ static findSafeWriteSplitPoint(combined, maxLen, scanWindow = 4096) {
8015
+ if (typeof combined !== 'string' || combined.length <= maxLen) return combined ? combined.length : 0;
8016
+ let splitAt = maxLen;
8017
+ const startScan = Math.max(0, maxLen - scanWindow);
8018
+ for (let i = maxLen - 1; i > startScan && i > 0; i--) {
8019
+ const code = combined.charCodeAt(i);
8020
+ // ESC (\x1b) always begins a new control sequence — safe to split before it.
8021
+ if (code === 0x1b) {
8022
+ splitAt = i;
8023
+ break;
8024
+ }
8025
+ // Don't split inside a UTF-16 surrogate pair. Two arrangements
8026
+ // need to back off:
8027
+ // (a) i is a TRAIL surrogate (0xDC00-0xDFFF) and i-1 is its
8028
+ // LEAD partner (0xD800-0xDBFF). Splitting at i would leave
8029
+ // the lone lead at the end of chunk-1 — and the lone trail
8030
+ // at the start of chunk-2 — both halves rendering as
8031
+ // U+FFFD. Move split back to before the LEAD.
8032
+ // (b) i is itself a LEAD surrogate (0xD800-0xDBFF) whose TRAIL
8033
+ // partner is at i+1. Splitting at i would put the LEAD at
8034
+ // the END of chunk-1 with no partner. Split at i instead
8035
+ // moves the entire pair into chunk-2.
8036
+ if (code >= 0xDC00 && code <= 0xDFFF) {
8037
+ if (i > 0) {
8038
+ const prev = combined.charCodeAt(i - 1);
8039
+ if (prev >= 0xD800 && prev <= 0xDBFF) {
8040
+ splitAt = i - 1;
8041
+ break;
8042
+ }
8043
+ }
8044
+ splitAt = i;
8045
+ break;
8046
+ }
8047
+ if (code >= 0xD800 && code <= 0xDBFF) {
8048
+ splitAt = i;
8049
+ break;
8050
+ }
8051
+ }
8052
+ return splitAt;
8053
+ }
8054
+
7948
8055
  // Parse and handle OSC 52 clipboard sequences from terminal data stream.
7949
8056
  // Extracts clipboard content, writes it to browser clipboard, and safely
7950
8057
  // handles sequences that span across data chunks.
7951
8058
  // Also handles tmux DCS passthrough: \x1bPtmux;\x1b\x1b]52;c;...\x07\x1b\\
7952
- _handleOsc52(data) {
7953
- if (!data || data.indexOf('52;') === -1) return data;
8059
+ //
8060
+ // Cross-chunk handling: an OSC 52 sequence may arrive split across two
8061
+ // `_flushWriteChunks` calls (e.g. `\x1b]52;c;` in one frame and the
8062
+ // base64 + BEL in the next). When we detect an incomplete sequence we
8063
+ // stash the partial bytes on `session.pendingOsc52` and strip them
8064
+ // from the data sent to xterm.js; the next call prepends that buffer
8065
+ // and processes the whole sequence as one.
8066
+ _handleOsc52(session, data) {
8067
+ if (!data) return data;
7954
8068
 
7955
- let result = data;
8069
+ // If a previous frame left a pending partial OSC 52 / DCS sequence,
8070
+ // prepend it so the now-complete sequence can be processed as a unit.
8071
+ let working = data;
8072
+ if (session.pendingOsc52) {
8073
+ working = session.pendingOsc52 + working;
8074
+ session.pendingOsc52 = null;
8075
+ }
8076
+
8077
+ // Fast path: nothing OSC-52-shaped in the payload (and no pending
8078
+ // partial). Skip the heavy reshaping work below.
8079
+ if (working.indexOf('52;') === -1 && working.indexOf('\x1bPtmux;') === -1 && working.indexOf('\x1bP\x1b') === -1) {
8080
+ return working;
8081
+ }
8082
+
8083
+ let result = working;
7956
8084
 
7957
8085
  // Handle tmux/screen DCS passthrough wrapper:
7958
8086
  // \x1bPtmux;\x1b wraps an inner escape sequence, terminated by \x1b\\
@@ -7980,7 +8108,13 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
7980
8108
  const inner = result.substring(dcsStart + dcsPrefixLen, dcsEnd);
7981
8109
  result = result.substring(0, dcsStart) + inner + result.substring(dcsEnd + 2);
7982
8110
  } else {
7983
- break; // Incomplete DCS, leave for next chunk
8111
+ // Incomplete DCS — save the tail (from dcsStart onward) onto
8112
+ // pendingOsc52 so the next frame can finish processing it.
8113
+ // Strip it from `result` so xterm doesn't buffer the partial
8114
+ // DCS itself.
8115
+ session.pendingOsc52 = result.substring(dcsStart);
8116
+ result = result.substring(0, dcsStart);
8117
+ break;
7984
8118
  }
7985
8119
  } else {
7986
8120
  break;
@@ -8011,6 +8145,14 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8011
8145
  }
8012
8146
 
8013
8147
  if (endIdx === -1) {
8148
+ // Incomplete OSC 52 — save the tail (from startIdx onward) onto
8149
+ // pendingOsc52 so the next frame can finish processing it.
8150
+ // Strip it from `result` so xterm doesn't buffer the partial
8151
+ // OSC sequence itself (which would cause the eventual clipboard
8152
+ // payload to leak through to xterm.js as soon as the rest of
8153
+ // the sequence arrives in the next frame).
8154
+ session.pendingOsc52 = result.substring(startIdx);
8155
+ result = result.substring(0, startIdx);
8014
8156
  break;
8015
8157
  }
8016
8158
 
@@ -8126,32 +8268,16 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8126
8268
  // Intercept OSC 52 clipboard sequences before writing to terminal.
8127
8269
  // OSC 52 format: ESC ] 52 ; <target> ; <base64> (BEL or ST)
8128
8270
  // This is more reliable than registerOscHandler which may not fire.
8129
- combined = this._handleOsc52(combined);
8271
+ combined = this._handleOsc52(session, combined);
8130
8272
 
8131
8273
  // Cap write size per frame. terminal.write() is synchronous and blocks
8132
8274
  // the main thread. We spill overflow to the next frame via flushRemaining.
8133
8275
  const MAX_WRITE_PER_FRAME = 32768;
8134
8276
 
8135
8277
  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
- }
8278
+ // Find a safe split point using the static helper so the logic is
8279
+ // unit-testable without an xterm.js terminal instance.
8280
+ const splitAt = SSHIFTClient.findSafeWriteSplitPoint(combined, MAX_WRITE_PER_FRAME);
8155
8281
  terminal.write(combined.substring(0, splitAt));
8156
8282
  session.flushRemaining = combined.substring(splitAt);
8157
8283
  session.writeRAF = requestAnimationFrame(() => {
@@ -8165,6 +8291,19 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8165
8291
  // SFTP Session Management
8166
8292
  createSFTPTab(name, connectionData, restoreSessionId = null) {
8167
8293
  const sessionId = restoreSessionId || 'sftp-' + Date.now();
8294
+
8295
+ // Idempotency: bail out if this session is already in the DOM + map.
8296
+ const existingDomTab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
8297
+ if (existingDomTab && this.sftpSessions.has(sessionId)) {
8298
+ console.log('[SSHIFT] createSFTPTab: session already exists, returning existing id:', sessionId);
8299
+ return sessionId;
8300
+ }
8301
+ if (existingDomTab) {
8302
+ existingDomTab.remove();
8303
+ const existingWrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
8304
+ if (existingWrapper) existingWrapper.remove();
8305
+ }
8306
+
8168
8307
  console.log('[SSHIFT] Creating SFTP tab with sessionId:', sessionId);
8169
8308
 
8170
8309
  const tab = this.createTabElement(sessionId, name, 'sftp');
@@ -9058,11 +9197,10 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9058
9197
  this.sftpSessions.delete(sessionId);
9059
9198
  }
9060
9199
 
9061
- // Remove from DOM
9062
- const tab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
9200
+ // Remove from DOM (use querySelectorAll to catch any duplicates)
9201
+ const tabs = document.querySelectorAll(`.tab[data-session-id="${sessionId}"]`);
9063
9202
  const wrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
9064
-
9065
- if (tab) tab.remove();
9203
+ tabs.forEach(t => t.remove());
9066
9204
  if (wrapper) wrapper.remove();
9067
9205
 
9068
9206
  // Update scroll arrows visibility
@@ -9157,10 +9295,10 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9157
9295
  this.sftpSessions.delete(sessionId);
9158
9296
  }
9159
9297
 
9160
- // Remove from DOM
9161
- const tab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
9298
+ // Remove from DOM (use querySelectorAll to catch any duplicates)
9299
+ const tabs = document.querySelectorAll(`.tab[data-session-id="${sessionId}"]`);
9162
9300
  const wrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
9163
- if (tab) tab.remove();
9301
+ tabs.forEach(t => t.remove());
9164
9302
  if (wrapper) wrapper.remove();
9165
9303
 
9166
9304
  // Update scroll arrows
@@ -9204,20 +9342,19 @@ handleTabOpened(data) {
9204
9342
  this._serverPanelMap.set(data.sessionId, data.panelId);
9205
9343
  }
9206
9344
 
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);
9345
+ // Create the tab without connecting (we'll join the existing session).
9346
+ // Defensive dedupe: only create if no DOM tab exists yet for this session.
9347
+ const existingTabNodes = document.querySelectorAll(
9348
+ `.tab[data-session-id="${data.sessionId}"]`
9349
+ );
9350
+ if (existingTabNodes.length === 0) {
9351
+ if (data.type === 'ssh') {
9352
+ this.createSSHTab(data.name, data.connectionData, data.sessionId);
9353
+ } else if (data.type === 'sftp') {
9354
+ this.createSFTPTab(data.name, data.connectionData, data.sessionId);
9355
+ }
9356
+ } else {
9357
+ console.log('[SSHIFT] Tab DOM already exists for session, skipping:', data.sessionId);
9221
9358
  }
9222
9359
 
9223
9360
  // Update mobile tabs dropdown
@@ -9267,11 +9404,10 @@ handleTabOpened(data) {
9267
9404
  this.sftpSessions.delete(sessionId);
9268
9405
  }
9269
9406
 
9270
- // Remove from DOM
9271
- const tab = document.querySelector(`.tab[data-session-id="${sessionId}"]`);
9407
+ // Remove from DOM (querySelectorAll to handle any duplicates)
9408
+ const tabs = document.querySelectorAll(`.tab[data-session-id="${sessionId}"]`);
9272
9409
  const wrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
9273
-
9274
- if (tab) tab.remove();
9410
+ tabs.forEach(t => t.remove());
9275
9411
  if (wrapper) wrapper.remove();
9276
9412
 
9277
9413
  // Check if there are remaining tabs in the panel
@@ -9325,6 +9461,7 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null)
9325
9461
  // Suppress switchTab during creation so we can activate the correct tab at the end
9326
9462
  this._suppressTabSwitch = true;
9327
9463
 
9464
+ try {
9328
9465
  // On initial sync, remove any client-side tabs that don't exist on the server.
9329
9466
  // This ensures the server is the single source of truth and prevents duplicates
9330
9467
  // from stale localStorage caches (e.g. when switching between devices).
@@ -9393,9 +9530,13 @@ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null)
9393
9530
 
9394
9531
  // Apply any flash states that arrived before DOM elements existed
9395
9532
  this.applyFlashStates();
9396
-
9397
- this.isRestoring = false;
9398
- this._suppressTabSwitch = false;
9533
+ } finally {
9534
+ // Guarantee the sync flags clear even if a throw happens mid-sync.
9535
+ // Without this the UI would dead-lock (switchTab suppressed forever
9536
+ // and restoreTabs blocked waiting on isRestoring).
9537
+ this.isRestoring = false;
9538
+ this._suppressTabSwitch = false;
9539
+ }
9399
9540
 
9400
9541
  // Activate the correct tab per panel based on server state
9401
9542
  if (activeTabsByPanel && !this.isMobile) {