@lethevimlet/sshift 1.7.4 → 1.7.6

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.
@@ -38,7 +38,6 @@ class SSHIFTClient {
38
38
  this.isRestoring = false; // Flag to prevent saving during restoration
39
39
  this.isSyncingTabs = false; // Flag to prevent saveTabs emission during tabs-sync
40
40
  this._serverPanelMap = new Map(); // sessionId -> panelId from server (preserved for mobile)
41
- this._serverLayout = null; // Layout from server (preserved for mobile saves)
42
41
  this._initialSyncDone = false; // Whether initial open-tabs sync from server has completed
43
42
  this._serverSyncTimeout = null; // Timeout for fallback to localStorage restore
44
43
  // saveTabs dedup/debounce state — prevents redundant localStorage writes
@@ -93,8 +92,7 @@ class SSHIFTClient {
93
92
 
94
93
  // Layout system
95
94
  this.layouts = null; // Will be loaded from config/layouts.json
96
- this.currentLayout = null; // Current active layout
97
- this.pendingLayoutSync = null; // Queue for layout sync before layouts are loaded
95
+ this.currentLayout = null; // Current active layout (per-device, localStorage)
98
96
 
99
97
  console.log('[SSHIFT] Mobile detection - isMobile:', this.isMobile, 'window width:', window.innerWidth);
100
98
 
@@ -488,9 +486,11 @@ class SSHIFTClient {
488
486
  });
489
487
  });
490
488
 
491
- // Save tabs with current layout (mobile saves server layout, not 'single')
489
+ // Save tabs with this device's layout. The layout field is kept for
490
+ // payload compatibility (the server relays it in tabs-sync) but no
491
+ // client applies it — layout is a per-device localStorage preference.
492
492
  const savedLayout = this.isMobile
493
- ? (this._serverLayout || 'single')
493
+ ? 'single'
494
494
  : (this.currentLayout?.id || 'single');
495
495
  const tabsData = {
496
496
  tabs,
@@ -1190,8 +1190,16 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1190
1190
  if (session.terminal && !session.webglAddon && (session.webglContextLossCount || 0) < 3) {
1191
1191
  console.log('[SSHIFT] Attempting WebGL addon recreation after context loss');
1192
1192
  this._initWebGLAddon(session, false);
1193
- if (session.fitAddon && !document.hidden) {
1194
- try { session.fitAddon.fit(); } catch (_) {}
1193
+ if (!document.hidden) {
1194
+ // Guarded refit — see _refreshAllWebGLSessions for why a bare
1195
+ // fitAddon.fit() on a hidden container is destructive.
1196
+ this._fitTerminal(session);
1197
+ } else {
1198
+ // Refit as soon as the tab becomes visible again — the
1199
+ // freshly recreated renderer would otherwise paint at the
1200
+ // pre-loss cell pitch (interlace artefact) until a manual
1201
+ // resize. The visibilitychange handler consumes this flag.
1202
+ session.needsResize = true;
1195
1203
  }
1196
1204
  // After context loss the local terminal's rasterised
1197
1205
  // cells may have been cleared; reconcile with the
@@ -1245,9 +1253,9 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1245
1253
  } else {
1246
1254
  try { webglAddon.clearTextureAtlas(); } catch (_) {}
1247
1255
  session.terminal.refresh(0, session.terminal.rows - 1);
1248
- if (session.fitAddon) {
1249
- try { session.fitAddon.fit(); } catch (_) {}
1250
- }
1256
+ // Guarded refit — a bare fitAddon.fit() here would resize a hidden
1257
+ // session to 10x5 (see _refreshAllWebGLSessions).
1258
+ this._fitTerminal(session);
1251
1259
  }
1252
1260
 
1253
1261
  return true;
@@ -1272,13 +1280,23 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1272
1280
  const refresh = (session) => {
1273
1281
  if (!session || !session.terminal || !this.webglRenderer) return;
1274
1282
  if (session.webglAddon) {
1275
- try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
1276
- session.terminal.refresh(0, session.terminal.rows - 1);
1283
+ // Use the full recompute (the exact path a real window resize
1284
+ // triggers), not just an atlas clear: while the tab was hidden
1285
+ // the renderer's device cell pitch can go stale, and repainting
1286
+ // at a stale pitch faithfully reproduces the interlace "black
1287
+ // band" artefact. measure() + handleResize + atlas rebuild +
1288
+ // refresh heals both stale glyphs AND pitch mismatches.
1289
+ this._forceRendererDimensionRecompute(session);
1277
1290
  } else if ((session.webglContextLossCount || 0) < 3 && typeof window.WebglAddon === 'function') {
1278
1291
  this._initWebGLAddon(session, false);
1279
- if (session.fitAddon) {
1280
- try { session.fitAddon.fit(); } catch (_) {}
1281
- }
1292
+ // Refit through _fitTerminal, never fitAddon.fit() directly: a raw
1293
+ // fit() on a session whose wrapper is hidden reads the *computed*
1294
+ // (not used) style of the container, so `height: 100%` parses as
1295
+ // 100px and the terminal is resized to a bogus 10x5 — which the
1296
+ // controller then pushes to the remote PTY, wrecking whatever is
1297
+ // running in that background tab. _fitTerminal refuses to fit a
1298
+ // hidden or not-yet-laid-out container.
1299
+ this._fitTerminal(session);
1282
1300
  }
1283
1301
  };
1284
1302
  this.sessions.forEach(refresh);
@@ -1333,6 +1351,14 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1333
1351
  _fitTerminal(session, retryCount = 0) {
1334
1352
  if (!session || !session.fitAddon || !session.terminal) return false;
1335
1353
 
1354
+ // Non-controllers must mirror the server's dimensions (they receive them
1355
+ // via ssh-resize-sync); fitting them to the local container makes the
1356
+ // shared session diverge and can start a resize war between clients.
1357
+ if (session.isController === false) {
1358
+ session.needsResize = true;
1359
+ return false;
1360
+ }
1361
+
1336
1362
  const wrapper = document.getElementById(`terminal-wrapper-${session.id}`);
1337
1363
  const container = document.getElementById(`terminal-${session.id}`);
1338
1364
  if (!wrapper || !container) return false;
@@ -1407,9 +1433,44 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1407
1433
  // bottom-row garbage and garbled status lines after resize.
1408
1434
  this._forceRendererDimensionRecompute(session);
1409
1435
 
1436
+ // Make sure the remote PTY actually learns about this size. See
1437
+ // syncRemoteTerminalSize — xterm only fires onResize when cols/rows
1438
+ // change, so a fit that lands back on the dimensions the client already
1439
+ // had never notifies the server, even when the server is still on the
1440
+ // size it was given for the previous layout.
1441
+ this.syncRemoteTerminalSize(session);
1442
+
1410
1443
  return true;
1411
1444
  }
1412
1445
 
1446
+ // Push the terminal's current dimensions to the remote PTY when the server
1447
+ // is not already known to be at that size.
1448
+ //
1449
+ // The only automatic notification path is xterm's onResize event, which
1450
+ // fires ONLY when cols/rows actually change. That is not enough:
1451
+ // - a refit after a layout change can land on the same cols/rows the
1452
+ // client already had while the server is still sized for the previous
1453
+ // layout (nothing is emitted, the remote program keeps its old shape);
1454
+ // - the onResize emit is debounced and can be lost if another resize
1455
+ // event cancels the timer before it fires.
1456
+ // `remoteCols`/`remoteRows` track the last size the server is known to
1457
+ // have, so this is a no-op in the common case and cheap when it is not.
1458
+ syncRemoteTerminalSize(session) {
1459
+ if (!session || !session.terminal || !session.connected) return;
1460
+ if (!session.isController || session.isResyncing) return;
1461
+ if (!this.socket || !this.socket.connected) return;
1462
+
1463
+ const cols = session.terminal.cols;
1464
+ const rows = session.terminal.rows;
1465
+ if (!cols || !rows) return;
1466
+ if (session.remoteCols === cols && session.remoteRows === rows) return;
1467
+
1468
+ session.remoteCols = cols;
1469
+ session.remoteRows = rows;
1470
+ this.socket.emit('ssh-resize', { sessionId: session.id, cols, rows });
1471
+ console.log('[SSHIFT] Synced remote PTY size for', session.id, `${cols}x${rows}`);
1472
+ }
1473
+
1413
1474
  forceResizeTerminal(sessionId) {
1414
1475
  if (!sessionId) return;
1415
1476
  const session = this.sessions.get(sessionId) || this.sftpSessions.get(sessionId);
@@ -1471,6 +1532,19 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1471
1532
  void container.offsetWidth;
1472
1533
  void container.offsetHeight;
1473
1534
 
1535
+ // Same guard as _fitTerminal: a hidden pane reports its percentage CSS
1536
+ // verbatim ("100%" → 100px) and a fit against it produces a ~10x5
1537
+ // terminal that would be pushed straight to the remote PTY.
1538
+ if (!wrapper.classList.contains('active')) {
1539
+ session.needsResize = true;
1540
+ return false;
1541
+ }
1542
+ const rect = container.getBoundingClientRect();
1543
+ if (rect.width < 50 || rect.height < 50) {
1544
+ session.needsResize = true;
1545
+ return false;
1546
+ }
1547
+
1474
1548
  // (b) Commit the renderer's cell metrics before fit reads them.
1475
1549
  this._syncCharSizeThenClearAtlas(session);
1476
1550
 
@@ -1509,6 +1583,8 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1509
1583
  }
1510
1584
  // Emit synchronously (we already debounced upstream by only calling
1511
1585
  // this on discrete events: take-control / panel grab settlement).
1586
+ session.remoteCols = cols;
1587
+ session.remoteRows = rows;
1512
1588
  this.socket.emit('ssh-resize', { sessionId: sid, cols, rows });
1513
1589
  } catch (_) {}
1514
1590
  }
