@lethevimlet/sshift 1.9.8 → 1.9.9

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.
@@ -351,7 +351,29 @@ class MobileTerminalHandler {
351
351
  this.touchState.isSelecting = true;
352
352
  this.touchState.isDragging = true;
353
353
  this.touchState.dragHandle = type;
354
+ // The container never sees this touchstart (stopPropagation), so
355
+ // reset the gesture flags of the long press that made the selection
356
+ // here; otherwise a cancelled drag left isDragging stuck (see the
357
+ // touchcancel listener below).
358
+ this.touchState.isLongPress = false;
359
+ this.touchState.gestureHandled = false;
354
360
  handle.classList.add('active');
361
+
362
+ // The handle hangs below the text and the finger lands on the
363
+ // handle, not on the character. Remember how far the finger is from
364
+ // the middle of the selected cell, so a sideways drag stays on the
365
+ // same row instead of jumping to the row under the handle.
366
+ this._dragGrabOffset = { x: 0, y: 0 };
367
+ const touch = e.touches && e.touches[0];
368
+ const anchor = type === 'start' ? this.selection.start : this.selection.end;
369
+ const cell = anchor ? this._terminalToScreenCoords(anchor.x, anchor.y) : null;
370
+ const containerRect = this.container.getBoundingClientRect();
371
+ if (touch && cell) {
372
+ this._dragGrabOffset = {
373
+ x: touch.clientX - (containerRect.left + cell.x + cell.width / 2),
374
+ y: touch.clientY - (containerRect.top + cell.y + cell.height / 2)
375
+ };
376
+ }
355
377
  }, { passive: false });
356
378
 
