@gajae-code/tui 0.13.0 → 0.13.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.13.2] - 2026-08-13
6
+
7
+ ### Fixed
8
+
9
+ - A fast double-Esc (or triple-Esc) whose ESC bytes coalesce into one stdin chunk — which tmux always produces within its escape-time window, and SSH batching produces routinely — is now emitted as individual Escape key presses instead of a single `"\x1b\x1b"` sequence that parsed as the unbound `alt+escape` and silently swallowed both presses. This restores the double-Esc draft-clear and double-Esc selector gestures under tmux/SSH. Option-as-Meta sequences with a real continuation (e.g. Option+Up as `ESC ESC [ A`) remain atomic, and an ESC-cancelled incomplete sequence is still emitted whole.
10
+ - An ambiguous trailing run of Escape bytes now stays buffered until a continuation or the flush timeout resolves it, so `ESC ESC ESC` followed by `[A` in the next chunk still decodes as Escape then `alt+up` instead of two Escapes plus a plain Up that fired the destructive double-Escape gesture.
11
+ - Escape presses immediately followed by a bracketed paste in the same read are now emitted as individual Escape presses instead of one coalesced sequence that parsed as the unbound `alt+escape` and swallowed every press.
12
+ - A long run of Escape bytes arriving as many small reads no longer rescans the accumulated buffer on every read; only the two-byte ambiguous tail stays buffered, so 50,000 byte-by-byte Escape reads cost 50ms instead of 2.4s.
13
+ - A long run of Escape bytes followed by another key now decodes in linear time instead of rescanning the remaining input on every step, which blocked the event loop for over a second on a 50,000-byte run.
14
+ - Apple Terminal.app now retains its default keyboard mode when it does not support the Kitty keyboard protocol, avoiding the modifyOtherKeys fallback that breaks Korean/Hangul IME composition.
15
+
16
+ ## [0.13.1] - 2026-08-11
17
+
5
18
  ### Added
6
19
 
7
20
  - Added atomic same-line deletion APIs and an `Editor` undo callback for keeping application state synchronized with editor history.
@@ -10,6 +23,8 @@
10
23
  - macOS Terminal.app Option+Arrow input is now buffered and decoded as a single Meta-wrapped escape sequence, so Option+Up/Down can open and navigate queued-message selectors.
11
24
  - Terminal.app Meta-prefix decoding now covers legacy Option shortcuts for printable symbols, digits, spaces, and Ctrl+Option symbol chords while preserving enhanced Kitty and modifyOtherKeys Super/Command matching.
12
25
  - Kitty and modifyOtherKeys function-key sequences now match consistently for F1–F12, including unmodified CSI forms.
26
+ - Kitty protocol release/repeat and modifyOtherKeys lock-mask handling now fail closed and stay symmetric across native and TypeScript key matching, including duplicate macOS modifier aliases.
27
+ - TypeScript Kitty and modifyOtherKeys printable decoding now rejects surrogate and out-of-range Unicode code points before text extraction.
13
28
 
14
29
  ## [0.12.21] - 2026-08-09
15
30
 
@@ -26,6 +41,7 @@
26
41
  ### Changed
27
42
 
28
43
  - Native fuzzy matching and image encoding bindings now load only when their TUI feature is used instead of at module startup.
44
+ - Kitty-protocol shortcuts can match modified Korean Dubeolsik compatibility-jamo input when terminals omit base-layout metadata, without treating unmodified or Shift-only text input as shortcuts.
29
45
 
30
46
  ### Fixed
31
47
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@gajae-code/tui",
4
- "version": "0.13.0",
4
+ "version": "0.13.2",
5
5
  "description": "Terminal User Interface library with differential rendering for efficient text-based applications",
6
6
  "homepage": "https://gajae-code.com",
7
7
  "author": "Yeachan-Heo and Gajae Code Contributors",
@@ -36,8 +36,8 @@
36
36
  "fmt": "biome format --write ."
37
37
  },
