Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 95 additions & 5 deletions libs/code/deepagents_code/widgets/chat_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,22 @@ def _default_history_path() -> Path:
_PASTE_BURST_START_CHARS = {"'", '"'}
"""Characters that can start dropped-path payloads."""

_PASTE_BURST_MIN_CHARS = 3
"""Consecutive fast keystrokes before a stream is treated as a paste burst.

Terminals that lack bracketed paste replay a paste as individual key events.
Counting a short run of rapid chars distinguishes that from human typing,
which has much larger inter-key gaps.
"""

_PASTE_ENTER_SUPPRESS_WINDOW_SECONDS = 0.12
"""Window after recent burst activity during which `enter` inserts a newline.

Keeps multi-line pastes grouped as one input even when newlines arrive as
`enter` key events slightly after the surrounding characters (e.g. across
terminal read boundaries), instead of submitting mid-paste.
"""

_BACKSLASH_ENTER_GAP_SECONDS = 0.15
"""Maximum gap between a `\\` key and a following `enter` key to treat the
pair as a terminal-emitted shift+enter sequence.
Expand Down Expand Up @@ -408,12 +424,18 @@ def __init__(self, **kwargs: Any) -> None:
self._chat_input_owner: ChatInput | None = None
self._skip_history_change_events = 0
self._completion_active = False
# Buffer quote-prefixed high-frequency key bursts from terminals that
# emulate paste via rapid key events instead of dispatching a paste
# event.
# Buffer high-frequency key bursts from terminals that emulate paste via
# rapid key events instead of dispatching a paste event.
self._paste_burst_buffer = ""
self._paste_burst_last_char_time: float | None = None
self._paste_burst_timer: Timer | None = None
# Counts consecutive rapid keystrokes so a paste-like stream can be
# detected even when it doesn't begin with a quote.
self._paste_burst_run = 0
self._paste_burst_last_key_time: float | None = None
# Deadline until which `enter` inserts a newline rather than submitting,
# keeping multi-line pastes grouped across read boundaries.
self._paste_burst_window_until: float | None = None
# See _BACKSLASH_ENTER_GAP_SECONDS for context.
self._backslash_pending_time: float | None = None

Expand Down Expand Up @@ -651,6 +673,7 @@ def _start_paste_burst(self, char: str, now: float) -> None:
"""Start buffering a paste-like keystroke burst."""
self._paste_burst_buffer = char
self._paste_burst_last_char_time = now
self._paste_burst_window_until = now + _PASTE_ENTER_SUPPRESS_WINDOW_SECONDS
self._schedule_paste_burst_flush()

def _append_paste_burst(self, text: str, now: float) -> None:
Expand All @@ -660,13 +683,51 @@ def _append_paste_burst(self, text: str, now: float) -> None:
return
self._paste_burst_buffer += text
self._paste_burst_last_char_time = now
self._paste_burst_window_until = now + _PASTE_ENTER_SUPPRESS_WINDOW_SECONDS
self._schedule_paste_burst_flush()

def _note_paste_burst_keystroke(self, now: float) -> None:
"""Track inter-key timing to count consecutive rapid keystrokes."""
last = self._paste_burst_last_key_time
if last is not None and (now - last) <= _PASTE_BURST_CHAR_GAP_SECONDS:
self._paste_burst_run += 1
else:
self._paste_burst_run = 1
self._paste_burst_last_key_time = now

def _reset_paste_burst_run(self) -> None:
"""Clear consecutive-keystroke tracking after non-burst input."""
self._paste_burst_run = 0
self._paste_burst_last_key_time = None

def _enter_inserts_newline_during_burst(self, now: float) -> bool:
"""Return whether `enter` should insert a newline rather than submit.

True while a burst is buffering or within the suppression window that
outlives it, except in slash-command context where `enter` must keep
its submit/dispatch semantics.
"""
if self._in_slash_command_context():
return False
if self._paste_burst_buffer:
return True
until = self._paste_burst_window_until
return until is not None and now <= until

def _in_slash_command_context(self) -> bool:
"""Return whether the current input is composing a slash command."""
owner = self._chat_input_owner
if owner is not None and owner.mode == "command":
return True
return self.text.startswith("/")

def _should_start_paste_burst(self, char: str) -> bool:
"""Return whether a keypress should start paste-burst buffering.