@@ -1737,12 +1813,11 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1737
1813
 
1738
1814
  // Update all terminal themes
1739
1815
  this.updateTerminalThemes(newTheme);
1740
-
1741
- // Sync theme to server for cross-device sync
1742
- if (this.socket && this.socket.connected) {
1743
- this.socket.emit('theme-change', { theme: newTheme });
1744
- }
1745
-
1816
+
1817
+ // Theme is a PER-DEVICE preference (localStorage only) — it is no
1818
+ // longer synced through the server, so it survives server restarts
1819
+ // and can differ between devices/browsers.
1820
+
1746
1821
  // Fade out the wave
1747
1822
  wave.classList.add('fade-out');
1748
1823
 
@@ -1981,10 +2056,8 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1981
2056
  console.warn('[SSHIFT] Failed to re-apply terminal themes after accent change:', e.message);
1982
2057
  }
1983
2058
 
1984
- // Sync accent to server for cross-device sync
1985
- if (this.socket && this.socket.connected) {
1986
- this.socket.emit('accent-change', { accent: accent });
1987
- }
2059
+ // Accent is a PER-DEVICE preference (localStorage only) — no longer
2060
+ // synced through the server.
1988
2061
  }
1989
2062
 
1990
2063
  updateAccentPreview(accent) {
@@ -2148,46 +2221,27 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2148
2221
  console.log('[SSHIFT] Setting layout:', layoutId);
2149
2222
  this.saveCurrentLayout(layoutId);
2150
2223
  this.updateLayoutActiveState(layoutId);
2151
-
2224
+
2152
2225
  // Find the layout definition
2153
2226
  const layout = this.layouts?.find(l => l.id === layoutId);
2154
2227
  if (layout) {
2155
- // Emit event for layout change (to be implemented later)
2228
+ // Apply the layout locally
2156
2229
  this.onLayoutChange(layout);
2157
2230
  }
2158
-
2159
- // Sync layout to server for cross-tab sync
2160
- if (this.sticky && this.socket) {
2161
- this.socket.emit('layout-change', { layoutId });
2162
- }
2163
- }
2164
2231
 
2165
- setLayoutFromServer(layoutId, syncedTabs = null) {
2166
- console.log('[SSHIFT] Setting layout from server:', layoutId);
2167
-
2168
- // If layouts aren't loaded yet, queue this for later
2169
- if (!this.layouts) {
2170
- console.log('[SSHIFT] Layouts not loaded yet, queuing layout sync for:', layoutId);
2171
- this.pendingLayoutSync = layoutId;
2172
- this.pendingLayoutTabs = syncedTabs;
2173
- return;
2174
- }
2175
-
2176
- // Don't sync back to server (avoid loop)
2177
- this.saveCurrentLayout(layoutId);
2178
- this.updateLayoutActiveState(layoutId);
2179
-
2180
- // Find the layout definition
2181
- const layout = this.layouts.find(l => l.id === layoutId);
2182
- if (layout) {
2183
- this.currentLayout = layout;
2184
- // Pass syncedTabs to applyLayout which will handle distribution
2185
- this.applyLayout(layout, syncedTabs);
2186
-
2187
- setTimeout(() => this.handleResize(), 50);
2188
- }
2232
+ // Layout preference is PER-DEVICE (localStorage only, survives server
2233
+ // restarts, can differ between devices). Panel ASSIGNMENTS of tabs are
2234
+ // still synced via saveTabs/tabs-sync; each device maps them into its
2235
+ // own layout (tabs assigned to panels that don't exist locally fall
2236
+ // back to the first panel — see distributeTabsToPanels).
2189
2237
  }
2190
2238
 