38
38
  "dependencies": {
39
- "@gajae-code/natives": "0.13.0",
40
- "@gajae-code/utils": "0.13.0",
39
+ "@gajae-code/natives": "0.13.2",
40
+ "@gajae-code/utils": "0.13.2",
41
41
  "lru-cache": "11.3.6",
42
42
  "marked": "18.0.6"
43
43
  },
package/src/keys.ts CHANGED
@@ -301,7 +301,7 @@ export function parseKeyId(value: string): ParsedKeyId | undefined {
301
301
  .map(part => part.trim());
302
302
  const modifiers: KeyModifier[] = [];
303
303
  for (const part of modifierParts) {
304
- const modifier = KEY_MODIFIER_ALIASES[part];
304
+ const modifier = Object.hasOwn(KEY_MODIFIER_ALIASES, part) ? KEY_MODIFIER_ALIASES[part] : undefined;
305
305
  if (!modifier || modifiers.includes(modifier)) return undefined;
306
306
  modifiers.push(modifier);
307
307
  }
@@ -427,9 +427,9 @@ interface ParsedKittySequence {
427
427
 
428
428
  // Regex for Kitty protocol event type detection
429
429
  // Matches CSI sequences with :2 (repeat) or :3 (release) event type
430
- // Format: \x1b[...;modifier:event_type<terminator> where terminator is u, ~, or A-F/H
431
- const KITTY_RELEASE_PATTERN = /^\x1b\[[\d:;]*:3[u~ABCDHF]$/;
432
- const KITTY_REPEAT_PATTERN = /^\x1b\[[\d:;]*:2[u~ABCDHF]$/;
430
+ // Format: \x1b[...;modifier:event_type<terminator> where terminator is u, ~, navigation, or function-key finals
431
+ const KITTY_RELEASE_PATTERN = /^\x1b\[[\d:;]*:3[u~ABCDEFHPQRS]$/;
432
+ const KITTY_REPEAT_PATTERN = /^\x1b\[[\d:;]*:2[u~ABCDEFHPQRS]$/;
433
433
  const KITTY_CSI_U_PATTERN = /^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?(?:;([\d:]*))?u$/;
434
434
  const KITTY_MOD_SHIFT = 1;
435
435
  const KITTY_MOD_ALT = 2;
@@ -437,6 +437,77 @@ const KITTY_MOD_CTRL = 4;
437
437
  const KITTY_MOD_SUPER = 8;
438
438
  const KITTY_MOD_NUM_LOCK = 128;
439
439
  const KITTY_LOCK_MASK = 64 + 128; // Caps Lock + Num Lock
440
+ const KOREAN_DUBEOLSIK_BASE_KEYS = new Map<number, BaseKey>(
441
+ [
442
+ ["ㄱ", "r"],
443
+ ["ㄲ", "r"],
444
+ ["ㄴ", "s"],
445
+ ["ㄷ", "e"],
446
+ ["ㄸ", "e"],
447
+ ["ㄹ", "f"],
448
+ ["ㅁ", "a"],
449
+ ["ㅂ", "q"],
450
+ ["ㅃ", "q"],
451
+ ["ㅅ", "t"],
452
+ ["ㅆ", "t"],
453
+ ["ㅇ", "d"],
454
+ ["ㅈ", "w"],
455
+ ["ㅉ", "w"],
456
+ ["ㅊ", "c"],
457
+ ["ㅋ", "z"],
458
+ ["ㅌ", "x"],
459
+ ["ㅍ", "v"],
460
+ ["ㅎ", "g"],
461
+ ["ㅏ", "k"],
462
+ ["ㅐ", "o"],
463
+ ["ㅑ", "i"],
464
+ ["ㅒ", "o"],
465
+ ["ㅓ", "j"],
466
+ ["ㅔ", "p"],
467
+ ["ㅕ", "u"],
468
+ ["ㅖ", "p"],
469
+ ["ㅗ", "h"],
470
+ ["ㅛ", "y"],
471
+ ["ㅜ", "n"],
472
+ ["ㅠ", "b"],
473
+ ["ㅡ", "m"],
474
+ ["ㅣ", "l"],
475
+ ].map(([character, key]) => [character.codePointAt(0)!, key as BaseKey]),
476
+ );
477
+
478
+ function matchesKoreanDubeolsikKittySequence(data: string, keyId: KeyId): boolean {
479
+ const event = parseKittySequence(data);
480
+ if (!event || event.eventType === 3 || event.baseLayoutKey !== undefined) return false;
481
+
482
+ const baseKey = KOREAN_DUBEOLSIK_BASE_KEYS.get(event.codepoint);
483
+ if (!baseKey) return false;
484
+
485
+ const expected = parseKeyId(keyId);
486
+ if (
487
+ !expected?.modifiers.some(modifier => modifier === "alt" || modifier === "ctrl" || modifier === "super") ||
488
+ expected.baseKey !== baseKey
489
+ )
490
+ return false;
491
+
492
+ let expectedModifier = 0;
493
+ for (const modifier of expected.modifiers) {
494
+ switch (modifier) {
495
+ case "shift":
496
+ expectedModifier |= KITTY_MOD_SHIFT;
497
+ break;
498
+ case "alt":
499
+ expectedModifier |= KITTY_MOD_ALT;
500
+ break;
501
+ case "ctrl":
502
+ expectedModifier |= KITTY_MOD_CTRL;
503
+ break;
504
+ case "super":
505
+ expectedModifier |= KITTY_MOD_SUPER;
506
+ break;
507
+ }
508
+ }
509
+ return (event.modifier & ~KITTY_LOCK_MASK) === expectedModifier;
510
+ }
440
511
  const MODIFY_OTHER_KEYS_PATTERN = /^\x1b\[27;(\d+);(\d+)~$/;
441
512
  const KITTY_KEYPAD_OPERATOR_TEXT: Record<number, string> = {
442
513
  57410: "/",
@@ -517,18 +588,37 @@ function hasControlChars(data: string): boolean {
517
588
  });
518
589
  }
519
590
 
591
+ function isValidProtocolNumber(value: number): boolean {
592
+ return Number.isSafeInteger(value) && value >= 0 && value <= 0xffffffff;
593
+ }
594
+
595
+ function isPrintableCodePoint(value: number): boolean {
596
+ return (
597
+ Number.isSafeInteger(value) &&
598
+ value >= 32 &&
599
+ value <= 0x10ffff &&
600
+ value !== 0x7f &&
601
+ !(value >= 0x80 && value <= 0x9f) &&
602
+ !(value >= 0xd800 && value <= 0xdfff)
603
+ );
604
+ }
605
+
520
606
  function decodeKittyPrintable(data: string): string | undefined {
521
607
  const match = data.match(KITTY_CSI_U_PATTERN);
522
608
  if (!match) return undefined;
523
609
 
524
610
  const codepoint = Number.parseInt(match[1] ?? "", 10);
525
- if (!Number.isFinite(codepoint)) return undefined;
611
+ if (!isValidProtocolNumber(codepoint)) return undefined;
526
612
 
527
- if (match[5] === "3") return undefined;
613
+ const eventTypeText = match[5];
614
+ const eventType =
615
+ eventTypeText === undefined || eventTypeText.length === 0 ? undefined : Number.parseInt(eventTypeText, 10);
616
+ if (eventType !== undefined && eventType !== 1 && eventType !== 2) return undefined;
528
617
 
529
618
  const shiftedKey = match[2] && match[2].length > 0 ? Number.parseInt(match[2], 10) : undefined;
530
619
  const modValue = match[4] ? Number.parseInt(match[4], 10) : 1;
531
- const modifier = Number.isFinite(modValue) ? modValue - 1 : 0;
620
+ if (!isValidProtocolNumber(modValue) || modValue < 1) return undefined;
621
+ const modifier = modValue - 1;
532
622
  const effectiveMod = modifier & ~KITTY_LOCK_MASK;
533
623
  const supportedModifierMask = KITTY_MOD_SHIFT | KITTY_MOD_ALT | KITTY_MOD_CTRL | KITTY_MOD_SUPER;
534
624
 
@@ -541,7 +631,7 @@ function decodeKittyPrintable(data: string): string | undefined {
541
631
  .split(":")
542
632
  .filter(Boolean)
543
633
  .map(value => Number.parseInt(value, 10))
544
- .filter(value => Number.isFinite(value) && value >= 32);
634
+ .filter(value => isPrintableCodePoint(value));
545
635
  if (codepoints.length > 0) {
546
636
  try {
547
637
  return String.fromCodePoint(...codepoints);
@@ -549,6 +639,7 @@ function decodeKittyPrintable(data: string): string | undefined {
549
639
  return undefined;
550
640
  }
551
641
  }
642
+ return undefined;
552
643
  }
553
644
  const keypadOperatorText = KITTY_KEYPAD_OPERATOR_TEXT[codepoint];
554
645
  if (keypadOperatorText) return keypadOperatorText;
@@ -567,7 +658,7 @@ function decodeKittyPrintable(data: string): string | undefined {
567
658
  return undefined;
568
659
  }
569
660
 
570
- if (!Number.isFinite(effectiveCodepoint) || effectiveCodepoint < 32) return undefined;
661
+ if (!isPrintableCodePoint(effectiveCodepoint)) return undefined;
571
662
 
572
663
  try {
573
664
  return String.fromCodePoint(effectiveCodepoint);
@@ -584,7 +675,7 @@ function decodeKittyPrintable(data: string): string | undefined {
584
675
  */
585
676
  export function extractPrintableText(data: string): string | undefined {
586
677
  const printable = decodePrintableKey(data);
587
- if (printable !== undefined) return printable;
678
+ if (printable !== undefined && !hasControlChars(printable)) return printable;
588
679
  if (data.length === 0 || hasControlChars(data)) return undefined;
589
680
  return data;
590
681
  }
@@ -603,7 +694,7 @@ function parseModifyOtherKeysSequence(data: string): ParsedModifyOtherKeysSequen
603
694
  if (!match) return null;
604
695
  const modValue = Number.parseInt(match[1] ?? "", 10);
605
696
  const codepoint = Number.parseInt(match[2] ?? "", 10);
606
- if (!Number.isFinite(modValue) || !Number.isFinite(codepoint)) return null;
697
+ if (!isValidProtocolNumber(modValue) || modValue < 1 || !isValidProtocolNumber(codepoint)) return null;
607
698
  return { codepoint, modifier: modValue - 1 };
608
699
  }
609
700
 
@@ -618,7 +709,7 @@ function decodeModifyOtherKeysPrintable(data: string): string | undefined {
618
709
  if (!parsed) return undefined;
619
710
  const modifier = parsed.modifier & ~KITTY_LOCK_MASK;
620
711
  if ((modifier & ~KITTY_MOD_SHIFT) !== 0) return undefined;
621
- if (!Number.isFinite(parsed.codepoint) || parsed.codepoint < 32) return undefined;
712
+ if (!isPrintableCodePoint(parsed.codepoint)) return undefined;
622
713
  try {
623
714
  return String.fromCodePoint(parsed.codepoint);
624
715
  } catch {
@@ -653,7 +744,10 @@ export function decodePrintableKey(data: string): string | undefined {
653
744
  * @param keyId - Key identifier (e.g., "ctrl+c", "escape", Key.ctrl("c"))
654
745
  */
655
746
  export function matchesKey(data: string, keyId: KeyId): boolean {
656
- return nativeKeys().matchesKey(data, keyId, kittyProtocolActive);
747
+ return (
748
+ nativeKeys().matchesKey(data, keyId, kittyProtocolActive) ||
749
+ (kittyProtocolActive && matchesKoreanDubeolsikKittySequence(data, keyId))
750
+ );
657
751
  }
658
752
 
659
753
  /**
@@ -278,12 +278,33 @@ function continuesAsStringTerminator(remaining: string, index: number): boolean
278
278
  return afterEsc === undefined || afterEsc === "\\";
279
279
  }
280
280
 
281
- function extractCompleteSequences(buffer: string): { sequences: string[]; remainder: string } {
281
+ /**
282
+ * A buffered run of nothing but ESC bytes is N real Escape key presses, not an
283
+ * Option-as-Meta prefix. Emitting the run as one sequence parses as the unbound
284
+ * `alt+escape` and silently swallows every press, so any path that gives up on a
285
+ * continuation must split the run first.
286
+ */
287
+ function splitResolvedEscapeRun(buffer: string): string[] {
288
+ return /^\x1b{2,}$/.test(buffer) ? buffer.split("") : [buffer];
289
+ }
290
+
291
+ /**
292
+ * `knownEscapeRunLength` is the number of leading ESC bytes a previous call
293
+ * already measured and returned as an all-Escape remainder. Resuming the scan
294
+ * there keeps a run delivered across many small reads linear overall instead of
295
+ * re-walking the whole accumulated prefix on every chunk.
296
+ */
297
+ function extractCompleteSequences(
298
+ buffer: string,
299
+ knownEscapeRunLength = 0,
300
+ ): { sequences: string[]; remainder: string; escapeRunRemainder: number } {
282
301
  const sequences: string[] = [];
283
302
  let pos = 0;
284
303
 
285
304
  while (pos < buffer.length) {
286
- const remaining = buffer.slice(pos);
305
+ // Slicing at 0 would copy the whole buffer on every call, which is the
306
+ // dominant cost when a long Escape run arrives as many single-byte reads.
307
+ const remaining = pos === 0 ? buffer : buffer.slice(pos);
287
308
 
288
309
  // Try to extract a sequence starting at this position
289
310
  if (remaining.startsWith(ESC)) {
@@ -299,6 +320,37 @@ function extractCompleteSequences(buffer: string): { sequences: string[]; remain
299
320
  pos += 2;
300
321
  continue;
301
322
  }
323
+ // Measure the ESC run once. Testing the whole suffix on every iteration
324
+ // while the cut below advances only two bytes made a long run quadratic.
325
+ let runLength = pos === 0 ? Math.max(knownEscapeRunLength, 1) : 1;
326
+ while (runLength < remaining.length && remaining[runLength] === ESC) runLength++;
327
+ // A trailing run of nothing but ESC bytes is ambiguous: the next chunk
328
+ // may still deliver the continuation that turns its last ESC into a Meta
329
+ // prefix (ESC ESC ESC + "[A" is bare Escape then Option+Up). Splitting it
330
+ // now would emit an extra Escape and downgrade the wrapped key to a plain
331
+ // one, firing the destructive double-Escape gesture. Keep the whole run
332
+ // buffered; the flush timeout emits it as individual Escape presses.
333
+ if (runLength === remaining.length) {
334
+ // Only the last two bytes of the run are still ambiguous: a Meta prefix
335
+ // is at most ESC ESC, so any earlier ESC is already a settled press.
336
+ // Emitting them now keeps the retained buffer bounded; holding the whole
337
+ // run made every later read rescan it, which is quadratic for a long run
338
+ // delivered as many small chunks. Order of emitted presses is unchanged.
339
+ const settled = runLength - 2;
340
+ if (settled > 0) {
341
+ for (let index = 0; index < settled; index++) sequences.push(ESC);
342
+ return { sequences, remainder: remaining.slice(settled), escapeRunRemainder: 2 };
343
+ }
344
+ return { sequences, remainder: remaining, escapeRunRemainder: runLength };
345
+ }
346
+ // Only the final two ESC bytes can still form a Meta prefix for the
347
+ // continuation that follows the run; everything before them is a settled
348
+ // Escape press. Emitting them in one step keeps the walk linear.
349
+ if (runLength > 2) {
350
+ for (let index = 0; index < runLength - 2; index++) sequences.push(ESC);
351
+ pos += runLength - 2;
352
+ continue;
353
+ }
302
354
  // Find the end of this escape sequence
303
355
  let seqEnd = 1;
304
356
  while (seqEnd <= remaining.length) {
@@ -315,7 +367,23 @@ function extractCompleteSequences(buffer: string): { sequences: string[]; remain
315
367
  // here keeps an unterminated sequence from swallowing the next key.
316
368
  // seqEnd === 1 is excluded so Meta sequences (ESC ESC) still parse.
317
369
  if (remaining[seqEnd] === ESC && seqEnd >= 2 && !continuesAsStringTerminator(remaining, seqEnd)) {
318
- sequences.push(candidate);
370
+ // A bare Escape may be followed in the same read by a Meta-wrapped
371
+ // sequence (ESC ESC ESC [ A). Keep the final Meta prefix intact;
372
+ // splitting all three ESC bytes would turn the wrapped arrow into a
373
+ // plain arrow after a destructive double-Escape gesture.
374
+ const trailing = remaining.slice(seqEnd);
375
+ if (/^\x1b+$/.test(candidate) && /^\x1b[^\x1b]/.test(trailing)) {
376
+ sequences.push(...candidate.slice(0, -1).split(""));
377
+ pos += seqEnd - 1;
378
+ break;
379
+ }
380
+ // A cut candidate of nothing but ESC bytes is real Escape key
381
+ // presses, not an Option-as-Meta prefix: a following ESC proves
382
+ // no continuation (like "[A") belongs to it. Emitting the pair
383
+ // as one sequence would parse as the unbound "alt+escape" and
384
+ // silently swallow both presses.
385
+ if (/^\x1b+$/.test(candidate)) sequences.push(...candidate.split(""));
386
+ else sequences.push(candidate);
319
387
  pos += seqEnd;
320
388
  break;
321
389
  }
@@ -329,7 +397,7 @@ function extractCompleteSequences(buffer: string): { sequences: string[]; remain
329
397
  }
330
398
 
331
399
  if (seqEnd > remaining.length) {
332
- return { sequences, remainder: remaining };
400
+ return { sequences, remainder: remaining, escapeRunRemainder: 0 };
333
401
  }
334
402
  } else {
335
403
  // Not an escape sequence - take a single Unicode code point. Keep a
@@ -337,7 +405,7 @@ function extractCompleteSequences(buffer: string): { sequences: string[]; remain
337
405
  // complete it.
338
406
  const firstCodeUnit = remaining.charCodeAt(0);
339
407
  if (isHighSurrogate(firstCodeUnit)) {
340
- if (remaining.length === 1) return { sequences, remainder: remaining };
408
+ if (remaining.length === 1) return { sequences, remainder: remaining, escapeRunRemainder: 0 };
341
409
  const secondCodeUnit = remaining.charCodeAt(1);
342
410
  if (isLowSurrogate(secondCodeUnit)) {
343
411
  sequences.push(remaining.slice(0, 2));
@@ -350,7 +418,7 @@ function extractCompleteSequences(buffer: string): { sequences: string[]; remain
350
418
  }
351
419
  }
352
420
 
353
- return { sequences, remainder: "" };
421
+ return { sequences, remainder: "", escapeRunRemainder: 0 };
354
422
  }
355
423
 
356
424
  export type StdinBufferOptions = {
@@ -379,6 +447,9 @@ export type StdinBufferEventMap = {
379
447
  */
380
448
  export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
381
449
  #buffer: string = "";
450
+ // Length of the leading all-Escape run already measured in #buffer, so a run
451
+ // arriving as many small reads is scanned once overall instead of per chunk.
452
+ #bufferedEscapeRunLength = 0;
382
453
  #timeout?: NodeJS.Timeout;
383
454
  readonly #timeoutMs: number;
384
455
  #pasteMode: boolean = false;
@@ -486,6 +557,7 @@ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
486
557
  if (this.#pasteMode) {
487
558
  this.#pasteBuffer += this.#buffer;
488
559
  this.#buffer = "";
560
+ this.#bufferedEscapeRunLength = 0;
489
561
 
490
562
  const endIndex = this.#pasteBuffer.indexOf(BRACKETED_PASTE_END);
491
563
  if (endIndex !== -1) {
@@ -505,7 +577,11 @@ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
505
577
  return;
506
578
  }
507
579
 
508
- const startIndex = this.#buffer.indexOf(BRACKETED_PASTE_START);
580
+ // A known all-Escape prefix cannot contain the paste introducer, so start
581
+ // the scan just far enough back to catch a marker straddling the boundary.
582
+ // Rescanning the whole retained run on every read made a long run quadratic.
583
+ const pasteScanFrom = Math.max(0, this.#bufferedEscapeRunLength - BRACKETED_PASTE_START.length);
584
+ const startIndex = this.#buffer.indexOf(BRACKETED_PASTE_START, pasteScanFrom);
509
585
  if (startIndex !== -1) {
510
586
  if (startIndex > 0) {
511
587
  const beforePaste = this.#buffer.slice(0, startIndex);
@@ -513,8 +589,12 @@ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
513
589
  for (const sequence of result.sequences) {
514
590
  this.#emitDataSequence(sequence);
515
591
  }
592
+ // A bracketed paste start proves no Meta continuation is coming for a
593
+ // buffered Escape run, so resolve it into individual presses here too.
516
594
  if (result.remainder.length > 0) {
517
- this.#emitDataSequence(result.remainder);
595
+ for (const sequence of splitResolvedEscapeRun(result.remainder)) {
596
+ this.#emitDataSequence(sequence);
597
+ }
518
598
  }
519
599
  }
520
600
 
@@ -523,6 +603,7 @@ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
523
603
  this.#pasteMode = true;
524
604
  this.#pasteBuffer = this.#buffer;
525
605
  this.#buffer = "";
606
+ this.#bufferedEscapeRunLength = 0;
526
607
 
527
608
  const endIndex = this.#pasteBuffer.indexOf(BRACKETED_PASTE_END);
528
609
  if (endIndex !== -1) {
@@ -542,8 +623,11 @@ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
542
623
  return;
543
624
  }
544
625
 
545
- const result = extractCompleteSequences(this.#buffer);
626
+ const result = extractCompleteSequences(this.#buffer, this.#bufferedEscapeRunLength);
546
627
  this.#buffer = result.remainder;
628
+ // Remember an all-Escape remainder so the next chunk resumes the run scan
629
+ // at its end rather than re-walking every byte received so far.
630
+ this.#bufferedEscapeRunLength = result.escapeRunRemainder;
547
631
 
548
632
  for (const sequence of result.sequences) {
549
633
  if (isSgrMousePrefix(sequence) && !isSgrMouseSequence(sequence)) continue;
@@ -574,11 +658,13 @@ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
574
658
  }
575
659
  const remainder = suffix.slice(index);
576
660
  this.#buffer = "";
661
+ this.#bufferedEscapeRunLength = 0;
577
662
  this.#pendingKittyPrintableCodepoint = undefined;
578
663
  if (remainder) this.process(remainder);
579
664
  return;
580
665
  }
581
666
  this.#buffer = "";
667
+ this.#bufferedEscapeRunLength = 0;
582
668
  this.#pendingKittyPrintableCodepoint = undefined;
583
669
  this.#sgrQuarantine = true;
584
670
  this.#sgrQuarantineBytes = suffix.length;
@@ -709,12 +795,23 @@ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
709
795
 
710
796
  if (isSgrMousePrefix(this.#buffer)) {
711
797
  this.#buffer = "";
798
+ this.#bufferedEscapeRunLength = 0;
712
799
  this.#pendingKittyPrintableCodepoint = undefined;
713
800
  return pendingMeta === undefined ? [] : [pendingMeta];
714
801
  }
715
802
 
716
- const sequences = pendingMeta === undefined ? [this.#buffer] : [pendingMeta, this.#buffer];
803
+ // A buffer of nothing but ESC bytes at flush time is N real Escape key
804
+ // presses that arrived faster than the flush window (tmux forwards a
805
+ // quick double-Esc as one "\x1b\x1b" chunk within escape-time). Keeping
806
+ // the pair atomic is only correct while a continuation can still turn it
807
+ // into an Option-as-Meta sequence (ESC ESC [ A); once the flush timeout
808
+ // fires, no continuation is coming, and emitting the pair as one
809
+ // sequence parses as the unbound "alt+escape" — silently swallowing
810
+ // both presses and breaking the double-Esc draft-clear gesture.
811
+ const flushedBuffer = splitResolvedEscapeRun(this.#buffer);
812
+ const sequences = pendingMeta === undefined ? flushedBuffer : [pendingMeta, ...flushedBuffer];
717
813
  this.#buffer = "";
814
+ this.#bufferedEscapeRunLength = 0;
718
815
  this.#pendingKittyPrintableCodepoint = undefined;
719
816
  return sequences;
720
817
  }
@@ -725,6 +822,7 @@ export class StdinBuffer extends EventEmitter<StdinBufferEventMap> {
725
822
  this.#timeout = undefined;
726
823
  }
727
824
  this.#buffer = "";
825
+ this.#bufferedEscapeRunLength = 0;
728
826
  this.#pasteMode = false;
729
827
  this.#pasteBuffer = "";
730
828
  this.#pendingKittyPrintableCodepoint = undefined;
package/src/terminal.ts CHANGED
@@ -51,6 +51,10 @@ export function keyboardEnhancementEnabled(): boolean {
51
51
  return $flag("GJC_TUI_KEYBOARD_PROTOCOL", true);
52
52
  }
53
53
 
54
+ function isAppleTerminal(): boolean {
55
+ return $env.TERM_PROGRAM === "Apple_Terminal";
56
+ }
57
+
54
58
  /**
55
59
  * Minimal terminal interface for TUI
56
60
  */
@@ -794,18 +798,18 @@ export class ProcessTerminal implements Terminal {
794
798
  }
795
799
  this.#safeWrite("\x1b[?u");
796
800
  this.#stdinBuffer?.noteProbeIssued();
797
- // Windows Terminal and conhost do not implement the Kitty keyboard
801
+ // Windows Terminal and Apple Terminal do not implement the Kitty keyboard
798
802
  // protocol, so the query above never activates it there. They do honor the
799
- // modifyOtherKeys fallback below — but that mode breaks Windows CJK/Hangul
800
- // IME composition: Alt+Enter (and other chords) bypass the IME commit, so
801
- // the syllable still being composed is never delivered to the app and the
803
+ // modifyOtherKeys fallback below — but that mode breaks CJK/Hangul IME
804
+ // composition: Alt+Enter (and other chords) bypass the IME commit, so the
805
+ // syllable still being composed is never delivered to the app and the
802
806
  // action fires on empty text (e.g. queue-message no-ops unless the user
803
807
  // types a trailing space to force a commit first). Skip the fallback on
804
- // win32; legacy encodings still deliver Alt+Enter (ESC CR) and the newline
805
- // chords, and IME composition works again. Opt back in with
808
+ // these terminals; legacy encodings still deliver Alt+Enter (ESC CR) and
809
+ // the newline chords, and IME composition works again. Opt back in with
806
810
  // GJC_TUI_KEYBOARD_PROTOCOL=0 disabling all enhancement, or force-enable
807
- // elsewhere if a Kitty-capable Windows terminal appears.
808
- if (process.platform === "win32") {
811
+ // elsewhere if a Kitty-capable terminal appears.
812
+ if (process.platform === "win32" || isAppleTerminal()) {
809
813
  return;
810
814
  }
811
815
  this.#modifyOtherKeysTimeout = setTimeout(() => {