@lethevimlet/sshift 1.7.5 → 1.7.7

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,
@@ -1194,6 +1194,12 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1194
1194
  // Guarded refit — see _refreshAllWebGLSessions for why a bare
1195
1195
  // fitAddon.fit() on a hidden container is destructive.
1196
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;
1197
1203
  }
1198
1204
  // After context loss the local terminal's rasterised
1199
1205
  // cells may have been cleared; reconcile with the
@@ -1274,8 +1280,13 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1274
1280
  const refresh = (session) => {
1275
1281
  if (!session || !session.terminal || !this.webglRenderer) return;
1276
1282
  if (session.webglAddon) {
1277
- try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
1278
- 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);
1279
1290
  } else if ((session.webglContextLossCount || 0) < 3 && typeof window.WebglAddon === 'function') {
1280
1291
  this._initWebGLAddon(session, false);
1281
1292
  // Refit through _fitTerminal, never fitAddon.fit() directly: a raw
@@ -1802,12 +1813,11 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1802
1813
 
1803
1814
  // Update all terminal themes
1804
1815
  this.updateTerminalThemes(newTheme);
1805
-
1806
- // Sync theme to server for cross-device sync
1807
- if (this.socket && this.socket.connected) {
1808
- this.socket.emit('theme-change', { theme: newTheme });
1809
- }
1810
-
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
+
1811
1821
  // Fade out the wave
1812
1822
  wave.classList.add('fade-out');
1813
1823
 
@@ -2046,10 +2056,8 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2046
2056
  console.warn('[SSHIFT] Failed to re-apply terminal themes after accent change:', e.message);
2047
2057
  }
2048
2058
 
2049
- // Sync accent to server for cross-device sync
2050
- if (this.socket && this.socket.connected) {
2051
- this.socket.emit('accent-change', { accent: accent });
2052
- }
2059
+ // Accent is a PER-DEVICE preference (localStorage only) — no longer
2060
+ // synced through the server.
2053
2061
  }
2054
2062
 
2055
2063
  updateAccentPreview(accent) {
@@ -2213,51 +2221,27 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2213
2221
  console.log('[SSHIFT] Setting layout:', layoutId);
2214
2222
  this.saveCurrentLayout(layoutId);
2215
2223
  this.updateLayoutActiveState(layoutId);
2216
-
2224
+
2217
2225
  // Find the layout definition
2218
2226
  const layout = this.layouts?.find(l => l.id === layoutId);
2219
2227
  if (layout) {
2220
- // Emit event for layout change (to be implemented later)
2228
+ // Apply the layout locally
2221
2229
  this.onLayoutChange(layout);
2222
2230
  }
2223
-
2224
- // Sync layout to server for cross-tab sync
2225
- if (this.sticky && this.socket) {
2226
- this.socket.emit('layout-change', { layoutId });
2227
- }
2228
- }
2229
2231
 
2230
- setLayoutFromServer(layoutId, syncedTabs = null) {
2231
- console.log('[SSHIFT] Setting layout from server:', layoutId);
2232
-
2233
- // If layouts aren't loaded yet, queue this for later
2234
- if (!this.layouts) {
2235
- console.log('[SSHIFT] Layouts not loaded yet, queuing layout sync for:', layoutId);
2236
- this.pendingLayoutSync = layoutId;
2237
- this.pendingLayoutTabs = syncedTabs;
2238
- return;
2239
- }
2240
-
2241
- // Don't sync back to server (avoid loop)
2242
- this.saveCurrentLayout(layoutId);
2243
- this.updateLayoutActiveState(layoutId);
2244
-
2245
- // Find the layout definition
2246
- const layout = this.layouts.find(l => l.id === layoutId);
2247
- if (layout) {
2248
- this.currentLayout = layout;
2249
- // Pass syncedTabs to applyLayout which will handle distribution
2250
- this.applyLayout(layout, syncedTabs);
2251
-
2252
- // Same staggered refit the local (dropdown) path gets — a client that
2253
- // receives the layout from another browser tab has to re-measure its
2254
- // panes just as thoroughly, or its terminals keep the previous shape.
2255
- this.refitAllTerminals();
2256
-
2257
- setTimeout(() => this.handleResize(), 50);
2258
- }
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).
2259
2237
  }
