@lethevimlet/sshift 1.8.0 → 1.8.2

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.
@@ -59,6 +59,24 @@ class MobileTerminalHandler {
59
59
  // terminal. All input diffing runs against this persistent baseline —
60
60
  // see _syncTextareaToTerminal().
61
61
  this._sentValue = '';
62
+ // Ring buffer of the last keyboard/IME events on the hidden textarea
63
+ // (Debug Info → "Copy Input Trace"). Gboard behaviour cannot be
64
+ // reproduced on a desktop; this is how device reports become
65
+ // actionable.
66
+ this._inputTrace = [];
67
+ // xterm focus capture (see _captureTerminalFocus)
68
+ this._xtermCore = null;
69
+ this._xtermTextareaFocusListener = null;
70
+ // Post-composition catch-up sync timer (see _onCompositionEnd)
71
+ this._deferredSyncTimer = null;
72
+ // True during the blur/focus pair that re-opens a dismissed keyboard:
73
+ // the field content must survive it (see _reshowKeyboard).
74
+ this._suppressBlurReset = false;
75
+ // Tallest layout viewport seen per width: with
76
+ // `interactive-widget=resizes-content` the virtual keyboard shrinks
77
+ // window.innerHeight, so "current height well below the max" means
78
+ // the keyboard is up (see _keyboardProbablyHidden).
79
+ this._maxInnerHeightByWidth = {};
62
80
  this.contextMenuUserPositioned = false; // Track if user has manually positioned the menu
63
81
 
64
82
  // Configuration
@@ -212,12 +230,78 @@ class MobileTerminalHandler {
212
230
  this._createSelectionHandles();
213
231
  this._createContextMenu();
214
232
  this._createHiddenTextarea();
233
+ this._captureTerminalFocus();
234
+ this._noteViewportHeight();
215
235
 
216
236
  // Attach event listeners
217
237
  this._attachEventListeners();
218
238
 
219
239
  console.log('[MobileTerminal] Initialized for session:', this.sessionId);
220
240
  }
241
+
242
+ /**
243
+ * Route every xterm focus request to the hidden textarea (v1.8.2).
244
+ *
245
+ * xterm registers its own `mousedown` listener on the terminal element
246
+ * that focuses ITS helper textarea. On a phone a tap fires
247
+ * touchstart/touchend (our handlers focus the mobile textarea) and then
248
+ * the browser's compatibility mousedown about 1 ms later, which let
249
+ * xterm steal the focus straight back. Verified in headless Chrome with
250
+ * touch emulation: `document.activeElement` ended on
251
+ * `.xterm-helper-textarea` after every tap. Gboard was therefore typing
252
+ * into xterm's textarea, whose Android IME handling (clear the field
253
+ * after every input) is the well-known source of repeated/duplicated
254
+ * words with suggestions, and the diff pipeline below never saw a
255
+ * single keystroke on real devices.
256
+ *
257
+ * The core's `focus()` is shadowed with an own property (the mousedown
258
+ * listener calls `this.focus()` dynamically) and restored in destroy();
259
+ * a focus listener on xterm's textarea is the safety net for any other
260
+ * path that manages to focus it.
261
+ * @private
262
+ */
263
+ _captureTerminalFocus() {
264
+ const t = this.terminal;
265
+ if (!t) return;
266
+ const core = t._core;
267
+ if (core && typeof core.focus === 'function' &&
268
+ !Object.prototype.hasOwnProperty.call(core, 'focus')) {
269
+ this._xtermCore = core;
270
+ core.focus = () => { this._focusHiddenTextarea(); };
271
+ }
272
+ const ta = t.textarea;
273
+ if (ta && typeof ta.addEventListener === 'function') {
274
+ try { ta.tabIndex = -1; } catch (_) {}
275
+ this._xtermTextareaFocusListener = () => {
276
+ if (!this.hiddenTextarea) return;
277
+ this._trace('xterm-focus', {});
278
+ this._focusHiddenTextarea();
279
+ // Could not take it (selection mode): at least keep Gboard off
280
+ // xterm's textarea so no input ever flows through xterm's path.
281
+ if (typeof document !== 'undefined' && document.activeElement === ta &&
282
+ typeof ta.blur === 'function') {
283
+ ta.blur();
284
+ }
285
+ };
286
+ ta.addEventListener('focus', this._xtermTextareaFocusListener);
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Undo _captureTerminalFocus.
292
+ * @private
293
+ */
294
+ _releaseTerminalFocus() {
295
+ if (this._xtermCore) {
296
+ try { delete this._xtermCore.focus; } catch (_) {}
297
+ this._xtermCore = null;
298
+ }
299
+ const ta = this.terminal && this.terminal.textarea;
300
+ if (ta && this._xtermTextareaFocusListener && typeof ta.removeEventListener === 'function') {
301
+ ta.removeEventListener('focus', this._xtermTextareaFocusListener);
302
+ }
303
+ this._xtermTextareaFocusListener = null;
304
+ }
221
305
 
222
306
  /**
223
307
  * Create the selection overlay element
@@ -490,68 +574,190 @@ class MobileTerminalHandler {
490
574
  // empty snapshot, desyncing Gboard's own state from the textarea and
491
575
  // making it re-insert the full text on the next suggestion tap.
492
576
  this.hiddenTextarea.addEventListener('input', (e) => {
493
- if (this.touchState.isSelecting) {
494
- e.preventDefault();
495
- this._resetInputTracking();
496
- return;
497
- }
498
-
499
- // While a composition is in flight we don't send anything; the
500
- // textarea is synced once on compositionend. (Sending live
501
- // composition updates would spam the terminal with backspace/retype
502
- // churn while the IME reshapes the word.)
503
- if (e.isComposing || this._isComposing || e.inputType === 'insertCompositionText') {
504
- return;
505
- }
577
+ this._trace('input', {
578
+ inputType: e.inputType,
579
+ data: e.data,
580
+ composing: !!(e.isComposing || this._isComposing)
581
+ });
506
582
 
507
- if (this.touchState.isDragging) {
583
+ if (this.touchState.isDragging || this.selection.active) {
508
584
  return;
509
585
  }
510
586
 
587
+ // Sync on EVERY input event, including the ones fired while an IME
588
+ // composition is in flight (v1.8.2). Composition updates are almost
589
+ // always plain appends (one letter, or a whole glided word), so the
590
+ // diff emits just the new characters and the terminal echoes the
591
+ // word as it is typed, exactly like a physical keyboard. When Gboard
592
+ // reshapes the composed word (autocorrect, suggestion tap) the diff
593
+ // erases back to the divergence and retypes, which is what a human
594
+ // would do. Waiting for compositionend (v1.7.x) made every word
595
+ // appear only when the space was pressed and lost the final commit
596
+ // whenever Chrome delivered compositionend before the last DOM
597
+ // update. The diff is idempotent, so extra events cost nothing.
511
598
  this._syncTextareaToTerminal();
512
599
  });
513
600
 
514
601
  // Handle keydown for special keys
515
602
  this.hiddenTextarea.addEventListener('keydown', (e) => {
516
- if (this.touchState.isSelecting) {
603
+ this._handleTextareaKeyDown(e);
604
+ });
605
+
606
+ this._attachTextareaFocusListeners();
607
+ }
608
+
609
+ /**
610
+ * keydown on the hidden textarea. Extracted for unit tests.
611
+ *
612
+ * Text keys are left to the browser (the input diff mirrors them).
613
+ * Enter inserts a newline that the diff turns into \r. Backspace on an
614
+ * empty field is sent straight to the terminal (the browser has nothing
615
+ * to delete, so no input event would follow). Every other non-text key
616
+ * (arrows, Home/End, Delete, F-keys, Ctrl/Alt chords from a physical
617
+ * keyboard) is translated to its escape sequence here, because on
618
+ * mobile xterm's own textarea never has focus any more (see
619
+ * _captureTerminalFocus) and the caret must not move inside the field.
620
+ * @private
621
+ */
622
+ _handleTextareaKeyDown(e) {
623
+ if (e.key === 'Enter' || e.key === 'Backspace' || e.key === 'Tab') {
624
+ this._trace('keydown', { key: e.key, composing: this._isComposing });
625
+ }
626
+ if (this.selection.active) {
627
+ e.preventDefault();
628
+ return;
629
+ }
630
+
631
+ // IME-driven keydowns (keyCode 229 / "Unidentified" / "Process")
632
+ // carry no key; the IME edits the field through input events.
633
+ // Never preventDefault them: on some Gboard builds the Enter key
634
+ // arrives this way while a word is still composing, and swallowing
635
+ // it meant "Enter needs two taps".
636
+ if (e.keyCode === 229 || e.key === 'Unidentified' || e.key === 'Process') {
637
+ return;
638
+ }
639
+
640
+ if (e.key === 'Enter') {
641
+ // Let the browser insert the newline into the textarea. The input
642
+ // diff (_syncTextareaToTerminal) translates it to \r and KEEPS the
643
+ // submitted text in the field. Clearing the field here (the old
644
+ // behaviour) was a programmatic edit that Gboard never sees: its
645
+ // own model of the field still held the previous sentence, and the
646
+ // next suggestion tap re-committed "old sentence + new word" —
647
+ // which the diff then faithfully re-typed into the terminal
648
+ // (the "autocomplete repeats previous sentences" bug). The field
649
+ // is only cleared when the keyboard is collapsed (textarea blurred),
650
+ // at which point the IME session is torn down anyway.
651
+ return;
652
+ } else if (e.key === 'Backspace') {
653
+ // Let the browser handle backspace in the textarea; the input diff
654
+ // will detect the deletion and send \x7f to the terminal.
655
+ // Only prevent default if the textarea is empty (nothing to delete).
656
+ if (!this.hiddenTextarea.value) {
517
657
  e.preventDefault();
518
- return;
658
+ this._sendToTerminal('\x7f');
519
659
  }
520
-
521
- if (this._isComposing) {
660
+ } else if (e.key === 'Tab') {
661
+ e.preventDefault();
662
+ this._sendToTerminal('\t');
663
+ // No tracking reset: see the Enter comment above.
664
+ } else {
665
+ const seq = this._specialKeySequence(e);
666
+ if (seq) {
522
667
  e.preventDefault();
523
- return;
668
+ this._trace('special', { key: e.key, seq });
669
+ this._sendToTerminal(seq);
524
670
  }
671
+ }
672
+ }
525
673
 
526
- if (e.key === 'Enter') {
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;
538
- } else if (e.key === 'Backspace') {
539
- // Let the browser handle backspace in the textarea; the input diff
540
- // will detect the deletion and send \x7f to the terminal.
541
- // Only prevent default if the textarea is empty (nothing to delete).
542
- if (!this.hiddenTextarea.value) {
543
- e.preventDefault();
544
- this._sendToTerminal('\x7f');
674
+ /**
675
+ * Escape sequence for a physical-keyboard special key, or null when the
676
+ * browser should handle the key (plain text, paste/copy/select-all
677
+ * chords that the app handles elsewhere, bare modifiers).
678
+ * @private
679
+ */
680
+ _specialKeySequence(e) {
681
+ const key = e.key;
682
+ if (!key) return null;
683
+ const ctrl = !!e.ctrlKey;
684
+ const alt = !!e.altKey;
685
+ const meta = !!e.metaKey;
686
+ const shift = !!e.shiftKey;
687
+ const mod = 1 + (shift ? 1 : 0) + (alt ? 2 : 0) + (ctrl ? 4 : 0);
688
+ const app = !!(this.terminal && this.terminal.modes && this.terminal.modes.applicationCursorKeysMode);
689
+
690
+ if (key.length === 1) {
691
+ if (!ctrl && !alt && !meta) return null; // typed text → input diff
692
+ if (meta) return null;
693
+ const lower = key.toLowerCase();
694
+ // Ctrl+V / Ctrl+Shift+V paste and Ctrl+A select-all are handled by
695
+ // the document-level handler (_handleKeyDown); Ctrl+C copies when a
696
+ // selection is active (that case returned earlier).
697
+ if (ctrl && !alt && (lower === 'v' || lower === 'a')) return null;
698
+ let seq = null;
699
+ if (ctrl) {
700
+ const code = lower.charCodeAt(0);
701
+ if (code >= 97 && code <= 122) seq = String.fromCharCode(code - 96);
702
+ else if (key === ' ' || key === '@' || key === '2') seq = '\x00';
703
+ else if (key === '[' || key === '3') seq = '\x1b';
704
+ else if (key === '\\' || key === '4') seq = '\x1c';
705
+ else if (key === ']' || key === '5') seq = '\x1d';
706
+ else if (key === '^' || key === '6') seq = '\x1e';
707
+ else if (key === '_' || key === '7' || key === '-') seq = '\x1f';
708
+ else if (key === '8' || key === '?') seq = '\x7f';
709
+ else seq = key;
710
+ } else {
711
+ seq = key;
712
+ }
713
+ return alt ? '\x1b' + seq : seq;
714
+ }
715
+
716
+ const cursor = (letter) => {
717
+ if (mod > 1) return '\x1b[1;' + mod + letter;
718
+ return (app ? '\x1bO' : '\x1b[') + letter;
719
+ };
720
+ const tilde = (n) => (mod > 1 ? '\x1b[' + n + ';' + mod + '~' : '\x1b[' + n + '~');
721
+ const fkey = (n) => {
722
+ if (n <= 4) {
723
+ const l = 'PQRS'[n - 1];
724
+ return mod > 1 ? '\x1b[1;' + mod + l : '\x1bO' + l;
725
+ }
726
+ const codes = { 5: 15, 6: 17, 7: 18, 8: 19, 9: 20, 10: 21, 11: 23, 12: 24 };
727
+ return tilde(codes[n]);
728
+ };
729
+
730
+ switch (key) {
731
+ case 'ArrowUp': return cursor('A');
732
+ case 'ArrowDown': return cursor('B');
733
+ case 'ArrowRight': return cursor('C');
734
+ case 'ArrowLeft': return cursor('D');
735
+ case 'Home': return cursor('H');
736
+ case 'End': return cursor('F');
737
+ case 'PageUp': return tilde(5);
738
+ case 'PageDown': return tilde(6);
739
+ case 'Insert': return tilde(2);
740
+ case 'Delete': return tilde(3);
741
+ case 'Escape': return '\x1b';
742
+ default: {
743
+ const m = /^F(\d{1,2})$/.exec(key);
744
+ if (m) {
745
+ const n = parseInt(m[1], 10);
746
+ if (n >= 1 && n <= 12) return fkey(n);
545
747
  }
546
- } else if (e.key === 'Tab') {
547
- e.preventDefault();
548
- this._sendToTerminal('\t');
549
- // No tracking reset: see the Enter comment above.
748
+ return null;
550
749
  }
551
- });
552
-
750
+ }
751
+ }
752
+
753
+ /**
754
+ * The rest of the hidden-textarea listeners (focus/blur/composition).
755
+ * @private
756
+ */
757
+ _attachTextareaFocusListeners() {
553
758
  // Prevent focus when in selection mode or when selection is active
554
759
  this.hiddenTextarea.addEventListener('focus', (e) => {
760
+ this._trace('focus', {});
555
761
  if (this.touchState.isSelecting || this.selection.active) {
556
762
  e.preventDefault();
557
763
  this._intentionalBlur = true;
@@ -560,16 +766,83 @@ class MobileTerminalHandler {
560
766
  }
561
767
  });
562
768
 
769
+ // The blur tears down the IME session: a reset that had to wait for
770
+ // the field to lose focus (see _resetInputTracking) is applied now.
771
+ this.hiddenTextarea.addEventListener('blur', () => this._onTextareaBlur());
772
+
563
773
  // Composition events for IME/autocomplete handling
564
- this.hiddenTextarea.addEventListener('compositionstart', () => {
774
+ this.hiddenTextarea.addEventListener('compositionstart', (e) => {
775
+ this._trace('compositionstart', { data: e && e.data });
565
776
  this._isComposing = true;
566
777
  });
567
778
 
568
- this.hiddenTextarea.addEventListener('compositionend', () => {
779
+ this.hiddenTextarea.addEventListener('compositionend', (e) => {
780
+ this._trace('compositionend', { data: e && e.data });
569
781
  this._onCompositionEnd();
570
782
  });
571
783
  }
572
784
 
785
+ /**
786
+ * blur on the hidden textarea: the IME session is gone, so a reset that
787
+ * had to wait for the field to lose focus (see _resetInputTracking) is
788
+ * applied now — except during the blur/focus pair of _reshowKeyboard,
789
+ * which must keep the field exactly as the IME last saw it.
790
+ * @private
791
+ */
792
+ _onTextareaBlur() {
793
+ this._trace('blur', { reshow: this._suppressBlurReset });
794
+ this._isComposing = false;
795
+ if (this._pendingTrackingReset && !this._suppressBlurReset) {
796
+ this._resetInputTracking();
797
+ }
798
+ }
799
+
800
+ /**
801
+ * Record one keyboard/IME event (ring buffer, see Debug Info → Copy
802
+ * Input Trace). Values are trimmed so the trace stays small.
803
+ * @private
804
+ */
805
+ _trace(kind, extra) {
806
+ if (!this._inputTrace) this._inputTrace = [];
807
+ const ta = this.hiddenTextarea;
808
+ const value = ta && typeof ta.value === 'string' ? ta.value : '';
809
+ const entry = {
810
+ t: Date.now(),
811
+ kind,
812
+ len: value.length,
813
+ tail: value.length > 48 ? '…' + value.slice(-48) : value,
814
+ sel: ta && typeof ta.selectionStart === 'number' ? [ta.selectionStart, ta.selectionEnd] : undefined,
815
+ sentLen: this._sentValue ? this._sentValue.length : 0
816
+ };
817
+ if (typeof document !== 'undefined' && ta) {
818
+ entry.focused = document.activeElement === ta;
819
+ }
820
+ Object.keys(extra || {}).forEach(k => {
821
+ let v = extra[k];
822
+ if (typeof v === 'string' && v.length > 64) v = v.slice(0, 64) + '…';
823
+ if (v !== undefined) entry[k] = v;
824
+ });
825
+ this._inputTrace.push(entry);
826
+ if (this._inputTrace.length > 400) this._inputTrace.splice(0, this._inputTrace.length - 400);
827
+ }
828
+
829
+ /**
830
+ * @returns {Array} copy of the keyboard/IME event trace
831
+ */
832
+ getInputTrace() {
833
+ return (this._inputTrace || []).slice();
834
+ }
835
+
836
+ /**
837
+ * @returns {boolean} true while the hidden textarea owns focus (a live
838
+ * IME session may be tracking its content)
839
+ * @private
840
+ */
841
+ _isTextareaFocused() {
842
+ return typeof document !== 'undefined' && !!this.hiddenTextarea &&
843
+ document.activeElement === this.hiddenTextarea;
844
+ }
845
+
573
846
  /**
574
847
  * compositionend handler, extracted so the deferred-reset behaviour is
575
848
  * unit-testable without a DOM.
@@ -578,13 +851,13 @@ class MobileTerminalHandler {
578
851
  _onCompositionEnd() {
579
852
  this._isComposing = false;
580
853
  // A reset was requested while the composition was in flight
581
- // (e.g. Enter/Tab committed through the input path, or a selection
582
- // started mid-word): apply it now, discarding the composition
583
- // result, instead of having cleared the field under the IME.
854
+ // (e.g. a selection started mid-word): apply it now, discarding the
855
+ // composition result, instead of having cleared the field under the
856
+ // IME. If the field is still focused the reset stays deferred (until
857
+ // blur) and the composition result is synced like any other input.
584
858
  if (this._pendingTrackingReset) {
585
- this._pendingTrackingReset = false;
586
859
  this._resetInputTracking();
587
- return;
860
+ if (!this._pendingTrackingReset) return;
588
861
  }
589
862
  // Sync whatever the composition left in the textarea. Because the
590
863
  // diff runs against the persistent _sentValue baseline, this is
@@ -594,9 +867,29 @@ class MobileTerminalHandler {
594
867
  // diffs to nothing.
595
868
  if (!this.touchState.isDragging) {
596
869
  this._syncTextareaToTerminal();
870
+ // Chrome sometimes commits the final composition text to the DOM
871
+ // AFTER dispatching compositionend (and the matching input event
872
+ // can still carry isComposing=true). A catch-up sync on the next
873
+ // task sees the settled field; idempotent, so harmless otherwise.
874
+ this._scheduleDeferredSync();
597
875
  }
598
876
  }
599
877
 
878
+ /**
879
+ * Run one more diff sync on the next task (see _onCompositionEnd).
880
+ * @private
881
+ */
882
+ _scheduleDeferredSync() {
883
+ if (typeof setTimeout !== 'function') return;
884
+ if (this._deferredSyncTimer) clearTimeout(this._deferredSyncTimer);
885
+ this._deferredSyncTimer = setTimeout(() => {
886
+ this._deferredSyncTimer = null;
887
+ if (!this.hiddenTextarea) return;
888
+ if (this.touchState.isDragging || this.selection.active) return;
889
+ this._syncTextareaToTerminal();
890
+ }, 0);
891
+ }
892
+
600
893
  /**
601
894
  * Reset the textarea input tracking: clear the textarea and the
602
895
  * synced-content baseline together so future diffs start from a clean
@@ -610,17 +903,26 @@ class MobileTerminalHandler {
610
903
  * mismatch on the next suggestion tap, and re-inserts text computed
611
904
  * from the stale model — the "autocomplete types repetitive text"
612
905
  * bug. When composing, defer the reset to compositionend instead.
906
+ *
907
+ * Focus guard (v1.8.1): the same applies to ANY clear while the
908
+ * textarea is focused — the IME session is alive and keeps its own
909
+ * model. So a reset is only ever applied when the field is not focused
910
+ * (after the blur in _collapseKeyboard, or from the blur listener);
911
+ * otherwise it is remembered and applied on the next blur.
613
912
  * @private
614
913
  */
615
914
  _resetInputTracking() {
616
- if (this._isComposing) {
915
+ if (this._isComposing || this._isTextareaFocused()) {
617
916
  this._pendingTrackingReset = true;
917
+ this._trace('reset-deferred', { composing: this._isComposing });
618
918
  return;
619
919
  }
920
+ this._pendingTrackingReset = false;
620
921
  if (this.hiddenTextarea) {
621
922
  this.hiddenTextarea.value = '';
622
923
  }
623
924
  this._sentValue = '';
925
+ this._trace('reset', {});
624
926
  }
625
927
 
626
928
  /**
@@ -662,25 +964,49 @@ class MobileTerminalHandler {
662
964
 
663
965
  // The field accumulates every submitted line (separated by \n — see
664
966
  // 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).
967
+ // submitted and cannot be edited any more.
668
968
  const lineStart = prev.lastIndexOf('\n') + 1;
669
969
 
670
- // Erase back to the divergence point (clamped to the current line).
970
+ let removed;
971
+ let insert;
972
+ if (prefixLen >= lineStart) {
973
+ // Divergence inside the current line: erase back to it and retype.
974
+ removed = prev.substring(prefixLen);
975
+ insert = curr.substring(prefixLen);
976
+ } else if (prev.startsWith(curr)) {
977
+ // Pure deletion reaching back across the line break (Backspace on
978
+ // an empty line, or a swipe-to-delete that crossed it). A physical
979
+ // keyboard sends one DEL per press, so do the same — including one
980
+ // for the newline. On a shell prompt that is a no-op; in a
981
+ // multi-line TUI editor it joins lines, exactly like a real key.
982
+ removed = prev.substring(curr.length);
983
+ insert = '';
984
+ } else {
985
+ // The IME rewrote text on an already submitted line (only a stale
986
+ // keyboard model or a caret jump can do this). Nothing above the
987
+ // current line can be sent any more, so limit the damage to the
988
+ // current line: diff prev's and curr's last lines only.
989
+ const pLine = prev.substring(lineStart);
990
+ const cLine = curr.substring(curr.lastIndexOf('\n') + 1);
991
+ let p = 0;
992
+ const m = Math.min(pLine.length, cLine.length);
993
+ while (p < m && pLine[p] === cLine[p]) p++;
994
+ removed = pLine.substring(p);
995
+ insert = cLine.substring(p);
996
+ }
997
+
671
998
  // Count code points (not UTF-16 units) so astral characters (emoji
672
999
  // etc.) get one DEL each.
673
- const removed = prev.substring(Math.max(prefixLen, lineStart));
674
1000
  const deleteCount = removed ? Array.from(removed).length : 0;
675
1001
 
676
- // Retype the remainder. Translate newlines (some keyboards commit
677
- // Enter through the input path instead of a keydown) into \r.
678
- let insert = curr.substring(prefixLen);
1002
+ // Translate newlines (some keyboards commit Enter through the input
1003
+ // path instead of a keydown) into \r.
679
1004
  const hadNewline = /[\r\n]/.test(insert);
680
1005
  if (hadNewline) {
681
1006
  insert = insert.replace(/\r\n/g, '\r').replace(/\n/g, '\r');
682
1007
  }
683
1008
 
1009
+ this._trace('sync', { prefixLen, del: deleteCount, insert });
684
1010
  if (deleteCount > 0) {
685
1011
  this._sendToTerminal('\x7f'.repeat(deleteCount));
686
1012
  }
@@ -757,6 +1083,11 @@ class MobileTerminalHandler {
757
1083
  * Detach all event listeners
758
1084
  */
759
1085
  destroy() {
1086
+ this._releaseTerminalFocus();
1087
+ if (this._deferredSyncTimer) {
1088
+ clearTimeout(this._deferredSyncTimer);
1089
+ this._deferredSyncTimer = null;
1090
+ }
760
1091
  if (this.container) {
761
1092
  this.container.removeEventListener('touchstart', this._boundHandleTouchStart);
762
1093
  this.container.removeEventListener('touchmove', this._boundHandleTouchMove);
@@ -832,9 +1163,17 @@ class MobileTerminalHandler {
832
1163
  // during long press detection. This will be reset in touchEnd if it's
833
1164
  // a quick tap for text input.
834
1165
  this.touchState.isSelecting = true;
835
-
836
- // Always prevent keyboard from appearing during touch interactions
837
- this._collapseKeyboard();
1166
+
1167
+ // Do NOT collapse the keyboard here. Until v1.8.0 every touchstart
1168
+ // blurred AND cleared the hidden textarea and a quick tap re-focused
1169
+ // it ~100 ms later. That is a programmatic clear under a live Gboard
1170
+ // session (Chrome coalesces the blur/focus into one IME state update
1171
+ // when they land close together, so Gboard never restarts its field
1172
+ // model): the next suggestion tap then re-inserted text from the
1173
+ // stale model — the "autocomplete repeats words" family. A tap on the
1174
+ // terminal while typing is extremely common (dismissing a suggestion
1175
+ // popup, repositioning). Long press, double tap, selection and drags
1176
+ // collapse the keyboard themselves when they are detected.
838
1177
 
839
1178
  const touch = e.touches[0];
840
1179
  const now = Date.now();
@@ -926,19 +1265,28 @@ class MobileTerminalHandler {
926
1265
  return;
927
1266
  }
928
1267
 
929
- // Single tap - clear selection if exists, otherwise focus for input
930
- const touch = e.changedTouches[0];
931
- const timeSinceStart = Date.now() - this.touchState.startTime;
932
-
933
- if (timeSinceStart < 200) { // Quick tap
934
- if (this.selection.active) {
935
- this.clearSelection();
936
- } else {
937
- // Reset selecting mode to allow keyboard input for quick tap
938
- this.touchState.isSelecting = false;
939
- // Focus hidden textarea for keyboard input
940
- this._focusHiddenTextarea();
941
- }
1268
+ // The long-press window is over: whatever this touch was, it is not
1269
+ // a selection gesture any more. (Leaving isSelecting set — the old
1270
+ // behaviour for taps longer than 200 ms — blocked every later focus
1271
+ // request until the next touch.)
1272
+ this.touchState.isSelecting = false;
1273
+
1274
+ // A cancelled touch (browser took over the gesture) is not a tap.
1275
+ if (e && e.type === 'touchcancel') return;
1276
+
1277
+ // A scroll/drag is not a tap.
1278
+ const touch = e.changedTouches && e.changedTouches[0];
1279
+ if (touch) {
1280
+ const dx = touch.clientX - this.touchState.startX;
1281
+ const dy = touch.clientY - this.touchState.startY;
1282
+ if (Math.sqrt(dx * dx + dy * dy) > 10) return;
1283
+ }
1284
+
1285
+ // Tap: clear the selection if there is one, otherwise focus for input.
1286
+ if (this.selection.active) {
1287
+ this.clearSelection();
1288
+ } else {
1289
+ this._focusHiddenTextarea({ userGesture: true });
942
1290
  }
943
1291
  }
944
1292
 
@@ -1553,7 +1901,7 @@ class MobileTerminalHandler {
1553
1901
  * Focus hidden textarea for keyboard input
1554
1902
  * @private
1555
1903
  */
1556
- _focusHiddenTextarea() {
1904
+ _focusHiddenTextarea(opts) {
1557
1905
  // Don't focus keyboard if we're in selection mode or selection is active
1558
1906
  if (this.touchState.isSelecting || this.selection.active) {
1559
1907
  return;
@@ -1564,7 +1912,15 @@ class MobileTerminalHandler {
1564
1912
  // screen-sync while the keyboard stayed open): leave everything
1565
1913
  // untouched. Re-running the readonly dance or focusing again would
1566
1914
  // at best be a no-op and at worst tear down the IME session.
1915
+ //
1916
+ // Exception: the user tapped the terminal (a real gesture) while
1917
+ // the field is focused but the keyboard was dismissed with the
1918
+ // Android back button. focus() on an already focused element does
1919
+ // not bring the keyboard back, so re-open it explicitly.
1567
1920
  if (document.activeElement === this.hiddenTextarea) {
1921
+ if (opts && opts.userGesture && this._keyboardProbablyHidden()) {
1922
+ this._reshowKeyboard();
1923
+ }
1568
1924
  return;
1569
1925
  }
1570
1926
 
@@ -1589,12 +1945,71 @@ class MobileTerminalHandler {
1589
1945
  // autocomplete" regression). Force the caret to the end so typing
1590
1946
  // appends, matching both the diff and the remote prompt cursor.
1591
1947
  const len = this.hiddenTextarea.value.length;
1948
+ this._trace('focus-request', { from: document.activeElement ? document.activeElement.tagName : null });
1592
1949
  this.hiddenTextarea.focus();
1593
1950
  try { this.hiddenTextarea.setSelectionRange(len, len); } catch (_) {}
1594
1951
  this._keyboardCollapsed = false;
1595
1952
  }
1596
1953
  }
1597
1954
 
1955
+ /**
1956
+ * Re-open a dismissed virtual keyboard on an already focused field:
1957
+ * blur + focus inside the tap's user gesture. The field content is
1958
+ * deliberately kept across the pair (no pending reset is applied on
1959
+ * this blur) so Gboard's model cannot diverge from the DOM even if
1960
+ * Chrome coalesces the two focus changes into one IME update.
1961
+ * @private
1962
+ */
1963
+ _reshowKeyboard() {
1964
+ const ta = this.hiddenTextarea;
1965
+ if (!ta) return;
1966
+ this._trace('reshow', {});
1967
+ this._suppressBlurReset = true;
1968
+ this._intentionalBlur = true;
1969
+ try { ta.blur(); } finally { this._suppressBlurReset = false; }
1970
+ const len = typeof ta.value === 'string' ? ta.value.length : 0;
1971
+ ta.focus();
1972
+ try { ta.setSelectionRange(len, len); } catch (_) {}
1973
+ this._keyboardCollapsed = false;
1974
+ }
1975
+
1976
+ /**
1977
+ * Remember the tallest layout viewport seen at the current width
1978
+ * (called at init and on every resize / visual-viewport event).
1979
+ * @private
1980
+ */
1981
+ _noteViewportHeight() {
1982
+ if (typeof window === 'undefined') return;
1983
+ const w = window.innerWidth;
1984
+ const h = window.innerHeight;
1985
+ if (!(w > 0 && h > 0)) return;
1986
+ if (!(this._maxInnerHeightByWidth[w] >= h)) {
1987
+ this._maxInnerHeightByWidth[w] = h;
1988
+ }
1989
+ }
1990
+
1991
+ /**
1992
+ * Best-effort "is the virtual keyboard currently dismissed?" for a
1993
+ * focused field. Two signals: an overlay keyboard shrinks the visual
1994
+ * viewport below the layout viewport; a `resizes-content` keyboard
1995
+ * (this app's meta viewport) shrinks the layout viewport itself, which
1996
+ * shows as innerHeight well below the tallest height seen at this
1997
+ * width. When neither says "keyboard up", assume it is hidden — the
1998
+ * cost of a wrong guess is one blur/focus flicker, while a missed
1999
+ * re-open leaves the user with no way to get the keyboard back.
2000
+ * @private
2001
+ */
2002
+ _keyboardProbablyHidden() {
2003
+ if (typeof window === 'undefined') return false;
2004
+ this._noteViewportHeight();
2005
+ const vv = window.visualViewport;
2006
+ if (vv && typeof vv.height === 'number' && window.innerHeight - vv.height > 100) {
2007
+ return false;
2008
+ }
2009
+ const ref = this._maxInnerHeightByWidth[window.innerWidth] || window.innerHeight;
2010
+ return window.innerHeight >= ref - 120;
2011
+ }
2012
+
1598
2013
  /**
1599
2014
  * Collapse keyboard by blurring hidden textarea
1600
2015
  * @private
@@ -1605,6 +2020,7 @@ class MobileTerminalHandler {
1605
2020
  if (this._keyboardCollapsed) return;
1606
2021
  this._keyboardCollapsed = true;
1607
2022
  this._intentionalBlur = true;
2023
+ this._trace('collapse', {});
1608
2024
  this.hiddenTextarea.blur();
1609
2025
  // Restore readonly to prevent keyboard on any accidental focus
1610
2026
  this.hiddenTextarea.setAttribute('readonly', 'true');
@@ -1675,6 +2091,7 @@ class MobileTerminalHandler {
1675
2091
  * @private
1676
2092
  */
1677
2093
  _handleResize() {
2094
+ this._noteViewportHeight();
1678
2095
  if (this.selection.active) {
1679
2096
  requestAnimationFrame(() => {
1680
2097
  if (this.selection.active) {
@@ -1690,6 +2107,7 @@ class MobileTerminalHandler {
1690
2107
  */
1691
2108
  _handleVisualViewport() {
1692
2109
  if (!window.visualViewport) return;
2110
+ this._noteViewportHeight();
1693
2111
 
1694
2112
  const viewportHeight = window.visualViewport.height;
1695
2113
  const windowHeight = window.innerHeight;