codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
Documentation
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Paste-burst detection for terminals without reliable bracketed paste.

use std::time::{Duration, Instant};

const PASTE_BURST_MIN_CHARS: u16 = 3;
const PASTE_BURST_CHAR_INTERVAL: Duration = Duration::from_millis(8);
const PASTE_ENTER_SUPPRESS_WINDOW: Duration = Duration::from_millis(120);
#[cfg(not(windows))]
const PASTE_BURST_ACTIVE_IDLE_TIMEOUT: Duration = Duration::from_millis(8);
#[cfg(windows)]
const PASTE_BURST_ACTIVE_IDLE_TIMEOUT: Duration = Duration::from_millis(60);

#[derive(Default)]
pub(crate) struct PasteBurst {
    last_plain_char_time: Option<Instant>,
    consecutive_plain_char_burst: u16,
    burst_window_until: Option<Instant>,
    buffer: String,
    active: bool,
    pending_first_char: Option<(char, Instant)>,
}

pub(crate) enum CharDecision {
    BeginBuffer { retro_chars: u16 },
    BufferAppend,
    RetainFirstChar,
    BeginBufferFromPending,
}

pub(crate) struct RetroGrab {
    pub start_byte: usize,
    pub grabbed: String,
}

pub(crate) enum FlushResult {
    Paste(String),
    Typed(char),
    None,
}

impl PasteBurst {
    #[cfg(test)]
    pub fn recommended_flush_delay() -> Duration {
        PASTE_BURST_CHAR_INTERVAL + Duration::from_millis(1)
    }

    #[cfg(test)]
    pub(crate) fn recommended_active_flush_delay() -> Duration {
        PASTE_BURST_ACTIVE_IDLE_TIMEOUT + Duration::from_millis(1)
    }

    pub fn on_plain_char(&mut self, ch: char, now: Instant) -> CharDecision {
        self.note_plain_char(now);

        if self.active {
            self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
            return CharDecision::BufferAppend;
        }

        if let Some((held, held_at)) = self.pending_first_char
            && now.duration_since(held_at) <= PASTE_BURST_CHAR_INTERVAL
        {
            self.active = true;
            let _ = self.pending_first_char.take();
            self.buffer.push(held);
            self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
            return CharDecision::BeginBufferFromPending;
        }

        if self.consecutive_plain_char_burst >= PASTE_BURST_MIN_CHARS {
            return CharDecision::BeginBuffer {
                retro_chars: self.consecutive_plain_char_burst.saturating_sub(1),
            };
        }

        self.pending_first_char = Some((ch, now));
        CharDecision::RetainFirstChar
    }

    #[allow(dead_code)]
    pub fn on_plain_char_no_hold(&mut self, now: Instant) -> Option<CharDecision> {
        self.note_plain_char(now);

        if self.active {
            self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
            return Some(CharDecision::BufferAppend);
        }

        if self.consecutive_plain_char_burst >= PASTE_BURST_MIN_CHARS {
            return Some(CharDecision::BeginBuffer {
                retro_chars: self.consecutive_plain_char_burst.saturating_sub(1),
            });
        }

        None
    }

    pub(crate) fn note_plain_char(&mut self, now: Instant) -> u16 {
        match self.last_plain_char_time {
            Some(prev) if now.duration_since(prev) <= PASTE_BURST_CHAR_INTERVAL => {
                self.consecutive_plain_char_burst =
                    self.consecutive_plain_char_burst.saturating_add(1);
            }
            _ => self.consecutive_plain_char_burst = 1,
        }
        self.last_plain_char_time = Some(now);
        self.consecutive_plain_char_burst
    }