2260
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
+
2261
2245
  updateLayoutActiveState(layoutId) {
2262
2246
  document.querySelectorAll('.layout-option').forEach(option => {
2263
2247
  option.classList.toggle('active', option.dataset.layoutId === layoutId);
@@ -3278,15 +3262,6 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3278
3262
  // Load layouts
3279
3263
  this.layouts = await this.loadLayouts();
3280
3264
 
3281
- // Apply any pending layout sync that arrived before layouts were loaded
3282
- if (this.pendingLayoutSync) {
3283
- console.log('[SSHIFT] Applying pending layout sync:', this.pendingLayoutSync);
3284
- const pendingLayoutId = this.pendingLayoutSync;
3285
- this.pendingLayoutSync = null;
3286
- this.setLayoutFromServer(pendingLayoutId);
3287
- return; // setLayoutFromServer handles everything
3288
- }
3289
-
3290
3265
  // Get saved layout or default to 'single'
3291
3266
  const savedLayoutId = this.loadCurrentLayout();
3292
3267
  const layout = this.layouts.find(l => l.id === savedLayoutId) || this.layouts[0];
@@ -3438,29 +3413,20 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3438
3413
  this._pendingOpenTabs = null;
3439
3414
  this._pendingOpenTabsIsInitial = null;
3440
3415
 
3441
- // Store server layout for mobile preservation
3442
- if (pendingData.layout) {
3443
- this._serverLayout = pendingData.layout;
3444
- }
3445
-
3446
3416
  // Prevent saveTabs from emitting to server during deferred sync
3447
3417
  const wasSyncingTabs = this.isSyncingTabs;
3448
3418
  this.isSyncingTabs = true;
3449
3419
 
3450
3420
  try {
3451
3421
  if (pendingData.tabs.length > 0) {
3452
- // Sync layout BEFORE tabs so panels exist before distribution
3453
- if (pendingData.layout && !this.isMobile) {
3454
- this.setLayoutFromServer(pendingData.layout);
3455
- }
3422
+ // The local layout (per-device, applied by initLayoutSystem)
3423
+ // already created the panels — just distribute the synced tabs
3424
+ // into them.
3456
3425
  this.syncTabsFromServer(pendingData.tabs, isInitialSync, pendingData.activeTabsByPanel);
3457
3426
  } else {
3458
3427
  // Server has no tabs (e.g. right after restart). Treat it as a
3459
3428
  // fresh slate: clear stale localStorage and DO NOT resurrect
3460
3429
  // those sessions — they're gone on the server.
3461
- if (pendingData.layout && !this.isMobile) {
3462
- this.setLayoutFromServer(pendingData.layout);
3463
- }
3464
3430
  try { this.clearTabs(); } catch (_) {}
3465
3431
  }
3466
3432
  } finally {
@@ -3493,9 +3459,22 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3493
3459
  resizeTimeout = setTimeout(setViewportHeight, 100);
3494
3460
  });
3495
3461
 
3496
- // 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.
3497
3468
  if (window.visualViewport) {
3498
- 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);
3499
3478
  }
3500
3479
 
3501
3480
  // Update mobile detection on resize and re-apply layout if needed
@@ -3555,12 +3534,115 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3555
3534
 
3556
3535
  console.log(`[SSHIFT] Setting up touch scroll handlers on ${elementName}`);
3557
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
+
3558
3636
  element.addEventListener('touchstart', (e) => {
3559
3637
  if (e.touches.length === 1) {
3638
+ cancelMomentum();
3560
3639
  session.lastTouchY = e.touches[0].clientY;
3640
+ session.lastTouchX = e.touches[0].clientX;
3561
3641
  session.isScrolling = true;
3562
3642
  session.touchAccumulator = 0;
3643
+ session.scrollVelocity = 0;
3563
3644
  } else if (e.touches.length === 2) {
3645
+ cancelMomentum();
3564
3646
  session.isPinching = true;
3565
3647
  session.isScrolling = false;
3566
3648
  session.initialPinchDistance = this.getPinchDistance(e.touches[0], e.touches[1]);
@@ -3575,56 +3657,14 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3575
3657
  const currentTouchY = e.touches[0].clientY;
3576
3658
  const touchDiff = session.lastTouchY - currentTouchY;
3577
3659
  session.lastTouchY = currentTouchY;
3660
+ session.lastTouchX = e.touches[0].clientX;
3578
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;
3579
3665
 
3580
- const lineHeight = terminal._core?._renderService?.dimensions?.css?.cell?.height || 20;
3581
- const lineH = Math.max(lineHeight, 14);
3582
-
3583
- // When a TUI app has mouse tracking enabled (DECSET
3584
- // 1000/1002/1003), scrolling should send mouse wheel
3585
- // escape sequences directly to the PTY. Instead of
3586
- // dispatching synthetic WheelEvents (which xterm's own
3587
- // document-level touch handler can interfere with), we
3588
- // generate the SGR mouse format ourselves and emit it via
3589
- // ssh-data. SGR format: \x1b[<button;col;row;M
3590
- // Wheel up = button 64, wheel down = button 65.
3591
- const mouseProtocol = terminal._core?.coreMouseService?.activeProtocol;
3592
- const tuiMouseActive = mouseProtocol && mouseProtocol !== 'NONE';
3593
-
3594
- if (tuiMouseActive) {
3595
- if (Math.abs(session.touchAccumulator) >= lineH) {
3596
- // Compute the terminal cell under the touch point.
3597
- const screenEl = terminal.element?.querySelector('.xterm-screen');
3598
- if (screenEl) {
3599
- const rect = screenEl.getBoundingClientRect();
3600
- const cellW = terminal._core?._renderService?.dimensions?.css?.cell?.width || 8;
3601
- const cellH = lineHeight;
3602
- const touchX = e.touches[0].clientX - rect.left;
3603
- const touchY = e.touches[0].clientY - rect.top;
3604
- const col = Math.max(1, Math.min(terminal.cols, Math.floor(touchX / cellW) + 1));
3605
- const row = Math.max(1, Math.min(terminal.rows, Math.floor(touchY / cellH) + 1));
3606
-
3607
- const scrollLines = Math.trunc(Math.abs(session.touchAccumulator) / lineH);
3608
- const direction = session.touchAccumulator > 0 ? 1 : -1; // 1 = scroll down, -1 = scroll up
3609
- for (let i = 0; i < scrollLines; i++) {
3610
- // button 64 = wheel up, 65 = wheel down
3611
- const button = direction > 0 ? 65 : 64;
3612
- const seq = `\x1b[<${button};${col};${row}M`;
3613
- if (session.connected && session.isController) {
3614
- this.socket.emit('ssh-data', { sessionId, data: seq });
3615
- }
3616
- }
3617
- session.touchAccumulator = 0;
3618
- }
3619
- }
3620
- } else {
3621
- const linesToScroll = Math.trunc(Math.abs(session.touchAccumulator) / lineH);
3622
- if (linesToScroll > 0) {
3623
- const direction = session.touchAccumulator > 0 ? 1 : -1;
3624
- terminal.scrollLines(direction * linesToScroll);
3625
- session.touchAccumulator -= direction * linesToScroll * lineH;
3626
- }
3627
- }
3666
+ // Apply once per frame, not once per touchmove event.
3667
+ scheduleScrollApply();
3628
3668
  } else if (e.touches.length === 2 && session.isPinching) {
3629
3669
  e.preventDefault();
3630
3670
 
@@ -3658,7 +3698,24 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3658
3698
  session.isScrolling = false;
3659
3699
  session.initialPinchDistance = 0;
3660
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();
3661
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
+ }
3662
3719
 
3663
3720
  setTimeout(() => {
3664
3721
  this.checkIfAtBottom(sessionId);
@@ -3668,8 +3725,10 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3668
3725
  session.initialPinchDistance = 0;
3669
3726
  session.lastPinchDistance = 0;
3670
3727
  session.lastTouchY = e.touches[0].clientY;
3728
+ session.lastTouchX = e.touches[0].clientX;
3671
3729
  session.isScrolling = true;
3672
3730
  session.touchAccumulator = 0;
3731
+ session.scrollVelocity = 0;
3673
3732
  }
3674
3733
  }, { passive: true });
3675
3734
  };
@@ -3896,20 +3955,27 @@ const wheelHandler = (e) => {
3896
3955
  const session = this.sessions.get(sessionId);
3897
3956
  if (!session || !session.terminal) return;
3898
3957
 
3958
+ const terminal = session.terminal;
3959
+
3899
3960
  // Only auto-scroll if user is at the bottom
3900
3961
  // This allows users to scroll up and read previous output without being interrupted
3901
3962
  if (!session.isAtBottom) {
3902
- console.log('[SSHIFT] Not auto-scrolling - user has scrolled up');
3903
3963
  return;
3904
3964
  }
3905
-
3906
- const terminal = session.terminal;
3907
-
3965
+
3908
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
+
3909
3976
  // Use xterm.js scrollToBottom method
3910
3977
  if (typeof terminal.scrollToBottom === 'function') {
3911
3978
  terminal.scrollToBottom();
3912
- console.log('[SSHIFT] Auto-scrolled to bottom');
3913
3979
  }
3914
3980
  } catch (e) {
3915
3981
  console.warn('[SSHIFT] Error scrolling terminal:', e.message);
@@ -4105,7 +4171,21 @@ const wheelHandler = (e) => {
4105
4171
  }
4106
4172
  };
4107
4173
 
4108
- 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);
4109
4189
 
