@lethevimlet/sshift 1.7.9 → 1.8.1

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.
@@ -793,7 +793,7 @@ class SSHIFTClient {
793
793
  try { core._charSizeService.measure(); } catch (_) {}
794
794
  }
795
795
  this._fitTerminal(session);
796
- this._resetWebGLAtlas(session);
796
+ this._repaintTerminal(session);
797
797
  });
798
798
  });
799
799
  }
@@ -1042,88 +1042,96 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1042
1042
  // Don't persist - font size is session-only
1043
1043
  }
1044
1044
 
1045
- // Clear the WebGL glyph texture atlas and force a full repaint.
1046
- // The atlas caches rasterised glyphs; if it was built before the web font
1047
- // finished loading (or after a DPR / font-size change) those cached glyphs
1048
- // are blank or stale, producing the "black box" rendering artefacts.
1049
- // Clearing forces every cell to be re-rasterised with correct glyphs.
1050
- _resetWebGLAtlas(session) {
1051
- if (!session || !session.terminal) return;
1052
- if (session.webglAddon) {
1053
- try {
1054
- session.webglAddon.clearTextureAtlas();
1055
- } catch (_) {}
1056
- }
1057
- session.terminal.refresh(0, session.terminal.rows - 1);
1058
- }
1059
-
1060
- // Synchronously commit the renderer's cell dimensions after a font-size
1061
- // (or font-family) option change, then clear the glyph atlas.
1045
+ // ---------------------------------------------------------------------
1046
+ // Renderer helpers
1062
1047
  //