2239
+ // setLayoutFromServer was removed: layout is now a per-device preference
2240
+ // (localStorage only). Each device applies its own saved layout at
2241
+ // startup (initLayoutSystem) and maps synced tab panel assignments into
2242
+ // its local panels — panels that don't exist locally fall back to the
2243
+ // first panel (distributeTabsToPanels).
2244
+
2191
2245
  updateLayoutActiveState(layoutId) {
2192
2246
  document.querySelectorAll('.layout-option').forEach(option => {
2193
2247
  option.classList.toggle('active', option.dataset.layoutId === layoutId);
@@ -3208,15 +3262,6 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3208
3262
  // Load layouts
3209
3263
  this.layouts = await this.loadLayouts();
3210
3264
 
3211
- // Apply any pending layout sync that arrived before layouts were loaded
3212
- if (this.pendingLayoutSync) {
3213
- console.log('[SSHIFT] Applying pending layout sync:', this.pendingLayoutSync);
3214
- const pendingLayoutId = this.pendingLayoutSync;
3215
- this.pendingLayoutSync = null;
3216
- this.setLayoutFromServer(pendingLayoutId);
3217
- return; // setLayoutFromServer handles everything
3218
- }
3219
-
3220
3265
  // Get saved layout or default to 'single'
3221
3266
  const savedLayoutId = this.loadCurrentLayout();
3222
3267
  const layout = this.layouts.find(l => l.id === savedLayoutId) || this.layouts[0];
@@ -3368,29 +3413,20 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3368
3413
  this._pendingOpenTabs = null;
3369
3414
  this._pendingOpenTabsIsInitial = null;
3370
3415
 
3371
- // Store server layout for mobile preservation
3372
- if (pendingData.layout) {
3373
- this._serverLayout = pendingData.layout;
3374
- }
3375
-
3376
3416
  // Prevent saveTabs from emitting to server during deferred sync
3377
3417
  const wasSyncingTabs = this.isSyncingTabs;
3378
3418
  this.isSyncingTabs = true;
3379
3419
 
3380
3420
  try {
3381
3421
  if (pendingData.tabs.length > 0) {
3382
- // Sync layout BEFORE tabs so panels exist before distribution
3383
- if (pendingData.layout && !this.isMobile) {
3384
- this.setLayoutFromServer(pendingData.layout);
3385
- }
3422
+ // The local layout (per-device, applied by initLayoutSystem)
3423
+ // already created the panels — just distribute the synced tabs
3424
+ // into them.
3386
3425
  this.syncTabsFromServer(pendingData.tabs, isInitialSync, pendingData.activeTabsByPanel);
3387
3426
  } else {
3388
3427
  // Server has no tabs (e.g. right after restart). Treat it as a
3389
3428
  // fresh slate: clear stale localStorage and DO NOT resurrect
3390
3429
  // those sessions — they're gone on the server.
3391
- if (pendingData.layout && !this.isMobile) {
3392
- this.setLayoutFromServer(pendingData.layout);
3393
- }
3394
3430
  try { this.clearTabs(); } catch (_) {}
3395
3431
  }
3396
3432
  } finally {
@@ -3423,9 +3459,22 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3423
3459
  resizeTimeout = setTimeout(setViewportHeight, 100);
3424
3460
  });
3425
3461
 
3426
- // Update when virtual keyboard opens/closes on mobile
3462
+ // Update when virtual keyboard opens/closes on mobile.
3463
+ // visualViewport resize fires continuously on Android while the
3464
+ // browser chrome hides/shows during scroll and during keyboard
3465
+ // animations; writing --vh/--vvh on <html> invalidates every
3466
+ // calc(var(--vh)*…) consumer → full-page relayout. Coalesce to one
3467
+ // write per frame.
3427
3468
  if (window.visualViewport) {
3428
- window.visualViewport.addEventListener('resize', setViewportHeight);
3469
+ let vvhRAF = null;
3470
+ const setViewportHeightCoalesced = () => {
3471
+ if (vvhRAF) return;
3472
+ vvhRAF = requestAnimationFrame(() => {
3473
+ vvhRAF = null;
3474
+ setViewportHeight();
3475
+ });
3476
+ };
3477
+ window.visualViewport.addEventListener('resize', setViewportHeightCoalesced);
3429
3478
  }
3430
3479
 
3431
3480
  // Update mobile detection on resize and re-apply layout if needed
@@ -3485,12 +3534,115 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3485
3534
 
3486
3535
  console.log(`[SSHIFT] Setting up touch scroll handlers on ${elementName}`);
3487
3536
 
3537
+ // Apply the accumulated touch delta to the terminal. Shared by the
3538
+ // per-frame coalesced gesture scroll and the fling momentum loop.
3539
+ // Coalescing matters: touchmove fires faster than frames on 90/120Hz
3540
+ // phones, and terminal.scrollLines() is a synchronous buffer scroll +
3541
+ // repaint — running it several times per frame was the single
3542
+ // biggest source of scroll jank on mobile.
3543
+ const applyScrollDelta = () => {
3544
+ if (Math.abs(session.touchAccumulator) < 0.5) return;
3545
+
3546
+ const lineHeight = terminal._core?._renderService?.dimensions?.css?.cell?.height || 20;
3547
+ const lineH = Math.max(lineHeight, 14);
3548
+
3549
+ // When a TUI app has mouse tracking enabled (DECSET
3550
+ // 1000/1002/1003), scrolling should send mouse wheel
3551
+ // escape sequences directly to the PTY. Instead of
3552
+ // dispatching synthetic WheelEvents (which xterm's own
3553
+ // document-level touch handler can interfere with), we
3554
+ // generate the SGR mouse format ourselves and emit it via
3555
+ // ssh-data. SGR format: \x1b[<button;col;row;M
3556
+ // Wheel up = button 64, wheel down = button 65.
3557
+ const mouseProtocol = terminal._core?.coreMouseService?.activeProtocol;
3558
+ const tuiMouseActive = mouseProtocol && mouseProtocol !== 'NONE';
3559
+
3560
+ if (tuiMouseActive) {
3561
+ if (Math.abs(session.touchAccumulator) >= lineH) {
3562
+ // Compute the terminal cell under the touch point.
3563
+ const screenEl = terminal.element?.querySelector('.xterm-screen');
3564
+ if (screenEl) {
3565
+ const rect = screenEl.getBoundingClientRect();
3566
+ const cellW = terminal._core?._renderService?.dimensions?.css?.cell?.width || 8;
3567
+ const cellH = lineHeight;
3568
+ const touchX = session.lastTouchX - rect.left;
3569
+ const touchY = session.lastTouchY - rect.top;
3570
+ const col = Math.max(1, Math.min(terminal.cols, Math.floor(touchX / cellW) + 1));
3571
+ const row = Math.max(1, Math.min(terminal.rows, Math.floor(touchY / cellH) + 1));
3572
+
3573
+ const scrollLines = Math.trunc(Math.abs(session.touchAccumulator) / lineH);
3574
+ const direction = session.touchAccumulator > 0 ? 1 : -1; // 1 = scroll down, -1 = scroll up
3575
+ for (let i = 0; i < scrollLines; i++) {
3576
+ // button 64 = wheel up, 65 = wheel down
3577
+ const button = direction > 0 ? 65 : 64;
3578
+ const seq = `\x1b[<${button};${col};${row}M`;
3579
+ if (session.connected && session.isController) {
3580
+ this.socket.emit('ssh-data', { sessionId, data: seq });
3581
+ }
3582
+ }
3583
+ session.touchAccumulator = 0;
3584
+ }
3585
+ }
3586
+ } else {
3587
+ const linesToScroll = Math.trunc(Math.abs(session.touchAccumulator) / lineH);
3588
+ if (linesToScroll > 0) {
3589
+ const direction = session.touchAccumulator > 0 ? 1 : -1;
3590
+ terminal.scrollLines(direction * linesToScroll);
3591
+ session.touchAccumulator -= direction * linesToScroll * lineH;
3592
+ }
3593
+ }
3594
+ };
3595
+
3596
+ // Coalesced per-frame application of the touch delta.
3597
+ const scheduleScrollApply = () => {
3598
+ if (session.scrollApplyRAF) return;
3599
+ session.scrollApplyRAF = requestAnimationFrame(() => {
3600
+ session.scrollApplyRAF = null;
3601
+ applyScrollDelta();
3602
+ });
3603
+ };
3604
+
3605
+ // Fling momentum: after a fast swipe, keep scrolling with an
3606
+ // exponentially decaying velocity (the native-feeling "glide" that
3607
+ // was missing — content used to halt instantly on finger lift).
3608
+ // Gated: never in TUI mouse mode (wheel-mouse emulation should not
3609
+ // synthesize fling events) and cancelled by any new touch.
3610
+ const startMomentum = () => {
3611
+ const step = () => {
3612
+ session.momentumRAF = null;
3613
+ const mouseProtocol = terminal._core?.coreMouseService?.activeProtocol;
3614
+ if (mouseProtocol && mouseProtocol !== 'NONE') return;
3615
+ session.scrollVelocity *= 0.94;
3616
+ if (Math.abs(session.scrollVelocity) < 0.8) {
3617
+ session.scrollVelocity = 0;
3618
+ return;
3619
+ }
3620
+ session.touchAccumulator += session.scrollVelocity;
3621
+ applyScrollDelta();
3622
+ session.momentumRAF = requestAnimationFrame(step);
3623
+ };
3624
+ if (session.momentumRAF) cancelAnimationFrame(session.momentumRAF);
3625
+ session.momentumRAF = requestAnimationFrame(step);
3626
+ };
3627
+
3628
+ const cancelMomentum = () => {
3629
+ if (session.momentumRAF) {
3630
+ cancelAnimationFrame(session.momentumRAF);
3631
+ session.momentumRAF = null;
3632
+ }
3633
+ session.scrollVelocity = 0;
3634
+ };
3635
+
3488
3636
  element.addEventListener('touchstart', (e) => {
3489
3637
  if (e.touches.length === 1) {
3638
+ cancelMomentum();
3490
3639
  session.lastTouchY = e.touches[0].clientY;
3640
+ session.lastTouchX = e.touches[0].clientX;
3491
3641
  session.isScrolling = true;
3492
3642
  session.touchAccumulator = 0;
3643
+ session.scrollVelocity = 0;
3493
3644
  } else if (e.touches.length === 2) {
3645
+ cancelMomentum();
3494
3646
  session.isPinching = true;
3495
3647
  session.isScrolling = false;
3496
3648
  session.initialPinchDistance = this.getPinchDistance(e.touches[0], e.touches[1]);
@@ -3505,56 +3657,14 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3505
3657
  const currentTouchY = e.touches[0].clientY;
3506
3658
  const touchDiff = session.lastTouchY - currentTouchY;
3507
3659
  session.lastTouchY = currentTouchY;
3660
+ session.lastTouchX = e.touches[0].clientX;
3508
3661
  session.touchAccumulator += touchDiff;
3662
+ // Per-event velocity, smoothed; consumed by the fling momentum
3663
+ // loop on touchend. Positive = finger moved up = scroll down.
3664
+ session.scrollVelocity = 0.8 * (session.scrollVelocity || 0) + 0.2 * touchDiff;
3509
3665
 
3510
- const lineHeight = terminal._core?._renderService?.dimensions?.css?.cell?.height || 20;
3511
- const lineH = Math.max(lineHeight, 14);
3512
-
3513
- // When a TUI app has mouse tracking enabled (DECSET
3514
- // 1000/1002/1003), scrolling should send mouse wheel
3515
- // escape sequences directly to the PTY. Instead of
3516
- // dispatching synthetic WheelEvents (which xterm's own
3517
- // document-level touch handler can interfere with), we
3518
- // generate the SGR mouse format ourselves and emit it via
3519
- // ssh-data. SGR format: \x1b[<button;col;row;M
3520
- // Wheel up = button 64, wheel down = button 65.
3521
- const mouseProtocol = terminal._core?.coreMouseService?.activeProtocol;
3522
- const tuiMouseActive = mouseProtocol && mouseProtocol !== 'NONE';
3523
-
3524
- if (tuiMouseActive) {
3525
- if (Math.abs(session.touchAccumulator) >= lineH) {
3526
- // Compute the terminal cell under the touch point.
3527
- const screenEl = terminal.element?.querySelector('.xterm-screen');
3528
- if (screenEl) {
3529
- const rect = screenEl.getBoundingClientRect();
3530
- const cellW = terminal._core?._renderService?.dimensions?.css?.cell?.width || 8;
3531
- const cellH = lineHeight;
3532
- const touchX = e.touches[0].clientX - rect.left;
3533
- const touchY = e.touches[0].clientY - rect.top;
3534
- const col = Math.max(1, Math.min(terminal.cols, Math.floor(touchX / cellW) + 1));
3535
- const row = Math.max(1, Math.min(terminal.rows, Math.floor(touchY / cellH) + 1));
3536
-
3537
- const scrollLines = Math.trunc(Math.abs(session.touchAccumulator) / lineH);
3538
- const direction = session.touchAccumulator > 0 ? 1 : -1; // 1 = scroll down, -1 = scroll up
3539
- for (let i = 0; i < scrollLines; i++) {
3540
- // button 64 = wheel up, 65 = wheel down
3541
- const button = direction > 0 ? 65 : 64;
3542
- const seq = `\x1b[<${button};${col};${row}M`;
3543
- if (session.connected && session.isController) {
3544
- this.socket.emit('ssh-data', { sessionId, data: seq });
3545
- }
3546
- }
3547
- session.touchAccumulator = 0;
3548
- }
3549
- }
3550
- } else {
3551
- const linesToScroll = Math.trunc(Math.abs(session.touchAccumulator) / lineH);
3552
- if (linesToScroll > 0) {
3553
- const direction = session.touchAccumulator > 0 ? 1 : -1;
3554
- terminal.scrollLines(direction * linesToScroll);
3555
- session.touchAccumulator -= direction * linesToScroll * lineH;
3556
- }
3557
- }
3666
+ // Apply once per frame, not once per touchmove event.
3667
+ scheduleScrollApply();
3558
3668
  } else if (e.touches.length === 2 && session.isPinching) {
3559
3669
  e.preventDefault();
3560
3670
 
@@ -3588,7 +3698,24 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3588
3698
  session.isScrolling = false;
3589
3699
  session.initialPinchDistance = 0;
3590
3700
  session.lastPinchDistance = 0;
3701
+
3702
+ // Apply any delta accumulated since the last frame now (the
3703
+ // coalesced RAF may not have run yet), then hand over to the
3704
+ // fling loop if the gesture ended with enough velocity.
3705
+ if (session.scrollApplyRAF) {
3706
+ cancelAnimationFrame(session.scrollApplyRAF);
3707
+ session.scrollApplyRAF = null;
3708
+ }
3709
+ applyScrollDelta();
3591
3710
  session.touchAccumulator = 0;
3711
+
3712
+ const mouseProtocol = terminal._core?.coreMouseService?.activeProtocol;
3713
+ const tuiMouseActive = mouseProtocol && mouseProtocol !== 'NONE';
3714
+ if (!tuiMouseActive && Math.abs(session.scrollVelocity || 0) >= 3) {
3715
+ startMomentum();
3716
+ } else {
3717
+ session.scrollVelocity = 0;
3718
+ }
3592
3719
 
3593
3720
  setTimeout(() => {
3594
3721
  this.checkIfAtBottom(sessionId);
@@ -3598,8 +3725,10 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3598
3725
  session.initialPinchDistance = 0;
3599
3726
  session.lastPinchDistance = 0;
3600
3727
  session.lastTouchY = e.touches[0].clientY;
3728
+ session.lastTouchX = e.touches[0].clientX;
3601
3729
  session.isScrolling = true;
3602
3730
  session.touchAccumulator = 0;
3731
+ session.scrollVelocity = 0;
3603
3732
  }
3604
3733
  }, { passive: true });
3605
3734
  };
@@ -3826,20 +3955,27 @@ const wheelHandler = (e) => {
3826
3955
  const session = this.sessions.get(sessionId);
3827
3956
  if (!session || !session.terminal) return;
3828
3957
 
3958
+ const terminal = session.terminal;
3959
+
3829
3960
  // Only auto-scroll if user is at the bottom
3830
3961
  // This allows users to scroll up and read previous output without being interrupted
3831
3962
  if (!session.isAtBottom) {
3832
- console.log('[SSHIFT] Not auto-scrolling - user has scrolled up');
3833
3963
  return;
3834
3964
  }
3835
-
3836
- const terminal = session.terminal;
3837
-
3965
+
3838
3966
  try {
3967
+ // xterm already pins the viewport to the bottom while writing when
3968
+ // the user is at the bottom — calling scrollToBottom() on every data
3969
+ // frame duplicated that work (plus scroll+render churn) on mobile.
3970
+ // Only scroll when the viewport actually drifted off the bottom.
3971
+ const buffer = terminal.buffer.active;
3972
+ if (buffer.viewportY >= buffer.length - terminal.rows) {
3973
+ return;
3974
+ }
3975
+
3839
3976
  // Use xterm.js scrollToBottom method
3840
3977
  if (typeof terminal.scrollToBottom === 'function') {
3841
3978
  terminal.scrollToBottom();
3842
- console.log('[SSHIFT] Auto-scrolled to bottom');
3843
3979
  }
3844
3980
  } catch (e) {
3845
3981
  console.warn('[SSHIFT] Error scrolling terminal:', e.message);
@@ -4035,7 +4171,21 @@ const wheelHandler = (e) => {
4035
4171
  }
4036
4172
  };
4037
4173
 
4038
- window.visualViewport.addEventListener('resize', updatePosition);
4174
+ // Coalesce both visual-viewport listeners to one update per frame:
4175
+ // on Android these fire continuously during keyboard animations and
4176
+ // browser chrome show/hide; each handler does getComputedStyle calls
4177
+ // and writes inline styles / CSS variables, which force relayouts.
4178
+ let vvRAF = null;
4179
+ const updatePositionCoalesced = () => {
4180
+ if (vvRAF) return;
4181
+ vvRAF = requestAnimationFrame(() => {
4182
+ vvRAF = null;
4183
+ updatePosition();
4184
+ updateHeaderPosition();
4185
+ });
4186
+ };
4187
+
4188
+ window.visualViewport.addEventListener('resize', updatePositionCoalesced);
4039
4189
 
4040
4190
  // Also listen for visual viewport scroll to keep header/tabs pinned
4041
4191
  // Android can scroll the visual viewport when keyboard is open
@@ -4062,7 +4212,7 @@ const wheelHandler = (e) => {
4062
4212
  }
4063
4213
  };
4064
4214
 
4065
- window.visualViewport.addEventListener('scroll', updateHeaderPosition);
4215
+ window.visualViewport.addEventListener('scroll', updatePositionCoalesced);
4066
4216
 
4067
4217
  // Initial update
4068
4218
  updatePosition();
@@ -4374,6 +4524,7 @@ const wheelHandler = (e) => {
4374
4524
  session.syncTimeout = setTimeout(() => {
4375
4525
  console.warn('[SSHIFT] Sync timeout after rejoin for session:', sessionId);
4376
4526
  session.syncing = false;
4527
+ this._drainSyncBuffer(session);
4377
4528
  if (session.connected) {
4378
4529
  this.requestScreenSync(sessionId);
4379
4530
  }
@@ -4463,45 +4614,17 @@ const wheelHandler = (e) => {
4463
4614
  clearTimeout(this._serverSyncTimeout);
4464
4615
  this._serverSyncTimeout = null;
4465
4616
  }
4466
-
4467
- // Sync theme and accent from server
4468
- if (data.theme) {
4469
- const savedTheme = this.loadTheme();
4470
- if (savedTheme !== data.theme) {
4471
- console.log('[SSHIFT] Syncing theme from server:', data.theme);
4472
- document.documentElement.setAttribute('data-theme', data.theme);
4473
- this.theme = data.theme;
4474
- this.saveTheme(data.theme);
4475
- this.updateThemeIcon(data.theme);
4476
- // Terminal color settings are stored PER THEME — load the new
4477
- // theme's set before repainting, otherwise the previous theme's
4478
- // override/colors leak into this theme (and a later save would
4479
- // persist them under the wrong key).
4480
- this.loadTerminalColorSettings();
4481
- this.updateTerminalColorOverrideUI();
4482
- this.updateTerminalThemes(data.theme);
4483
- }
4484
- }
4485
-
4486
- if (data.accent) {
4487
- const savedAccent = this.loadAccent();
4488
- if (savedAccent !== data.accent) {
4489
- console.log('[SSHIFT] Syncing accent from server:', data.accent);
4490
- document.documentElement.setAttribute('data-accent', data.accent);
4491
- this.saveAccent(data.accent);
4492
- this.updateAccentPreview(data.accent);
4493
- this.updateAccentActiveState(data.accent);
4494
- }
4495
- }
4496
-
4617
+
4618
+ // Theme, accent and layout are PER-DEVICE preferences stored in
4619
+ // localStorage only. The server no longer broadcasts them (they
4620
+ // used to be clobbered here from its in-memory copy, which also
4621
+ // meant they were lost on every server restart). initThemeAndAccent
4622
+ // and initLayoutSystem apply the local values at startup.
4623
+
4497
4624
  // Only sync if sticky is enabled and init has completed.
4498
4625
  // If init hasn't finished yet (DOM not ready), defer processing
4499
4626
  // until init completes and the open-tabs event queue is flushed.
4500
4627
  if (this.sticky) {
4501
- // Store server layout for mobile tab preservation
4502
- if (data.layout) {
4503
- this._serverLayout = data.layout;
4504
- }
4505
4628
  // Prevent saveTabs from emitting to server during initial sync
4506
4629
  // (the server is our source of truth; we don't want to broadcast
4507
4630
  // incomplete state back to other clients)
@@ -4516,10 +4639,8 @@ const wheelHandler = (e) => {
4516
4639
  this._initialSyncDone = true;
4517
4640
  } else if (data.tabs.length > 0) {
4518
4641
  const isInitialSync = !this._initialSyncDone;
4519
- // Sync layout BEFORE tabs so panels exist before distribution
4520
- if (data.layout && !this.isMobile) {
4521
- this.setLayoutFromServer(data.layout);
4522
- }
4642
+ // The local per-device layout (initLayoutSystem) has already
4643
+ // created the panels — distribute the synced tabs into them.
4523
4644
  this.syncTabsFromServer(data.tabs, isInitialSync, data.activeTabsByPanel);
4524
4645
  } else if (!this._initialSyncDone) {
4525
4646
  // Server has no tabs and this is the first sync. This is the
@@ -4529,13 +4650,7 @@ const wheelHandler = (e) => {
4529
4650
  // sessions are gone on the server, recreating them as new
4530
4651
  // connections silently spawns duplicates and confuses other
4531
4652
  // clients). Drop the stale cache and start fresh.
4532
- if (data.layout && !this.isMobile) {
4533
- this.setLayoutFromServer(data.layout);
4534
- }
4535
4653
  try { this.clearTabs(); } catch (_) {}
4536
- } else if (data.layout && !this.isMobile) {
4537
- // No tabs change, but layout may have changed
4538
- this.setLayoutFromServer(data.layout);
4539
4654
  }
4540
4655
  this._initialSyncDone = true;
4541
4656
  } finally {
@@ -4543,8 +4658,6 @@ const wheelHandler = (e) => {
4543
4658
  this.isSyncingTabs = wasSyncingTabs;
4544
4659
  }
4545
4660
  }
4546
- // Layout sync is handled above before tab sync; skip redundant call on mobile
4547
- // (mobile always uses single panel)
4548
4661
  });
4549
4662
 
4550
4663
  // Handle tab opened event from another client
@@ -4604,55 +4717,19 @@ const wheelHandler = (e) => {
4604
4717
  }
4605
4718
  });
4606
4719
 
4607
- // Handle layout change from another client
4608
- this.socket.on('layout-changed', (data) => {
4609
- console.log('[SSHIFT] Layout changed by another client:', data.layoutId);
4610
- // Always store server layout even on mobile (for preservation in saves)
4611
- this._serverLayout = data.layoutId;
4612
- if (this.sticky && !this.isMobile) {
4613
- this.setLayoutFromServer(data.layoutId);
4614
- }
4615
- });
4616
-
4617
- // Handle theme change from another client
4618
- this.socket.on('theme-changed', (data) => {
4619
- console.log('[SSHIFT] Theme changed by another client:', data.theme);
4620
- const savedTheme = this.loadTheme();
4621
- if (savedTheme !== data.theme) {
4622
- document.documentElement.setAttribute('data-theme', data.theme);
4623
- this.theme = data.theme;
4624
- this.saveTheme(data.theme);
4625
- this.updateThemeIcon(data.theme);
4626
- // Load the new theme's per-theme terminal color settings before
4627
- // repainting (mirrors toggleTheme) so override/colors don't leak
4628
- // between themes.
4629
- this.loadTerminalColorSettings();
4630
- this.updateTerminalColorOverrideUI();
4631
- this.updateTerminalThemes(data.theme);
4632
- }
4633
- });
4634
-
4635
- // Handle accent change from another client
4636
- this.socket.on('accent-changed', (data) => {
4637
- console.log('[SSHIFT] Accent changed by another client:', data.accent);
4638
- const savedAccent = this.loadAccent();
4639
- if (savedAccent !== data.accent) {
4640
- document.documentElement.setAttribute('data-accent', data.accent);
4641
- this.saveAccent(data.accent);
4642
- this.updateAccentPreview(data.accent);
4643
- this.updateAccentActiveState(data.accent);
4644
- }
4645
- });
4720
+ // layout-changed / theme-changed / accent-changed handlers removed:
4721
+ // layout, theme and accent are per-device preferences (localStorage)
4722
+ // and are no longer broadcast between clients through the server.
4646
4723
 
4647
4724
  // Handle tabs sync from another client
4648
4725
  this.socket.on('tabs-sync', (data) => {
4649
- console.log('[SSHIFT] Tabs sync:', data.tabs?.length || 0, 'tabs, layout:', data.layout);
4726
+ console.log('[SSHIFT] Tabs sync:', data.tabs?.length || 0, 'tabs');
4650
4727
  if (this.sticky) {
4651
4728
  // Set flag to prevent re-emission during sync
4652
4729
  this.isSyncingTabs = true;
4653
4730
 
4654
4731
  try {
4655
- // Update server panel map and layout for mobile preservation
4732
+ // Update server panel map for mobile preservation
4656
4733
  if (data.tabs && Array.isArray(data.tabs)) {
4657
4734
  data.tabs.forEach(tab => {
4658
4735
  if (tab.sessionId && tab.panelId) {
@@ -4660,15 +4737,11 @@ const wheelHandler = (e) => {
4660
4737
  }
4661
4738
  });
4662
4739
  }
4663
- if (data.layout) {
4664
- this._serverLayout = data.layout;
4665
- }
4666
-
4667
- // Apply layout first if it's different
4668
- if (data.layout && data.layout !== this.currentLayout?.id) {
4669
- this.setLayoutFromServer(data.layout, data.tabs);
4670
- } else if (data.tabs && Array.isArray(data.tabs)) {
4671
- // Just reorder tabs without layout change
4740
+
4741
+ // Distribute the synced tabs into OUR local (per-device) layout.
4742
+ // Tabs whose panelId doesn't exist in this device's layout fall
4743
+ // back to the first panel (distributeTabsToPanels).
4744
+ if (data.tabs && Array.isArray(data.tabs)) {
4672
4745
  this.distributeTabsToPanels(data.tabs);
4673
4746
  }
4674
4747
  } finally {
@@ -4758,7 +4831,21 @@ const wheelHandler = (e) => {
4758
4831
 
4759
4832
  // Set syncing flag to prevent ssh-data from writing during sync
4760
4833
  session.syncing = true;
4761
-
4834
+
4835
+ // Discard any not-yet-flushed chunks: the server's serialized state
4836
+ // already includes everything the client has received so far (it is
4837
+ // generated from the server's own headless terminal). Writing stale
4838
+ // pre-sync chunks after the reset below would interleave old bytes
4839
+ // into the freshly restored state.
4840
+ if (session.writeRAF) {
4841
+ cancelAnimationFrame(session.writeRAF);
4842
+ session.writeRAF = null;
4843
+ }
4844
+ session.writeChunks = [];
4845
+ session.flushRemaining = null;
4846
+ // Fresh buffer for live data arriving while the sync state is written
4847
+ session.syncBuffer = [];
4848
+
4762
4849
  // Clear the terminal completely before applying the serialized state
4763
4850
  // Use reset() to clear both the buffer and the scrollback
4764
4851
  session.terminal.reset();
@@ -4776,6 +4863,7 @@ const wheelHandler = (e) => {
4776
4863
  } catch (e) {
4777
4864
  console.error('[SSHIFT] Error decoding base64 state:', e);
4778
4865
  session.syncing = false;
4866
+ this._drainSyncBuffer(session);
4779
4867
  return;
4780
4868
  }
4781
4869
  }
@@ -4787,6 +4875,10 @@ const wheelHandler = (e) => {
4787
4875
 
4788
4876
  // Clear syncing flag after sync is complete
4789
4877
  session.syncing = false;
4878
+ // Replay live output that arrived while the sync state was being
4879
+ // written — it is the continuation of the stream after the
4880
+ // serialization point, so appending it here preserves order.
4881
+ this._drainSyncBuffer(session);
4790
4882
  // Sync succeeded — reset the retry counter used by the
4791
4883
  // requestScreenSync safety timeout.
4792
4884
  session._syncRetries = 0;
@@ -4876,6 +4968,16 @@ const wheelHandler = (e) => {
4876
4968
  // 3. This can cause resize feedback loops between clients
4877
4969
  // The controller is responsible for determining terminal dimensions
4878
4970
  session.terminal.resize(data.cols, data.rows);
4971
+ // The server just told us the size it applied — remember it so we
4972
+ // don't bounce it straight back via syncRemoteTerminalSize.
4973
+ session.remoteCols = data.cols;
4974
+ session.remoteRows = data.rows;
4975
+
4976
+ // The WebGL atlas still holds glyphs rasterised at the pre-resize
4977
+ // cell pitch — repaint at the stale pitch produces the interlace
4978
+ // "black band" artefact (same family as the screen-sync path).
4979
+ // Force the full renderer dimension recompute + atlas rebuild.
4980
+ this._forceRendererDimensionRecompute(session);
4879
4981
  console.log('[SSHIFT] Terminal resized to match server dimensions');
4880
4982
 
4881
4983
  // Clear the syncing flag after a delay to ensure resize events settle
@@ -5116,6 +5218,9 @@ const wheelHandler = (e) => {
5116
5218
  session.syncTimeout = setTimeout(() => {
5117
5219
  console.warn('[SSHIFT] Sync timeout for session:', sessionId, 'retries:', session._syncRetries);
5118
5220
  session.syncing = false;
5221
+ // Don't lose live output that was buffered while waiting for a sync
5222
+ // that never arrived.
5223
+ this._drainSyncBuffer(session);
5119
5224
  if (session._syncRetries < 2 && session.connected) {
5120
5225
  session._syncRetries += 1;
5121
5226
  // Re-arm by calling ourselves once more. We pass a flag via the
@@ -5374,8 +5479,15 @@ const wheelHandler = (e) => {
5374
5479
  dl.chunks.push(bytes);
5375
5480
  dl.bytesDownloaded = data.bytesDownloaded;
5376
5481
  dl.totalBytes = data.totalBytes;
5377
- const percent = data.totalBytes > 0 ? Math.round((data.bytesDownloaded / data.totalBytes) * 100) : 0;
5378
- this.showTransferProgress(dl.sessionId, dl.fileName, percent, data.bytesDownloaded, data.totalBytes, 0, 0, false);
5482
+ // Throttle the progress UI to ~4 repaints/second — chunks arrive
5483
+ // dozens of times per second and each showTransferProgress call
5484
+ // does a batch of DOM queries/writes on the main thread.
5485
+ const now = Date.now();
5486
+ if (!dl._lastProgressUI || now - dl._lastProgressUI >= 250) {
5487
+ dl._lastProgressUI = now;
5488
+ const percent = data.totalBytes > 0 ? Math.round((data.bytesDownloaded / data.totalBytes) * 100) : 0;
5489
+ this.showTransferProgress(dl.sessionId, dl.fileName, percent, data.bytesDownloaded, data.totalBytes, 0, 0, false);
5490
+ }
5379
5491
  }
5380
5492
  });
5381
5493
 
@@ -8114,6 +8226,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8114
8226
  session.syncTimeout = setTimeout(() => {
8115
8227
  console.warn('[SSHIFT] Sync timeout for session:', restoreSessionId, 'retries:', session._syncRetries);
8116
8228
  session.syncing = false;
8229
+ this._drainSyncBuffer(session);
8117
8230
  if (session._syncRetries < 2 && session.connected) {
8118
8231
  session._syncRetries += 1;
8119
8232
  this.requestScreenSync(restoreSessionId);
@@ -8815,6 +8928,8 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8815
8928
  clearTimeout(sess.resizeTimeout);
8816
8929
  }
8817
8930
  sess.resizeTimeout = setTimeout(() => {
8931
+ sess.remoteCols = cols;
8932
+ sess.remoteRows = rows;
8818
8933
  this.socket.emit('ssh-resize', { sessionId, cols, rows });
8819
8934
  }, 100); // 100ms debounce
8820
8935
  }
@@ -9047,14 +9162,23 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9047
9162
  // Setup ResizeObserver to handle container size changes
9048
9163
  // This ensures the terminal is refitted when the container is resized
9049
9164
  // We observe the wrapper (parent) because it persists across layout changes
9165
+ //
9166
+ // NOTE: this debounce MUST use its own timer field. It used to share
9167
+ // `session.resizeTimeout` with the onResize handler above, which
9168
+ // schedules the `ssh-resize` emit that tells the remote PTY about the
9169
+ // new size. fit() changes the wrapper's inner geometry, so it
9170
+ // re-triggers this observer, which then cleared the *pending emit* and
9171
+ // replaced it with another (no-op) fit — the server never learned the
9172
+ // new size and the remote program kept drawing at the old width. That
9173
+ // is the "layout changed but the terminal keeps its previous shape" bug.
9050
9174
  const resizeObserver = new ResizeObserver((entries) => {
9051
9175
  // Only fit if this is the controller and terminal is visible
9052
9176
  if (session.isController && session.terminal && wrapper.classList.contains('active')) {
9053
9177
  try {
9054
- if (session.resizeTimeout) {
9055
- clearTimeout(session.resizeTimeout);
9178
+ if (session.roFitTimeout) {
9179
+ clearTimeout(session.roFitTimeout);
9056
9180
  }
9057
- session.resizeTimeout = setTimeout(() => {
9181
+ session.roFitTimeout = setTimeout(() => {
9058
9182
  try {
9059
9183
  if (session.fitAddon && session.terminal && wrapper.classList.contains('active')) {
9060
9184
  this._fitTerminal(session);
@@ -9101,8 +9225,20 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9101
9225
  }
9102
9226
  });
9103
9227
  };
9228
+ // xterm updates the scrollbar slider's inline style on every
9229
+ // scroll step and render — running querySelectorAll per mutation
9230
+ // stacked avoidable DOM work onto every scroll frame. Coalesce
9231
+ // to one fix pass per animation frame.
9232
+ let fixRAF = null;
9233
+ const fixScrollbarCoalesced = () => {
9234
+ if (fixRAF) return;
9235
+ fixRAF = requestAnimationFrame(() => {
9236
+ fixRAF = null;
9237
+ fixScrollbar();
9238
+ });
9239
+ };
9104
9240
  requestAnimationFrame(fixScrollbar);
9105
- const mo = new MutationObserver(fixScrollbar);
9241
+ const mo = new MutationObserver(fixScrollbarCoalesced);
9106
9242
  const scrollableEl = wrapper.querySelector('.xterm-scrollable-element');
9107
9243
  if (scrollableEl) {
9108
9244
  mo.observe(scrollableEl, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
@@ -9228,36 +9364,49 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9228
9364
 
9229
9365
  onSSHData(data) {
9230
9366
  const session = this.sessions.get(data.sessionId);
9231
- if (session && session.terminal) {
9232
- // Skip data if we're currently syncing the terminal state
9233
- if (session.syncing) {
9234
- return;
9367
+ if (!session) {
9368
+ console.warn('[SSHIFT] Received data for missing session:', data.sessionId);
9369
+ return;
9370
+ }
9371
+
9372
+ // While a screen sync is in flight the terminal is being reset and
9373
+ // re-filled from the server's serialized state. Live output that
9374
+ // arrives in the meantime is NOT stale — it is the continuation of
9375
+ // the stream AFTER the serialization point. Dropping it (the old
9376
+ // behaviour) permanently punched holes in line-diff TUI screens
9377
+ // (rows those apps never rewrite), leaving stale/black rows until
9378
+ // a manual resize. Buffer it and replay it right after the sync
9379
+ // state is written (see the ssh-screen-sync handler).
9380
+ if (session.syncing) {
9381
+ (session.syncBuffer || (session.syncBuffer = [])).push(data.data);
9382
+ return;
9383
+ }
9384
+
9385
+ try {
9386
+ // Buffer even when the terminal doesn't exist yet (initTerminal's
9387
+ // container-ready retry loop): _flushWriteChunks waits for the
9388
+ // terminal instead of dropping the first screenful of output,
9389
+ // which line-diff TUI apps would never repaint.
9390
+ session.writeChunks.push(data.data);
9391
+
9392
+ if (!session.writeRAF) {
9393
+ session.writeRAF = requestAnimationFrame(() => {
9394
+ this._flushWriteChunks(data.sessionId);
9395
+ });
9235
9396
  }
9236
-
9237
- try {
9238
- session.writeChunks.push(data.data);
9239
-
9240
- if (!session.writeRAF) {
9241
- session.writeRAF = requestAnimationFrame(() => {
9242
- this._flushWriteChunks(data.sessionId);
9243
- });
9244
- }
9245
-
9246
- // Auto-scroll to bottom on mobile when new data arrives
9247
- if (this.isMobile) {
9248
- if (session.scrollRAF) {
9249
- cancelAnimationFrame(session.scrollRAF);
9250
- }
9251
- session.scrollRAF = requestAnimationFrame(() => {
9252
- this.scrollTerminalToBottom(data.sessionId);
9253
- session.scrollRAF = null;
9254
- });
9397
+
9398
+ // Auto-scroll to bottom on mobile when new data arrives
9399
+ if (this.isMobile && session.terminal) {
9400
+ if (session.scrollRAF) {
9401
+ cancelAnimationFrame(session.scrollRAF);
9255
9402
  }
9256
- } catch (e) {
9257
- console.error('[SSHIFT] Error writing to terminal:', e.message);
9403
+ session.scrollRAF = requestAnimationFrame(() => {
9404
+ this.scrollTerminalToBottom(data.sessionId);
9405
+ session.scrollRAF = null;
9406
+ });
9258
9407
  }
9259
- } else {
9260
- console.warn('[SSHIFT] Received data for missing session/terminal:', data.sessionId);
9408
+ } catch (e) {
9409
+ console.error('[SSHIFT] Error writing to terminal:', e.message);
9261
9410
  }
9262
9411
  }
9263
9412
 
@@ -9453,10 +9602,63 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9453
9602
  return result;
9454
9603
  }
9455
9604
 
9605
+ // Move live data buffered during a screen sync (session.syncBuffer) back
9606
+ // into the normal write path and schedule a flush. Called when a sync
9607
+ // completes (or is aborted) so no live output is lost.
9608
+ _drainSyncBuffer(session) {
9609
+ if (!session || !session.terminal) { session.syncBuffer = []; return; }
9610
+ const buffered = session.syncBuffer || [];
9611
+ session.syncBuffer = [];
9612
+ if (buffered.length > 0) {
9613
+ session.writeChunks.push(...buffered);
9614
+ if (!session.writeRAF) {
9615
+ const sessionId = session.id;
9616
+ session.writeRAF = requestAnimationFrame(() => {
9617
+ this._flushWriteChunks(sessionId);
9618
+ });
9619
+ }
9620
+ }
9621
+ }
9622
+
9456
9623
  _flushWriteChunks(sessionId) {
9457
9624
  const session = this.sessions.get(sessionId);
9458
- if (!session || !session.terminal) {
9459
- if (session) session.writeRAF = null;
9625
+ if (!session) return;
9626
+
9627
+ // Terminal not created yet (initTerminal's container-ready retry loop):
9628
+ // keep the buffered chunks and retry shortly instead of dropping them.
9629
+ // A dropped first screenful leaves permanently stale rows in line-diff
9630
+ // TUI apps that never repaint unchanged rows. Bounded to 10s so a
9631
+ // session whose terminal never materialises can't poll forever.
9632
+ if (!session.terminal) {
9633
+ session.writeRAF = null;
9634
+ if (!session._flushWaitDeadline || session._flushWaitDeadline < Date.now()) {
9635
+ session._flushWaitDeadline = Date.now() + 10000;
9636
+ }
9637
+ if (Date.now() < session._flushWaitDeadline) {
9638
+ setTimeout(() => {
9639
+ const stillHere = this.sessions.get(sessionId);
9640
+ if (stillHere && !stillHere.writeRAF) {
9641
+ stillHere.writeRAF = requestAnimationFrame(() => {
9642
+ this._flushWriteChunks(sessionId);
9643
+ });
9644
+ }
9645
+ }, 50);
9646
+ } else {
9647
+ // Give up — drop the chunks (pre-change behaviour).
9648
+ session.writeChunks = [];
9649
+ session.flushRemaining = null;
9650
+ }
9651
+ return;
9652
+ }
9653
+
9654
+ // A screen sync is in flight (terminal.reset() + serialized-state
9655
+ // write). Writing live chunks now would interleave bytes into the
9656
+ // half-restored state; the sync completion drains any data that arrived
9657
+ // meanwhile. Re-check on the next frame until the sync finishes.
9658
+ if (session.syncing) {
9659
+ session.writeRAF = requestAnimationFrame(() => {
9660
+ this._flushWriteChunks(sessionId);
9661
+ });
9460
9662
  return;
9461
9663
  }
9462
9664
 
@@ -9565,6 +9767,15 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9565
9767
  // provides that same guarantee automatically: within ~350ms of any
9566
9768
  // burst ending, every row is re-rendered from the (correct) buffer.
9567
9769
  // Cost: one extra full-viewport render per burst — negligible.
9770
+ //
9771
+ // Two hardening additions for the two remaining holes:
9772
+ // 1. The trailing debounce above NEVER fires while output is continuous
9773
+ // (each write postpones it). A 2s max-wait repaint runs even mid-flood.
9774
+ // 2. A plain refresh() repaints at the CURRENT (possibly stale) device
9775
+ // cell pitch — it cannot heal a renderer dimension desync. The
9776
+ // max-wait repaint uses _forceRendererDimensionRecompute (the exact
9777
+ // path a real window resize triggers), which heals BOTH missed
9778
+ // dirty rows AND pitch mismatches.
9568
9779
  _scheduleSettleRefresh(session) {
9569
9780
  if (!session || !session.terminal) return;
9570
9781
  if (session.settleRefreshTimer) {
@@ -9572,10 +9783,29 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9572
9783
  }
9573
9784
  session.settleRefreshTimer = setTimeout(() => {
9574
9785
  session.settleRefreshTimer = null;
9786
+ if (session.settleRefreshMaxTimer) {
9787
+ clearTimeout(session.settleRefreshMaxTimer);
9788
+ session.settleRefreshMaxTimer = null;
9789
+ }
9575
9790
  const term = session.terminal;
9576
9791
  if (!term) return;
9577
9792
  try { term.refresh(0, term.rows - 1); } catch (_) {}
9578
9793
  }, 350);
9794
+
9795
+ // Safety net for continuous floods: guarantee a full dimension-
9796
+ // recompute repaint at least every 2s while writes keep arriving,
9797
+ // otherwise the trailing refresh above is postponed indefinitely.
9798
+ if (!session.settleRefreshMaxTimer) {
9799
+ session.settleRefreshMaxTimer = setTimeout(() => {
9800
+ session.settleRefreshMaxTimer = null;
9801
+ if (!session.terminal) return;
9802
+ if (session.settleRefreshTimer) {
9803
+ clearTimeout(session.settleRefreshTimer);
9804
+ session.settleRefreshTimer = null;
9805
+ }
9806
+ this._forceRendererDimensionRecompute(session);
9807
+ }, 2000);
9808
+ }
9579
9809
  }
9580
9810
 
9581
9811
  // SFTP Session Management
@@ -10449,6 +10679,11 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10449
10679
  this._resetWebGLAtlas(session);
10450
10680
  if (session.fontSize) {
10451
10681
  session.terminal.options.fontSize = session.fontSize;
10682
+ // Same race as the controller branch above: setting fontSize
10683
+ // async-invalidates _renderService.dimensions. Commit the cell
10684
+ // size synchronously (measure() + atlas clear) so the renderer
10685
+ // doesn't paint at a stale cell pitch — the interlace bug.
10686
+ this._syncCharSizeThenClearAtlas(session);
10452
10687
  }
10453
10688
  if (this.isMobile && session.mobileHandler && session.mobileHandler.hiddenTextarea) {
10454
10689
  session.mobileHandler._focusHiddenTextarea();
@@ -10497,11 +10732,15 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10497
10732
  session.resizeObserver.disconnect();
10498
10733
  session.resizeObserver = null;
10499
10734
  }
10500
- // Clean up resize timeout
10735
+ // Clean up resize timeouts (emit debounce + ResizeObserver fit debounce)
10501
10736
  if (session.resizeTimeout) {
10502
10737
  clearTimeout(session.resizeTimeout);
10503
10738
  session.resizeTimeout = null;
10504
10739
  }
10740
+ if (session.roFitTimeout) {
10741
+ clearTimeout(session.roFitTimeout);
10742
+ session.roFitTimeout = null;
10743
+ }
10505
10744
  // Clean up scrollbar MutationObserver (mobile-only)
10506
10745
  if (session._scrollbarObserver) {
10507
10746
  session._scrollbarObserver.disconnect();
@@ -10633,6 +10872,10 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10633
10872
  clearTimeout(session.resizeTimeout);
10634
10873
  session.resizeTimeout = null;
10635
10874
  }
10875
+ if (session.roFitTimeout) {
10876
+ clearTimeout(session.roFitTimeout);
10877
+ session.roFitTimeout = null;
10878
+ }
10636
10879
  if (session.wheelHandler && session.wheelElement) {
10637
10880
  session.wheelElement.removeEventListener('wheel', session.wheelHandler);
10638
10881
  }