Restricting to quote-prefixed input at an empty cursor reduces false
positives for normal typing and slash-command entry.
positives for normal typing and slash-command entry. General multi-line
pastes are handled by the Enter-suppression window instead, which keeps
their newlines from submitting without rerouting text insertion.
"""
if char not in _PASTE_BURST_START_CHARS:
return False
Expand Down Expand Up @@ -782,6 +843,22 @@ async def _on_key(self, event: events.Key) -> None:
event.stop()
return

# Track rapid keystroke runs so a terminal replaying a paste as key
# events (no bracketed paste) arms the Enter-suppression window, keeping
# the paste's newlines from submitting mid-stream. `enter` is exempt so
# newlines within a paste don't break the run.
if event.is_printable and event.character is not None:
self._note_paste_burst_keystroke(now)
if (
self._paste_burst_run >= _PASTE_BURST_MIN_CHARS
and not self._in_slash_command_context()
):
self._paste_burst_window_until = (
now + _PASTE_ENTER_SUPPRESS_WINDOW_SECONDS
)
elif event.key != "enter":
self._reset_paste_burst_run()

# Some terminals (e.g. VSCode built-in) send a literal backslash
# followed by enter for shift+enter. When enter arrives shortly
# after a backslash, delete the backslash and insert a newline.
Expand Down Expand Up @@ -837,10 +914,19 @@ async def _on_key(self, event: events.Key) -> None:
event.prevent_default()
return

# Plain Enter submits
# Plain Enter submits, unless a recent keystroke burst suggests this
# newline is part of a paste replayed as key events; then insert a
# newline and keep the window alive so the rest of the paste stays
# grouped instead of submitting mid-stream.
if event.key == "enter":
event.prevent_default()
event.stop()
if self._enter_inserts_newline_during_burst(now):
self._paste_burst_window_until = (
now + _PASTE_ENTER_SUPPRESS_WINDOW_SECONDS
)
self.action_insert_newline()
return
if (
self._chat_input_owner is not None
and self._chat_input_owner._handle_stale_slash_enter()
Expand Down Expand Up @@ -946,6 +1032,8 @@ def set_text_from_history(self, text: str, *, cursor_at_end: bool = True) -> Non
"""
self._paste_burst_buffer = ""
self._paste_burst_last_char_time = None
self._paste_burst_window_until = None
self._reset_paste_burst_run()
self._cancel_paste_burst_timer()
self._backslash_pending_time = None
self._skip_history_change_events += 1
Expand All @@ -969,6 +1057,8 @@ def clear_text(self) -> None:
self._skip_history_change_events += 1
self._paste_burst_buffer = ""
self._paste_burst_last_char_time = None
self._paste_burst_window_until = None
self._reset_paste_burst_run()
self._cancel_paste_burst_timer()
self._backslash_pending_time = None
self.text = ""
Expand Down
71 changes: 71 additions & 0 deletions libs/code/tests/unit_tests/test_chat_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -3126,3 +3126,74 @@ async def test_preserves_widget_focus(self) -> None:
await pilot.pause()

assert chat._text_area.has_focus is True


class TestPasteBurstEnterSuppression:
"""Multi-line pastes replayed as key events must not submit mid-stream.

Terminals without bracketed paste deliver a paste as rapid `Char`/`Enter`
key events. A short run of fast keystrokes arms a suppression window so the
embedded `enter` events insert newlines instead of submitting.
"""

async def test_rapid_burst_with_newline_does_not_submit(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A fast keystroke run followed by enter inserts a newline."""
# Widen the burst gap so wall-clock delays between pilot.press calls on
# slow CI runners still register as a single rapid burst.
monkeypatch.setattr(chat_input_module, "_PASTE_BURST_CHAR_GAP_SECONDS", 60.0)
monkeypatch.setattr(
chat_input_module, "_PASTE_ENTER_SUPPRESS_WINDOW_SECONDS", 60.0
)

app = _RecordingApp()
async with app.run_test() as pilot:
chat = app.query_one(ChatInput)
ta = chat._text_area
assert ta is not None

for char in "hello":
await pilot.press(char)
await pilot.press("enter")
await pilot.press("w")
await pilot.pause()

assert len(app.submitted) == 0
assert "\n" in ta.text

async def test_slow_typing_then_enter_submits(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Deliberate typing (no burst) keeps enter as submit."""
# Force every inter-key gap to exceed the burst threshold.
monkeypatch.setattr(chat_input_module, "_PASTE_BURST_CHAR_GAP_SECONDS", 0.0)

app = _RecordingApp()
async with app.run_test() as pilot:
chat = app.query_one(ChatInput)
ta = chat._text_area
assert ta is not None

for char in "hello":
await pilot.press(char)
await pilot.press("enter")
await pilot.pause()

assert len(app.submitted) == 1
assert app.submitted[0].value == "hello"

async def test_slash_command_enter_still_submits_during_burst(self) -> None:
"""Slash-command context keeps enter dispatching even after a burst."""
app = _RecordingApp()
async with app.run_test() as pilot:
chat = app.query_one(ChatInput)
ta = chat._text_area
assert ta is not None

for char in "/help":
await pilot.press(char)
await pilot.press("enter")
await pilot.pause()

assert len(app.submitted) == 1
Loading