1063
- // xterm.js v6 invalidates _renderService.dimensions ASYNCHRONOUSLY when an
1064
- // option like fontSize is set: the CharSizeService only re-measures on the
1065
- // next change tick. If fitAddon.fit() runs in the same synchronous frame
1066
- // it reads the STALE (pre-invalidation) cell height/width, so cols/rows are
1067
- // computed for one cell size while the renderer later paints at another.
1068
- // That mismatch paints every other row as an empty black band — the
1069
- // "interlace" bug (see comments at the Terminal construction path and at
1070
- // _fitTerminal). Calling _charSizeService.measure() fires
1071
- // onCharSizeChange synchronously, which the RenderService forwards to the
1072
- // renderer's handleCharSizeChanged so _updateDimensions runs BEFORE fit.
1073
- // This mirrors the proven fix used after document.fonts.ready at
1074
- // construction time. Without this, switchTab/setSessionFontSize race the
1075
- // fit and the terminal renders interlaced until a window resize forces a
1076
- // clean re-fit.
1077
- _syncCharSizeThenClearAtlas(session) {
1048
+ // IMPORTANT — how the xterm.js WebGL addon really works (v0.19):
1049
+ // * Cell metrics are owned by xterm itself. CharSizeService re-measures
1050
+ // on fontFamily/fontSize changes, RenderService forwards every char-size
1051
+ // / option / buffer-resize / DPR change to the renderer, and the
1052
+ // renderer recomputes its device cell pitch + canvas size from those.
1053
+ // There is no "stale pitch" state that a manual handleResize() heals
1054
+ // but a plain refresh() would not.
1055
+ // * The glyph texture atlas is SHARED between every terminal on the page
1056
+ // that has the same font/size/colours/DPR (CharAtlasCache). Calling
1057
+ // clearTextureAtlas() on ONE terminal wipes the atlas for ALL of them,
1058
+ // but only that one terminal rebuilds its vertex data. Every other
1059
+ // terminal keeps pointing at texture coordinates that now hold
1060
+ // different glyphs (or nothing) — rendering as scattered dots, commas
1061
+ // and fragments on a black canvas, flickering on each new wipe. The
1062
+ // previous code wiped the atlas after every output burst, tab switch
1063
+ // and screen sync, which is exactly the "gibberish" bug.
1064
+ // * Assigning canvas.width/height (even to the same value) blanks the
1065
+ // WebGL drawing buffer until the next frame — the old post-burst
1066
+ // "dimension recompute" made the terminal flicker while typing.
1067
+ //
1068
+ // So: repaints are plain refresh() calls, the atlas is only ever cleared
1069
+ // for ALL terminals at once, and only when the rasterised glyphs really
1070
+ // are stale (a web font finished loading after glyphs were drawn with
1071
+ // the fallback font).
1072
+ // ---------------------------------------------------------------------
1073
+
1074
+ // Commit the terminal's cell metrics synchronously. CharSizeService
1075
+ // fires onCharSizeChange only when the measured size actually changed,
1076
+ // and the RenderService then runs the renderer's full resize path. This
1077
+ // is a cheap no-op when nothing changed.
1078
+ _measureCharSize(session) {
1078
1079
  if (!session || !session.terminal) return;
1079
1080
  const core = session.terminal._core;
1080
1081
  if (core && core._charSizeService && typeof core._charSizeService.measure === 'function') {
1081
1082
  try { core._charSizeService.measure(); } catch (_) {}
1082
1083
  }
1083
- if (session.webglAddon) {
1084
- try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
1085
- }
1086
1084
  }
1087
1085
 
1088
- // Force the renderer to fully recompute its dimensions and resize its
1089
- // canvases at the current cell metrics — even when cols/rows and the
1090
- // measured char size are UNCHANGED.
1091
- //
1092
- // Why this exists: both cheaper paths short-circuit in that case —
1093
- // - fitAddon.fit() returns without calling _renderService.clear()/resize()
1094
- // when the proposed cols/rows equal the current ones, and
1095
- // - CharSizeService.measure() only fires onCharSizeChange when the
1096
- // measured width/height actually changed.
1097
- // So after take-control / screen-sync, nothing forces the WebGL renderer to
1098
- // re-run _updateDimensions(): it keeps painting at a stale device cell
1099
- // pitch and the terminal shows the "interlaced black line" pattern.
1100
- // Pressing font +/- fixed it because an ACTUAL fontSize change fires
1101
- // handleCharSizeChanged → renderer.handleResize; a window resize fixed it
1102
- // because the changed container produces different cols/rows and a real
1103
- // resize. This helper invokes that same full path directly:
1104
- // _renderService.handleResize → renderer.handleResize →
1105
- // _updateDimensions() + device-pixel canvas resize + full refresh —
1106
- // identical to what xterm.js itself runs on a genuine resize event.
1107
- _forceRendererDimensionRecompute(session) {
1086
+ // Full-viewport repaint from the buffer (after committing any pending
1087
+ // char-size change). Never touches the shared glyph atlas.
1088
+ _repaintTerminal(session) {
1108
1089
  if (!session || !session.terminal) return;
1090
+ this._measureCharSize(session);
1109
1091
  const term = session.terminal;
1110
- const core = term._core;
1111
- // Commit any pending char-size change first so the renderer recomputes
1112
- // from fresh metrics (no-op when the size didn't change).
1113
- if (core && core._charSizeService && typeof core._charSizeService.measure === 'function') {
1114
- try { core._charSizeService.measure(); } catch (_) {}
1115
- }
1116
- // Full renderer dimension recompute + canvas resize + full refresh.
1117
- if (core && core._renderService && typeof core._renderService.handleResize === 'function') {
1118
- try { core._renderService.handleResize(term.cols, term.rows); } catch (_) {}
1119
- }
1120
- // Rebuild the WebGL glyph atlas at the recomputed cell pitch.
1121
- if (session.webglAddon) {
1122
- try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
1123
- }
1124
1092
  try { term.refresh(0, term.rows - 1); } catch (_) {}
1125
1093
  }
1126
1094
 
1095
+ // Rebuild the (shared) WebGL glyph atlas for EVERY terminal on the page.
1096
+ // Each clearTextureAtlas() call wipes the atlas pages (a no-op once they
1097
+ // are already empty) and clears THAT terminal's render model so its
1098
+ // vertex data is rebuilt on the next frame. Doing it for all terminals
1099
+ // in one synchronous pass guarantees nobody keeps stale texture
1100
+ // coordinates. Only call this when the rasterised glyphs are actually
1101
+ // stale (font swap) — it forces every visible glyph to be re-rasterised.
1102
+ _clearAllWebGLAtlases() {
1103
+ const clear = (session) => {
1104
+ if (!session || !session.terminal || !session.webglAddon) return;
1105
+ try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
1106
+ try { session.terminal.refresh(0, session.terminal.rows - 1); } catch (_) {}
1107
+ };
1108
+ this.sessions.forEach(clear);
1109
+ this.sftpSessions.forEach(clear);
1110
+ }
1111
+
1112
+ // Web fonts (JetBrains Mono etc.) can finish loading AFTER a terminal
1113
+ // rasterised its first glyphs with the fallback font. The atlas config
1114
+ // (fontFamily string, metrics) may be identical, so xterm keeps the stale
1115
+ // glyphs. Rebuild the atlas for all terminals once fonts are ready and
1116
+ // again whenever the browser finishes loading additional fonts later
1117
+ // (e.g. fallback fonts pulled in for CJK / symbol glyphs).
1118
+ _setupFontAtlasListener() {
1119
+ if (this._fontAtlasListenerInstalled) return;
1120
+ this._fontAtlasListenerInstalled = true;
1121
+ if (typeof document === 'undefined' || !document.fonts) return;
1122
+ const rebuild = () => {
1123
+ this.sessions.forEach((s) => this._measureCharSize(s));
1124
+ this.sftpSessions.forEach((s) => this._measureCharSize(s));
1125
+ this._clearAllWebGLAtlases();
1126
+ };
1127
+ try { document.fonts.ready.then(rebuild); } catch (_) {}
1128
+ try {
1129
+ if (typeof document.fonts.addEventListener === 'function') {
1130
+ document.fonts.addEventListener('loadingdone', rebuild);
1131
+ }
1132
+ } catch (_) {}
1133
+ }
1134
+
1127
1135
  // Sub-pixel seam mitigation is handled by canvas/WebGL renderer +
1128
1136
  // customGlyphs: true, which draws block/box characters as vector fills
1129
1137
  // that meet exactly. letterSpacing nudging doesn't work because xterm.js
@@ -1132,7 +1140,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1132
1140
  // grid in its own coordinate system. The remaining mitigation is:
1133
1141
  // - customGlyphs: true (set in Terminal options)
1134
1142
  // - canvas or WebGL renderer as default (not DOM)
1135
- // - clearTextureAtlas() on DPR change (handled by _setupDPRListener)
1143
+ // - DPR changes are handled by xterm itself (new atlas config)
1136
1144
  // - clean base metrics: letterSpacing: 0, lineHeight: 1.0 in _fitTerminal
1137
1145
  _snapCellWidth() { /* no-op: see comment above */ }
1138
1146
 
@@ -1240,18 +1248,11 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1240
1248
  session._webglInitPending = false;
1241
1249
  console.log('[SSHIFT] WebglAddon loaded');
1242
1250
 
1243
- if (initialLoad) {
1244
- document.fonts.ready.then(() => {
1245
- if (session.webglAddon) {
1246
- try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
1247
- }
1248
- if (session.terminal) {
1249
- session.terminal.refresh(0, session.terminal.rows - 1);
1250
- }
1251
- console.log('[SSHIFT] WebGL atlas cleared after fonts ready');
1252
- });
1253
- } else {
1254
- try { webglAddon.clearTextureAtlas(); } catch (_) {}
1251
+ // Stale-glyph handling after a web-font swap is page-global (see
1252
+ // _setupFontAtlasListener) — the atlas is shared between terminals,
1253
+ // so a per-terminal clearTextureAtlas() here would corrupt every
1254
+ // OTHER terminal's glyph references.
1255
+ if (!initialLoad) {
1255
1256
  session.terminal.refresh(0, session.terminal.rows - 1);
1256
1257
  // Guarded refit — a bare fitAddon.fit() here would resize a hidden
1257
1258
  // session to 10x5 (see _refreshAllWebGLSessions).
@@ -1286,7 +1287,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1286
1287
  // at a stale pitch faithfully reproduces the interlace "black
1287
1288
  // band" artefact. measure() + handleResize + atlas rebuild +
1288
1289
  // refresh heals both stale glyphs AND pitch mismatches.
1289
- this._forceRendererDimensionRecompute(session);
1290
+ this._repaintTerminal(session);
1290
1291
  } else if ((session.webglContextLossCount || 0) < 3 && typeof window.WebglAddon === 'function') {
1291
1292
  this._initWebGLAddon(session, false);
1292
1293
  // Refit through _fitTerminal, never fitAddon.fit() directly: a raw
@@ -1317,7 +1318,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1317
1318
  console.log('[SSHIFT] devicePixelRatio changed from', currentDPR, 'to', newDPR);
1318
1319
  currentDPR = newDPR;
1319
1320
  this.sessions.forEach(session => {
1320
- this._resetWebGLAtlas(session);
1321
+ this._repaintTerminal(session);
1321
1322
  if (session.fitAddon && session.terminal && session.isController) {
1322
1323
  const wrapper = document.getElementById(`terminal-wrapper-${session.id}`);
1323
1324
  if (wrapper && wrapper.classList.contains('active')) {
@@ -1328,7 +1329,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1328
1329
  }
1329
1330
  });
1330
1331
  this.sftpSessions.forEach(session => {
1331
- this._resetWebGLAtlas(session);
1332
+ this._repaintTerminal(session);
1332
1333
  });
1333
1334
  }
1334
1335
  // Re-register for the new DPR value
@@ -1368,6 +1369,15 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1368
1369
  return false;
1369
1370
  }
1370
1371
 
1372
+ // Never fit while a screen sync is replaying the server's state: the
1373
+ // serialized screen is laid out for the server's cols/rows and a
1374
+ // resize mid-write garbles it. The sync completion handler re-fits
1375
+ // controllers (see the ssh-screen-sync handler).
1376
+ if (session.syncing) {
1377
+ session.needsResize = true;
1378
+ return false;
1379
+ }
1380
+
1371
1381
  // Guard: refuse to fit if the container hasn't reached a usable size.
1372
1382
  // A zero/very small container (e.g. a pane mid-layout-transition that
1373
1383
  // is briefly ~100x100px) produces bogus col/row counts. Those propagate
@@ -1431,7 +1441,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1431
1441
  // stale device cell pitch → interlaced black bands). The recompute
1432
1442
  // also flushes stale cells from the previous dimensions, preventing
1433
1443
  // bottom-row garbage and garbled status lines after resize.
1434
- this._forceRendererDimensionRecompute(session);
1444
+ this._repaintTerminal(session);
1435
1445
 
1436
1446
  // Make sure the remote PTY actually learns about this size. See
1437
1447
  // syncRemoteTerminalSize — xterm only fires onResize when cols/rows
@@ -1443,6 +1453,15 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1443
1453
  return true;
1444
1454
  }
1445
1455
 
1456
+ // Run a fit that _fitTerminal deferred while a screen sync was in flight
1457
+ // (needsResize). Controllers only — observers mirror the server's size.
1458
+ _runDeferredFit(session) {
1459
+ if (!session || !session.terminal || !session.fitAddon) return;
1460
+ if (!session.isController || !session.needsResize) return;
1461
+ session.needsResize = false;
1462
+ this._fitTerminal(session);
1463
+ }
1464
+
1446
1465
  // Push the terminal's current dimensions to the remote PTY when the server
1447
1466
  // is not already known to be at that size.
1448
1467
  //
@@ -1539,6 +1558,11 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1539
1558
  session.needsResize = true;
1540
1559
  return false;
1541
1560
  }
1561
+ if (session.syncing) {
1562
+ // See _fitTerminal: a screen sync is replaying the server's state.
1563
+ session.needsResize = true;
1564
+ return false;
1565
+ }
1542
1566
  const rect = container.getBoundingClientRect();
1543
1567
  if (rect.width < 50 || rect.height < 50) {
1544
1568
  session.needsResize = true;
@@ -1546,7 +1570,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1546
1570
  }
1547
1571
 
1548
1572
  // (b) Commit the renderer's cell metrics before fit reads them.
1549
- this._syncCharSizeThenClearAtlas(session);
1573
+ this._measureCharSize(session);
1550
1574
 
1551
1575
  // (c) Fit (resize the terminal buffer to the now-committed container).
1552
1576
  let ok = false;
@@ -1564,7 +1588,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1564
1588
  // nothing else would force the renderer to re-run
1565
1589
  // _updateDimensions(), and the stale device cell pitch keeps
1566
1590
  // painting every other row dark).
1567
- this._forceRendererDimensionRecompute(session);
1591
+ this._repaintTerminal(session);
1568
1592
 
1569
1593
  // (e) Notify the remote PTY of the corrected dimensions. Mirror the
1570
1594
  // debounced onResize handler but fire immediately so the server's
@@ -1612,7 +1636,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1612
1636
  // computed from a stale cell height and the terminal paints
1613
1637
  // interlaced black bands (the "interlace" bug).
1614
1638
  session.terminal.options.fontSize = size;
1615
- this._syncCharSizeThenClearAtlas(session);
1639
+ this._measureCharSize(session);
1616
1640
 
1617
1641
  if (session.fitAddon && session.isController) {
1618
1642
  this._fitTerminal(session);
@@ -1643,7 +1667,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1643
1667
  this.sessions.forEach((session) => {
1644
1668
  if (session.terminal) {
1645
1669
  session.terminal.options.fontSize = size;
1646
- this._syncCharSizeThenClearAtlas(session);
1670
+ this._measureCharSize(session);
1647
1671
  if (session.fitAddon && session.isController) {
1648
1672
  this._fitTerminal(session);
1649
1673
  }
@@ -1656,7 +1680,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1656
1680
  this.sftpSessions.forEach((session) => {
1657
1681
  if (session.terminal) {
1658
1682
  session.terminal.options.fontSize = size;
1659
- this._syncCharSizeThenClearAtlas(session);
1683
+ this._measureCharSize(session);
1660
1684
  if (session.fitAddon) {
1661
1685
  this._fitTerminal(session);
1662
1686
  }
@@ -1856,7 +1880,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1856
1880
  const newTheme = this.getTerminalTheme(theme);
1857
1881
  console.log('[SSHIFT] Applying theme to terminal:', newTheme);
1858
1882
  session.terminal.options.theme = newTheme;
1859
- this._resetWebGLAtlas(session);
1883
+ this._repaintTerminal(session);
1860
1884
 
1861
1885
  // Update wrapper background to match terminal background
1862
1886
  const wrapper = document.getElementById(`terminal-wrapper-${session.id}`);
@@ -1877,7 +1901,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
1877
1901
  if (session.terminal) {
1878
1902
  const newTheme = this.getTerminalTheme(theme);
1879
1903
  session.terminal.options.theme = newTheme;
1880
- this._resetWebGLAtlas(session);
1904
+ this._repaintTerminal(session);
1881
1905
 
1882
1906
  // Update wrapper background to match terminal background
1883
1907
  const wrapper = document.getElementById(`terminal-wrapper-${session.id}`);
@@ -2301,12 +2325,47 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2301
2325
  });
2302
2326
  }
2303
2327
 
2328
+ /**
2329
+ * The mobile top bar hosts two singleton controls (bookmarks button and
2330
+ * the "..." overflow menu with its big dropdown + listeners). They must
2331
+ * survive layout rebuilds (which recreate every tabs-container), so they
2332
+ * are moved, never recreated: parked in a hidden holder while the layout
2333
+ * is torn down, then mounted into the single panel's tabs-container.
2334
+ */
2335
+ _parkMobileBarSingletons() {
2336
+ let parking = document.getElementById('mobileBarParking');
2337
+ if (!parking) {
2338
+ parking = document.createElement('div');
2339
+ parking.id = 'mobileBarParking';
2340
+ parking.style.display = 'none';
2341
+ document.body.appendChild(parking);
2342
+ }
2343
+ ['mobileBookmarksBtn', 'mobileOverflowMenu'].forEach(id => {
2344
+ const el = document.getElementById(id);
2345
+ if (el && el.parentElement !== parking) parking.appendChild(el);
2346
+ });
2347
+ }
2348
+
2349
+ _mountMobileBarSingletons(tabsContainer) {
2350
+ if (!tabsContainer) return;
2351
+ const bookmarks = document.getElementById('mobileBookmarksBtn');
2352
+ if (bookmarks && bookmarks.parentElement !== tabsContainer) {
2353
+ tabsContainer.insertBefore(bookmarks, tabsContainer.firstChild);
2354
+ }
2355
+ const overflow = document.getElementById('mobileOverflowMenu');
2356
+ const actions = tabsContainer.querySelector('.tabs-actions');
2357
+ if (overflow && actions && overflow.parentElement !== actions) {
2358
+ actions.appendChild(overflow);
2359
+ }
2360
+ }
2361
+
2304
2362
  applyLayout(layout, syncedTabs = null) {
2305
2363
  const layoutContainer = document.getElementById('layoutContainer');
2306
2364
  if (!layoutContainer) {
2307
2365
  console.error('[SSHIFT] Layout container not found');
2308
2366
  return;
2309
2367
  }
2368
+ this._parkMobileBarSingletons();
2310
2369
 
2311
2370
  // On mobile, always force single panel mode
2312
2371
  const effectiveLayout = this.isMobile
@@ -2343,6 +2402,8 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2343
2402
  // Clear and recreate single panel
2344
2403
  layoutContainer.innerHTML = '';
2345
2404
  this.createSinglePanel(layoutContainer, 0);
2405
+ } else {
2406
+ this._mountMobileBarSingletons(existingPanel.querySelector('.tabs-container'));
2346
2407
  }
2347
2408
 
2348
2409
  this.currentLayout = layout;
@@ -2720,6 +2781,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2720
2781
  actions.appendChild(speechToTextBtn);
2721
2782
 
2722
2783
  container.appendChild(actions);
2784
+ if (isSingle) this._mountMobileBarSingletons(container);
2723
2785
 
2724
2786
  return container;
2725
2787
  }
@@ -2877,7 +2939,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2877
2939
  // cell height and paint interlaced black bands (the "interlace" bug).
2878
2940
  sftpSession.fontSize = Math.max(this.minFontSize, Math.min(this.maxFontSize, newSize));
2879
2941
  sftpSession.terminal.options.fontSize = sftpSession.fontSize;
2880
- this._syncCharSizeThenClearAtlas(sftpSession);
2942
+ this._measureCharSize(sftpSession);
2881
2943
 
2882
2944
  if (sftpSession.fitAddon) {
2883
2945
  this._fitTerminal(sftpSession);
@@ -3339,6 +3401,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3339
3401
  // derived from CSS pixels * DPR — a different DPR means every cached
3340
3402
  // glyph is now the wrong size and must be re-rasterised.
3341
3403
  this._setupDPRListener();
3404
+ this._setupFontAtlasListener();
3342
3405
 
3343
3406
  // Load sticky config first
3344
3407
  await this.loadStickyConfig();
@@ -4039,6 +4102,7 @@ const wheelHandler = (e) => {
4039
4102
  if (!element) return defaultHeight;
4040
4103
 
4041
4104
  const style = window.getComputedStyle(element);
4105
+ if (style.display === 'none') return 0;
4042
4106
  const height = parseFloat(style.height) || 0;
4043
4107
  const marginTop = parseFloat(style.marginTop) || 0;
4044
4108
  const marginBottom = parseFloat(style.marginBottom) || 0;
@@ -4790,6 +4854,7 @@ const wheelHandler = (e) => {
4790
4854
  // Drain it or it stays stuck (permanently missing rows in
4791
4855
  // line-diff TUI screens — the stale/black-line bug).
4792
4856
  this._drainSyncBuffer(session);
4857
+ this._runDeferredFit(session);
4793
4858
  }
4794
4859
 
4795
4860
  // Handle controller status
@@ -4892,6 +4957,32 @@ const wheelHandler = (e) => {
4892
4957
  }
4893
4958
  }
4894
4959
 
4960
+ // Bring the terminal to the server's geometry BEFORE replaying the
4961
+ // state. The serialized screen was produced for exactly
4962
+ // data.cols x data.rows. Replaying it into a terminal of a different
4963
+ // width wraps every full-width row: full-screen TUIs (alternate
4964
+ // buffer) end up with one text row followed by one overflow row —
4965
+ // the "alternating black line" pattern — and a later resize() does
4966
+ // NOT undo that, because xterm never reflows the alternate buffer.
4967
+ // (Previously the resize ran AFTER the write, into whatever size the
4968
+ // freshly created terminal happened to have, usually 80x24.)
4969
+ if (data.cols && data.rows &&
4970
+ (session.terminal.cols !== data.cols || session.terminal.rows !== data.rows)) {
4971
+ try {
4972
+ // isResyncing suppresses the onResize → ssh-resize echo for
4973
+ // this server-driven resize (it would otherwise bounce the
4974
+ // server's own size back at it).
4975
+ session.isResyncing = true;
4976
+ session.terminal.resize(data.cols, data.rows);
4977
+ session.remoteCols = data.cols;
4978
+ session.remoteRows = data.rows;
4979
+ console.log('[SSHIFT] Terminal resized to server dimensions before sync write:', data.cols, 'x', data.rows);
4980
+ } catch (e) {
4981
+ console.warn('[SSHIFT] Error resizing terminal for sync:', e.message);
4982
+ }
4983
+ session.isResyncing = false;
4984
+ }
4985
+
4895
4986
  // Write the serialized terminal state
4896
4987
  // This includes all escape sequences to reconstruct the screen
4897
4988
  session.terminal.write(state, () => {
@@ -4915,44 +5006,21 @@ const wheelHandler = (e) => {
4915
5006
  if (!data.partial) {
4916
5007
  session.terminal.scrollToBottom();
4917
5008
  }
4918
-
4919
- // Resize terminal to match the session's dimensions if provided
4920
- // Note: We do NOT call fit() here because:
4921
- // 1. This client is joining an existing session and is not the controller
4922
- // 2. The controller determines the terminal dimensions
4923
- // 3. fit() would recalculate dimensions for the local container
4924
- // 4. This can cause resize feedback loops between clients
4925
- if (data.cols && data.rows) {
4926
- try {
4927
- // Set resyncing flag BEFORE calling resize to prevent resize feedback loop
4928
- session.isResyncing = true;
4929
-
4930
- session.terminal.resize(data.cols, data.rows);
4931
- console.log('[SSHIFT] Terminal resized to match server dimensions:', data.cols, 'x', data.rows);
4932
-
4933
- // The serialized state was just written into a fresh
4934
- // buffer + the terminal was just resized. The WebGL
4935
- // renderer's glyph atlas still holds glyphs rasterised
4936
- // at the pre-resize cell size — painting them now would
4937
- // produce the "interlaced / every-other-row blank" bug
4938
- // (visible after "Take Control" on a just-refreshed
4939
- // browser tab; fixed when the user manually resizes the
4940
- // window because that re-runs the renderer resize path).
4941
- // Note: when the terminal is ALREADY at data.cols/rows the
4942
- // resize() above short-circuits inside xterm.js, so a plain
4943
- // atlas clear is not enough — force the full renderer
4944
- // dimension recompute (same path as a real resize) so the
4945
- // device cell pitch is recomputed and the atlas rebuilt.
4946
- this._forceRendererDimensionRecompute(session);
4947
-
4948
- // Clear the resyncing flag after a short delay
4949
- setTimeout(() => {
4950
- session.isResyncing = false;
4951
- }, 150);
4952
- } catch (e) {
4953
- console.warn('[SSHIFT] Error resizing terminal:', e.message);
4954
- session.isResyncing = false;
4955
- }
5009
+
5010
+ // Plain full repaint from the freshly restored buffer.
5011
+ this._repaintTerminal(session);
5012
+
5013
+ // Only the controller may change the session's geometry. Now that
5014
+ // the server's screen is in place, re-fit it to OUR container:
5015
+ // if the local size differs, fit() resizes the terminal and the
5016
+ // onResize handler pushes the new size to the PTY, so the remote
5017
+ // program repaints at the new size (the local buffer is reflowed
5018
+ // meanwhile). Observers keep the server's geometry.
5019
+ // Fits requested while the sync was in flight were deferred by
5020
+ // _fitTerminal (needsResize) — this is where they land.
5021
+ if (session.isController && session.fitAddon) {
5022
+ session.needsResize = false;
5023
+ this._fitTerminal(session);
4956
5024
  }
4957
5025
 
4958
5026
  // Focus the terminal
@@ -5001,7 +5069,7 @@ const wheelHandler = (e) => {
5001
5069
  // cell pitch — repaint at the stale pitch produces the interlace
5002
5070
  // "black band" artefact (same family as the screen-sync path).
5003
5071
  // Force the full renderer dimension recompute + atlas rebuild.
5004
- this._forceRendererDimensionRecompute(session);
5072
+ this._repaintTerminal(session);
5005
5073
  console.log('[SSHIFT] Terminal resized to match server dimensions');
5006
5074
 
5007
5075
  // Clear the syncing flag after a delay to ensure resize events settle
@@ -5245,6 +5313,7 @@ const wheelHandler = (e) => {
5245
5313
  // Don't lose live output that was buffered while waiting for a sync
5246
5314
  // that never arrived.
5247
5315
  this._drainSyncBuffer(session);
5316
+ this._runDeferredFit(session);
5248
5317
  if (session._syncRetries < 2 && session.connected) {
5249
5318
  session._syncRetries += 1;
5250
5319
  // Re-arm by calling ourselves once more. We pass a flag via the
@@ -5734,6 +5803,16 @@ const wheelHandler = (e) => {
5734
5803
  document.getElementById('menuBtn').addEventListener('click', () => {
5735
5804
  this.toggleSidebar();
5736
5805
  });
5806
+ // Mobile top bar (replaces the mobile header): bookmarks button in the
5807
+ // tabs bar, close button inside the sidebar (the sidebar covers the bar).
5808
+ ['mobileBookmarksBtn', 'sidebarCloseBtn'].forEach(id => {
5809
+ const el = document.getElementById(id);
5810
+ if (el) el.addEventListener('click', () => this.toggleSidebar());
5811
+ });
5812
+ const copyInputTraceBtn = document.getElementById('copyInputTraceBtn');
5813
+ if (copyInputTraceBtn) {
5814
+ copyInputTraceBtn.addEventListener('click', () => this.copyInputTrace());
5815
+ }
5737
5816
 
5738
5817
  // Sidebar overlay click to close
5739
5818
  const sidebarOverlay = document.getElementById('sidebarOverlay');
@@ -6954,14 +7033,16 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
6954
7033
  const certPathEl = document.getElementById('debugCertPath');
6955
7034
  const keyPathEl = document.getElementById('debugKeyPath');
6956
7035
  const certTypeEl = document.getElementById('debugCertType');
7036
+ const caCertPathEl = document.getElementById('debugCaCertPath');
6957
7037
 
6958
7038
  if (configPathEl) configPathEl.textContent = info.configPath || 'N/A';
6959
7039
  if (dataDirEl) dataDirEl.textContent = info.dataDir || 'N/A';
6960
7040
  if (certPathEl) certPathEl.textContent = info.certPath || 'N/A';
6961
7041
  if (keyPathEl) keyPathEl.textContent = info.keyPath || 'N/A';
6962
- if (certTypeEl) certTypeEl.textContent = info.usesCustomCert ? 'Custom' : 'Self-signed';
7042
+ if (caCertPathEl) caCertPathEl.textContent = info.caCertPath || 'N/A';
7043
+ if (certTypeEl) certTypeEl.textContent = info.certType || (info.usesCustomCert ? 'Custom' : 'Local CA-signed');
6963
7044
  }).catch(() => {
6964
- const ids = ['debugConfigPath', 'debugDataDir', 'debugCertPath', 'debugKeyPath', 'debugCertType'];
7045
+ const ids = ['debugConfigPath', 'debugDataDir', 'debugCertPath', 'debugKeyPath', 'debugCaCertPath', 'debugCertType'];
6965
7046
  ids.forEach(id => {
6966
7047
  const el = document.getElementById(id);
6967
7048
  if (el) el.textContent = 'Error loading';
@@ -6971,6 +7052,49 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
6971
7052
  this.openModal('debugInfoModal');
6972
7053
  }
6973
7054
 
7055
+ /**
7056
+ * Copy the mobile handlers' keyboard/IME event trace to the clipboard
7057
+ * (Debug Info dialog). This is the data needed to diagnose Gboard
7058
+ * autocomplete/duplication reports — it records every input,
7059
+ * composition, focus, sync and reset on the hidden textarea.
7060
+ */
7061
+ async copyInputTrace() {
7062
+ const trace = {};
7063
+ this.sessions.forEach((session, id) => {
7064
+ if (session.mobileHandler && typeof session.mobileHandler.getInputTrace === 'function') {
7065
+ trace[id] = session.mobileHandler.getInputTrace();
7066
+ }
7067
+ });
7068
+ const text = JSON.stringify({
7069
+ version: (window.SSHIFT_VERSION || document.getElementById('versionNumber')?.textContent || '').trim(),
7070
+ userAgent: navigator.userAgent,
7071
+ isMobile: this.isMobile,
7072
+ activeSessionId: this.activeSessionId,
7073
+ trace
7074
+ }, null, 1);
7075
+ console.log('[SSHIFT] Input trace:\n' + text);
7076
+ try {
7077
+ await navigator.clipboard.writeText(text);
7078
+ this.showToast('Input trace copied to clipboard', 'success');
7079
+ } catch (err) {
7080
+ // Clipboard API can be unavailable (insecure context, no gesture).
7081
+ // Fall back to a selectable textarea inside the dialog.
7082
+ let box = document.getElementById('inputTraceFallback');
7083
+ if (!box) {
7084
+ box = document.createElement('textarea');
7085
+ box.id = 'inputTraceFallback';
7086
+ box.readOnly = true;
7087
+ box.style.cssText = 'width:100%;height:160px;margin-top:8px;font-size:11px;font-family:monospace;';
7088
+ const body = document.querySelector('#debugInfoModal .modal-body') || document.getElementById('debugInfoModal');
7089
+ if (body) body.appendChild(box);
7090
+ }
7091
+ box.value = text;
7092
+ box.focus();
7093
+ box.select();
7094
+ this.showToast('Clipboard unavailable — trace shown below, long-press to copy', 'info');
7095
+ }
7096
+ }
7097
+
6974
7098
  // Sessions Modal
6975
7099
  async openSessionsModal() {
6976
7100
  this.openModal('manageSessionsModal');
@@ -8251,6 +8375,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8251
8375
  console.warn('[SSHIFT] Sync timeout for session:', restoreSessionId, 'retries:', session._syncRetries);
8252
8376
  session.syncing = false;
8253
8377
  this._drainSyncBuffer(session);
8378
+ this._runDeferredFit(session);
8254
8379
  if (session._syncRetries < 2 && session.connected) {
8255
8380
  session._syncRetries += 1;
8256
8381
  this.requestScreenSync(restoreSessionId);
@@ -8700,6 +8825,17 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8700
8825
  container.innerHTML = '';
8701
8826
 
8702
8827
  terminal.open(container);
8828
+
8829
+ // Attach the terminal + fit addon to the session NOW, before any
8830
+ // helper that takes `session` runs. _initWebGLAddon() (and every
8831
+ // other helper) bails out silently when `session.terminal` is null,
8832
+ // and the assignment used to live at the very end of initTerminal —
8833
+ // so the WebGL renderer was never loaded at creation time. Terminals
8834
+ // silently ran on the DOM renderer until a visibilitychange handler
8835
+ // happened to call _initWebGLAddon() much later, which is why the
8836
+ // WebGL-only artefacts were intermittent.
8837
+ session.terminal = terminal;
8838
+ session.fitAddon = fitAddon;
8703
8839
 
8704
8840
  // Initialise the WebGL renderer only if the wrapper is currently
8705
8841
  // visible. Loading WebGL on a hidden (display:none) terminal
@@ -8766,7 +8902,12 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8766
8902
  // Also register as fallback with xterm.js's OSC handler in case any
8767
8903
  // OSC 52 sequences slip through the data stream interceptor (e.g. from
8768
8904
  // screen sync restoration). The data stream interceptor is the primary handler.
8769
- terminal.registerOscHandler(52, (data) => {
8905
+ // xterm.js v5+/v6 exposes the OSC registration on terminal.parser
8906
+ // (terminal.registerOscHandler no longer exists).
8907
+ const oscRegistrar = (terminal.parser && typeof terminal.parser.registerOscHandler === 'function')
8908
+ ? terminal.parser
8909
+ : terminal;
8910
+ oscRegistrar.registerOscHandler(52, (data) => {
8770
8911
  console.log('[SSHIFT] OSC 52 handler fallback triggered (should be handled by stream interceptor)');
8771
8912
  const semicolonIndex = data.indexOf(';');
8772
8913
  if (semicolonIndex === -1) return true;
@@ -8828,11 +8969,8 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8828
8969
  try { core._charSizeService.measure(); } catch (_) {}
8829
8970
  }
8830
8971
 
8831
- // Clear the WebGL texture atlas after the font swap — glyphs cached
8832
- // before the swap were rasterised at the fallback font's metrics.
8833
- if (session.webglAddon) {
8834
- try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
8835
- }
8972
+ // (The shared WebGL glyph atlas is rebuilt for ALL terminals by
8973
+ // _setupFontAtlasListener once fonts are ready — never per-terminal.)
8836
8974
 
8837
8975
  // Also check if WebGL init was deferred due to hidden wrapper
8838
8976
  // (Bug 3) — the terminal may now be visible.
@@ -9783,29 +9921,23 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9783
9921
  // Full-viewport repaint shortly after an output burst settles.
9784
9922
  //
9785
9923
  // Under heavy output floods (TUI streaming + per-line scrollback trims
9786
- // while throttled + 32KB/frame capped writes) the WebGL renderer can
9787
- // miss dirty-row updates: some rows keep showing STALE content (old
9788
- // backgrounds / leftover fragments) even though the terminal BUFFER is
9789
- // correct. Line-diff TUI renderers (OpenCode, Bubble Tea apps, ...)
9790
- // never rewrite lines they consider unchanged, so those stale rows then
9791
- // persist indefinitely — visible as "interlaced black lines between
9792
- // text lines" where the app's painted background alternates with the
9793
- // terminal's default background. A font-size change or window resize
9794
- // "fixed" it because both force a full re-render from the buffer.
9924
+ // while throttled + 32KB/frame capped writes) the renderer can miss
9925
+ // dirty-row updates: some rows keep showing STALE content even though
9926
+ // the terminal BUFFER is correct. Line-diff TUI renderers (OpenCode,
9927
+ // Bubble Tea apps, ...) never rewrite lines they consider unchanged, so
9928
+ // those stale rows would persist until something forced a full
9929
+ // re-render from the buffer.
9795
9930
  //
9796
9931
  // This debounced refresh(0, rows-1) after the LAST write of a burst
9797
- // provides that same guarantee automatically: within ~350ms of any
9798
- // burst ending, every row is re-rendered from the (correct) buffer.
9799
- // Cost: one extra full-viewport render per burst — negligible.
9932
+ // guarantees that within ~350ms of any burst ending every row is
9933
+ // re-rendered from the (correct) buffer. A 2s max-wait repaint covers
9934
+ // continuous floods where the trailing debounce never fires.
9800
9935
  //
9801
- // Two hardening additions for the two remaining holes:
9802
- // 1. The trailing debounce above NEVER fires while output is continuous
9803
- // (each write postpones it). A 2s max-wait repaint runs even mid-flood.
9804
- // 2. A plain refresh() repaints at the CURRENT (possibly stale) device
9805
- // cell pitch — it cannot heal a renderer dimension desync. The
9806
- // max-wait repaint uses _forceRendererDimensionRecompute (the exact
9807
- // path a real window resize triggers), which heals BOTH missed
9808
- // dirty rows AND pitch mismatches.
9936
+ // Both are PLAIN repaints (_repaintTerminal). They must never resize the
9937
+ // canvas or clear the WebGL glyph atlas: the atlas is shared between all
9938
+ // terminals, so clearing it here after every keystroke echo corrupted
9939
+ // every other terminal's glyphs (scattered dots/commas) and re-sizing the
9940
+ // canvas blanked it for a frame (flicker while typing).
9809
9941
  _scheduleSettleRefresh(session) {
9810
9942
  if (!session || !session.terminal) return;
9811
9943
  if (session.settleRefreshTimer) {
@@ -9818,31 +9950,21 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9818
9950
  session.settleRefreshMaxTimer = null;
9819
9951
  }
9820
9952
  if (!session.terminal) return;
9821
- // Use the full dimension recompute (the exact path a font-size
9822
- // change triggers), NOT a plain refresh(): a plain refresh
9823
- // repaints at the CURRENT renderer cell pitch — if a pitch desync
9824
- // formed during the flood (the "alternating black bands between
9825
- // text lines" bug: rows painted empty at a mismatched pitch),
9826
- // repainting at the same broken pitch reproduces the bands.
9827
- // Users report a font/window resize reliably heals the artefact;
9828
- // this is the programmatic equivalent, applied automatically
9829
- // ~350ms after every output burst settles.
9830
- if (session.syncing) return; // sync completion does its own recompute
9831
- this._forceRendererDimensionRecompute(session);
9953
+ if (session.syncing) return; // sync completion does its own repaint
9954
+ this._repaintTerminal(session);
9832
9955
  }, 350);
9833
9956
 
9834
- // Safety net for continuous floods: guarantee a full dimension-
9835
- // recompute repaint at least every 2s while writes keep arriving,
9836
- // otherwise the trailing refresh above is postponed indefinitely.
9957
+ // Safety net for continuous floods: guarantee a full repaint at least
9958
+ // every 2s while writes keep arriving, otherwise the trailing refresh
9959
+ // above is postponed indefinitely.
9837
9960
  if (!session.settleRefreshMaxTimer) {
9838
9961
  const runMaxWait = () => {
9839
9962
  session.settleRefreshMaxTimer = null;
9840
9963
  if (!session.terminal) return;
9841
- // Never run the dimension recompute mid-screen-sync: the
9842
- // serialized state is still being parsed (terminal.reset() has
9843
- // run but the write hasn't completed), so a full repaint now
9844
- // paints a half-applied state and an atlas rebuild races the
9845
- // sync completion's own recompute. Retry later.
9964
+ // Never repaint mid-screen-sync: the serialized state is still
9965
+ // being parsed (terminal.reset() has run but the write hasn't
9966
+ // completed), so a full repaint now would paint a half-applied
9967
+ // state. Retry later.
9846
9968
  if (session.syncing) {
9847
9969
  session.settleRefreshMaxTimer = setTimeout(runMaxWait, 2000);
9848
9970
  return;
@@ -9851,7 +9973,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9851
9973
  clearTimeout(session.settleRefreshTimer);
9852
9974
  session.settleRefreshTimer = null;
9853
9975
  }
9854
- this._forceRendererDimensionRecompute(session);
9976
+ this._repaintTerminal(session);
9855
9977
  };
9856
9978
  session.settleRefreshMaxTimer = setTimeout(runMaxWait, 2000);
9857
9979
  }
@@ -10646,7 +10768,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10646
10768
  // While display:none, the terminal canvas has zero dimensions and
10647
10769
  // any cached glyphs are rendered at wrong colours/sizes (Bug 3).
10648
10770
  // Clearing + refreshing forces a clean redraw at the correct size.
10649
- this._resetWebGLAtlas(session);
10771
+ this._repaintTerminal(session);
10650
10772
 
10651
10773
  // Restore font size for this session. Setting fontSize async-
10652
10774
  // invalidates _renderService.dimensions; we must commit the new
@@ -10656,7 +10778,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10656
10778
  // (the "interlace" bug — see _syncCharSizeThenClearAtlas).
10657
10779
  if (session.fontSize && session.terminal) {
10658
10780
  session.terminal.options.fontSize = session.fontSize;
10659
- this._syncCharSizeThenClearAtlas(session);
10781
+ this._measureCharSize(session);
10660
10782
  console.log('[SSHIFT] Restored font size', session.fontSize, 'for session', sessionId);
10661
10783
  }
10662
10784
 
@@ -10725,14 +10847,14 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10725
10847
  } else if (session && session.terminal) {
10726
10848
  // For non-controllers, just focus the terminal and restore font size.
10727
10849
  // Also clear the WebGL atlas since this tab was hidden.
10728
- this._resetWebGLAtlas(session);
10850
+ this._repaintTerminal(session);
10729
10851
  if (session.fontSize) {
10730
10852
  session.terminal.options.fontSize = session.fontSize;
10731
10853
  // Same race as the controller branch above: setting fontSize
10732
10854
  // async-invalidates _renderService.dimensions. Commit the cell
10733
10855
  // size synchronously (measure() + atlas clear) so the renderer
10734
10856
  // doesn't paint at a stale cell pitch — the interlace bug.
10735
- this._syncCharSizeThenClearAtlas(session);
10857
+ this._measureCharSize(session);
10736
10858
  }
10737
10859
  if (this.isMobile && session.mobileHandler && session.mobileHandler.hiddenTextarea) {
10738
10860
  session.mobileHandler._focusHiddenTextarea();
@@ -10746,7 +10868,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10746
10868
  if (sftpSession && sftpSession.terminal) {
10747
10869
  if (sftpSession.fontSize) {
10748
10870
  sftpSession.terminal.options.fontSize = sftpSession.fontSize;
10749
- this._syncCharSizeThenClearAtlas(sftpSession);
10871
+ this._measureCharSize(sftpSession);
10750
10872
  }
10751
10873
  }
10752
10874