@lethevimlet/sshift 1.7.8 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.7.8",
3
+ "version": "1.8.0",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -133,7 +133,16 @@ function registerSSHHandlers(socket, io) {
133
133
  cols: state.cols,
134
134
  rows: state.rows,
135
135
  encoded: true,
136
- partial: false
136
+ partial: !!state.partial
137
+ });
138
+ } else if (sshManager.hasSession && sshManager.hasSession(data.sessionId)) {
139
+ // The session exists but its screen could not be serialized right
140
+ // now. That is an operational hiccup, not a dead session — a hard
141
+ // 'Session not found' would make the client treat the tab as gone.
142
+ socket.emit('ssh-error', {
143
+ sessionId: data.sessionId,
144
+ message: 'Screen sync unavailable, please retry',
145
+ advisory: true
137
146
  });
138
147
  } else {
139
148
  socket.emit('ssh-error', { message: 'Session not found', sessionId: data.sessionId });
@@ -1,6 +1,11 @@
1
1
  const { Client } = require('ssh2');
2
2
  const { Terminal } = require('@xterm/headless');
3
3
  const { SerializeAddon } = require('@xterm/addon-serialize');
4
+
5
+ // Screen-sync payload cap (raw, pre-base64) and the scrollback tiers tried
6
+ // when the full history is larger than that. See _serializeForSync().
7
+ const SYNC_FULL_MAX_BYTES = 768 * 1024;
8
+ const SYNC_SCROLLBACK_TIERS = [2000, 500, 100, 0];
4
9
  const { Unicode11Addon } = require('@xterm/addon-unicode11');
5
10
  const pluginManager = require('../plugins/plugin-manager');
6
11
  const { convertKeyIfNeeded } = require('../utils/key-converter');
@@ -359,59 +364,19 @@ class SSHManager {
359
364
  // Send current terminal state to the joining socket BEFORE joining the room
360
365
  // This ensures the client gets the full state before receiving any new data
361
366
  if (session.terminal && session.serializeAddon) {
362
- try {
363
- // Try to serialize full scrollback buffer first (includes all history)
364
- let serializedState = session.serializeAddon.serialize({ mode: 'all' });
365
-
366
- // Validate it's a string
367
- if (typeof serializedState !== 'string') {
368
- serializedState = String(serializedState);
369
- }
370
-
371
- // If full state is too large, fall back to viewport-only
372
- const fullMaxSize = 512 * 1024; // 512KB for full scrollback
373
- const viewportMaxSize = 50 * 1024; // 50KB fallback for viewport only
374
-
375
- if (serializedState.length > fullMaxSize) {
376
- console.warn(`[SSH] Full terminal state too large (${serializedState.length} bytes), falling back to viewport-only`);
377
- serializedState = session.serializeAddon.serialize({ mode: 'normal' });
378
- if (typeof serializedState !== 'string') {
379
- serializedState = String(serializedState);
380
- }
381
-
382
- if (serializedState.length > viewportMaxSize) {
383
- console.warn(`[SSH] Viewport state also too large (${serializedState.length} bytes), skipping sync`);
384
- } else {
385
- // Send viewport-only state
386
- const base64State = Buffer.from(serializedState, 'utf-8').toString('base64');
387
- socket.emit('ssh-screen-sync', {
388
- sessionId: sessionId,
389
- state: base64State,
390
- cols: session.cols,
391
- rows: session.rows,
392
- encoded: true,
393
- partial: true
394
- });
395
- hasTerminalState = true;
396
- }
397
- } else {
398
- // Send full state including scrollback
399
- const base64State = Buffer.from(serializedState, 'utf-8').toString('base64');
400
- console.log(`[SSH] Sending full serialized terminal state to socket ${socket.id}, size: ${serializedState.length}, base64: ${base64State.length}`);
401
-
402
- socket.emit('ssh-screen-sync', {
403
- sessionId: sessionId,
404
- state: base64State,
405
- cols: session.cols,
406
- rows: session.rows,
407
- encoded: true,
408
- partial: false
409
- });
410
-
411
- hasTerminalState = true;
412
- }
413
- } catch (err) {
414
- console.error(`[SSH] Error serializing terminal state:`, err.message);
367
+ const snapshot = this._serializeForSync(session, SYNC_FULL_MAX_BYTES);
368
+ if (snapshot) {
369
+ const base64State = Buffer.from(snapshot.state, 'utf-8').toString('base64');
370
+ console.log(`[SSH] Sending serialized terminal state to socket ${socket.id}, size: ${snapshot.state.length}, base64: ${base64State.length}, scrollback: ${snapshot.scrollbackLines === undefined ? 'full' : snapshot.scrollbackLines}`);
371
+ socket.emit('ssh-screen-sync', {
372
+ sessionId: sessionId,
373
+ state: base64State,
374
+ cols: session.cols,
375
+ rows: session.rows,
376
+ encoded: true,
377
+ partial: snapshot.partial
378
+ });
379
+ hasTerminalState = true;
415
380
  }
416
381
  }
417
382
 
@@ -628,31 +593,58 @@ if (this.io) {
628
593
  if (!session || !session.terminal || !session.serializeAddon) {
629
594
  return null;
630
595
  }
631
-
632
- try {
633
- // Serialize full scrollback buffer to preserve history on reload
634
- let serializedState = session.serializeAddon.serialize({ mode: 'all' });
635
-
636
- // Validate size - allow up to 1MB for manual sync requests
637
- const maxSize = 1024 * 1024; // 1MB max
638
- if (serializedState.length > maxSize) {
639
- console.warn(`[SSH] Terminal state too large (${serializedState.length} bytes), falling back to viewport-only`);
640
- serializedState = session.serializeAddon.serialize({ mode: 'normal' });
641
- if (serializedState.length > maxSize) {
642
- console.warn(`[SSH] Viewport state also too large (${serializedState.length} bytes), returning null`);
643
- return null;
596
+ const snapshot = this._serializeForSync(session, SYNC_FULL_MAX_BYTES);
597
+ if (!snapshot) return null;
598
+ return {
599
+ state: snapshot.state,
600
+ cols: session.cols,
601
+ rows: session.rows,
602
+ partial: snapshot.partial
603
+ };
604
+ }
605
+
606
+ hasSession(sessionId) {
607
+ return this.sessions.has(sessionId);
608
+ }
609
+
610
+ // Serialize a session's screen for a client sync, shrinking the amount
611
+ // of scrollback until the payload fits under `maxBytes`.
612
+ //
613
+ // The old code tried `serialize({ mode: 'normal' })` as a "viewport-only"
614
+ // fallback. `mode` is not a SerializeAddon option — that call returned the
615
+ // exact same full-scrollback payload, so any long-running session whose
616
+ // history serialized above the cap got NO screen state at all: the
617
+ // joining browser saw only the live stream from that point on, and
618
+ // line-diff TUIs (which never repaint rows they consider unchanged) left
619
+ // it with a screen full of black rows until a resize forced a full
620
+ // repaint. That is the "alternating text/black lines when opening a new
621
+ // window" bug.
622
+ //
623
+ // Tiers: full scrollback → recent scrollback → viewport only. The viewport
624
+ // tier is a few KB and is always sent, so a sync can only fail if the
625
+ // serialize addon itself throws.
626
+ _serializeForSync(session, maxBytes) {
627
+ if (!session || !session.terminal || !session.serializeAddon) return null;
628
+ const tiers = [undefined, ...SYNC_SCROLLBACK_TIERS];
629
+ for (const scrollback of tiers) {
630
+ let state;
631
+ try {
632
+ state = scrollback === undefined
633
+ ? session.serializeAddon.serialize()
634
+ : session.serializeAddon.serialize({ scrollback });
635
+ } catch (err) {
636
+ console.error(`[SSH] Error serializing terminal state (scrollback=${scrollback}):`, err.message);
637
+ continue;
638
+ }
639
+ if (typeof state !== 'string') state = String(state);
640
+ if (state.length <= maxBytes || scrollback === 0) {
641
+ if (scrollback !== undefined) {
642
+ console.warn(`[SSH] Terminal state trimmed to ${scrollback} scrollback lines (${state.length} bytes) for sync`);
644
643
  }
644
+ return { state, partial: scrollback !== undefined, scrollbackLines: scrollback };
645
645
  }
646
-
647
- return {
648
- state: serializedState,
649
- cols: session.cols,
650
- rows: session.rows
651
- };
652
- } catch (err) {
653
- console.error(`[SSH] Error getting terminal state:`, err.message);
654
- return null;
655
646
  }
647
+ return null;
656
648
  }
657
649
 
658
650
  // Get ONLY the visible viewport of a session (no scrollback).
@@ -1501,6 +1501,23 @@
1501
1501
  }
1502
1502
  }
1503
1503
 
1504
+ // Normalize Unicode11Addon
1505
+ if (typeof window.Unicode11Addon === 'object' && window.Unicode11Addon !== null) {
1506
+ if (window.Unicode11Addon.Unicode11Addon) {
1507
+ window.Unicode11Addon = window.Unicode11Addon.Unicode11Addon;
1508
+ } else if (window.Unicode11Addon.default) {
1509
+ window.Unicode11Addon = window.Unicode11Addon.default;
1510
+ }
1511
+ } else if (typeof window.Unicode11Addon === 'undefined') {
1512
+ if (typeof Unicode11Addon !== 'undefined') {
1513
+ if (typeof Unicode11Addon === 'object' && Unicode11Addon !== null) {
1514
+ window.Unicode11Addon = Unicode11Addon.Unicode11Addon || Unicode11Addon.default || Unicode11Addon;
1515
+ } else if (typeof Unicode11Addon === 'function') {
1516
+ window.Unicode11Addon = Unicode11Addon;
1517
+ }
1518
+ }
1519
+ }
1520
+
1504
1521
  // Normalize ImageAddon
1505
1522
  if (typeof window.ImageAddon === 'object' && window.ImageAddon !== null) {
1506
1523
  if (window.ImageAddon.ImageAddon) {
@@ -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
1047
+ //
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.
1062
1067
  //
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) {
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}`);
@@ -2877,7 +2901,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
2877
2901
  // cell height and paint interlaced black bands (the "interlace" bug).
2878
2902
  sftpSession.fontSize = Math.max(this.minFontSize, Math.min(this.maxFontSize, newSize));
2879
2903
  sftpSession.terminal.options.fontSize = sftpSession.fontSize;
2880
- this._syncCharSizeThenClearAtlas(sftpSession);
2904
+ this._measureCharSize(sftpSession);
2881
2905
 
2882
2906
  if (sftpSession.fitAddon) {
2883
2907
  this._fitTerminal(sftpSession);
@@ -3339,6 +3363,7 @@ sendChunkedInput(sessionId, data, chunkSize = 2048) {
3339
3363
  // derived from CSS pixels * DPR — a different DPR means every cached
3340
3364
  // glyph is now the wrong size and must be re-rasterised.
3341
3365
  this._setupDPRListener();
3366
+ this._setupFontAtlasListener();
3342
3367
 
3343
3368
  // Load sticky config first
3344
3369
  await this.loadStickyConfig();
@@ -4437,19 +4462,16 @@ const wheelHandler = (e) => {
4437
4462
  console.log('[SSHIFT] Sent mobile key:', keyName, 'sequence:', keySequence);
4438
4463
  }
4439
4464
 
4440
- // Keys-bar keys change the remote line/cursor in ways the hidden
4441
- // textarea cannot model (Tab completes a word, arrows move the
4442
- // cursor mid-line, Ctrl+C/U/D abort or clear the line, Esc aborts).
4443
- // The textarea diff assumes the remote cursor sits at the END of
4444
- // the sent baseline — that model is dead now. Reset the field and
4445
- // baseline so typing continues from a clean slate: new input
4446
- // appends at the remote cursor position, exactly like a real
4447
- // keyboard. _resetInputTracking is composition-guarded, so an
4448
- // in-flight Gboard composition is not corrupted mid-word (the
4449
- // reset is deferred to compositionend).
4450
- if (this.isMobile && session.mobileHandler && session.mobileHandler.hiddenTextarea) {
4451
- session.mobileHandler._resetInputTracking();
4452
- }
4465
+ // NOTE: do NOT reset the mobile handler's input tracking here.
4466
+ // v1.7.8 did (to drop the textarea's stale model of the remote line
4467
+ // after Tab/arrows/Ctrl+C) and it reintroduced the Gboard duplication
4468
+ // family, WORSE: the keys-bar taps don't blur the hidden textarea, so
4469
+ // the clear happened under a LIVE IME session — invisible to Gboard,
4470
+ // whose stale field model then re-inserted text ("characters go
4471
+ // crazy"). With an active composition the deferred reset even
4472
+ // discarded the in-flight word. The staleness after line-clearing
4473
+ // keys is minor and mostly invisible (typing still appends at the
4474
+ // remote cursor); the reset was far worse.
4453
4475
 
4454
4476
  // Focus terminal after sending key
4455
4477
  if (this.isMobile && session.mobileHandler && session.mobileHandler.hiddenTextarea) {
@@ -4793,6 +4815,7 @@ const wheelHandler = (e) => {
4793
4815
  // Drain it or it stays stuck (permanently missing rows in
4794
4816
  // line-diff TUI screens — the stale/black-line bug).
4795
4817
  this._drainSyncBuffer(session);
4818
+ this._runDeferredFit(session);
4796
4819
  }
4797
4820
 
4798
4821
  // Handle controller status
@@ -4864,6 +4887,14 @@ const wheelHandler = (e) => {
4864
4887
  session.flushRemaining = null;
4865
4888
  // Fresh buffer for live data arriving while the sync state is written
4866
4889
  session.syncBuffer = [];
4890
+ // A partial OSC 52 / DCS sequence stashed before the reset must
4891
+ // NOT survive into the post-sync stream: it was captured against
4892
+ // the pre-reset state, and _handleOsc52 would prepend it to the
4893
+ // next flush — the parser then eats real output into a bogus
4894
+ // clipboard sequence (garbled/missing characters right after
4895
+ // take-control / tab-switch syncs). It is already consumed
4896
+ // server-side (contained in the serialized state) — drop it.
4897
+ session.pendingOsc52 = null;
4867
4898
 
4868
4899
  // Clear the terminal completely before applying the serialized state
4869
4900
  // Use reset() to clear both the buffer and the scrollback
@@ -4887,6 +4918,32 @@ const wheelHandler = (e) => {
4887
4918
  }
4888
4919
  }
4889
4920
 
4921
+ // Bring the terminal to the server's geometry BEFORE replaying the
4922
+ // state. The serialized screen was produced for exactly
4923
+ // data.cols x data.rows. Replaying it into a terminal of a different
4924
+ // width wraps every full-width row: full-screen TUIs (alternate
4925
+ // buffer) end up with one text row followed by one overflow row —
4926
+ // the "alternating black line" pattern — and a later resize() does
4927
+ // NOT undo that, because xterm never reflows the alternate buffer.
4928
+ // (Previously the resize ran AFTER the write, into whatever size the
4929
+ // freshly created terminal happened to have, usually 80x24.)
4930
+ if (data.cols && data.rows &&
4931
+ (session.terminal.cols !== data.cols || session.terminal.rows !== data.rows)) {
4932
+ try {
4933
+ // isResyncing suppresses the onResize → ssh-resize echo for
4934
+ // this server-driven resize (it would otherwise bounce the
4935
+ // server's own size back at it).
4936
+ session.isResyncing = true;
4937
+ session.terminal.resize(data.cols, data.rows);
4938
+ session.remoteCols = data.cols;
4939
+ session.remoteRows = data.rows;
4940
+ console.log('[SSHIFT] Terminal resized to server dimensions before sync write:', data.cols, 'x', data.rows);
4941
+ } catch (e) {
4942
+ console.warn('[SSHIFT] Error resizing terminal for sync:', e.message);
4943
+ }
4944
+ session.isResyncing = false;
4945
+ }
4946
+
4890
4947
  // Write the serialized terminal state
4891
4948
  // This includes all escape sequences to reconstruct the screen
4892
4949
  session.terminal.write(state, () => {
@@ -4910,44 +4967,21 @@ const wheelHandler = (e) => {
4910
4967
  if (!data.partial) {
4911
4968
  session.terminal.scrollToBottom();
4912
4969
  }
4913
-
4914
- // Resize terminal to match the session's dimensions if provided
4915
- // Note: We do NOT call fit() here because:
4916
- // 1. This client is joining an existing session and is not the controller
4917
- // 2. The controller determines the terminal dimensions
4918
- // 3. fit() would recalculate dimensions for the local container
4919
- // 4. This can cause resize feedback loops between clients
4920
- if (data.cols && data.rows) {
4921
- try {
4922
- // Set resyncing flag BEFORE calling resize to prevent resize feedback loop
4923
- session.isResyncing = true;
4924
-
4925
- session.terminal.resize(data.cols, data.rows);
4926
- console.log('[SSHIFT] Terminal resized to match server dimensions:', data.cols, 'x', data.rows);
4927
-
4928
- // The serialized state was just written into a fresh
4929
- // buffer + the terminal was just resized. The WebGL
4930
- // renderer's glyph atlas still holds glyphs rasterised
4931
- // at the pre-resize cell size — painting them now would
4932
- // produce the "interlaced / every-other-row blank" bug
4933
- // (visible after "Take Control" on a just-refreshed
4934
- // browser tab; fixed when the user manually resizes the
4935
- // window because that re-runs the renderer resize path).
4936
- // Note: when the terminal is ALREADY at data.cols/rows the
4937
- // resize() above short-circuits inside xterm.js, so a plain
4938
- // atlas clear is not enough — force the full renderer
4939
- // dimension recompute (same path as a real resize) so the
4940
- // device cell pitch is recomputed and the atlas rebuilt.
4941
- this._forceRendererDimensionRecompute(session);
4942
-
4943
- // Clear the resyncing flag after a short delay
4944
- setTimeout(() => {
4945
- session.isResyncing = false;
4946
- }, 150);
4947
- } catch (e) {
4948
- console.warn('[SSHIFT] Error resizing terminal:', e.message);
4949
- session.isResyncing = false;
4950
- }
4970
+
4971
+ // Plain full repaint from the freshly restored buffer.
4972
+ this._repaintTerminal(session);
4973
+
4974
+ // Only the controller may change the session's geometry. Now that
4975
+ // the server's screen is in place, re-fit it to OUR container:
4976
+ // if the local size differs, fit() resizes the terminal and the
4977
+ // onResize handler pushes the new size to the PTY, so the remote
4978
+ // program repaints at the new size (the local buffer is reflowed
4979
+ // meanwhile). Observers keep the server's geometry.
4980
+ // Fits requested while the sync was in flight were deferred by
4981
+ // _fitTerminal (needsResize) — this is where they land.
4982
+ if (session.isController && session.fitAddon) {
4983
+ session.needsResize = false;
4984
+ this._fitTerminal(session);
4951
4985
  }
4952
4986
 
4953
4987
  // Focus the terminal
@@ -4996,7 +5030,7 @@ const wheelHandler = (e) => {
4996
5030
  // cell pitch — repaint at the stale pitch produces the interlace
4997
5031
  // "black band" artefact (same family as the screen-sync path).
4998
5032
  // Force the full renderer dimension recompute + atlas rebuild.
4999
- this._forceRendererDimensionRecompute(session);
5033
+ this._repaintTerminal(session);
5000
5034
  console.log('[SSHIFT] Terminal resized to match server dimensions');
5001
5035
 
5002
5036
  // Clear the syncing flag after a delay to ensure resize events settle
@@ -5240,6 +5274,7 @@ const wheelHandler = (e) => {
5240
5274
  // Don't lose live output that was buffered while waiting for a sync
5241
5275
  // that never arrived.
5242
5276
  this._drainSyncBuffer(session);
5277
+ this._runDeferredFit(session);
5243
5278
  if (session._syncRetries < 2 && session.connected) {
5244
5279
  session._syncRetries += 1;
5245
5280
  // Re-arm by calling ourselves once more. We pass a flag via the
@@ -8246,6 +8281,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8246
8281
  console.warn('[SSHIFT] Sync timeout for session:', restoreSessionId, 'retries:', session._syncRetries);
8247
8282
  session.syncing = false;
8248
8283
  this._drainSyncBuffer(session);
8284
+ this._runDeferredFit(session);
8249
8285
  if (session._syncRetries < 2 && session.connected) {
8250
8286
  session._syncRetries += 1;
8251
8287
  this.requestScreenSync(restoreSessionId);
@@ -8695,6 +8731,17 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8695
8731
  container.innerHTML = '';
8696
8732
 
8697
8733
  terminal.open(container);
8734
+
8735
+ // Attach the terminal + fit addon to the session NOW, before any
8736
+ // helper that takes `session` runs. _initWebGLAddon() (and every
8737
+ // other helper) bails out silently when `session.terminal` is null,
8738
+ // and the assignment used to live at the very end of initTerminal —
8739
+ // so the WebGL renderer was never loaded at creation time. Terminals
8740
+ // silently ran on the DOM renderer until a visibilitychange handler
8741
+ // happened to call _initWebGLAddon() much later, which is why the
8742
+ // WebGL-only artefacts were intermittent.
8743
+ session.terminal = terminal;
8744
+ session.fitAddon = fitAddon;
8698
8745
 
8699
8746
  // Initialise the WebGL renderer only if the wrapper is currently
8700
8747
  // visible. Loading WebGL on a hidden (display:none) terminal
@@ -8761,7 +8808,12 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8761
8808
  // Also register as fallback with xterm.js's OSC handler in case any
8762
8809
  // OSC 52 sequences slip through the data stream interceptor (e.g. from
8763
8810
  // screen sync restoration). The data stream interceptor is the primary handler.
8764
- terminal.registerOscHandler(52, (data) => {
8811
+ // xterm.js v5+/v6 exposes the OSC registration on terminal.parser
8812
+ // (terminal.registerOscHandler no longer exists).
8813
+ const oscRegistrar = (terminal.parser && typeof terminal.parser.registerOscHandler === 'function')
8814
+ ? terminal.parser
8815
+ : terminal;
8816
+ oscRegistrar.registerOscHandler(52, (data) => {
8765
8817
  console.log('[SSHIFT] OSC 52 handler fallback triggered (should be handled by stream interceptor)');
8766
8818
  const semicolonIndex = data.indexOf(';');
8767
8819
  if (semicolonIndex === -1) return true;
@@ -8823,11 +8875,8 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
8823
8875
  try { core._charSizeService.measure(); } catch (_) {}
8824
8876
  }
8825
8877
 
8826
- // Clear the WebGL texture atlas after the font swap — glyphs cached
8827
- // before the swap were rasterised at the fallback font's metrics.
8828
- if (session.webglAddon) {
8829
- try { session.webglAddon.clearTextureAtlas(); } catch (_) {}
8830
- }
8878
+ // (The shared WebGL glyph atlas is rebuilt for ALL terminals by
8879
+ // _setupFontAtlasListener once fonts are ready — never per-terminal.)
8831
8880
 
8832
8881
  // Also check if WebGL init was deferred due to hidden wrapper
8833
8882
  // (Bug 3) — the terminal may now be visible.
@@ -9778,29 +9827,23 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9778
9827
  // Full-viewport repaint shortly after an output burst settles.
9779
9828
  //
9780
9829
  // Under heavy output floods (TUI streaming + per-line scrollback trims
9781
- // while throttled + 32KB/frame capped writes) the WebGL renderer can
9782
- // miss dirty-row updates: some rows keep showing STALE content (old
9783
- // backgrounds / leftover fragments) even though the terminal BUFFER is
9784
- // correct. Line-diff TUI renderers (OpenCode, Bubble Tea apps, ...)
9785
- // never rewrite lines they consider unchanged, so those stale rows then
9786
- // persist indefinitely — visible as "interlaced black lines between
9787
- // text lines" where the app's painted background alternates with the
9788
- // terminal's default background. A font-size change or window resize
9789
- // "fixed" it because both force a full re-render from the buffer.
9830
+ // while throttled + 32KB/frame capped writes) the renderer can miss
9831
+ // dirty-row updates: some rows keep showing STALE content even though
9832
+ // the terminal BUFFER is correct. Line-diff TUI renderers (OpenCode,
9833
+ // Bubble Tea apps, ...) never rewrite lines they consider unchanged, so
9834
+ // those stale rows would persist until something forced a full
9835
+ // re-render from the buffer.
9790
9836
  //
9791
9837
  // This debounced refresh(0, rows-1) after the LAST write of a burst
9792
- // provides that same guarantee automatically: within ~350ms of any
9793
- // burst ending, every row is re-rendered from the (correct) buffer.
9794
- // Cost: one extra full-viewport render per burst — negligible.
9838
+ // guarantees that within ~350ms of any burst ending every row is
9839
+ // re-rendered from the (correct) buffer. A 2s max-wait repaint covers
9840
+ // continuous floods where the trailing debounce never fires.
9795
9841
  //
9796
- // Two hardening additions for the two remaining holes:
9797
- // 1. The trailing debounce above NEVER fires while output is continuous
9798
- // (each write postpones it). A 2s max-wait repaint runs even mid-flood.
9799
- // 2. A plain refresh() repaints at the CURRENT (possibly stale) device
9800
- // cell pitch — it cannot heal a renderer dimension desync. The
9801
- // max-wait repaint uses _forceRendererDimensionRecompute (the exact
9802
- // path a real window resize triggers), which heals BOTH missed
9803
- // dirty rows AND pitch mismatches.
9842
+ // Both are PLAIN repaints (_repaintTerminal). They must never resize the
9843
+ // canvas or clear the WebGL glyph atlas: the atlas is shared between all
9844
+ // terminals, so clearing it here after every keystroke echo corrupted
9845
+ // every other terminal's glyphs (scattered dots/commas) and re-sizing the
9846
+ // canvas blanked it for a frame (flicker while typing).
9804
9847
  _scheduleSettleRefresh(session) {
9805
9848
  if (!session || !session.terminal) return;
9806
9849
  if (session.settleRefreshTimer) {
@@ -9812,24 +9855,33 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
9812
9855
  clearTimeout(session.settleRefreshMaxTimer);
9813
9856
  session.settleRefreshMaxTimer = null;
9814
9857
  }
9815
- const term = session.terminal;
9816
- if (!term) return;
9817
- try { term.refresh(0, term.rows - 1); } catch (_) {}
9858
+ if (!session.terminal) return;
9859
+ if (session.syncing) return; // sync completion does its own repaint
9860
+ this._repaintTerminal(session);
9818
9861
  }, 350);
9819
9862
 
9820
- // Safety net for continuous floods: guarantee a full dimension-
9821
- // recompute repaint at least every 2s while writes keep arriving,
9822
- // otherwise the trailing refresh above is postponed indefinitely.
9863
+ // Safety net for continuous floods: guarantee a full repaint at least
9864
+ // every 2s while writes keep arriving, otherwise the trailing refresh
9865
+ // above is postponed indefinitely.
9823
9866
  if (!session.settleRefreshMaxTimer) {
9824
- session.settleRefreshMaxTimer = setTimeout(() => {
9867
+ const runMaxWait = () => {
9825
9868
  session.settleRefreshMaxTimer = null;
9826
9869
  if (!session.terminal) return;
9870
+ // Never repaint mid-screen-sync: the serialized state is still
9871
+ // being parsed (terminal.reset() has run but the write hasn't
9872
+ // completed), so a full repaint now would paint a half-applied
9873
+ // state. Retry later.
9874
+ if (session.syncing) {
9875
+ session.settleRefreshMaxTimer = setTimeout(runMaxWait, 2000);
9876
+ return;
9877
+ }
9827
9878
  if (session.settleRefreshTimer) {
9828
9879
  clearTimeout(session.settleRefreshTimer);
9829
9880
  session.settleRefreshTimer = null;
9830
9881
  }
9831
- this._forceRendererDimensionRecompute(session);
9832
- }, 2000);
9882
+ this._repaintTerminal(session);
9883
+ };
9884
+ session.settleRefreshMaxTimer = setTimeout(runMaxWait, 2000);
9833
9885
  }
9834
9886
  }
9835
9887
 
@@ -10622,7 +10674,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10622
10674
  // While display:none, the terminal canvas has zero dimensions and
10623
10675
  // any cached glyphs are rendered at wrong colours/sizes (Bug 3).
10624
10676
  // Clearing + refreshing forces a clean redraw at the correct size.
10625
- this._resetWebGLAtlas(session);
10677
+ this._repaintTerminal(session);
10626
10678
 
10627
10679
  // Restore font size for this session. Setting fontSize async-
10628
10680
  // invalidates _renderService.dimensions; we must commit the new
@@ -10632,7 +10684,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10632
10684
  // (the "interlace" bug — see _syncCharSizeThenClearAtlas).
10633
10685
  if (session.fontSize && session.terminal) {
10634
10686
  session.terminal.options.fontSize = session.fontSize;
10635
- this._syncCharSizeThenClearAtlas(session);
10687
+ this._measureCharSize(session);
10636
10688
  console.log('[SSHIFT] Restored font size', session.fontSize, 'for session', sessionId);
10637
10689
  }
10638
10690
 
@@ -10701,14 +10753,14 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10701
10753
  } else if (session && session.terminal) {
10702
10754
  // For non-controllers, just focus the terminal and restore font size.
10703
10755
  // Also clear the WebGL atlas since this tab was hidden.
10704
- this._resetWebGLAtlas(session);
10756
+ this._repaintTerminal(session);
10705
10757
  if (session.fontSize) {
10706
10758
  session.terminal.options.fontSize = session.fontSize;
10707
10759
  // Same race as the controller branch above: setting fontSize
10708
10760
  // async-invalidates _renderService.dimensions. Commit the cell
10709
10761
  // size synchronously (measure() + atlas clear) so the renderer
10710
10762
  // doesn't paint at a stale cell pitch — the interlace bug.
10711
- this._syncCharSizeThenClearAtlas(session);
10763
+ this._measureCharSize(session);
10712
10764
  }
10713
10765
  if (this.isMobile && session.mobileHandler && session.mobileHandler.hiddenTextarea) {
10714
10766
  session.mobileHandler._focusHiddenTextarea();
@@ -10722,7 +10774,7 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10722
10774
  if (sftpSession && sftpSession.terminal) {
10723
10775
  if (sftpSession.fontSize) {
10724
10776
  sftpSession.terminal.options.fontSize = sftpSession.fontSize;
10725
- this._syncCharSizeThenClearAtlas(sftpSession);
10777
+ this._measureCharSize(sftpSession);
10726
10778
  }
10727
10779
  }
10728
10780
 
@@ -524,9 +524,17 @@ class MobileTerminalHandler {
524
524
  }
525
525
 
526
526
  if (e.key === 'Enter') {
527
- e.preventDefault();
528
- this._sendToTerminal('\r');
529
- this._resetInputTracking();
527
+ // Let the browser insert the newline into the textarea. The input
528
+ // diff (_syncTextareaToTerminal) translates it to \r and KEEPS the
529
+ // submitted text in the field. Clearing the field here (the old
530
+ // behaviour) was a programmatic edit that Gboard never sees: its
531
+ // own model of the field still held the previous sentence, and the
532
+ // next suggestion tap re-committed "old sentence + new word" —
533
+ // which the diff then faithfully re-typed into the terminal
534
+ // (the "autocomplete repeats previous sentences" bug). The field
535
+ // is only cleared when the keyboard is collapsed (textarea blurred),
536
+ // at which point the IME session is torn down anyway.
537
+ return;
530
538
  } else if (e.key === 'Backspace') {
531
539
  // Let the browser handle backspace in the textarea; the input diff
532
540
  // will detect the deletion and send \x7f to the terminal.
@@ -538,7 +546,7 @@ class MobileTerminalHandler {
538
546
  } else if (e.key === 'Tab') {
539
547
  e.preventDefault();
540
548
  this._sendToTerminal('\t');
541
- this._resetInputTracking();
549
+ // No tracking reset: see the Enter comment above.
542
550
  }
543
551
  });
544
552
 
@@ -652,9 +660,17 @@ class MobileTerminalHandler {
652
660
  }
653
661
  }
654
662
 
655
- // Erase back to the divergence point. Count code points (not UTF-16
656
- // units) so astral characters (emoji etc.) get one DEL each.
657
- const removed = prev.substring(prefixLen);
663
+ // The field accumulates every submitted line (separated by \n — see
664
+ // the Enter keydown comment). Lines above the current one were already
665
+ // submitted and cannot be edited any more, so a divergence before the
666
+ // current line's start must never turn into DELs (in a multi-line TUI
667
+ // editor a DEL at column 0 joins lines).
668
+ const lineStart = prev.lastIndexOf('\n') + 1;
669
+
670
+ // Erase back to the divergence point (clamped to the current line).
671
+ // Count code points (not UTF-16 units) so astral characters (emoji
672
+ // etc.) get one DEL each.
673
+ const removed = prev.substring(Math.max(prefixLen, lineStart));
658
674
  const deleteCount = removed ? Array.from(removed).length : 0;
659
675
 
660
676
  // Retype the remainder. Translate newlines (some keyboards commit
@@ -672,13 +688,9 @@ class MobileTerminalHandler {
672
688
  this._sendToTerminal(insert);
673
689
  }
674
690
 
675
- if (hadNewline) {
676
- // The line was submitted — start from a clean slate (mirrors the
677
- // Enter keydown path).
678
- this._resetInputTracking();
679
- } else {
680
- this._sentValue = curr;
681
- }
691
+ // Keep the submitted text (including the newline) as the baseline —
692
+ // never clear the field while the IME may still be tracking it.
693
+ this._sentValue = curr;
682
694
  }
683
695
 
684
696
  /**
@@ -1596,6 +1608,13 @@ class MobileTerminalHandler {
1596
1608
  this.hiddenTextarea.blur();
1597
1609
  // Restore readonly to prevent keyboard on any accidental focus
1598
1610
  this.hiddenTextarea.setAttribute('readonly', 'true');
1611
+ // The blur tore down the IME session, so this is the one place a
1612
+ // programmatic clear cannot desync Gboard's field model. Drop the
1613
+ // accumulated (already submitted) text so the field doesn't grow
1614
+ // for the whole session. Blur also ends any composition.
1615
+ this._isComposing = false;
1616
+ this._pendingTrackingReset = false;
1617
+ this._resetInputTracking();
1599
1618
  // Also blur any active element that might have focus
1600
1619
  if (document.activeElement && document.activeElement !== document.body) {
1601
1620
  document.activeElement.blur();