    pub fn flush_if_due(&mut self, now: Instant) -> FlushResult {
        let timeout = if self.is_active_internal() {
            PASTE_BURST_ACTIVE_IDLE_TIMEOUT
        } else {
            PASTE_BURST_CHAR_INTERVAL
        };
        let timed_out = self
            .last_plain_char_time
            .is_some_and(|t| now.duration_since(t) > timeout);

        if timed_out && self.is_active_internal() {
            self.active = false;
            let out = std::mem::take(&mut self.buffer);
            // `burst_window_until` intentionally survives the flush: the idle
            // timeout is only 8ms, and a paste's trailing newline can land
            // just after it over a laggy link (SSH/tmux). Dropping the window
            // here would let that pasted newline submit a partial paste
            // (#1073). The window stays *bounded* instead: absorbing an Enter
            // outside an active burst no longer re-arms it, so suppression
            // always ends `PASTE_ENTER_SUPPRESS_WINDOW` after the last real
            // keystroke.
            FlushResult::Paste(out)
        } else if timed_out {
            if let Some((ch, _)) = self.pending_first_char.take() {
                FlushResult::Typed(ch)
            } else {
                FlushResult::None
            }
        } else {
            FlushResult::None
        }
    }

    /// Return the remaining delay before a pending char/paste buffer must flush.
    ///
    /// This lets the UI event loop avoid sleeping past the flush deadline.
    #[must_use]
    pub fn next_flush_delay(&self, now: Instant) -> Option<Duration> {
        let last = self.last_plain_char_time?;
        let timeout = if self.is_active_internal() {
            PASTE_BURST_ACTIVE_IDLE_TIMEOUT
        } else {
            PASTE_BURST_CHAR_INTERVAL
        };
        Some(timeout.saturating_sub(now.duration_since(last)))
    }

    pub fn append_newline_if_active(&mut self, now: Instant) -> bool {
        if self.is_active() {
            self.buffer.push('\n');
            self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
            true
        } else {
            false
        }
    }

    pub fn newline_should_insert_instead_of_submit(&self, now: Instant) -> bool {
        let in_burst_window = self.burst_window_until.is_some_and(|until| now <= until);
        self.is_active() || in_burst_window
    }

    pub fn extend_window(&mut self, now: Instant) {
        self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
    }

    pub fn begin_with_retro_grabbed(&mut self, grabbed: String, now: Instant) {
        if !grabbed.is_empty() {
            self.buffer.push_str(&grabbed);
        }
        self.active = true;
        self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
    }

    pub fn append_char_to_buffer(&mut self, ch: char, now: Instant) {
        self.buffer.push(ch);
        self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
    }

    #[allow(dead_code)]
    pub fn try_append_char_if_active(&mut self, ch: char, now: Instant) -> bool {
        if self.active || !self.buffer.is_empty() {
            self.append_char_to_buffer(ch, now);
            true
        } else {
            false
        }
    }

    pub fn decide_begin_buffer(
        &mut self,
        now: Instant,
        before: &str,
        retro_chars: usize,
    ) -> Option<RetroGrab> {
        let start_byte = retro_start_index(before, retro_chars);
        let grabbed = before[start_byte..].to_string();
        // Short CJK first-line pastes (e.g. "请联网搜索:" copied from a web
        // chat) used to fail the heuristic — no whitespace and under the
        // 16-char threshold meant the trailing pasted newline fell through
        // as a real Enter and submitted the first line on its own.
        // Treating any non-ASCII run as paste-like fixes this without
        // false-firing on ASCII typing (#1302, PR #1342 from @reidliu41).
        let looks_pastey = grabbed.chars().any(char::is_whitespace)
            || !grabbed.is_ascii()
            || grabbed.chars().count() >= 16;
        if looks_pastey {
            self.begin_with_retro_grabbed(grabbed.clone(), now);
            Some(RetroGrab {
                start_byte,
                grabbed,
            })
        } else {
            None
        }
    }

    pub fn flush_before_modified_input(&mut self) -> Option<String> {
        if !self.is_active() {
            return None;
        }
        self.active = false;
        let mut out = std::mem::take(&mut self.buffer);
        if let Some((ch, _)) = self.pending_first_char.take() {
            out.push(ch);
        }
        Some(out)
    }