4110
4190
  // Also listen for visual viewport scroll to keep header/tabs pinned
4111
4191
  // Android can scroll the visual viewport when keyboard is open
@@ -4132,7 +4212,7 @@ const wheelHandler = (e) => {
4132
4212
  }
4133
4213
  };
4134
4214
 
4135
- window.visualViewport.addEventListener('scroll', updateHeaderPosition);
4215
+ window.visualViewport.addEventListener('scroll', updatePositionCoalesced);
4136
4216
 
4137
4217
  // Initial update
4138
4218
  updatePosition();
@@ -4444,6 +4524,7 @@ const wheelHandler = (e) => {
4444
4524
  session.syncTimeout = setTimeout(() => {
4445
4525
  console.warn('[SSHIFT] Sync timeout after rejoin for session:', sessionId);
4446
4526
  session.syncing = false;
4527
+ this._drainSyncBuffer(session);
4447
4528
  if (session.connected) {
4448
4529
  this.requestScreenSync(sessionId);
4449
4530
  }
@@ -4533,45 +4614,17 @@ const wheelHandler = (e) => {
4533
4614
  clearTimeout(this._serverSyncTimeout);
4534
4615
  this._serverSyncTimeout = null;
4535
4616
  }
4536
-
4537
- // Sync theme and accent from server
4538
- if (data.theme) {
4539
- const savedTheme = this.loadTheme();
4540
- if (savedTheme !== data.theme) {
4541
- console.log('[SSHIFT] Syncing theme from server:', data.theme);
4542
- document.documentElement.setAttribute('data-theme', data.theme);
4543
- this.theme = data.theme;
4544
- this.saveTheme(data.theme);
4545
- this.updateThemeIcon(data.theme);
4546
- // Terminal color settings are stored PER THEME — load the new
4547
- // theme's set before repainting, otherwise the previous theme's
4548
- // override/colors leak into this theme (and a later save would
4549
- // persist them under the wrong key).
4550
- this.loadTerminalColorSettings();
4551
- this.updateTerminalColorOverrideUI();
4552
- this.updateTerminalThemes(data.theme);
4553
- }
4554
- }
4555
-
4556
- if (data.accent) {
4557
- const savedAccent = this.loadAccent();
4558
- if (savedAccent !== data.accent) {
4559
- console.log('[SSHIFT] Syncing accent from server:', data.accent);
4560
- document.documentElement.setAttribute('data-accent', data.accent);
4561
- this.saveAccent(data.accent);
4562
- this.updateAccentPreview(data.accent);
4563
- this.updateAccentActiveState(data.accent);
4564
- }
4565
- }
4566
-
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
+
4567
4624
  // Only sync if sticky is enabled and init has completed.
4568
4625
  // If init hasn't finished yet (DOM not ready), defer processing
4569
4626
  // until init completes and the open-tabs event queue is flushed.
4570
4627
  if (this.sticky) {
4571
- // Store server layout for mobile tab preservation
4572
- if (data.layout) {
4573
- this._serverLayout = data.layout;
4574
- }
4575
4628
  // Prevent saveTabs from emitting to server during initial sync
4576
4629
  // (the server is our source of truth; we don't want to broadcast
4577
4630
  // incomplete state back to other clients)
@@ -4586,10 +4639,8 @@ const wheelHandler = (e) => {
4586
4639
  this._initialSyncDone = true;
4587
4640
  } else if (data.tabs.length > 0) {
4588
4641
  const isInitialSync = !this._initialSyncDone;
4589
- // Sync layout BEFORE tabs so panels exist before distribution
4590
- if (data.layout && !this.isMobile) {
4591
- this.setLayoutFromServer(data.layout);
4592
- }
4642
+ // The local per-device layout (initLayoutSystem) has already
4643
+ // created the panels — distribute the synced tabs into them.
4593
4644
  this.syncTabsFromServer(data.tabs, isInitialSync, data.activeTabsByPanel);
4594
4645
  } else if (!this._initialSyncDone) {
4595
4646
  // Server has no tabs and this is the first sync. This is the
@@ -4599,13 +4650,7 @@ const wheelHandler = (e) => {
4599
4650
  // sessions are gone on the server, recreating them as new
4600
4651
  // connections silently spawns duplicates and confuses other
4601
4652
  // clients). Drop the stale cache and start fresh.
4602
- if (data.layout && !this.isMobile) {
4603
- this.setLayoutFromServer(data.layout);
4604
- }
4605
4653
  try { this.clearTabs(); } catch (_) {}
4606
- } else if (data.layout && !this.isMobile) {
4607
- // No tabs change, but layout may have changed
4608
- this.setLayoutFromServer(data.layout);
4609
4654
  }
4610
4655
  this._initialSyncDone = true;
4611
4656
  } finally {
@@ -4613,8 +4658,6 @@ const wheelHandler = (e) => {
4613
4658
  this.isSyncingTabs = wasSyncingTabs;
4614
4659
  }
4615
4660
  }
4616
- // Layout sync is handled above before tab sync; skip redundant call on mobile
4617
- // (mobile always uses single panel)
4618
4661
  });
4619
4662
 
4620
4663
  // Handle tab opened event from another client
@@ -4674,55 +4717,19 @@ const wheelHandler = (e) => {
4674
4717
  }
4675
4718
  });