357
379
  handle.addEventListener('touchmove', (e) => {
@@ -359,7 +381,8 @@ class MobileTerminalHandler {
359
381
  e.preventDefault();
360
382
 
361
383
  const touch = e.touches[0];
362
- const coords = this._screenToTerminalCoords(touch.clientX, touch.clientY);
384
+ const off = this._dragGrabOffset || { x: 0, y: 0 };
385
+ const coords = this._screenToTerminalCoords(touch.clientX - off.x, touch.clientY - off.y);
363
386
 
364
387
  if (coords) {
365
388
  if (type === 'start') {
@@ -372,8 +395,8 @@ class MobileTerminalHandler {
372
395
  }
373
396
  }, { passive: false });
374
397
 
375
- handle.addEventListener('touchend', (e) => {
376
- e.preventDefault();
398
+ const endDrag = (e) => {
399
+ if (e.cancelable) e.preventDefault();
377
400
  e.stopPropagation();
378
401
  this.touchState.isDragging = false;
379
402
  this.touchState.dragHandle = null;
@@ -383,7 +406,10 @@ class MobileTerminalHandler {
383
406
  if (this.selection.active) {
384
407
  this._positionContextMenu();
385
408
  }
386
- }, { passive: false });
409
+ };
410
+ handle.addEventListener('touchend', endDrag, { passive: false });
411
+ // The OS can cancel a touch (notification shade, back gesture, call).
412
+ handle.addEventListener('touchcancel', endDrag, { passive: false });
387
413
  }
388
414
 
389
415
  /**
@@ -455,12 +481,14 @@ class MobileTerminalHandler {
455
481
  }, { passive: true });
456
482
  });
457
483
 
458
- // Close menu on outside click
459
- document.addEventListener('click', (e) => {
460
- if (!this.contextMenu.contains(e.target)) {
461
- this.hideContextMenu();
462
- }
463
- });
484
+ // Close menu on outside click. Ignore the click a browser may still
485
+ // synthesize from the gesture that opened the menu.
486
+ this._boundDocumentClick = (e) => {
487
+ if (!this.contextMenu || this.contextMenu.contains(e.target)) return;
488
+ if (this._menuShownAt && Date.now() - this._menuShownAt < 400) return;
489
+ this.hideContextMenu();
490
+ };
491
+ document.addEventListener('click', this._boundDocumentClick);
464
492
  }
465
493
 
466
494
  /**
@@ -492,7 +520,11 @@ class MobileTerminalHandler {
492
520
  dragHandle.style.cursor = 'grabbing';
493
521
  }, { passive: false });
494
522
 
495
- document.addEventListener('touchmove', (e) => {
523
+ // Touch events keep targeting the element the touch started on, so
524
+ // the move/end listeners live on the drag handle itself (they used to
525
+ // be added to document per handler and were never removed, keeping
526
+ // every closed tab's handler and terminal alive).
527
+ dragHandle.addEventListener('touchmove', (e) => {
496
528
  if (!isDragging) return;
497
529
 
498
530
  const touch = e.touches[0];
@@ -514,12 +546,14 @@ class MobileTerminalHandler {
514
546
  this.contextMenuUserPositioned = true;
515
547
  }, { passive: true });
516
548
 
517
- document.addEventListener('touchend', () => {
549
+ const endMenuDrag = () => {
518
550
  if (isDragging) {
519
551
  isDragging = false;
520
552
  dragHandle.style.cursor = 'grab';
521
553
  }
522
- });
554
+ };
555
+ dragHandle.addEventListener('touchend', endMenuDrag);
556
+ dragHandle.addEventListener('touchcancel', endMenuDrag);
523
557
  }
524
558
 
525
559
  /**
@@ -1048,14 +1082,37 @@ class MobileTerminalHandler {
1048
1082
  // Terminal resize events - refresh selection overlay when dimensions change
1049
1083
  if (this.terminal && this.terminal.onResize) {
1050
1084
  this._resizeDisposable = this.terminal.onResize(() => {
1085
+ // A width change reflows the buffer (long lines wrap differently,
1086
+ // rows shift): move the selection with its text before redrawing.
1087
+ if (this.selection.active) this._remapSelectionAfterReflow();
1051
1088
  requestAnimationFrame(() => {
1052
1089
  if (this.selection.active) {
1053
1090
  this._updateSelection();
1091
+ this._revealSelection();
1054
1092
  }
1055
1093
  });
1056
1094
  });
1057
1095
  }
1058
1096
 
1097
+ // Output keeps arriving while text is selected. When the scrollback is
1098
+ // full, every new line drops the oldest one and shifts all buffer rows
1099
+ // up: follow the selected text through its markers. A switch to the
1100
+ // alternate screen (vim, less, a TUI) leaves nothing to point at.
1101
+ if (this.terminal && typeof this.terminal.onWriteParsed === 'function') {
1102
+ this._writeParsedDisposable = this.terminal.onWriteParsed(() => {
1103
+ if (!this.selection.active || !this._selAnchor || this._selFollowRAF) return;
1104
+ this._selFollowRAF = requestAnimationFrame(() => {
1105
+ this._selFollowRAF = null;
1106
+ if (!this._destroyed) this._followSelectionAnchor();
1107
+ });
1108
+ });
1109
+ }
1110
+ if (this.terminal && this.terminal.buffer && typeof this.terminal.buffer.onBufferChange === 'function') {
1111
+ this._bufferChangeDisposable = this.terminal.buffer.onBufferChange(() => {
1112
+ if (this.selection.active) this.clearSelection();
1113
+ });
1114
+ }
1115
+
1059
1116
  // Listen for native scroll on .xterm-viewport element
1060
1117
  const viewportEl = this.terminal.element
1061
1118
  ? this.terminal.element.querySelector('.xterm-viewport')
@@ -1083,6 +1140,29 @@ class MobileTerminalHandler {
1083
1140
  * Detach all event listeners
1084
1141
  */
1085
1142
  destroy() {
1143
+ // Queued frame callbacks / timers check this and do nothing.
1144
+ this._destroyed = true;
1145
+ for (const key of ['_writeParsedDisposable', '_bufferChangeDisposable']) {
1146
+ if (this[key]) {
1147
+ try { this[key].dispose(); } catch (_) {}
1148
+ this[key] = null;
1149
+ }
1150
+ }
1151
+ if (this._selFollowRAF) {
1152
+ cancelAnimationFrame(this._selFollowRAF);
1153
+ this._selFollowRAF = null;
1154
+ }
1155
+ if (this.touchState && this.touchState.longPressTimer) {
1156
+ clearTimeout(this.touchState.longPressTimer);
1157
+ this.touchState.longPressTimer = null;
1158
+ }
1159
+ if (this._selectionUpdateRAF) {
1160
+ cancelAnimationFrame(this._selectionUpdateRAF);
1161
+ this._selectionUpdateRAF = null;
1162
+ }
1163
+ this._stopScrollTracking();
1164
+ if (this.selection) this.selection.active = false;
1165
+ this._disposeSelectionAnchor();
1086
1166
  this._releaseTerminalFocus();
1087
1167
  if (this._deferredSyncTimer) {
1088
1168
  clearTimeout(this._deferredSyncTimer);
@@ -1104,6 +1184,10 @@ class MobileTerminalHandler {
1104
1184
  }
1105
1185
 
1106
1186
  document.removeEventListener('keydown', this._boundHandleKeyDown);
1187
+ if (this._boundDocumentClick) {
1188
+ document.removeEventListener('click', this._boundDocumentClick);
1189
+ this._boundDocumentClick = null;
1190
+ }
1107
1191
 
1108
1192
  // Dispose terminal resize listener
1109
1193
  if (this._resizeDisposable) {
@@ -1158,6 +1242,19 @@ class MobileTerminalHandler {
1158
1242
  _handleTouchStart(e) {
1159
1243
  // Ignore if not on mobile or if dragging a handle
1160
1244
  if (!this.app.isMobile || this.touchState.isDragging) return;
1245
+
1246
+ // A second finger (pinch zoom) is never a tap, double tap or long press.
1247
+ if (e.touches && e.touches.length > 1) {
1248
+ if (this.touchState.longPressTimer) {
1249
+ clearTimeout(this.touchState.longPressTimer);
1250
+ this.touchState.longPressTimer = null;
1251
+ }
1252
+ this.touchState.multiTouch = true;
1253
+ this.touchState.isSelecting = false;
1254
+ this.touchState.lastTapTime = 0;
1255
+ return;
1256
+ }
1257
+ this.touchState.multiTouch = false;
1161
1258
 
1162
1259
  // Set selecting mode immediately to prevent keyboard from appearing
1163
1260
  // during long press detection. This will be reset in touchEnd if it's
@@ -1185,21 +1282,27 @@ class MobileTerminalHandler {
1185
1282
 
1186
1283
  // Check for double-tap
1187
1284
  const timeSinceLastTap = now - this.touchState.lastTapTime;
1285
+ this.touchState.gestureHandled = false;
1188
1286
  if (timeSinceLastTap < this.config.doubleTapDelay) {
1189
1287
  // Double-tap detected - select line
1190
1288
  e.preventDefault();
1191
1289
  this._handleDoubleTap(touch);
1192
1290
  this.touchState.lastTapTime = 0;
1291
+ // The touchend of this same tap must not be treated as a new tap
1292
+ // (which clears the selection it just made — the v1.8.2 regression).
1293
+ this.touchState.gestureHandled = true;
1193
1294
  return;
1194
1295
  }
1195
1296
 
1196
1297
  // Start long-press timer
1298
+ if (this.touchState.longPressTimer) clearTimeout(this.touchState.longPressTimer);
1197
1299
  this.touchState.longPressTimer = setTimeout(() => {
1300
+ this.touchState.longPressTimer = null;
1198
1301
  this.touchState.isLongPress = true;
1199
1302
  this._handleLongPress(touch);
1200
1303
  }, this.config.longPressDelay);
1201
-
1202
- this.touchState.lastTapTime = now;
1304
+ // lastTapTime is set in touchend, and only for real taps: two quick
1305
+ // scroll flicks used to count as a double tap and select a line.
1203
1306
  }
1204
1307
 
1205
1308
  /**
@@ -1228,7 +1331,11 @@ class MobileTerminalHandler {
1228
1331
  if (this.selection.active && this.touchState.isDragging) {
1229
1332
  e.preventDefault();
1230
1333
  const touch = e.touches[0];
1231
- const coords = this._screenToTerminalCoords(touch.clientX, touch.clientY);
1334
+ // Same grab offset as the handle's own touchmove (the event bubbles
1335
+ // here from the handle; without it this handler overwrote the
1336
+ // corrected position with the row under the finger).
1337
+ const off = this._dragGrabOffset || { x: 0, y: 0 };
1338
+ const coords = this._screenToTerminalCoords(touch.clientX - off.x, touch.clientY - off.y);
1232
1339
 
1233
1340
  if (coords) {
1234
1341
  if (this.touchState.dragHandle === 'start') {
@@ -1247,6 +1354,18 @@ class MobileTerminalHandler {
1247
1354
  */
1248
1355
  _handleTouchEnd(e) {
1249
1356
  if (!this.app.isMobile) return;
1357
+
1358
+ // Pinch: wait for the last finger, and never treat it as a tap.
1359
+ if (e && e.touches && e.touches.length > 0) return;
1360
+ if (this.touchState.multiTouch) {
1361
+ this.touchState.multiTouch = false;
1362
+ this.touchState.isSelecting = false;
1363
+ if (this.touchState.longPressTimer) {
1364
+ clearTimeout(this.touchState.longPressTimer);
1365
+ this.touchState.longPressTimer = null;
1366
+ }
1367
+ return;
1368
+ }
1250
1369
 
1251
1370
  // Clear long-press timer
1252
1371
  if (this.touchState.longPressTimer) {
@@ -1254,8 +1373,15 @@ class MobileTerminalHandler {
1254
1373
  this.touchState.longPressTimer = null;
1255
1374
  }
1256
1375
 
1257
- // If it was a long-press, don't do anything else
1258
- if (this.touchState.isLongPress) {
1376
+ // A long press or double tap already did its job (selected text,
1377
+ // opened the menu). Swallow the touchend so the browser does not
1378
+ // synthesize mousedown/click from it: that click reached the
1379
+ // document-level "click outside closes the menu" listener and hid
1380
+ // the copy/paste menu the gesture had just opened, and a tap-style
1381
+ // touchend cleared the double-tap line selection.
1382
+ if (this.touchState.isLongPress || this.touchState.gestureHandled) {
1383
+ this.touchState.gestureHandled = false;
1384
+ if (e && e.cancelable) e.preventDefault();
1259
1385
  return;
1260
1386
  }
1261
1387
 
@@ -1282,6 +1408,9 @@ class MobileTerminalHandler {
1282
1408
  if (Math.sqrt(dx * dx + dy * dy) > 10) return;
1283
1409
  }
1284
1410
 
1411
+ // A real tap: remembered for double-tap detection (start-to-start).
1412
+ this.touchState.lastTapTime = this.touchState.startTime;
1413
+
1285
1414
  // Tap: clear the selection if there is one, otherwise focus for input.
1286
1415
  if (this.selection.active) {
1287
1416
  this.clearSelection();
@@ -1296,7 +1425,10 @@ class MobileTerminalHandler {
1296
1425
  */
1297
1426
  _handleDoubleTap(touch) {
1298
1427
  const coords = this._screenToTerminalCoords(touch.clientX, touch.clientY);
1299
- if (!coords) return;
1428
+ if (!coords) {
1429
+ this.touchState.isSelecting = false;
1430
+ return;
1431
+ }
1300
1432
 
1301
1433
  // Set selecting mode to prevent keyboard from appearing
1302
1434
  this.touchState.isSelecting = true;
@@ -1318,8 +1450,13 @@ class MobileTerminalHandler {
1318
1450
  * @private
1319
1451
  */
1320
1452
  _handleLongPress(touch) {
1453
+ if (this._destroyed) return;
1321
1454
  const coords = this._screenToTerminalCoords(touch.clientX, touch.clientY);
1322
- if (!coords) return;
1455
+ if (!coords) {
1456
+ this.touchState.isLongPress = false;
1457
+ this.touchState.isSelecting = false;
1458
+ return;
1459
+ }
1323
1460
 
1324
1461
  // Set selecting mode to prevent keyboard from appearing
1325
1462
  this.touchState.isSelecting = true;
@@ -1344,34 +1481,44 @@ class MobileTerminalHandler {
1344
1481
  * @private
1345
1482
  */
1346
1483
  _getWordAtPosition(x, y) {
1347
- // Get the line buffer
1484
+ // Work on cells, not on translateToString() indexes: a wide character
1485
+ // (CJK, many emoji) takes two cells but one string position, and an
1486
+ // astral character takes one cell but two UTF-16 units, so string
1487
+ // indexes drifted from columns and long press picked the wrong word.
1348
1488
  const buffer = this.terminal.buffer.active;
1349
1489
  const line = buffer.getLine(y);
1350
-
1351
1490
  if (!line) return null;
1352
-
1353
- const lineText = line.translateToString(true);
1354
-
1355
- // Find word boundaries
1356
- let start = x;
1357
- let end = x;
1358
-
1359
- // Expand left
1360
- while (start > 0 && this._isWordChar(lineText[start - 1])) {
1361
- start--;
1362
- }
1363
-
1364
- // Expand right
1365
- while (end < lineText.length && this._isWordChar(lineText[end])) {
1366
- end++;
1367
- }
1368
-
1369
- if (start === end) {
1370
- // No word found, select single character
1371
- return { start: { x, y }, end: { x, y } };
1491
+
1492
+ const cols = Math.min(line.length, this.terminal.cols);
1493
+ const cell = typeof buffer.getNullCell === 'function' ? buffer.getNullCell() : undefined;
1494
+ const chars = new Array(cols);
1495
+ const widths = new Array(cols);
1496
+ for (let i = 0; i < cols; i++) {
1497
+ const c = line.getCell(i, cell);
1498
+ chars[i] = c ? c.getChars() : '';
1499
+ widths[i] = c ? c.getWidth() : 1;
1500
+ }
1501
+ // The right half of a wide character (width 0) belongs to the cell
1502
+ // before it.
1503
+ const isWord = (i) => {
1504
+ let j = i;
1505
+ while (j > 0 && widths[j] === 0) j--;
1506
+ return this._isWordChar(chars[j]);
1507
+ };
1508
+ let px = Math.max(0, Math.min(cols - 1, x));
1509
+ while (px > 0 && widths[px] === 0) px--;
1510
+
1511
+ if (!isWord(px)) {
1512
+ // No word: select the character (both cells if it is wide).
1513
+ const w = Math.max(1, widths[px] || 1);
1514
+ return { start: { x: px, y }, end: { x: Math.min(cols - 1, px + w - 1), y } };
1372
1515
  }
1373
-
1374
- return { start: { x: start, y }, end: { x: end - 1, y } };
1516
+ let start = px;
1517
+ while (start > 0 && isWord(start - 1)) start--;
1518
+ while (start > 0 && widths[start] === 0) start--;
1519
+ let end = px;
1520
+ while (end + 1 < cols && isWord(end + 1)) end++;
1521
+ return { start: { x: start, y }, end: { x: end, y } };
1375
1522
  }
1376
1523
 
1377
1524
  /**
@@ -1379,7 +1526,10 @@ class MobileTerminalHandler {
1379
1526
  * @private
1380
1527
  */
1381
1528
  _isWordChar(char) {
1382
- return /[\w\-_./@]/.test(char);
1529
+ // Letters and digits of any script (accents, CJK, Cyrillic...), plus
1530
+ // the punctuation that belongs to paths, hosts and emails.
1531
+ if (!char) return false;
1532
+ return /^[\p{L}\p{N}\p{M}_\-./@~:+]+$/u.test(char);
1383
1533
  }
1384
1534
 
1385
1535
  /**
@@ -1452,6 +1602,7 @@ class MobileTerminalHandler {
1452
1602
  * @private
1453
1603
  */
1454
1604
  _updateSelection() {
1605
+ if (this._destroyed) return;
1455
1606
  if (!this.selection.active || !this.selection.start || !this.selection.end) {
1456
1607
  this._stopScrollTracking();
1457
1608
  this.selectionOverlay.style.display = 'none';
@@ -1469,6 +1620,14 @@ class MobileTerminalHandler {
1469
1620
  // Normalize selection (start should be before end)
1470
1621
  const start = this.selection.start;
1471
1622
  const end = this.selection.end;
1623
+
1624
+ // Keep a reflow-proof anchor of the endpoints (see
1625
+ // _remapSelectionAfterReflow). A pending width change is remapped
1626
+ // first so a stale anchor never overwrites the moved selection.
1627
+ if (this._selAnchor && this._selAnchor.cols !== this.terminal.cols) {
1628
+ this._remapSelectionAfterReflow();
1629
+ }
1630
+ this._anchorSelection();
1472
1631
 
1473
1632
  // Get selection text
1474
1633
  this.selection.text = this._getSelectionText();
@@ -1521,13 +1680,19 @@ class MobileTerminalHandler {
1521
1680
  lineText = line.translateToString(false);
1522
1681
  }
1523
1682
 
1524
- text += lineText;
1525
- if (y < endPos.y) {
1683
+ // A row continued by a soft wrap is one logical line: no newline and
1684
+ // no trimming (its trailing cells are real text). Otherwise drop the
1685
+ // blank cells xterm pads every row with up to the terminal width.
1686
+ const next = y < endPos.y ? buffer.getLine(y + 1) : null;
1687
+ const wrapsIntoNext = !!(next && next.isWrapped);
1688
+ text += wrapsIntoNext ? lineText : lineText.replace(/\s+$/, '');
1689
+ if (y < endPos.y && !wrapsIntoNext) {
1526
1690
  text += '\n';
1527
1691
  }
1528
1692
  }
1529
1693
 
1530
- return text.trim();
1694
+ // Keep the first line's indentation (copied code); drop trailing blanks.
1695
+ return text.replace(/\s+$/, '');
1531
1696
  }
1532
1697
 
1533
1698
  /**
@@ -1654,7 +1819,7 @@ class MobileTerminalHandler {
1654
1819
  * @private
1655
1820
  */
1656
1821
  _startScrollTracking() {
1657
- if (this._scrollTracking) return;
1822
+ if (this._scrollTracking || this._destroyed) return;
1658
1823
  this._scrollTracking = true;
1659
1824
  this._lastScrollOffset = this.terminal.buffer.active.viewportY;
1660
1825
  this._scrollTrackLoop();
@@ -1745,6 +1910,7 @@ class MobileTerminalHandler {
1745
1910
 
1746
1911
  this.contextMenu.style.left = `${posX}px`;
1747
1912
  this.contextMenu.style.top = `${posY}px`;
1913
+ if (this.contextMenu.style.display !== 'block') this._menuShownAt = Date.now();
1748
1914
  this.contextMenu.style.display = 'block';
1749
1915
  }
1750
1916
 
@@ -1791,13 +1957,21 @@ class MobileTerminalHandler {
1791
1957
  async _copySelection() {
1792
1958
  if (!this.selection.text) return;
1793
1959
 
1960
+ // The app helper tries the Clipboard API and falls back to
1961
+ // execCommand('copy'), which also works on plain-http origins where
1962
+ // navigator.clipboard does not exist.
1963
+ let ok = false;
1794
1964
  try {
1795
- await navigator.clipboard.writeText(this.selection.text);
1796
- this.app.showToast('Copied to clipboard', 'success');
1965
+ if (this.app && typeof this.app.copyToClipboard === 'function') {
1966
+ ok = await this.app.copyToClipboard(this.selection.text);
1967
+ } else {
1968
+ await navigator.clipboard.writeText(this.selection.text);
1969
+ ok = true;
1970
+ }
1797
1971
  } catch (err) {
1798
1972
  console.error('[MobileTerminal] Failed to copy:', err);
1799
- this.app.showToast('Failed to copy', 'error');
1800
1973
  }
1974
+ this.app.showToast(ok ? 'Copied to clipboard' : 'Failed to copy', ok ? 'success' : 'error');
1801
1975
  }
1802
1976
 
1803
1977
  /**
@@ -1806,11 +1980,20 @@ class MobileTerminalHandler {
1806
1980
  */
1807
1981
  async _pasteFromClipboard() {
1808
1982
  try {
1983
+ if (!navigator.clipboard || typeof navigator.clipboard.readText !== 'function') {
1984
+ throw new Error('Clipboard API not available');
1985
+ }
1809
1986
  const text = await navigator.clipboard.readText();
1810
1987
  this._pasteText(text);
1811
1988
  } catch (err) {
1812
- console.error('[MobileTerminal] Failed to paste:', err);
1813
- this.app.showToast('Failed to paste', 'error');
1989
+ // No API (plain http) or permission denied: let the user paste into
1990
+ // the app's paste dialog with the OS paste action instead.
1991
+ console.warn('[MobileTerminal] Clipboard read failed, opening paste dialog:', err && err.message);
1992
+ if (this.app && typeof this.app.showPasteModal === 'function') {
1993
+ this.app.showPasteModal(this.sessionId);
1994
+ } else {
1995
+ this.app.showToast('Failed to paste', 'error');
1996
+ }
1814
1997
  }
1815
1998
  }
1816
1999
 
@@ -1833,7 +2016,15 @@ class MobileTerminalHandler {
1833
2016
  * @private
1834
2017
  */
1835
2018
  async _readClipboard() {
2019
+ // Pre-reading runs from the long-press timer, not a user gesture: only
2020
+ // do it when reading is already allowed, so it never pops a browser
2021
+ // permission prompt or paste callout on every long press. Paste reads
2022
+ // the clipboard itself when tapped.
1836
2023
  try {
2024
+ this.app.terminalClipboardContent = null;
2025
+ if (!navigator.clipboard || !navigator.permissions || typeof navigator.permissions.query !== 'function') return;
2026
+ const status = await navigator.permissions.query({ name: 'clipboard-read' });
2027
+ if (!status || status.state !== 'granted') return;
1837
2028
  this.app.terminalClipboardContent = await navigator.clipboard.readText();
1838
2029
  } catch (err) {
1839
2030
  // Clipboard read might fail due to permissions
@@ -1862,11 +2053,146 @@ class MobileTerminalHandler {
1862
2053
  /**
1863
2054
  * Clear selection
1864
2055
  */
2056
+ /**
2057
+ * Record each selection endpoint as (marker on the first row of its
2058
+ * logical line, character offset into that logical line). xterm moves
2059
+ * markers when a resize reflows the buffer, so the endpoints can be
2060
+ * recomputed for the new width: resizing the text (font size, pinch
2061
+ * zoom) changes the column count, and plain row/column coordinates then
2062
+ * pointed at different text or at rows scrolled out of view.
2063
+ * @private
2064
+ */
2065
+ _anchorSelection() {
2066
+ const sel = this.selection;
2067
+ const t = this.terminal;
2068
+ if (!sel.active || !sel.start || !sel.end || !t || typeof t.registerMarker !== 'function') return;
2069
+ const a = this._selAnchor;
2070
+ if (a && a.cols === t.cols && a.sx === sel.start.x && a.sy === sel.start.y &&
2071
+ a.ex === sel.end.x && a.ey === sel.end.y && !a.start.marker.isDisposed && !a.end.marker.isDisposed) {
2072
+ return; // unchanged
2073
+ }
2074
+ const make = (pos) => {
2075
+ const buffer = t.buffer.active;
2076
+ let row = pos.y;
2077
+ while (row > 0) {
2078
+ const line = buffer.getLine(row);
2079
+ if (!line || !line.isWrapped) break;
2080
+ row--;
2081
+ }
2082
+ const cursorLine = buffer.baseY + buffer.cursorY;
2083
+ let marker = null;
2084
+ try { marker = t.registerMarker(row - cursorLine); } catch (_) {}
2085
+ if (!marker) return null;
2086
+ return { marker, offset: (pos.y - row) * t.cols + pos.x };
2087
+ };
2088
+ const start = make(sel.start);
2089
+ const end = make(sel.end);
2090
+ this._disposeSelectionAnchor();
2091
+ if (!start || !end) {
2092
+ if (start) start.marker.dispose();
2093
+ if (end) end.marker.dispose();
2094
+ return;
2095
+ }
2096
+ this._selAnchor = {
2097
+ start, end, cols: t.cols,
2098
+ sx: sel.start.x, sy: sel.start.y, ex: sel.end.x, ey: sel.end.y
2099
+ };
2100
+ }
2101
+
2102
+ /** @private */
2103
+ _disposeSelectionAnchor() {
2104
+ if (!this._selAnchor) return;
2105
+ try { this._selAnchor.start.marker.dispose(); } catch (_) {}
2106
+ try { this._selAnchor.end.marker.dispose(); } catch (_) {}
2107
+ this._selAnchor = null;
2108
+ }
2109
+
2110
+ /**
2111
+ * After a width change, move the selection endpoints to where their
2112
+ * text now is. Clears the selection if its lines were dropped (marker
2113
+ * disposed: trimmed scrollback or a full screen resync).
2114
+ * @private
2115
+ */
2116
+ _remapSelectionAfterReflow() {
2117
+ const a = this._selAnchor;
2118
+ const t = this.terminal;
2119
+ if (!a || !t || a.cols === t.cols) return;
2120
+ if (a.start.marker.isDisposed || a.end.marker.isDisposed ||
2121
+ a.start.marker.line < 0 || a.end.marker.line < 0) {
2122
+ this._disposeSelectionAnchor();
2123
+ this.clearSelection();
2124
+ return;
2125
+ }
2126
+ const cols = t.cols;
2127
+ const last = t.buffer.active.length - 1;
2128
+ const place = (p) => ({
2129
+ x: Math.min(cols - 1, p.offset % cols),
2130
+ y: Math.max(0, Math.min(last, p.marker.line + Math.floor(p.offset / cols)))
2131
+ });
2132
+ this.selection.start = place(a.start);
2133
+ this.selection.end = place(a.end);
2134
+ // Re-anchor at the new width (offsets stay valid, rows may differ).
2135
+ a.cols = cols;
2136
+ a.sx = this.selection.start.x; a.sy = this.selection.start.y;
2137
+ a.ex = this.selection.end.x; a.ey = this.selection.end.y;
2138
+ }
2139
+
2140
+ /**
2141
+ * Same width, but the anchored lines moved (scrollback trimmed while
2142
+ * output streams in): shift the endpoints with them. Clears the
2143
+ * selection when its lines left the buffer.
2144
+ * @private
2145
+ */
2146
+ _followSelectionAnchor() {
2147
+ const a = this._selAnchor;
2148
+ if (!a || !this.selection.active) return;
2149
+ if (a.cols !== this.terminal.cols) {
2150
+ this._remapSelectionAfterReflow();
2151
+ this._updateSelection();
2152
+ return;
2153
+ }
2154
+ if (a.start.marker.isDisposed || a.end.marker.isDisposed ||
2155
+ a.start.marker.line < 0 || a.end.marker.line < 0) {
2156
+ this.clearSelection();
2157
+ return;
2158
+ }
2159
+ const startRow = a.start.marker.line + Math.floor(a.start.offset / a.cols);
2160
+ if (startRow === a.sy) return; // nothing moved
2161
+ const delta = startRow - a.sy;
2162
+ this.selection.start = { x: this.selection.start.x, y: this.selection.start.y + delta };
2163
+ this.selection.end = { x: this.selection.end.x, y: this.selection.end.y + delta };
2164
+ a.sy += delta;
2165
+ a.ey += delta;
2166
+ this._updateSelection();
2167
+ }
2168
+
2169
+ /**
2170
+ * Scroll so the selection is on screen (a resize usually jumps the
2171
+ * viewport to the bottom).
2172
+ * @private
2173
+ */
2174
+ _revealSelection() {
2175
+ const t = this.terminal;
2176
+ const sel = this.selection;
2177
+ if (!t || !sel.active || !sel.start || !sel.end) return;
2178
+ const top = Math.min(sel.start.y, sel.end.y);
2179
+ const bottom = Math.max(sel.start.y, sel.end.y);
2180
+ const vy = t.buffer.active.viewportY;
2181
+ if (top >= vy && bottom < vy + t.rows) return;
2182
+ const target = Math.max(0, top - Math.floor(t.rows / 3));
2183
+ try { t.scrollToLine(target); } catch (_) {}
2184
+ requestAnimationFrame(() => {
2185
+ if (this.selection.active) this._updateSelection();
2186
+ });
2187
+ }
2188
+
1865
2189
  clearSelection() {
2190
+ this._disposeSelectionAnchor();
1866
2191
  this.selection.active = false;
1867
2192
  this.selection.start = null;
1868
2193
  this.selection.end = null;
1869
2194
  this.selection.text = '';
2195
+ this.hideContextMenu();
1870
2196
 
1871
2197
  // Stop scroll tracking since selection is cleared
1872
2198
  this._stopScrollTracking();
@@ -2118,9 +2444,14 @@ class MobileTerminalHandler {
2118
2444
  this.viewport.isKeyboardVisible = keyboardHeight > 100; // Threshold for keyboard detection
2119
2445
  this.viewport.keyboardHeight = keyboardHeight;
2120
2446
 
2121
- // Adjust terminal container if keyboard is visible
2122
- if (this.viewport.isKeyboardVisible !== wasKeyboardVisible) {
2123
- this._adjustForKeyboard();
2447
+ // Adjust when the keyboard appears/disappears, and also while it stays
2448
+ // up but the space changes (rotation, emoji panel, floating keyboard):
2449
+ // the old code only reacted to the show/hide flip and kept a stale
2450
+ // pixel height after a rotation.
2451
+ const heightChanged = this.viewport.isKeyboardVisible &&
2452
+ Math.abs((this._appliedKeyboardViewportHeight || 0) - viewportHeight) > 1;
2453
+ if (this.viewport.isKeyboardVisible !== wasKeyboardVisible || heightChanged) {
2454
+ this._adjustForKeyboard({ skipScroll: this.viewport.isKeyboardVisible === wasKeyboardVisible });
2124
2455
  }
2125
2456
  }
2126
2457
 
@@ -2128,20 +2459,29 @@ class MobileTerminalHandler {
2128
2459
  * Adjust terminal for virtual keyboard
2129
2460
  * @private
2130
2461
  */
2131
- _adjustForKeyboard() {
2132
- if (!this.terminalElement) return;
2462
+ _adjustForKeyboard(opts) {
2463
+ if (!this.terminalElement || this._destroyed) return;
2133
2464
 
2134
2465
  if (this.viewport.isKeyboardVisible) {
2135
2466
  // Keyboard is visible - adjust viewport
2136
2467
  const availableHeight = window.visualViewport.height;
2468
+ this._appliedKeyboardViewportHeight = availableHeight;
2137
2469
  this.terminalElement.style.height = `${availableHeight}px`;
2138
2470
 
2139
- // Scroll terminal into view
2140
- this.terminalElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
2471
+ // Scroll terminal into view (only when the keyboard just appeared,
2472
+ // and only for the tab on screen)
2473
+ const isActive = !this.app || this.app.activeSessionId === this.sessionId;
2474
+ if (isActive && !(opts && opts.skipScroll)) {
2475
+ this.terminalElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
2476
+ }
2141
2477
  } else {
2142
2478
  // Keyboard is hidden - restore original height
2479
+ this._appliedKeyboardViewportHeight = 0;
2143
2480
  this.terminalElement.style.height = '';
2144
2481
  }
2482
+ // Hidden tabs only keep their inline height in step; the refit happens
2483
+ // when they are shown (switchTab fits the terminal).
2484
+ if (this.app && this.app.activeSessionId !== this.sessionId) return;
2145
2485
 
2146
2486
  // Refit terminal. Prefer the app's guarded refit (it refuses to fit a
2147
2487
  // hidden/unlaid-out container, which a bare fit() would resize to a
@@ -2166,27 +2506,44 @@ class MobileTerminalHandler {
2166
2506
  * @private
2167
2507
  */
2168
2508
  _handleKeyDown(e) {
2169
- // Handle keyboard shortcuts
2170
- if (e.ctrlKey || e.metaKey) {
2171
- switch (e.key.toLowerCase()) {
2172
- case 'c':
2173
- if (this.selection.active) {
2174
- e.preventDefault();
2175
- this._copySelection();
2176
- }
2177
- break;
2178
- case 'v':
2509
+ // Every session's handler listens on document. Only the one whose
2510
+ // input field has focus (or, with no editable focus, the active tab's
2511
+ // handler while it holds a selection) may act; otherwise Ctrl+V pasted
2512
+ // into EVERY open tab and Ctrl+V/Ctrl+A were swallowed in other inputs.
2513
+ if (!(e.ctrlKey || e.metaKey) || typeof e.key !== 'string') return;
2514
+ const target = e.target;
2515
+ const ownField = !!this.hiddenTextarea && target === this.hiddenTextarea;
2516
+ const editable = target && target !== document.body &&
2517
+ (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName || ''));
2518
+ const isActiveTab = this.app && this.app.activeSessionId === this.sessionId;
2519
+ if (!ownField && (editable || !isActiveTab)) return;
2520
+
2521
+ switch (e.key.toLowerCase()) {
2522
+ case 'c':
2523
+ if (this.selection.active) {
2179
2524
  e.preventDefault();
2180
- this._pasteInProgress = true;
2181
- this._pasteFromClipboard().finally(() => {
2182
- setTimeout(() => { this._pasteInProgress = false; }, 100);
2183
- });
2184
- break;
2185
- case 'a':
2525
+ this._copySelection();
2526
+ }
2527
+ break;
2528
+ case 'v':
2529
+ if (!ownField && !this.selection.active) return;
2530
+ e.preventDefault();
2531
+ this._pasteInProgress = true;
2532
+ this._pasteFromClipboard().finally(() => {
2533
+ setTimeout(() => { this._pasteInProgress = false; }, 100);
2534
+ });
2535
+ break;
2536
+ case 'a':
2537
+ if (this.selection.active) {
2186
2538
  e.preventDefault();
2187
2539
  this._selectAll();
2188
- break;
2189
- }
2540
+ } else if (ownField && e.ctrlKey && !e.metaKey && !e.altKey) {
2541
+ // Typing in the terminal: Ctrl+A is the shell's
2542
+ // beginning-of-line, not "select the hidden field".
2543
+ e.preventDefault();
2544
+ this._sendToTerminal('\x01');
2545
+ }
2546
+ break;
2190
2547
  }
2191
2548
  }
2192
2549
  }