    /// Reset burst-accumulation state without clearing the suppression window.
    ///
    /// Used when a non-char key (Tab, etc.) arrives during an active burst as
    /// part of table-data paste. The buffer was flushed upstream; only the
    /// active state is reset so `burst_window_until` stays alive and a trailing
    /// Enter is still absorbed as a newline (#2134).
    ///
    /// # Panics
    ///
    /// Panics in debug builds if `buffer` is non-empty — the caller must flush
    /// via `flush_before_modified_input` first.
    pub fn deactivate_keep_window(&mut self) {
        debug_assert!(
            self.buffer.is_empty(),
            "buffer must be flushed before deactivating"
        );
        self.consecutive_plain_char_burst = 0;
        self.last_plain_char_time = None;
        self.active = false;
        self.pending_first_char = None;
        // burst_window_until intentionally NOT cleared
    }

    pub fn is_active(&self) -> bool {
        self.is_active_internal() || self.pending_first_char.is_some()
    }

    fn is_active_internal(&self) -> bool {
        self.active || !self.buffer.is_empty()
    }

    pub fn clear_after_explicit_paste(&mut self) {
        self.last_plain_char_time = None;
        self.consecutive_plain_char_burst = 0;
        self.burst_window_until = None;
        self.active = false;
        self.buffer.clear();
        self.pending_first_char = None;
    }

    /// Arm the Enter-suppression window for a non-ASCII character that was
    /// inserted straight into the composer instead of being buffered (the
    /// IME / raw-CJK path in `tui::paste`).
    ///
    /// `rapid_chars` is the run length reported by [`Self::note_plain_char`].
    ///
    /// A *lone* commit only earns a burst-interval window. An IME candidate
    /// commit is ordinary typing: the user may press Enter to send a
    /// message ending in a CJK character tens of milliseconds later, and the
    /// full 120ms window turned that Enter into a stray newline. A real raw
    /// paste delivers its trailing newline within microseconds of the last
    /// character, so the short window still absorbs it — including the
    /// single-character first line of a CJK paste (#1302).
    ///
    /// Two or more characters at paste speed mean the stream *is* a paste,
    /// so the full window applies and later lines stay absorbed.
    pub fn arm_window_for_direct_char(&mut self, now: Instant, rapid_chars: u16) {
        if rapid_chars >= 2 {
            self.extend_window(now);
        } else {
            self.burst_window_until = Some(now + PASTE_BURST_CHAR_INTERVAL);
        }
    }
}