4676
4719
 
4677
- // Handle layout change from another client
4678
- this.socket.on('layout-changed', (data) => {
4679
- console.log('[SSHIFT] Layout changed by another client:', data.layoutId);
4680
- // Always store server layout even on mobile (for preservation in saves)
4681
- this._serverLayout = data.layoutId;
4682
- if (this.sticky && !this.isMobile) {
4683
- this.setLayoutFromServer(data.layoutId);
4684
- }
4685
- });
4686
-
4687
- // Handle theme change from another client
4688
- this.socket.on('theme-changed', (data) => {
4689
- console.log('[SSHIFT] Theme changed by another client:', data.theme);
4690
- const savedTheme = this.loadTheme();
4691
- if (savedTheme !== data.theme) {
4692
- document.documentElement.setAttribute('data-theme', data.theme);
4693
- this.theme = data.theme;
4694
- this.saveTheme(data.theme);
4695
- this.updateThemeIcon(data.theme);
4696
- // Load the new theme's per-theme terminal color settings before
4697
- // repainting (mirrors toggleTheme) so override/colors don't leak
4698
- // between themes.
4699
- this.loadTerminalColorSettings();
4700
- this.updateTerminalColorOverrideUI();
4701
- this.updateTerminalThemes(data.theme);
4702
- }
4703
- });
4704
-
4705
- // Handle accent change from another client
4706
- this.socket.on('accent-changed', (data) => {
4707
- console.log('[SSHIFT] Accent changed by another client:', data.accent);
4708
- const savedAccent = this.loadAccent();
4709
- if (savedAccent !== data.accent) {
4710
- document.documentElement.setAttribute('data-accent', data.accent);
4711
- this.saveAccent(data.accent);
4712
- this.updateAccentPreview(data.accent);
4713
- this.updateAccentActiveState(data.accent);
4714
- }
4715
- });
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.
4716
4723
 
