@lethevimlet/sshift 1.3.1 → 1.3.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.3.1",
3
+ "version": "1.3.3",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -241,10 +241,6 @@ function registerSystemEndpoints(app, io) {
241
241
  // API: Trigger update
242
242
  app.post('/api/update', async (req, res) => {
243
243
  try {
244
- const isLocalhost = req.hostname === 'localhost' || req.hostname === '127.0.0.1' || req.hostname === '::1';
245
- if (!isLocalhost && !req.headers.authorization && !req.query.token) {
246
- return res.status(403).json({ error: 'Remote update requires authentication. Set a password or use localhost.' });
247
- }
248
244
 
249
245
  const { spawn, execSync } = require('child_process');
250
246
  const platform = process.platform;
@@ -9,11 +9,12 @@ const {
9
9
  getTabOrder,
10
10
  addToTabOrder,
11
11
  setTabOrder,
12
- setCloseTimer,
12
+ setCloseTimer,
13
13
  clearCloseTimer,
14
14
  getCloseTimer,
15
15
  updateTabName,
16
16
  updateTabPanel,
17
+ setActiveTab,
17
18
  getOpenTabs,
18
19
  getCurrentTheme,
19
20
  setCurrentTheme,
@@ -96,22 +97,32 @@ function registerTabHandlers(socket, io) {
96
97
  console.log('[TAB] Tabs save:', data.tabs?.length || 0, 'tabs, layout:', data.layout);
97
98
 
98
99
  // Update tab order with panel assignments
99
- if (data.tabs && Array.isArray(data.tabs)) {
100
+ if (data.tabs && Array.isArray(data.tabs) && data.tabs.length > 0) {
100
101
  setTabOrder(data.tabs.map(t => typeof t === 'string' ? t : t.sessionId));
101
102
 
102
- // Update panel assignments in openTabs
103
+ // Update panel assignments and active tabs in openTabs
103
104
  data.tabs.forEach(tabData => {
104
105
  if (typeof tabData === 'object' && tabData.sessionId && tabData.panelId) {
105
106
  updateTabPanel(tabData.sessionId, tabData.panelId);
107
+ // Track which tab is active per panel
108
+ if (tabData.active) {
109
+ setActiveTab(tabData.panelId, tabData.sessionId);
110
+ }
106
111
  }
107
112
  });
108
113
  }
114
+ // Don't update tab order for empty tab lists — a new client syncing
115
+ // before receiving server tabs would wipe the server-side tab order.
116
+ // The server is the single source of truth for tab order.
109
117
 
110
- // Broadcast to all other clients
111
- socket.broadcast.emit('tabs-sync', {
112
- tabs: data.tabs,
113
- layout: data.layout
114
- });
118
+ // Broadcast to all other clients only if there are tabs to sync.
119
+ // Empty tab lists during initial sync should not disrupt other clients.
120
+ if (data.tabs && data.tabs.length > 0) {
121
+ socket.broadcast.emit('tabs-sync', {
122
+ tabs: data.tabs,
123
+ layout: data.layout
124
+ });
125
+ }
115
126
  });
116
127
 
117
128
  // Tab rename - sync across all sessions
@@ -382,7 +382,7 @@ async function initializeServer() {
382
382
  console.log('Client connected:', socket.id);
383
383
 
384
384
  // Send current open tabs to new client
385
- const { getOpenTabs, getTabOrder, getCurrentTheme, getCurrentAccent } = require('./utils/tab-manager');
385
+ const { getOpenTabs, getTabOrder, getCurrentTheme, getCurrentAccent, getActiveTabsByPanel } = require('./utils/tab-manager');
386
386
  const { getCurrentLayout } = require('./endpoints/ws/layout');
387
387
 
388
388
  const openTabs = getOpenTabs();
@@ -390,12 +390,20 @@ async function initializeServer() {
390
390
  const currentLayout = getCurrentLayout();
391
391
  const currentTheme = getCurrentTheme();
392
392
  const currentAccent = getCurrentAccent();
393
+ const activeTabsByPanelMap = getActiveTabsByPanel();
394
+ const activeTabsByPanel = Object.fromEntries(activeTabsByPanelMap);
393
395
 
394
- // Exclude activeSockets (Set object) to avoid Socket.IO serialization issues
396
+ // Build ordered tabs and default active tab per panel if not tracked yet.
397
+ // When a panel has no recorded active tab (e.g. server restart), the first
398
+ // tab in that panel becomes active.
399
+ const tabsByPanel = {};
395
400
  const orderedTabs = tabOrder
396
401
  .filter(sessionId => openTabs.has(sessionId))
397
402
  .map(sessionId => {
398
403
  const tab = openTabs.get(sessionId);
404
+ const panelId = tab.panelId || 'panel-0';
405
+ if (!tabsByPanel[panelId]) tabsByPanel[panelId] = [];
406
+ tabsByPanel[panelId].push(sessionId);
399
407
  return {
400
408
  sessionId,
401
409
  name: tab.name,
@@ -405,17 +413,29 @@ async function initializeServer() {
405
413
  port: tab.connectionData?.port,
406
414
  username: tab.connectionData?.username,
407
415
  name: tab.connectionData?.name
408
- // Exclude password, privateKey, and other sensitive data
409
416
  },
410
417
  sticky: tab.sticky,
411
- panelId: tab.panelId || 'panel-0' // Include panel assignment
412
- // Exclude activeSockets (Set) to avoid serialization issues
418
+ panelId,
419
+ active: false // set below
413
420
  };
414
421
  });
415
422
 
423
+ // Determine active tab per panel: use tracked active, or default to first tab
424
+ for (const [panelId, sessionIds] of Object.entries(tabsByPanel)) {
425
+ const tracked = activeTabsByPanelMap.get(panelId);
426
+ const activeId = (tracked && sessionIds.includes(tracked)) ? tracked : sessionIds[0];
427
+ if (activeId) activeTabsByPanel[panelId] = activeId;
428
+ }
429
+
430
+ // Mark active tab in orderedTabs
431
+ orderedTabs.forEach(tab => {
432
+ tab.active = activeTabsByPanel[tab.panelId] === tab.sessionId;
433
+ });
434
+
416
435
  socket.emit('open-tabs', {
417
436
  tabs: orderedTabs,
418
437
  layout: currentLayout,
438
+ activeTabsByPanel,
419
439
  theme: currentTheme,
420
440
  accent: currentAccent
421
441
  });
@@ -1,5 +1,6 @@
1
1
  const { Client } = require('ssh2');
2
2
  const { convertKeyIfNeeded } = require('../utils/key-converter');
3
+ const { removeTab } = require('../utils/tab-manager');
3
4
 
4
5
  class SFTPManager {
5
6
  constructor() {
@@ -102,6 +103,7 @@ class SFTPManager {
102
103
  console.error(`[SFTP] Connection error: ${err.message}`);
103
104
  socket.emit('sftp-error', { sessionId, message: err.message });
104
105
  this.sessions.delete(sessionId);
106
+ removeTab(sessionId);
105
107
  reject(err);
106
108
  });
107
109
 
@@ -109,6 +111,7 @@ class SFTPManager {
109
111
  console.log(`[SFTP] Connection closed: ${sessionId}`);
110
112
  socket.emit('sftp-disconnected', { sessionId });
111
113
  this.sessions.delete(sessionId);
114
+ removeTab(sessionId);
112
115
  });
113
116
 
114
117
  try {
@@ -386,6 +389,7 @@ class SFTPManager {
386
389
  session.conn.end();
387
390
  }
388
391
  this.sessions.delete(sessionId);
392
+ removeTab(sessionId);
389
393
  }
390
394
  }
391
395
 
@@ -4,6 +4,7 @@ const { SerializeAddon } = require('@xterm/addon-serialize');
4
4
  const { Unicode11Addon } = require('@xterm/addon-unicode11');
5
5
  const pluginManager = require('../plugins/plugin-manager');
6
6
  const { convertKeyIfNeeded } = require('../utils/key-converter');
7
+ const { removeTab } = require('../utils/tab-manager');
7
8
 
8
9
  class SSHManager {
9
10
  constructor() {
@@ -191,7 +192,11 @@ class SSHManager {
191
192
  this.flushData(sessionId);
192
193
  this.broadcastToSession(sessionId, 'ssh-disconnected', { sessionId });
193
194
  this.disconnect(sessionId);
194
- if (this.io) this.io.emit('sessions-updated');
195
+ removeTab(sessionId);
196
+ if (this.io) {
197
+ this.io.emit('tab-closed', { sessionId });
198
+ this.io.emit('sessions-updated');
199
+ }
195
200
  });
196
201
 
197
202
  stream.on('exit', (code, signal) => {
@@ -212,7 +217,11 @@ class SSHManager {
212
217
  console.error(`[SSH] Connection error: ${err.message}`);
213
218
  socket.emit('ssh-error', { sessionId, message: err.message });
214
219
  this.sessions.delete(sessionId);
215
- if (this.io) this.io.emit('sessions-updated');
220
+ removeTab(sessionId);
221
+ if (this.io) {
222
+ this.io.emit('tab-closed', { sessionId });
223
+ this.io.emit('sessions-updated');
224
+ }
216
225
  reject(err);
217
226
  });
218
227
 
@@ -220,7 +229,11 @@ class SSHManager {
220
229
  console.log(`[SSH] Connection closed: ${sessionId}`);
221
230
  this.broadcastToSession(sessionId, 'ssh-disconnected', { sessionId });
222
231
  this.sessions.delete(sessionId);
223
- if (this.io) this.io.emit('sessions-updated');
232
+ removeTab(sessionId);
233
+ if (this.io) {
234
+ this.io.emit('tab-closed', { sessionId });
235
+ this.io.emit('sessions-updated');
236
+ }
224
237
  });
225
238
 
226
239
  try {
@@ -623,6 +636,7 @@ class SSHManager {
623
636
  session.terminal.dispose();
624
637
  }
625
638
  this.sessions.delete(sessionId);
639
+ removeTab(sessionId);
626
640
  // Notify plugins about disconnect
627
641
  pluginManager.onSessionDisconnect(sessionId);
628
642
  }
@@ -10,7 +10,10 @@ const openTabs = new Map();
10
10
  // Array of sessionIds in order
11
11
  let tabOrder = [];
12
12
 
13
- // Current active layout for sync
13
+ // Active tab per panel: Map<panelId, sessionId>
14
+ const activeTabsByPanel = new Map();
15
+
16
+ // Current layout for sync
14
17
  let currentLayout = 'single';
15
18
 
16
19
  // Theme and accent for cross-device sync
@@ -95,6 +98,12 @@ function getTab(sessionId) {
95
98
  function removeTab(sessionId) {
96
99
  openTabs.delete(sessionId);
97
100
  tabOrder = tabOrder.filter(id => id !== sessionId);
101
+ // Clean up active tab references
102
+ for (const [panelId, activeId] of activeTabsByPanel) {
103
+ if (activeId === sessionId) {
104
+ activeTabsByPanel.delete(panelId);
105
+ }
106
+ }
98
107
  }
99
108
 
100
109
  /**
@@ -199,6 +208,34 @@ function updateTabPanel(sessionId, panelId) {
199
208
  }
200
209
  }
201
210
 
211
+ /**
212
+ * Set active tab for a panel
213
+ * @param {string} panelId - Panel ID
214
+ * @param {string} sessionId - Session ID that is active
215
+ */
216
+ function setActiveTab(panelId, sessionId) {
217
+ if (sessionId && openTabs.has(sessionId)) {
218
+ activeTabsByPanel.set(panelId, sessionId);
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Get active tab for a panel
224
+ * @param {string} panelId - Panel ID
225
+ * @returns {string|undefined} Session ID of active tab
226
+ */
227
+ function getActiveTab(panelId) {
228
+ return activeTabsByPanel.get(panelId);
229
+ }
230
+
231
+ /**
232
+ * Get all active tabs by panel
233
+ * @returns {Map} Map of panelId -> sessionId
234
+ */
235
+ function getActiveTabsByPanel() {
236
+ return activeTabsByPanel;
237
+ }
238
+
202
239
  /**
203
240
  * Get current theme
204
241
  * @returns {string} Current theme
@@ -258,6 +295,9 @@ module.exports = {
258
295
  getCloseTimer,
259
296
  updateTabName,
260
297
  updateTabPanel,
298
+ setActiveTab,
299
+ getActiveTab,
300
+ getActiveTabsByPanel,
261
301
  getCurrentTheme,
262
302
  setCurrentTheme,
263
303
  getCurrentAccent,
@@ -596,6 +596,18 @@ body {
596
596
  text-overflow: ellipsis;
597
597
  }
598
598
 
599
+ .mobile-tab-option .tab-panel-badge {
600
+ font-size: 10px;
601
+ padding: 1px 5px;
602
+ border-radius: 8px;
603
+ background: var(--bg-tertiary);
604
+ color: var(--text-muted);
605
+ border: 1px solid var(--border-color);
606
+ white-space: nowrap;
607
+ flex-shrink: 0;
608
+ line-height: 1.2;
609
+ }
610
+
599
611
  .mobile-tab-option .tab-close {
600
612
  display: flex;
601
613
  align-items: center;
@@ -7,8 +7,9 @@ class SSHIFTClient {
7
7
  this.socket = io({
8
8
  transports: ['websocket', 'polling'],
9
9
  reconnection: true,
10
- reconnectionAttempts: 5,
10
+ reconnectionAttempts: Infinity,
11
11
  reconnectionDelay: 1000,
12
+ reconnectionDelayMax: 30000,
12
13
  auth: authToken ? { token: authToken } : {}
13
14
  });
14
15
  console.log('[SSHIFT] Socket created');
@@ -18,6 +19,11 @@ class SSHIFTClient {
18
19
  this.sessions = new Map();
19
20
  this.activeSessionId = null; // Global active session (for backwards compatibility)
20
21
  this.activeSessionsByPanel = new Map(); // Per-panel active sessions: Map<panelId, sessionId>
22
+ this._wasDisconnected = false; // Track reconnection state for toast messages
23
+ this._initReady = false; // Set true once init() completes
24
+ this._pendingOpenTabs = null; // Deferred open-tabs data
25
+ this._pendingOpenTabsIsInitial = false;
26
+ this._suppressTabSwitch = false; // Suppress switchTab during sync
21
27
  this.bookmarks = [];
22
28
  this.folders = [];
23
29
  this.currentConnectionType = 'ssh';
@@ -31,6 +37,8 @@ class SSHIFTClient {
31
37
  this.savedTabs = []; // Store tab information
32
38
  this.isRestoring = false; // Flag to prevent saving during restoration
33
39
  this.isSyncingTabs = false; // Flag to prevent saveTabs emission during tabs-sync
40
+ this._serverPanelMap = new Map(); // sessionId -> panelId from server (preserved for mobile)
41
+ this._serverLayout = null; // Layout from server (preserved for mobile saves)
34
42
  this._initialSyncDone = false; // Whether initial open-tabs sync from server has completed
35
43
  this._serverSyncTimeout = null; // Timeout for fallback to localStorage restore
36
44
  this.sftpClipboard = null; // For cut/copy/paste: { action: 'cut'|'copy', path: string, name: string, sessionId: string }
@@ -457,22 +465,31 @@ class SSHIFTClient {
457
465
  const session = this.sessions.get(sessionId) || this.sftpSessions.get(sessionId);
458
466
 
459
467
  if (session) {
468
+ // On mobile (single panel), preserve the server-assigned panel instead of panel-0
469
+ const effectivePanelId = this.isMobile
470
+ ? (this._serverPanelMap.get(sessionId) || panelId)
471
+ : panelId;
472
+ // Keep server panel map in sync with desktop reality
473
+ this._serverPanelMap.set(sessionId, effectivePanelId);
460
474
  tabs.push({
461
475
  sessionId,
462
476
  name: session.name,
463
477
  type: session.type,
464
478
  connectionData: session.connectionData,
465
479
  active: sessionId === activeInThisPanel, // Active in this specific panel
466
- panelId: panelId
480
+ panelId: effectivePanelId
467
481
  });
468
482
  }
469
483
  });
470
484
  });
471
485
 
472
- // Save tabs with current layout
486
+ // Save tabs with current layout (mobile saves server layout, not 'single')
487
+ const savedLayout = this.isMobile
488
+ ? (this._serverLayout || 'single')
489
+ : (this.currentLayout?.id || 'single');
473
490
  const tabsData = {
474
491
  tabs,
475
- layout: this.currentLayout?.id || 'single'
492
+ layout: savedLayout
476
493
  };
477
494
 
478
495
  localStorage.setItem('openTabs', JSON.stringify(tabsData));
@@ -510,6 +527,44 @@ class SSHIFTClient {
510
527
  return Array.from(panels).map(p => p.id);
511
528
  }
512
529
 
530
+ getClockwisePanels() {
531
+ const panels = this.getAllPanels();
532
+ if (panels.length <= 1) return panels;
533
+
534
+ // Parse panel IDs: 'panel-0' (single) or 'panel-{col}-{row}' (multi)
535
+ const parsed = panels.map(id => {
536
+ const parts = id.replace('panel-', '').split('-');
537
+ if (parts.length === 1) return { id, col: 0, row: 0 };
538
+ return { id, col: parseInt(parts[0]), row: parseInt(parts[1]) };
539
+ });
540
+
541
+ // Group panels by row
542
+ const rows = {};
543
+ parsed.forEach(p => {
544
+ if (!rows[p.row]) rows[p.row] = [];
545
+ rows[p.row].push(p);
546
+ });
547
+
548
+ // Sort rows numerically
549
+ const sortedRowKeys = Object.keys(rows).map(Number).sort((a, b) => a - b);
550
+
551
+ // Clockwise from top-left: row 0 left→right, row 1 right→left (snake/boustrophedon)
552
+ // This gives: top-left, top-right, bottom-right, bottom-left for a 2x2 grid
553
+ const result = [];
554
+ sortedRowKeys.forEach((rowKey, rowIndex) => {
555
+ const rowPanels = rows[rowKey].sort((a, b) => a.col - b.col);
556
+ if (rowIndex % 2 === 0) {
557
+ // Even rows: left to right
558
+ result.push(...rowPanels);
559
+ } else {
560
+ // Odd rows: right to left
561
+ result.push(...rowPanels.reverse());
562
+ }
563
+ });
564
+
565
+ return result.map(p => p.id);
566
+ }
567
+
513
568
  // Get tabs container for a panel
514
569
  getTabsContainer(panelId) {
515
570
  // For single panel (panel-0), use original IDs without prefix
@@ -551,14 +606,15 @@ class SSHIFTClient {
551
606
 
552
607
  const panels = this.getAllPanels();
553
608
  const panelCount = panels.length;
609
+ const clockwisePanels = this.getClockwisePanels();
554
610
 
555
- console.log('[SSHIFT] Distributing', allSessions.length, 'tabs across', panelCount, 'panels');
611
+ console.log('[SSHIFT] Distributing', allSessions.length, 'tabs across', panelCount, 'panels (clockwise order:', clockwisePanels.join(', '), ')');
556
612
 
557
613
  // Store current active sessions before redistribution
558
614
  const previousActiveSessions = new Map(this.activeSessionsByPanel);
559
615
 
560
616
  // If we have synced tabs from another browser tab, use them
561
- if (syncedTabs && Array.isArray(syncedTabs)) {
617
+ if (syncedTabs && Array.isArray(syncedTabs) && syncedTabs.length > 0) {
562
618
  // Group tabs by panelId
563
619
  const tabsByPanel = {};
564
620
  panels.forEach(p => tabsByPanel[p] = []);
@@ -566,7 +622,7 @@ class SSHIFTClient {
566
622
  syncedTabs.forEach(tabData => {
567
623
  const targetPanel = tabData.panelId && panels.includes(tabData.panelId)
568
624
  ? tabData.panelId
569
- : panels[0];
625
+ : clockwisePanels[0];
570
626
  tabsByPanel[targetPanel].push(tabData);
571
627
  });
572
628
 
@@ -586,10 +642,9 @@ class SSHIFTClient {
586
642
  }
587
643
  });
588
644
  } else {
589
- // No synced data - distribute evenly across panels
590
- // First, collect all existing tabs in order
645
+ // No synced data - collect all existing tabs in clockwise panel order
591
646
  const existingTabs = [];
592
- panels.forEach(panelId => {
647
+ clockwisePanels.forEach(panelId => {
593
648
  const tabsContainer = this.getTabsContainer(panelId);
594
649
  if (tabsContainer) {
595
650
  Array.from(tabsContainer.children).forEach(tab => {
@@ -601,41 +656,35 @@ class SSHIFTClient {
601
656
  }
602
657
  });
603
658
 
604
- // If we have more panels than tabs, put all in first panel
605
- // If we have more tabs than panels, distribute evenly
606
659
  if (panelCount === 1) {
607
- // Single panel - all tabs go there
608
660
  existingTabs.forEach(tabData => {
609
661
  this.moveTabToPanel(tabData.sessionId, 'panel-0');
610
662
  });
611
663
  } else {
612
- // Multi-panel - distribute evenly
664
+ // Distribute in clockwise order: tab 1→first panel, tab 2→second panel, etc.
613
665
  existingTabs.forEach((tabData, index) => {
614
- const targetPanel = panels[index % panelCount];
666
+ const targetPanel = clockwisePanels[index % panelCount];
615
667
  this.moveTabToPanel(tabData.sessionId, targetPanel);
616
668
  });
617
669
  }
618
670
 
619
- // Activate tabs in each panel
671
+ // Build tabsByPanel for activation
620
672
  const tabsByPanel = {};
621
673
  panels.forEach(p => tabsByPanel[p] = []);
622
674
 
623
675
  existingTabs.forEach((tabData, index) => {
624
- const targetPanel = panelCount === 1 ? 'panel-0' : panels[index % panelCount];
676
+ const targetPanel = panelCount === 1 ? 'panel-0' : clockwisePanels[index % panelCount];
625
677
  tabsByPanel[targetPanel].push(tabData.sessionId);
626
678
  });
627
679
 
628
680
  // Restore active sessions or activate first tab in each panel
629
681
  Object.entries(tabsByPanel).forEach(([panelId, sessionIds]) => {
630
682
  if (sessionIds.length > 0) {
631
- // Check if we had a previously active session in this panel
632
683
  const previousActive = previousActiveSessions.get(panelId);
633
684
 
634
- // If the previous active session is still in this panel, restore it
635
685
  if (previousActive && sessionIds.includes(previousActive)) {
636
686
  this.switchTab(previousActive, panelId);
637
687
  } else {
638
- // Otherwise, activate the first tab
639
688
  this.switchTab(sessionIds[0], panelId);
640
689
  }
641
690
  }
@@ -702,6 +751,9 @@ class SSHIFTClient {
702
751
  }
703
752
 
704
753
  console.log('[SSHIFT] Moved tab', sessionId, 'from', currentPanelId, 'to', targetPanelId);
754
+
755
+ // Update server panel map for mobile preservation
756
+ this._serverPanelMap.set(sessionId, targetPanelId);
705
757
  }
706
758
 
707
759
  // Hide empty state for a specific panel
@@ -1124,8 +1176,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1124
1176
  foreground: '#e6edf3',
1125
1177
  cursor: '#c10059',
1126
1178
  cursorAccent: '#0d1117',
1127
- selectionBackground: 'rgba(193, 0, 89, 0.3)',
1128
- selectionForeground: '#e6edf3'
1179
+ selectionBackground: 'rgba(193, 0, 89, 0.3)'
1129
1180
  // Don't set ANSI colors - let terminal use its defaults for colored output
1130
1181
  };
1131
1182
  console.log('[SSHIFT] getTerminalTheme (override disabled):', defaultTheme);
@@ -1139,7 +1190,6 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1139
1190
  cursor: '#c10059',
1140
1191
  cursorAccent: this.terminalBgColor || '#0d1117',
1141
1192
  selectionBackground: this.hexToRgba(this.terminalSelectionColor || '#264f78', 0.5),
1142
- selectionForeground: this.terminalFgColor || '#e6edf3',
1143
1193
  black: isDark ? '#484f58' : '#6e7681',
1144
1194
  red: '#f85149',
1145
1195
  green: '#3fb950',
@@ -2371,6 +2421,10 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2371
2421
  async init() {
2372
2422
  console.log('[SSHIFT] Setting up listeners...');
2373
2423
 
2424
+ // Register socket listeners FIRST, before any async operations,
2425
+ // so we don't miss the open-tabs event on initial connection.
2426
+ this.setupSocketListeners();
2427
+
2374
2428
  await this.checkAuthStatus();
2375
2429
 
2376
2430
  // Fix mobile viewport height issues
@@ -2385,7 +2439,6 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2385
2439
  // Initialize layout system (must be before setupEventListeners)
2386
2440
  await this.initLayoutSystem();
2387
2441
 
2388
- this.setupSocketListeners();
2389
2442
  this.setupEventListeners();
2390
2443
  this.loadBookmarks(); // This will also load folders
2391
2444
  this.applySidebarState();
@@ -2423,8 +2476,41 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2423
2476
 
2424
2477
  this.handleResize();
2425
2478
  console.log('[SSHIFT] Client initialized');
2479
+
2480
+ // Mark init as complete and process any deferred open-tabs
2481
+ this._initReady = true;
2482
+ if (this._pendingOpenTabs) {
2483
+ console.log('[SSHIFT] Processing deferred open-tabs');
2484
+ const pendingData = this._pendingOpenTabs;
2485
+ const isInitialSync = this._pendingOpenTabsIsInitial;
2486
+ this._pendingOpenTabs = null;
2487
+ this._pendingOpenTabsIsInitial = null;
2488
+
2489
+ // Store server layout for mobile preservation
2490
+ if (pendingData.layout) {
2491
+ this._serverLayout = pendingData.layout;
2492
+ }
2493
+
2494
+ // Prevent saveTabs from emitting to server during deferred sync
2495
+ const wasSyncingTabs = this.isSyncingTabs;
2496
+ this.isSyncingTabs = true;
2497
+
2498
+ try {
2499
+ if (pendingData.tabs.length > 0) {
2500
+ // Sync layout BEFORE tabs so panels exist before distribution
2501
+ if (pendingData.layout && !this.isMobile) {
2502
+ this.setLayoutFromServer(pendingData.layout);
2503
+ }
2504
+ this.syncTabsFromServer(pendingData.tabs, isInitialSync, pendingData.activeTabsByPanel);
2505
+ } else {
2506
+ this.restoreTabs();
2507
+ }
2508
+ } finally {
2509
+ this.isSyncingTabs = wasSyncingTabs;
2510
+ }
2511
+ }
2426
2512
  }
2427
-
2513
+
2428
2514
  // Fix mobile viewport height issues caused by address/navigation bars
2429
2515
  fixMobileViewport() {
2430
2516
  // Set CSS custom property for actual viewport height
@@ -3316,9 +3402,9 @@ const wheelHandler = (e) => {
3316
3402
 
3317
3403
  let sessionId;
3318
3404
 
3319
- // If sticky is enabled, try to join existing session
3320
- // Otherwise, create a new session with the same connection data
3321
- const restoreSessionId = this.sticky ? savedTab.sessionId : null;
3405
+ // restoreTabs() is only called when the server has no active sessions
3406
+ // (e.g. server restart), so we must create new connections, not join.
3407
+ const restoreSessionId = null;
3322
3408
 
3323
3409
  if (savedTab.type === 'ssh') {
3324
3410
  sessionId = this.createSSHTab(savedTab.name, savedTab.connectionData, restoreSessionId);
@@ -3386,7 +3472,11 @@ const wheelHandler = (e) => {
3386
3472
  setupSocketListeners() {
3387
3473
  this.socket.on('connect', () => {
3388
3474
  console.log('[SSHIFT] Connected to server, socket ID:', this.socket.id);
3389
- if (!this.isUpdating) {
3475
+ const wasDisconnected = this._wasDisconnected;
3476
+ this._wasDisconnected = false;
3477
+ if (wasDisconnected && !this.isUpdating) {
3478
+ this.showToast('Reconnected to server', 'success');
3479
+ } else if (!this.isUpdating) {
3390
3480
  this.showToast('Connected to server', 'success');
3391
3481
  }
3392
3482
  this.loadBookmarks();
@@ -3394,8 +3484,20 @@ const wheelHandler = (e) => {
3394
3484
 
3395
3485
  this.socket.on('disconnect', (reason) => {
3396
3486
  console.log('[SSHIFT] Disconnected from server:', reason);
3397
- if (!this.isUpdating) {
3398
- this.showToast('Disconnected from server: ' + reason, 'error');
3487
+ this._wasDisconnected = true;
3488
+ if (reason === 'io server disconnect') {
3489
+ // Server intentionally disconnected us (e.g. auth failure) — don't auto-reconnect
3490
+ // Socket.IO won't retry after server-initiated disconnect anyway
3491
+ } else if (!this.isUpdating) {
3492
+ this.showToast('Disconnected from server — will reconnect automatically', 'warning');
3493
+ }
3494
+ });
3495
+
3496
+ // When the tab becomes visible again, immediately try to reconnect if disconnected
3497
+ document.addEventListener('visibilitychange', () => {
3498
+ if (!document.hidden && !this.socket.connected) {
3499
+ console.log('[SSHIFT] Tab visible and socket disconnected, triggering reconnect');
3500
+ this.socket.connect();
3399
3501
  }
3400
3502
  });
3401
3503
 
@@ -3405,9 +3507,10 @@ const wheelHandler = (e) => {
3405
3507
  this.authToken = null;
3406
3508
  localStorage.removeItem('sshift_auth_token');
3407
3509
  this.showLockScreen();
3408
- } else if (!this.isUpdating) {
3409
- this.showToast('Connection error: ' + error.message, 'error');
3410
3510
  }
3511
+ // Don't show generic connection error toasts during reconnection —
3512
+ // the user already sees "Disconnected" and the auto-reconnect handles it.
3513
+ // Only show for explicit user actions (not isUpdating suppresses during update).
3411
3514
  });
3412
3515
 
3413
3516
  // Handle receiving open tabs from server (for cross-tab sync)
@@ -3444,25 +3547,53 @@ const wheelHandler = (e) => {
3444
3547
  }
3445
3548
  }
3446
3549
 
3447
- // Only sync if sticky is enabled
3448
- // Server is the single source of truth for tabs in sticky mode.
3449
- // On initial sync, reconcile local state to match server state.
3450
- // On reconnection, only add missing tabs to avoid disrupting locally-created tabs.
3550
+ // Only sync if sticky is enabled and init has completed.
3551
+ // If init hasn't finished yet (DOM not ready), defer processing
3552
+ // until init completes and the open-tabs event queue is flushed.
3451
3553
  if (this.sticky) {
3452
- if (data.tabs.length > 0) {
3453
- const isInitialSync = !this._initialSyncDone;
3454
- this.syncTabsFromServer(data.tabs, isInitialSync);
3455
- } else if (!this._initialSyncDone) {
3456
- // Server has no tabs and this is the first sync (e.g. server restart).
3457
- // Fall back to localStorage restore to reconnect sessions.
3458
- this.restoreTabs();
3554
+ // Store server layout for mobile tab preservation
3555
+ if (data.layout) {
3556
+ this._serverLayout = data.layout;
3557
+ }
3558
+ // Prevent saveTabs from emitting to server during initial sync
3559
+ // (the server is our source of truth; we don't want to broadcast
3560
+ // incomplete state back to other clients)
3561
+ const wasSyncingTabs = this.isSyncingTabs;
3562
+ this.isSyncingTabs = true;
3563
+
3564
+ try {
3565
+ if (!this._initReady) {
3566
+ console.log('[SSHIFT] Deferring open-tabs processing until init completes');
3567
+ this._pendingOpenTabs = data;
3568
+ this._pendingOpenTabsIsInitial = !this._initialSyncDone;
3569
+ this._initialSyncDone = true;
3570
+ } else if (data.tabs.length > 0) {
3571
+ const isInitialSync = !this._initialSyncDone;
3572
+ // Sync layout BEFORE tabs so panels exist before distribution
3573
+ if (data.layout && !this.isMobile) {
3574
+ this.setLayoutFromServer(data.layout);
3575
+ }
3576
+ this.syncTabsFromServer(data.tabs, isInitialSync, data.activeTabsByPanel);
3577
+ } else if (!this._initialSyncDone) {
3578
+ // Server has no tabs and this is the first sync (e.g. server restart).
3579
+ // Still apply layout from server even with no tabs.
3580
+ if (data.layout && !this.isMobile) {
3581
+ this.setLayoutFromServer(data.layout);
3582
+ }
3583
+ // Fall back to localStorage restore to reconnect sessions.
3584
+ this.restoreTabs();
3585
+ } else if (data.layout && !this.isMobile) {
3586
+ // No tabs change, but layout may have changed
3587
+ this.setLayoutFromServer(data.layout);
3588
+ }
3589
+ this._initialSyncDone = true;
3590
+ } finally {
3591
+ // Restore previous syncing state (syncTabsFromServer manages its own)
3592
+ this.isSyncingTabs = wasSyncingTabs;
3459
3593
  }
3460
- this._initialSyncDone = true;
3461
- }
3462
- // Sync layout if provided (but not on mobile - mobile always uses single panel)
3463
- if (data.layout && this.sticky && !this.isMobile) {
3464
- this.setLayoutFromServer(data.layout);
3465
3594
  }
3595
+ // Layout sync is handled above before tab sync; skip redundant call on mobile
3596
+ // (mobile always uses single panel)
3466
3597
  });
3467
3598
 
3468
3599
  // Handle tab opened event from another client
@@ -3525,6 +3656,8 @@ const wheelHandler = (e) => {
3525
3656
  // Handle layout change from another client
3526
3657
  this.socket.on('layout-changed', (data) => {
3527
3658
  console.log('[SSHIFT] Layout changed by another client:', data.layoutId);
3659
+ // Always store server layout even on mobile (for preservation in saves)
3660
+ this._serverLayout = data.layoutId;
3528
3661
  if (this.sticky && !this.isMobile) {
3529
3662
  this.setLayoutFromServer(data.layoutId);
3530
3663
  }
@@ -3563,6 +3696,18 @@ const wheelHandler = (e) => {
3563
3696
  this.isSyncingTabs = true;
3564
3697
 
3565
3698
  try {
3699
+ // Update server panel map and layout for mobile preservation
3700
+ if (data.tabs && Array.isArray(data.tabs)) {
3701
+ data.tabs.forEach(tab => {
3702
+ if (tab.sessionId && tab.panelId) {
3703
+ this._serverPanelMap.set(tab.sessionId, tab.panelId);
3704
+ }
3705
+ });
3706
+ }
3707
+ if (data.layout) {
3708
+ this._serverLayout = data.layout;
3709
+ }
3710
+
3566
3711
  // Apply layout first if it's different
3567
3712
  if (data.layout && data.layout !== this.currentLayout?.id) {
3568
3713
  this.setLayoutFromServer(data.layout, data.tabs);
@@ -5636,41 +5781,57 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
5636
5781
  mobileTabsToggle.classList.remove('flashing');
5637
5782
  }
5638
5783
  } else {
5639
- // Desktop: Update dropdowns per panel (original behavior)
5640
- // If panelId is provided, update only that panel's dropdown
5641
- // Otherwise, update all mobile dropdowns across all panels
5642
- const panels = panelId ? [panelId] : this.getAllPanels();
5643
-
5644
- panels.forEach(pid => {
5784
+ // Desktop multi-panel: Each panel's dropdown shows ALL tabs with panel indicators
5785
+ const allPanels = this.getAllPanels();
5786
+ const isSingleLayout = allPanels.length <= 1;
5787
+ const panelsToUpdate = panelId ? [panelId] : allPanels;
5788
+ const allTabsByPanel = {};
5789
+ allPanels.forEach(pid => {
5790
+ const tabsContainer = this.getTabsContainer(pid);
5791
+ allTabsByPanel[pid] = tabsContainer ? Array.from(tabsContainer.children) : [];
5792
+ });
5793
+ const allPanelTabs = [];
5794
+ const clockwisePanels = isSingleLayout ? allPanels : this.getClockwisePanels();
5795
+ clockwisePanels.forEach(pid => {
5796
+ allPanelTabs.push(...(allTabsByPanel[pid] || []).map(tab => ({
5797
+ sessionId: tab.dataset.sessionId,
5798
+ panelId: pid,
5799
+ tabElement: tab
5800
+ })));
5801
+ });
5802
+
5803
+ panelsToUpdate.forEach(pid => {
5645
5804
  const mobileTabsLabel = document.getElementById(pid === 'panel-0' ? 'mobileTabsLabel' : `${pid}-mobileTabsLabel`);
5646
5805
  const mobileTabsMenu = document.getElementById(pid === 'panel-0' ? 'mobileTabsMenu' : `${pid}-mobileTabsMenu`);
5647
5806
  const mobileTabsToggle = document.getElementById(pid === 'panel-0' ? 'mobileTabsToggle' : `${pid}-mobileTabsToggle`);
5648
5807
 
5649
5808
  if (!mobileTabsLabel || !mobileTabsMenu || !mobileTabsToggle) return;
5650
5809
 
5651
- // Get tabs for this panel
5652
- const tabsContainer = this.getTabsContainer(pid);
5653
- const tabs = tabsContainer ? Array.from(tabsContainer.children) : [];
5810
+ // For single layout, only show this panel's tabs; for multi-panel, show all tabs
5811
+ const tabsToShow = isSingleLayout
5812
+ ? (allTabsByPanel[pid] || []).map(tab => ({
5813
+ sessionId: tab.dataset.sessionId,
5814
+ panelId: pid,
5815
+ tabElement: tab
5816
+ }))
5817
+ : allPanelTabs;
5654
5818
 
5655
- // Clear existing menu
5656
5819
  mobileTabsMenu.innerHTML = '';
5657
5820
 
5658
- // Find active tab
5659
5821
  let activeTabName = 'No Active Tabs';
5660
5822
  let activeTabIcon = 'fa-terminal';
5661
5823
 
5662
- // Add menu options for each tab
5663
- tabs.forEach(tab => {
5664
- const sessionId = tab.dataset.sessionId;
5824
+ tabsToShow.forEach(({ sessionId, panelId: tabPanelId }) => {
5665
5825
  const session = this.sessions.get(sessionId) || this.sftpSessions.get(sessionId);
5666
- const isActive = tab.classList.contains('active');
5826
+ const isActiveInPanel = this.activeSessionsByPanel.get(pid) === sessionId;
5827
+ const isActive = this.activeSessionsByPanel.get(tabPanelId) === sessionId;
5667
5828
 
5668
5829
  if (session) {
5669
5830
  const icon = session.type === 'sftp' ? 'fa-folder-open' : 'fa-terminal';
5670
5831
  const iconClass = session.type === 'sftp' ? 'sftp' : 'ssh';
5671
5832
  const name = session.name || sessionId;
5672
5833
 
5673
- if (isActive) {
5834
+ if (isActiveInPanel) {
5674
5835
  activeTabName = name;
5675
5836
  activeTabIcon = icon;
5676
5837
  }
@@ -5681,9 +5842,13 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
5681
5842
  if (this._flashingSessions && this._flashingSessions.has(sessionId)) {
5682
5843
  option.classList.add('flashing');
5683
5844
  }
5845
+ const panelIndicator = !isSingleLayout && tabPanelId !== pid
5846
+ ? `<span class="tab-panel-badge">${tabPanelId.replace('panel-', '')}</span>`
5847
+ : '';
5684
5848
  option.innerHTML = `
5685
5849
  <i class="fas ${icon} tab-icon ${iconClass}"></i>
5686
5850
  <span class="tab-name">${name}</span>
5851
+ ${panelIndicator}
5687
5852
  <button class="tab-rename" data-session-id="${sessionId}" title="Rename">
5688
5853
  <i class="fas fa-pen"></i>
5689
5854
  </button>
@@ -5692,11 +5857,10 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
5692
5857
  </button>
5693
5858
  `;
5694
5859
 
5695
- // Click to switch tab (on the option div, not on the rename/close buttons)
5696
5860
  option.addEventListener('click', (e) => {
5697
5861
  if (!e.target.closest('.tab-rename') && !e.target.closest('.tab-close')) {
5698
- const panelId = this.getPanelForSession(sessionId);
5699
- this.switchTab(sessionId, panelId);
5862
+ const targetPanel = this.getPanelForSession(sessionId);
5863
+ this.switchTab(sessionId, targetPanel);
5700
5864
  mobileTabsMenu.classList.remove('show');
5701
5865
  mobileTabsToggle.classList.remove('active');
5702
5866
  }
@@ -5704,7 +5868,6 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
5704
5868
 
5705
5869
  mobileTabsMenu.appendChild(option);
5706
5870
 
5707
- // Rename button
5708
5871
  const renameBtn = option.querySelector('.tab-rename');
5709
5872
  renameBtn.addEventListener('click', (e) => {
5710
5873
  e.stopPropagation();
@@ -5713,7 +5876,6 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
5713
5876
  mobileTabsToggle.classList.remove('active');
5714
5877
  });
5715
5878
 
5716
- // Close button
5717
5879
  const closeBtn = option.querySelector('.tab-close');
5718
5880
  closeBtn.addEventListener('click', (e) => {
5719
5881
  e.stopPropagation();
@@ -5722,14 +5884,12 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
5722
5884
  }
5723
5885
  });
5724
5886
 
5725
- // Update toggle button
5726
5887
  const iconElement = mobileTabsToggle.querySelector('.tab-icon-active');
5727
5888
  if (iconElement) {
5728
5889
  iconElement.className = `fas ${activeTabIcon} tab-icon-active`;
5729
5890
  }
5730
5891
  mobileTabsLabel.textContent = activeTabName;
5731
5892
 
5732
- // Restore flashing state on toggle if any tab is flashing
5733
5893
  if (mobileTabsToggle) {
5734
5894
  if (this._flashingSessions && this._flashingSessions.size > 0) {
5735
5895
  mobileTabsToggle.classList.add('flashing');
@@ -6717,8 +6877,10 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
6717
6877
  setTimeout(() => this.initTerminal(sessionId, retryCount + 1), 100);
6718
6878
  return;
6719
6879
  } else {
6720
- console.error('[SSHIFT] Container failed to become visible after 10 attempts');
6721
- this.showToast('Failed to initialize terminal - container not visible', 'error');
6880
+ console.error('[SSHIFT] Container failed to become visible after 10 attempts, retrying...');
6881
+ // Don't show a toast — the terminal will initialize on the next resize
6882
+ // or when the tab becomes active. Showing a toast is disruptive and confusing.
6883
+ setTimeout(() => this.initTerminal(sessionId, 0), 500);
6722
6884
  return;
6723
6885
  }
6724
6886
  }
@@ -8235,6 +8397,19 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8235
8397
  }
8236
8398
 
8237
8399
  switchTab(sessionId, panelId = null) {
8400
+ // During sync, skip switchTab calls — we'll activate the correct tab at the end.
8401
+ // But we still need to ensure the terminal wrapper is visible for initTerminal,
8402
+ // so we temporarily show the wrapper without updating active state.
8403
+ if (this._suppressTabSwitch) {
8404
+ const targetPanelId = panelId || this.getPanelForSession(sessionId);
8405
+ const wrapperId = `terminal-wrapper-${sessionId}`;
8406
+ const wrapper = document.getElementById(wrapperId);
8407
+ if (wrapper) {
8408
+ wrapper.classList.add('active');
8409
+ }
8410
+ return;
8411
+ }
8412
+
8238
8413
  console.log('[SSHIFT] switchTab called for session:', sessionId, 'panel:', panelId);
8239
8414
 
8240
8415
  // Stop any active flash on this tab since user is viewing it
@@ -8351,6 +8526,9 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8351
8526
 
8352
8527
  // Get the panel this session belongs to before removing it
8353
8528
  const panelId = this.getPanelForSession(sessionId);
8529
+
8530
+ // Clean up server panel map
8531
+ this._serverPanelMap.delete(sessionId);
8354
8532
 
8355
8533
  // Notify server that this tab is closing (for cross-client sync)
8356
8534
  this.socket.emit('tab-close', { sessionId });
@@ -8467,6 +8645,9 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8467
8645
  if (!session) return;
8468
8646
 
8469
8647
  console.log('[SSHIFT] Removing tab locally:', sessionId);
8648
+
8649
+ // Clean up server panel map
8650
+ this._serverPanelMap.delete(sessionId);
8470
8651
 
8471
8652
  const panelId = this.getPanelForSession(sessionId);
8472
8653
 
@@ -8538,7 +8719,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8538
8719
  }
8539
8720
 
8540
8721
  // Handle tab opened by another client
8541
- handleTabOpened(data) {
8722
+ handleTabOpened(data) {
8542
8723
  // Check if we already have this session
8543
8724
  if (this.sessions.has(data.sessionId) || this.sftpSessions.has(data.sessionId)) {
8544
8725
  console.log('[SSHIFT] Already have session:', data.sessionId);
@@ -8547,6 +8728,20 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8547
8728
 
8548
8729
  console.log('[SSHIFT] Creating tab for session from another client:', data.sessionId);
8549
8730
 
8731
+ // Store server panel assignment for mobile preservation
8732
+ if (data.panelId) {
8733
+ this._serverPanelMap.set(data.sessionId, data.panelId);
8734
+ }
8735
+
8736
+ // Create the tab without connecting (we'll join the existing session)
8737
+ if (data.type === 'ssh') {
8738
+ this.createSSHTab(data.name, data.connectionData, data.sessionId);
8739
+ } else if (data.type === 'sftp') {
8740
+ this.createSFTPTab(data.name, data.connectionData, data.sessionId);
8741
+ }
8742
+
8743
+ console.log('[SSHIFT] Creating tab for session from another client:', data.sessionId);
8744
+
8550
8745
  // Create the tab without connecting (we'll join the existing session)
8551
8746
  if (data.type === 'ssh') {
8552
8747
  this.createSSHTab(data.name, data.connectionData, data.sessionId);
@@ -8637,7 +8832,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8637
8832
  }
8638
8833
 
8639
8834
  // Sync tabs from server (called on connect when sticky is enabled)
8640
- async syncTabsFromServer(tabs, isInitialSync = false) {
8835
+ async syncTabsFromServer(tabs, isInitialSync = false, activeTabsByPanel = null) {
8641
8836
  // Wait for any in-progress restoration to complete before syncing
8642
8837
  // This prevents the race condition where restoreTabs starts first,
8643
8838
  // sets isRestoring=true, and then this function returns early, missing
@@ -8651,6 +8846,14 @@ async syncTabsFromServer(tabs, isInitialSync = false) {
8651
8846
  console.log('[SSHIFT] Syncing tabs from server:', tabs.length, 'isInitialSync:', isInitialSync);
8652
8847
  this.isRestoring = true;
8653
8848
 
8849
+ // Store server panel assignments and layout for mobile preservation
8850
+ tabs.forEach(tab => {
8851
+ this._serverPanelMap.set(tab.sessionId, tab.panelId || 'panel-0');
8852
+ });
8853
+
8854
+ // Suppress switchTab during creation so we can activate the correct tab at the end
8855
+ this._suppressTabSwitch = true;
8856
+
8654
8857
  // On initial sync, remove any client-side tabs that don't exist on the server.
8655
8858
  // This ensures the server is the single source of truth and prevents duplicates
8656
8859
  // from stale localStorage caches (e.g. when switching between devices).
@@ -8669,6 +8872,19 @@ async syncTabsFromServer(tabs, isInitialSync = false) {
8669
8872
  }
8670
8873
  }
8671
8874
 
8875
+ // Merge credentials from localStorage into server tab data.
8876
+ // The server strips password/privateKey from open-tabs for security,
8877
+ // but we need them locally for auto-reconnection if ssh-join fails
8878
+ // (e.g. server restarted while sessions were active).
8879
+ const localTabsData = this.loadTabs();
8880
+ const localTabs = Array.isArray(localTabsData) ? localTabsData : (localTabsData?.tabs || []);
8881
+ const localTabsBySessionId = new Map();
8882
+ for (const lt of localTabs) {
8883
+ if (lt.sessionId && lt.connectionData) {
8884
+ localTabsBySessionId.set(lt.sessionId, lt.connectionData);
8885
+ }
8886
+ }
8887
+
8672
8888
  for (const tab of tabs) {
8673
8889
  // Check if we already have this session
8674
8890
  if (this.sessions.has(tab.sessionId) || this.sftpSessions.has(tab.sessionId)) {
@@ -8676,6 +8892,12 @@ async syncTabsFromServer(tabs, isInitialSync = false) {
8676
8892
  continue;
8677
8893
  }
8678
8894
 
8895
+ // Merge saved credentials into the server's stripped connectionData
8896
+ const localConnData = localTabsBySessionId.get(tab.sessionId);
8897
+ if (localConnData && (localConnData.password || localConnData.privateKey)) {
8898
+ tab.connectionData = { ...tab.connectionData, ...localConnData };
8899
+ }
8900
+
8679
8901
  console.log('[SSHIFT] Creating tab from server sync:', tab.name, tab.type);
8680
8902
 
8681
8903
  // Create the tab and join the existing session
@@ -8698,13 +8920,35 @@ async syncTabsFromServer(tabs, isInitialSync = false) {
8698
8920
  this.distributeTabsToPanels(tabs);
8699
8921
  }
8700
8922
 
8701
- // Update mobile tabs dropdown after syncing
8702
- this.updateMobileTabsDropdown();
8703
-
8704
8923
  // Apply any flash states that arrived before DOM elements existed
8705
8924
  this.applyFlashStates();
8706
8925
 
8707
8926
  this.isRestoring = false;
8927
+ this._suppressTabSwitch = false;
8928
+
8929
+ // Activate the correct tab per panel based on server state
8930
+ if (activeTabsByPanel && !this.isMobile) {
8931
+ for (const [panelId, sessionId] of Object.entries(activeTabsByPanel)) {
8932
+ if (this.sessions.has(sessionId) || this.sftpSessions.has(sessionId)) {
8933
+ this.switchTab(sessionId, panelId);
8934
+ }
8935
+ }
8936
+ } else if (activeTabsByPanel) {
8937
+ // Mobile: use the first active tab from any panel
8938
+ const firstActive = Object.values(activeTabsByPanel).find(id => this.sessions.has(id) || this.sftpSessions.has(id));
8939
+ if (firstActive) {
8940
+ this.switchTab(firstActive);
8941
+ }
8942
+ } else if (tabs.length > 0) {
8943
+ // No active tab info from server — default to first tab
8944
+ const firstTab = tabs[0];
8945
+ if (this.sessions.has(firstTab.sessionId) || this.sftpSessions.has(firstTab.sessionId)) {
8946
+ this.switchTab(firstTab.sessionId, firstTab.panelId);
8947
+ }
8948
+ }
8949
+
8950
+ // Update mobile tabs dropdown after activating the correct tab
8951
+ this.updateMobileTabsDropdown();
8708
8952
 
8709
8953
  // Save the final tab state to localStorage after sync completes
8710
8954
  this.saveTabs();