pub(crate) fn retro_start_index(before: &str, retro_chars: usize) -> usize {
    if retro_chars == 0 {
        return before.len();
    }
    before
        .char_indices()
        .rev()
        .nth(retro_chars.saturating_sub(1))
        .map(|(idx, _)| idx)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ascii_first_char_is_held_then_flushes_as_typed() {
        let mut burst = PasteBurst::default();
        let t0 = Instant::now();
        assert!(matches!(
            burst.on_plain_char('a', t0),
            CharDecision::RetainFirstChar
        ));

        let t1 = t0 + PasteBurst::recommended_flush_delay() + Duration::from_millis(1);
        assert!(matches!(burst.flush_if_due(t1), FlushResult::Typed('a')));
        assert!(!burst.is_active());
    }

    #[test]
    fn ascii_two_fast_chars_start_buffer_from_pending_and_flush_as_paste() {
        let mut burst = PasteBurst::default();
        let t0 = Instant::now();
        assert!(matches!(
            burst.on_plain_char('a', t0),
            CharDecision::RetainFirstChar
        ));

        let t1 = t0 + Duration::from_millis(1);
        assert!(matches!(
            burst.on_plain_char('b', t1),
            CharDecision::BeginBufferFromPending
        ));
        burst.append_char_to_buffer('b', t1);

        let t2 = t1 + PasteBurst::recommended_active_flush_delay() + Duration::from_millis(1);
        assert!(matches!(
            burst.flush_if_due(t2),
            FlushResult::Paste(ref s) if s == "ab"
        ));
    }

    #[test]
    fn flush_before_modified_input_includes_pending_first_char() {
        let mut burst = PasteBurst::default();
        let t0 = Instant::now();
        assert!(matches!(
            burst.on_plain_char('a', t0),
            CharDecision::RetainFirstChar
        ));

        assert_eq!(burst.flush_before_modified_input(), Some("a".to_string()));
        assert!(!burst.is_active());
    }

    #[test]
    fn next_flush_delay_counts_down_to_zero() {
        let mut burst = PasteBurst::default();
        let t0 = Instant::now();
        let _ = burst.on_plain_char('a', t0);

        let almost_due = t0 + Duration::from_millis(7);
        let remaining = burst
            .next_flush_delay(almost_due)
            .expect("delay should exist");
        assert!(remaining <= Duration::from_millis(1));

        let due = t0 + Duration::from_millis(20);
        assert_eq!(burst.next_flush_delay(due), Some(Duration::ZERO));
    }

    /// Simulate #2134: when a non-char key (Tab) arrives during table-data
    /// paste, `deactivate_keep_window` resets accumulation state but
    /// preserves the Enter-suppression window so a trailing newline is still
    /// absorbed instead of submitting the partial input.
    #[test]
    fn deactivate_keep_window_preserves_enter_suppression_window() {
        let mut burst = PasteBurst::default();
        let t0 = Instant::now();

        assert!(matches!(
            burst.on_plain_char('a', t0),
            CharDecision::RetainFirstChar
        ));
        let t1 = t0 + Duration::from_millis(1);
        assert!(matches!(
            burst.on_plain_char('b', t1),
            CharDecision::BeginBufferFromPending
        ));
        burst.append_char_to_buffer('b', t1);
        assert!(burst.is_active());
        assert!(burst.newline_should_insert_instead_of_submit(t1));

        let flushed = burst.flush_before_modified_input();
        assert!(flushed.is_some());
        assert!(!burst.is_active());

        burst.deactivate_keep_window();

        assert!(!burst.is_active());

        let t_tab = t1 + Duration::from_millis(2);
        assert!(
            burst.newline_should_insert_instead_of_submit(t_tab),
            "Enter within suppression window should insert newline, not submit"
        );

        let t_expired = t_tab + PASTE_ENTER_SUPPRESS_WINDOW + Duration::from_millis(1);
        assert!(
            !burst.newline_should_insert_instead_of_submit(t_expired),
            "Enter after suppression window expires should submit"
        );
    }

    /// The idle flush must NOT drop the Enter-suppression window. The active
    /// idle timeout is only 8ms, so a paste's trailing newline can easily
    /// land just after the flush on a laggy link — dropping the window there
    /// would submit a partial paste (#1073).
    #[test]
    fn idle_flush_keeps_enter_suppression_window_alive() {
        let mut burst = PasteBurst::default();
        let t0 = Instant::now();

        let _ = burst.on_plain_char('a', t0);
        let t1 = t0 + Duration::from_millis(1);
        assert!(matches!(
            burst.on_plain_char('b', t1),
            CharDecision::BeginBufferFromPending
        ));
        burst.append_char_to_buffer('b', t1);

        let t_flush = t1 + PasteBurst::recommended_active_flush_delay();
        assert!(matches!(
            burst.flush_if_due(t_flush),
            FlushResult::Paste(ref s) if s == "ab"
        ));
        assert!(!burst.is_active());
        assert!(
            burst.newline_should_insert_instead_of_submit(t_flush),
            "a trailing pasted newline arriving right after the idle flush \
             must still be absorbed instead of submitting"
        );
    }

    /// …but the window is *bounded*: it expires 120ms after the last real
    /// keystroke and nothing about the flush re-arms it, so the user's next
    /// Enter submits.
    #[test]
    fn enter_suppression_window_expires_after_the_last_keystroke() {
        let mut burst = PasteBurst::default();
        let t0 = Instant::now();

        let _ = burst.on_plain_char('a', t0);
        let t1 = t0 + Duration::from_millis(1);
        let _ = burst.on_plain_char('b', t1);
        burst.append_char_to_buffer('b', t1);
        let t_flush = t1 + PasteBurst::recommended_active_flush_delay();
        let _ = burst.flush_if_due(t_flush);

        let t_late = t1 + PASTE_ENTER_SUPPRESS_WINDOW + Duration::from_millis(1);
        assert!(
            !burst.newline_should_insert_instead_of_submit(t_late),
            "Enter more than the suppression window after the paste must submit"
        );
    }

    /// A lone IME candidate commit is ordinary typing: it may only hold Enter
    /// for one burst interval, so a user finishing a CJK sentence and
    /// pressing Enter actually sends.
    #[test]
    fn lone_non_ascii_commit_arms_only_a_burst_interval_window() {
        let mut burst = PasteBurst::default();
        let t0 = Instant::now();

        let rapid = burst.note_plain_char(t0);
        assert_eq!(rapid, 1, "an isolated commit is a run of one");
        burst.arm_window_for_direct_char(t0, rapid);

        assert!(
            burst.newline_should_insert_instead_of_submit(t0 + PASTE_BURST_CHAR_INTERVAL),
            "a raw paste delivers its trailing newline within the burst \
             interval and must still be absorbed (#1302)"
        );
        assert!(
            !burst.newline_should_insert_instead_of_submit(
                t0 + PASTE_BURST_CHAR_INTERVAL + Duration::from_millis(1)
            ),
            "an IME commit must not swallow the Enter a human presses \
             tens of milliseconds later"
        );
    }

    /// Two non-ASCII characters at paste speed mean the stream is a paste,
    /// so the full suppression window applies to later lines.
    #[test]
    fn rapid_non_ascii_run_arms_the_full_suppression_window() {
        let mut burst = PasteBurst::default();
        let t0 = Instant::now();

        let rapid = burst.note_plain_char(t0);
        burst.arm_window_for_direct_char(t0, rapid);
        let t1 = t0 + Duration::from_millis(1);
        let rapid = burst.note_plain_char(t1);
        assert_eq!(rapid, 2);
        burst.arm_window_for_direct_char(t1, rapid);

        assert!(
            burst.newline_should_insert_instead_of_submit(t1 + PASTE_ENTER_SUPPRESS_WINDOW),
            "a raw CJK paste must keep absorbing its embedded newlines"
        );
        assert!(
            !burst.newline_should_insert_instead_of_submit(
                t1 + PASTE_ENTER_SUPPRESS_WINDOW + Duration::from_millis(1)
            ),
            "even a paste-speed run releases Enter once the window lapses"
        );
    }

    /// A slow IME sequence never accumulates a rapid run, so every commit
    /// re-arms only the short window and Enter stays available throughout.
    #[test]
    fn slow_ime_sequence_never_holds_enter() {
        let mut burst = PasteBurst::default();
        let t0 = Instant::now();

        // "你好世界" committed one character at a time with human gaps.
        for i in 0..4u64 {
            let now = t0 + Duration::from_millis(50 * i);
            let rapid = burst.note_plain_char(now);
            assert_eq!(rapid, 1, "50ms gaps are never a paste-speed run");
            burst.arm_window_for_direct_char(now, rapid);
        }

        let last = t0 + Duration::from_millis(150);
        assert!(
            !burst.newline_should_insert_instead_of_submit(last + Duration::from_millis(30)),
            "Enter after an IME-typed CJK message must submit"
        );
    }
}