4717
4724
  // Handle tabs sync from another client
4718
4725
  this.socket.on('tabs-sync', (data) => {
4719
- console.log('[SSHIFT] Tabs sync:', data.tabs?.length || 0, 'tabs, layout:', data.layout);
4726
+ console.log('[SSHIFT] Tabs sync:', data.tabs?.length || 0, 'tabs');
4720
4727
  if (this.sticky) {
4721
4728
  // Set flag to prevent re-emission during sync
4722
4729
  this.isSyncingTabs = true;
4723
4730
 
4724
4731
  try {
4725
- // Update server panel map and layout for mobile preservation
4732
+ // Update server panel map for mobile preservation
4726
4733
  if (data.tabs && Array.isArray(data.tabs)) {
4727
4734
  data.tabs.forEach(tab => {
4728
4735
  if (tab.sessionId && tab.panelId) {
@@ -4730,15 +4737,11 @@ const wheelHandler = (e) => {
4730
4737
  }
4731
4738
  });
4732
4739
  }
4733
- if (data.layout) {
4734
- this._serverLayout = data.layout;
4735
- }
4736
-
4737
- // Apply layout first if it's different
4738
- if (data.layout && data.layout !== this.currentLayout?.id) {
4739
- this.setLayoutFromServer(data.layout, data.tabs);
4740
- } else if (data.tabs && Array.isArray(data.tabs)) {
4741
- // 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)) {
4742
4745
  this.distributeTabsToPanels(data.tabs);
4743
4746
  }
4744
4747
  } finally {
@@ -4828,7 +4831,21 @@ const wheelHandler = (e) => {
4828
4831
 
4829
4832
  // Set syncing flag to prevent ssh-data from writing during sync
4830
4833
  session.syncing = true;
4831
-
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
+
4832
4849
  // Clear the terminal completely before applying the serialized state
4833
4850
  // Use reset() to clear both the buffer and the scrollback
4834
4851
  session.terminal.reset();
@@ -4846,6 +4863,7 @@ const wheelHandler = (e) => {
4846
4863
  } catch (e) {
4847
4864
  console.error('[SSHIFT] Error decoding base64 state:', e);
4848
4865
  session.syncing = false;
4866
+ this._drainSyncBuffer(session);
4849
4867
  return;
4850
4868
  }
4851
4869
  }
@@ -4857,6 +4875,10 @@ const wheelHandler = (e) => {
4857
4875
 
4858
4876
  // Clear syncing flag after sync is complete
4859
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);
4860
4882
  // Sync succeeded — reset the retry counter used by the
4861
4883
  // requestScreenSync safety timeout.
4862
4884
  session._syncRetries = 0;
@@ -4950,6 +4972,12 @@ const wheelHandler = (e) => {
4950
4972
  // don't bounce it straight back via syncRemoteTerminalSize.
4951
4973
  session.remoteCols = data.cols;
4952
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);
4953
4981
  console.log('[SSHIFT] Terminal resized to match server dimensions');
4954
4982
 
4955
4983
  // Clear the syncing flag after a delay to ensure resize events settle
@@ -5190,6 +5218,9 @@ const wheelHandler = (e) => {
5190
5218
  session.syncTimeout = setTimeout(() => {
5191
5219
  console.warn('[SSHIFT] Sync timeout for session:', sessionId, 'retries:', session._syncRetries);
5192
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);
5193
5224
  if (session._syncRetries < 2 && session.connected) {
5194
5225
  session._syncRetries += 1;
5195
5226
  // Re-arm by calling ourselves once more. We pass a flag via the
@@ -5448,8 +5479,15 @@ const wheelHandler = (e) => {
5448
5479
  dl.chunks.push(bytes);
5449
5480
  dl.bytesDownloaded = data.bytesDownloaded;
5450
5481
  dl.totalBytes = data.totalBytes;
5451
- const percent = data.totalBytes > 0 ? Math.round((data.bytesDownloaded / data.totalBytes) * 100) : 0;
5452
- 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
+ }
5453
5491
  }
5454
5492
  });
5455
5493
 
@@ -8188,6 +8226,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8188
8226
  session.syncTimeout = setTimeout(() => {
8189
8227
  console.warn('[SSHIFT] Sync timeout for session:', restoreSessionId, 'retries:', session._syncRetries);
8190
8228
  session.syncing = false;
8229
+ this._drainSyncBuffer(session);
8191
8230
  if (session._syncRetries < 2 && session.connected) {
8192
8231
  session._syncRetries += 1;
8193
8232
  this.requestScreenSync(restoreSessionId);
@@ -9186,8 +9225,20 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9186
9225
  }
9187
9226
  });
9188
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
+ };
9189
9240
  requestAnimationFrame(fixScrollbar);
9190
- const mo = new MutationObserver(fixScrollbar);
9241
+ const mo = new MutationObserver(fixScrollbarCoalesced);
9191
9242
  const scrollableEl = wrapper.querySelector('.xterm-scrollable-element');
9192
9243
  if (scrollableEl) {
9193
9244
  mo.observe(scrollableEl, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });
@@ -9313,36 +9364,49 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9313
9364
 
9314
9365
  onSSHData(data) {
9315
9366
  const session = this.sessions.get(data.sessionId);
9316
- if (session && session.terminal) {
9317
- // Skip data if we're currently syncing the terminal state
9318
- if (session.syncing) {
9319
- 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
+ });
9320
9396
  }
9321
-
9322
- try {
9323
- session.writeChunks.push(data.data);
9324
-
9325
- if (!session.writeRAF) {
9326
- session.writeRAF = requestAnimationFrame(() => {
9327
- this._flushWriteChunks(data.sessionId);
9328
- });
9329
- }
9330
-
9331
- // Auto-scroll to bottom on mobile when new data arrives
9332
- if (this.isMobile) {
9333
- if (session.scrollRAF) {
9334
- cancelAnimationFrame(session.scrollRAF);
9335
- }
9336
- session.scrollRAF = requestAnimationFrame(() => {
9337
- this.scrollTerminalToBottom(data.sessionId);
9338
- session.scrollRAF = null;
9339
- });
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);
9340
9402
  }
9341
- } catch (e) {
9342
- console.error('[SSHIFT] Error writing to terminal:', e.message);
9403
+ session.scrollRAF = requestAnimationFrame(() => {
9404
+ this.scrollTerminalToBottom(data.sessionId);
9405
+ session.scrollRAF = null;
9406
+ });
9343
9407
  }
9344
- } else {
9345
- console.warn('[SSHIFT] Received data for missing session/terminal:', data.sessionId);
9408
+ } catch (e) {
9409
+ console.error('[SSHIFT] Error writing to terminal:', e.message);
9346
9410
  }
9347
9411
  }
9348
9412
 
@@ -9538,10 +9602,63 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9538
9602
  return result;
9539
9603
  }
