Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

refactor: centralize terminal input handling

wcl4bd326405a80
diff --git a/deeptutor_cli/chat.py b/deeptutor_cli/chat.py
index 043637b4c..a7ab66bf9 100644
--- a/deeptutor_cli/chat.py
+++ b/deeptutor_cli/chat.py
@@ -2,12 +2,11 @@
from __future__ import annotations
-from contextlib import contextmanager, suppress
+from contextlib import suppress
from dataclasses import dataclass, field
import json
import shlex
-import sys
-from typing import Any, Iterator, TextIO
+from typing import Any
from rich.panel import Panel
import typer
@@ -19,6 +18,7 @@ from .common import (
maybe_run,
parse_config_items,
parse_json_object,
+ read_console_input,
regenerate_and_render,
render_tool_result_entry,
run_turn_and_render,
@@ -268,64 +268,19 @@ def _apply_command(raw: str, state: ChatState) -> bool:
return True
-@contextmanager
-def _utf8_aware_terminal_input(stream: TextIO) -> Iterator[None]:
- """Make canonical-mode erase treat UTF-8 input as complete characters."""
-
- try:
- import termios
- except ImportError:
- yield
- return
-
- encoding = (stream.encoding or "").lower().replace("_", "-")
- if encoding not in {"utf-8", "utf8"} or not hasattr(termios, "IUTF8"):
- yield
- return
-
- try:
- if not stream.isatty():
- yield
- return
- file_descriptor = stream.fileno()
- original_attributes = termios.tcgetattr(file_descriptor)
- except (AttributeError, OSError, ValueError):
- yield
- return
-
- if original_attributes[0] & termios.IUTF8:
- yield
- return
-
- updated_attributes = original_attributes.copy()
- updated_attributes[0] |= termios.IUTF8
- try:
- termios.tcsetattr(file_descriptor, termios.TCSANOW, updated_attributes)
- except OSError:
- yield
- return
-
- try:
- yield
- finally:
- with suppress(OSError):
- termios.tcsetattr(file_descriptor, termios.TCSANOW, original_attributes)
-
-
def _read_repl_input() -> str:
"""Read one REPL message, supporting backslash-continued multi-line input."""
lines: list[str] = []
prompt = "[bold green]You>[/] "
- with _utf8_aware_terminal_input(sys.stdin):
- while True:
- line = console.input(prompt)
- if line.endswith("\\"):
- lines.append(line[:-1])
- prompt = "[dim]...[/] "
- continue
- lines.append(line)
- return "\n".join(lines).strip()
+ while True:
+ line = read_console_input(prompt)
+ if line.endswith("\\"):
+ lines.append(line[:-1])
+ prompt = "[dim]...[/] "
+ continue
+ lines.append(line)
+ return "\n".join(lines).strip()
def _print_state(state: ChatState) -> None:
diff --git a/deeptutor_cli/common.py b/deeptutor_cli/common.py
index a4c39e043..0c9a41791 100644
--- a/deeptutor_cli/common.py
+++ b/deeptutor_cli/common.py
@@ -8,7 +8,7 @@ import json
from pathlib import Path
import signal
import sys
-from typing import Any, Callable
+from typing import Any, Callable, Iterator, TextIO
from rich.console import Console
from rich.markdown import Markdown
@@ -34,6 +34,57 @@ tool_results = ToolResultBuffer()
_LLM_ROUND_CALL_KINDS = frozenset({"agent_loop_round", "llm_final_response"})
+def _utf8_aware_terminal_input(stream: TextIO) -> Iterator[None]:
+ """Make canonical-mode erase treat UTF-8 input as complete characters."""
+
+ try:
+ import termios
+ except ImportError:
+ yield
+ return
+
+ encoding = (stream.encoding or "").lower().replace("_", "-")
+ if encoding not in {"utf-8", "utf8"} or not hasattr(termios, "IUTF8"):
+ yield
+ return
+
+ try:
+ if not stream.isatty():
+ yield
+ return
+ file_descriptor = stream.fileno()
+ original_attributes = termios.tcgetattr(file_descriptor)
+ except (AttributeError, OSError, ValueError):
+ yield
+ return
+
+ if original_attributes[0] & termios.IUTF8:
+ yield
+ return
+
+ updated_attributes = original_attributes.copy()
+ updated_attributes[0] |= termios.IUTF8
+ try:
+ termios.tcsetattr(file_descriptor, termios.TCSANOW, updated_attributes)
+ except OSError:
+ yield
+ return
+
+ try:
+ yield
+ finally:
+ with contextlib.suppress(OSError):
+ termios.tcsetattr(file_descriptor, termios.TCSANOW, original_attributes)
+
+
+def read_console_input(prompt: str) -> str:
+ """Read from the shared console with UTF-8-aware terminal editing."""
+
+ with _utf8_aware_terminal_input(sys.stdin):
+ return console.input(prompt)
+
+
class TurnInterrupted(Exception):
"""User aborted the running turn (Ctrl-C / Ctrl-D at a prompt)."""
@@ -545,7 +596,7 @@ class TurnStreamRenderer:
if self._sigint is not None:
self._sigint.suspend()
try:
- return console.input(prompt)
+ return read_console_input(prompt)
except (KeyboardInterrupt, EOFError):
return None
finally: