1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Paste-burst handling — turn rapid keystrokes (terminals without bracketed
//! paste) into a single committed buffer instead of N individual chars.
//!
//! Extracted from `tui/ui.rs` (P1.2). The owning state machine lives on
//! `App.paste_burst` (`tui::paste_burst`); these helpers wire it to the key
//! event loop and the composer's text buffer.
use std::time::Instant;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::app::{App, looks_like_slash_command_input};
use super::paste_burst::CharDecision;
/// Process a key in the context of paste-burst detection. Returns `true`
/// when the key was fully handled by the paste machinery (caller skips
/// further input handling); `false` when the key still needs the normal
/// composer path.
pub fn handle_paste_burst_key(app: &mut App, key: &KeyEvent, now: Instant) -> bool {
if !app.use_paste_burst_detection {
return false;
}
// Once we've observed a real `Event::Paste` in this session, bracketed
// paste is verified working and the rapid-keystroke heuristic is
// unnecessary. Skipping it eliminates false positives on fast typing /
// IME commits / autocomplete on terminals with reliable bracketed
// paste (the dominant case on iTerm2 / Ghostty / WezTerm / Windows
// Terminal).
if app.bracketed_paste_seen {
return false;
}
let has_ctrl_alt_or_super = key.modifiers.contains(KeyModifiers::CONTROL)
|| key.modifiers.contains(KeyModifiers::ALT)
|| key.modifiers.contains(KeyModifiers::SUPER);
match key.code {
KeyCode::Enter => {
if !in_command_context(app) && app.paste_burst.append_newline_if_active(now) {
return true;
}
if !in_command_context(app)
&& app.paste_burst.newline_should_insert_instead_of_submit(now)
{
app.insert_char('\n');
// Deliberately no `extend_window` here. This Enter arrived
// with no burst being assembled, so it is only *maybe* a
// pasted newline. Re-arming on that guess let each absorbed
// Enter buy another 120ms, so a user pressing Enter to send
// never submitted — every press just added a newline. The
// window now always expires 120ms after the last real
// keystroke; newlines genuinely inside a paste are absorbed
// by `append_newline_if_active` above, which does re-arm.
return true;
}
}
KeyCode::Char(c) if !has_ctrl_alt_or_super => {
if !c.is_ascii() {
// IME-committed characters (Chinese, Japanese, Korean)
// arrive as individual KeyCode::Char events, typically with
// tens-of-milliseconds gaps between each committed character.
// Paste-burst buffering would lose characters when the IME
// commits slower than the burst heuristic's timing window.
//
// We still call note_plain_char + arm the suppression window
// so that:
// 1. The burst timing counter advances for non-IME fast
// typing on terminals without bracketed paste support.
// 2. The Enter-suppression window stays open during a rapid
// non-ASCII sequence, preventing premature submission.
// But the character is inserted directly into the composer
// rather than placed into the paste-burst buffer.
//
// The window is sized by how fast the characters are
// arriving: a lone IME candidate commit is ordinary typing
// and must not swallow the Enter that follows it, while a
// run of characters at paste speed keeps the full window.
// See `PasteBurst::arm_window_for_direct_char`.
if let Some(pending) = app.paste_burst.flush_before_modified_input() {
app.insert_str(&pending);
}
let rapid_chars = app.paste_burst.note_plain_char(now);
app.paste_burst.arm_window_for_direct_char(now, rapid_chars);
app.insert_char(c);
return true;
}
let decision = app.paste_burst.on_plain_char(c, now);
return handle_paste_burst_decision(app, decision, c, now);
}
_ => {}
}
false
}
/// Apply a paste-burst decision to the composer buffer. Some decisions
/// retroactively grab the last few chars from the input back into the
/// pending paste buffer (when the heuristic decides the recent typing was
/// actually a paste).
pub fn handle_paste_burst_decision(
app: &mut App,
decision: CharDecision,
c: char,
now: Instant,
) -> bool {
match decision {
CharDecision::RetainFirstChar => true,
CharDecision::BeginBufferFromPending | CharDecision::BufferAppend => {
app.paste_burst.append_char_to_buffer(c, now);
true
}
CharDecision::BeginBuffer { retro_chars } => {
if apply_paste_burst_retro_capture(app, retro_chars as usize, c, now) {
return true;
}
app.insert_char(c);
true
}
}
}
fn apply_paste_burst_retro_capture(
app: &mut App,
retro_chars: usize,
c: char,
now: Instant,
) -> bool {
let cursor_byte = app.cursor_byte_index();
let before = &app.composer.input[..cursor_byte];
let Some(grab) = app
.composer
.paste_burst
.decide_begin_buffer(now, before, retro_chars)
else {
return false;
};
if !grab.grabbed.is_empty() {
app.input.replace_range(grab.start_byte..cursor_byte, "");
let removed = grab.grabbed.chars().count();
app.cursor_position = app.cursor_position.saturating_sub(removed);
}
app.paste_burst.append_char_to_buffer(c, now);
true
}
fn in_command_context(app: &App) -> bool {
looks_like_slash_command_input(&app.input)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use crate::tui::app::TuiOptions;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::path::PathBuf;
use std::time::{Duration, Instant};
fn test_app() -> App {
let options = TuiOptions {
..crate::test_support::test_tui_options(PathBuf::from("."))
};
let mut app = App::new(options, &Config::default());
app.use_paste_burst_detection = true;
app
}
fn plain(ch: char) -> KeyEvent {
KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE)
}
#[test]
fn raw_short_cjk_multiline_paste_buffers_enter_instead_of_submitting() {
// #1302: pasting short CJK content like "请联网搜索:\nSTM32 …" used
// to silently submit the first line because the heuristic decided
// it wasn't paste-like (no whitespace + under 16 chars). The
// non-ASCII bypass now classifies it as a paste so the Enter is
// absorbed into the burst buffer.
let mut app = test_app();
let t0 = Instant::now();
let pasted = "请联网搜索:\nSTM32 商业应用案例";
for (i, ch) in pasted.chars().enumerate() {
let key = if ch == '\n' {
KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)
} else {
plain(ch)
};
let handled =
handle_paste_burst_key(&mut app, &key, t0 + Duration::from_millis(i as u64));
assert!(
handled,
"raw paste character {ch:?} must be handled by paste-burst detection"
);
}
// Non-ASCII characters are now inserted directly into the composer
// rather than buffered by paste burst. The Enter suppression window
// kept the newline from submitting prematurely.
assert_eq!(app.input, pasted);
}
#[test]
fn raw_multiline_paste_buffers_enter_instead_of_submitting() {
let mut app = test_app();
let t0 = Instant::now();
assert!(handle_paste_burst_key(&mut app, &plain('a'), t0));
assert!(handle_paste_burst_key(
&mut app,
&plain('b'),
t0 + Duration::from_millis(1)
));
assert!(handle_paste_burst_key(
&mut app,
&plain('c'),
t0 + Duration::from_millis(2)
));
assert!(handle_paste_burst_key(
&mut app,
&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
t0 + Duration::from_millis(3)
));
assert!(app.input.is_empty(), "paste remains buffered until idle");
assert!(app.flush_paste_burst_if_due(
t0 + Duration::from_millis(3)
+ crate::tui::paste_burst::PasteBurst::recommended_active_flush_delay()
));
assert_eq!(app.input, "abc\n");
}
/// A raw CJK paste can open with a one-character line
/// ("好\n…"). That single character never forms a paste-speed *run*, so
/// the short window is all that protects the embedded newline — the
/// newline arrives within the burst interval, so it must still be
/// absorbed rather than submitting "好" on its own (#1302).
#[test]
fn raw_paste_with_single_char_first_line_still_absorbs_its_newline() {
let mut app = test_app();
let t0 = Instant::now();
assert!(handle_paste_burst_key(&mut app, &plain('好'), t0));
assert!(
handle_paste_burst_key(
&mut app,
&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
t0 + Duration::from_millis(1),
),
"the newline of a raw paste lands within the burst interval and \
must be absorbed, not submitted"
);
assert_eq!(app.input, "好\n");
}
/// The IME half of the same ambiguity: one committed character followed
/// by a human-speed Enter is a send gesture. `handle_paste_burst_key`
/// must decline the Enter so it reaches the normal submit path.
#[test]
fn ime_commit_then_human_enter_falls_through_to_submit() {
let mut app = test_app();
let t0 = Instant::now();
assert!(handle_paste_burst_key(&mut app, &plain('好'), t0));
assert_eq!(app.input, "好");
assert!(
!handle_paste_burst_key(
&mut app,
&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
t0 + Duration::from_millis(30),
),
"Enter 30ms after an IME candidate commit is a send, not a \
pasted newline"
);
assert_eq!(app.input, "好", "no stray newline may be inserted");
}
/// A whole IME-typed CJK sentence, one commit at a time at human speed,
/// followed by Enter: every character lands verbatim and the Enter still
/// reaches the submit path.
#[test]
fn ime_typed_sentence_then_enter_falls_through_to_submit() {
let mut app = test_app();
let t0 = Instant::now();
for (i, ch) in "你好世界".chars().enumerate() {
let now = t0 + Duration::from_millis(50 * i as u64);
assert!(handle_paste_burst_key(&mut app, &plain(ch), now));
}
assert_eq!(app.input, "你好世界");
assert!(
!handle_paste_burst_key(
&mut app,
&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
t0 + Duration::from_millis(180),
),
"Enter after an IME-typed CJK message must submit"
);
assert_eq!(app.input, "你好世界");
}
/// Absorbing an Enter outside an active burst must not re-arm the
/// suppression window. It used to, so each swallowed Enter bought
/// another 120ms and a user pressing Enter to send only ever added
/// newlines. The first Enter is still absorbed (#1073 trailing-newline
/// protection); the next one submits.
#[test]
fn absorbed_enter_does_not_extend_the_suppression_window() {
let mut app = test_app();
let t0 = Instant::now();
// Unbracketed paste of "abc" with no trailing newline.
for (i, ch) in "abc".chars().enumerate() {
let now = t0 + Duration::from_millis(i as u64);
assert!(handle_paste_burst_key(&mut app, &plain(ch), now));
}
let last_char = t0 + Duration::from_millis(2);
assert!(app.flush_paste_burst_if_due(
last_char + crate::tui::paste_burst::PasteBurst::recommended_active_flush_delay()
));
assert_eq!(app.input, "abc");
// Still inside the window: this could be the paste's trailing
// newline, so it is absorbed.
assert!(handle_paste_burst_key(
&mut app,
&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
last_char + Duration::from_millis(60),
));
assert_eq!(app.input, "abc\n");
// Past the window measured from the last *keystroke* — the absorbed
// Enter bought no extra time, so this one submits.
assert!(
!handle_paste_burst_key(
&mut app,
&KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
last_char + Duration::from_millis(121),
),
"the second Enter must reach the submit path"
);
assert_eq!(app.input, "abc\n", "no second newline may be inserted");
}
#[test]
fn paste_buffered_question_mark_does_not_fall_through_to_help_shortcut() {
let mut app = test_app();
let t0 = Instant::now();
assert!(handle_paste_burst_key(&mut app, &plain('?'), t0));
assert!(app.input.is_empty(), "shortcut char stays buffered first");
assert!(app.view_stack.is_empty(), "help modal must not open");
assert!(app.flush_paste_burst_if_due(
t0 + crate::tui::paste_burst::PasteBurst::recommended_flush_delay()
));
assert_eq!(app.input, "?");
}
/// Pin the IME-input contract: macOS/Windows input methods commit
/// each Chinese character as a single `KeyCode::Char(c)` event
/// after the candidate popup closes. Each codepoint fits in a
/// `char` (no surrogate pair concerns for BMP chars), so a
/// straightforward sequence of plain-char events must land in
/// `app.input` verbatim — no ASCII filter, no byte-vs-char index
/// drift, no paste-burst false-positive that buffers the chars
/// indefinitely.
#[test]
fn ime_chinese_chars_route_through_to_composer() {
let mut app = test_app();
let t0 = Instant::now();
// Type the four Chinese codepoints "你好世界" one event at a
// time, with realistic ~50ms gaps so the paste-burst heuristic
// doesn't classify them as a paste burst.
for (i, ch) in "你好世界".chars().enumerate() {
let now = t0 + Duration::from_millis(50 * i as u64);
let _ = handle_paste_burst_key(&mut app, &plain(ch), now);
}
// Past the active-flush delay so any buffered burst commits.
let after = t0
+ Duration::from_millis(50 * 4)
+ crate::tui::paste_burst::PasteBurst::recommended_active_flush_delay();
let _ = app.flush_paste_burst_if_due(after);
assert_eq!(
app.input, "你好世界",
"IME-typed Chinese characters must land in composer verbatim"
);
assert_eq!(
app.cursor_position, 4,
"cursor advances by one per codepoint, not per UTF-8 byte"
);
}
/// Pin the bracketed-paste contract for CJK content: pasted
/// Chinese text (e.g. when a user copies a question from a
/// Chinese website and pastes into the composer) must preserve
/// every codepoint and not double-count multi-byte chars in the
/// cursor position.
#[test]
fn bracketed_paste_preserves_chinese_and_mixed_text() {
let mut app = test_app();
app.insert_paste_text("你好世界 hello 世界 café");
assert_eq!(app.input, "你好世界 hello 世界 café");
// 4 + 1 + 5 + 1 + 2 + 1 + 4 = 18 codepoints (counting é as one).
assert_eq!(app.cursor_position, 18);
}
#[test]
fn paste_burst_detection_can_be_disabled_without_disabling_bracketed_paste() {
let mut app = test_app();
app.use_paste_burst_detection = false;
assert!(!handle_paste_burst_key(
&mut app,
&plain('a'),
Instant::now()
));
assert!(app.input.is_empty());
app.insert_paste_text("line 1\r\nline 2");
assert_eq!(app.input, "line 1\nline 2");
assert!(app.use_bracketed_paste);
}
/// Once the session has observed a real `Event::Paste`, the
/// rapid-keystroke heuristic must short-circuit. This pins the new
/// "auto-disable paste-burst on verified bracketed paste" behavior so
/// fast typing / IME commits / autocomplete on capable terminals can't
/// be mis-classified as a paste burst.
#[test]
fn paste_burst_short_circuits_after_bracketed_paste_observed() {
let mut app = test_app();
app.use_paste_burst_detection = true;
app.bracketed_paste_seen = true;
let t0 = Instant::now();
for (i, ch) in "abcdefgh".chars().enumerate() {
// Type fast enough that paste-burst would normally fire.
let now = t0 + Duration::from_millis(i as u64);
assert!(
!handle_paste_burst_key(&mut app, &plain(ch), now),
"paste-burst must NOT consume keys once bracketed paste verified"
);
}
// No buffering — every char fell through to the normal composer
// path (the test harness doesn't insert chars when the burst
// handler returns false; we only assert the short-circuit
// contract here).
assert!(app.input.is_empty());
}
}