9540
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
+
9541
9623
  _flushWriteChunks(sessionId) {
9542
9624
  const session = this.sessions.get(sessionId);
9543
- if (!session || !session.terminal) {
9544
- 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
+ });
9545
9662
  return;
9546
9663
  }
9547
9664
 
@@ -9650,6 +9767,15 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9650
9767
  // provides that same guarantee automatically: within ~350ms of any
9651
9768
  // burst ending, every row is re-rendered from the (correct) buffer.
9652
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.
9653
9779
  _scheduleSettleRefresh(session) {
9654
9780
  if (!session || !session.terminal) return;
9655
9781
  if (session.settleRefreshTimer) {
@@ -9657,10 +9783,29 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9657
9783
  }
9658
9784
  session.settleRefreshTimer = setTimeout(() => {
9659
9785
  session.settleRefreshTimer = null;
9786
+ if (session.settleRefreshMaxTimer) {
9787
+ clearTimeout(session.settleRefreshMaxTimer);
9788
+ session.settleRefreshMaxTimer = null;
9789
+ }
9660
9790
  const term = session.terminal;
9661
9791
  if (!term) return;
9662
9792
  try { term.refresh(0, term.rows - 1); } catch (_) {}
9663
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
+ }
9664
9809
  }
9665
9810
 
9666
9811
  // SFTP Session Management
@@ -10534,6 +10679,11 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10534
10679
  this._resetWebGLAtlas(session);
10535
10680
  if (session.fontSize) {
10536
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);
10537
10687
  }
10538
10688
  if (this.isMobile && session.mobileHandler && session.mobileHandler.hiddenTextarea) {
10539
10689
  session.mobileHandler._focusHiddenTextarea();