Skip to content

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

fix: harden CLI UTF-8 terminal input

wcl4b8016cf019b
diff --git a/deeptutor_cli/chat.py b/deeptutor_cli/chat.py
index 44f6bcf22..043637b4c 100644
--- a/deeptutor_cli/chat.py
+++ b/deeptutor_cli/chat.py
@@ -2,11 +2,12 @@
from __future__ import annotations
-from contextlib import suppress
+from contextlib import contextmanager, suppress
from dataclasses import dataclass, field
import json
import shlex
-from typing import Any
+import sys
+from typing import Any, Iterator, TextIO
from rich.panel import Panel
import typer
@@ -129,6 +130,12 @@ async def _chat_repl(state: ChatState) -> None:
except (EOFError, KeyboardInterrupt):
console.print()
break
+ except UnicodeDecodeError:
+ console.print(
+ "[yellow]Unable to decode terminal input. "
+ "Check the terminal encoding and try again.[/]"
+ )
+ continue
if not user_input:
continue
@@ -261,19 +268,64 @@ 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>[/] "
- while True:
- line = console.input(prompt)
- if line.endswith("\\"):
- lines.append(line[:-1])
- prompt = "[dim]...[/] "
- continue
- lines.append(line)
- return "\n".join(lines).strip()
+ 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()
def _print_state(state: ChatState) -> None:
diff --git a/tests/cli/test_chat_cli.py b/tests/cli/test_chat_cli.py
index ecca2ca12..e9ec68864 100644
--- a/tests/cli/test_chat_cli.py
+++ b/tests/cli/test_chat_cli.py
@@ -170,6 +170,28 @@ def test_chat_repl_backslash_continuation_sends_single_message(monkeypatch) -> N
assert captured_requests[0].content == "Please review this code:\ndef fib(n): return n"
+def test_chat_repl_survives_invalid_utf8_input(monkeypatch) -> None:
+ inputs = iter(
+ [
+ UnicodeDecodeError("utf-8", b"\xe8\x83", 0, 2, "unexpected end of data"),
+ "/quit",
+ ]
+ )
+
+ def _read_input() -> str:
+ value = next(inputs)
+ if isinstance(value, Exception):
+ raise value
+ return value
+
+ monkeypatch.setattr("deeptutor_cli.chat._read_repl_input", _read_input)
+
+ result = runner.invoke(app, ["chat"])
+
+ assert result.exit_code == 0, result.output
+ assert "Unable to decode terminal input" in result.output
+
+
def test_plugin_info_includes_capability_aliases_and_availability() -> None:
result = runner.invoke(app, ["plugin", "info", "deep_solve"])
diff --git a/tests/cli/test_chat_terminal.py b/tests/cli/test_chat_terminal.py
new file mode 100644
index 000000000..02a1b78c7
--- /dev/null
+++ b/tests/cli/test_chat_terminal.py
@@ -0,0 +1,73 @@
+"""POSIX terminal behavior tests for the interactive chat CLI."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import select
+import subprocess
+import sys
+import time
+
+import pytest
+
+pty = pytest.importorskip("pty")
+termios = pytest.importorskip("termios")
+
+
[email protected](not hasattr(termios, "IUTF8"), reason="IUTF8 is not available")
+def test_chat_repl_handles_utf8_backspace_and_restores_terminal_mode() -> None:
+ master_fd, slave_fd = pty.openpty()
+ original = termios.tcgetattr(slave_fd)
+ original[0] &= ~termios.IUTF8
+ termios.tcsetattr(slave_fd, termios.TCSANOW, original)
+
+ project_root = Path(__file__).resolve().parents[2]
+ env = os.environ.copy()
+ env["PYTHONIOENCODING"] = "utf-8:strict"
+ process = subprocess.Popen(
+ [
+ sys.executable,
+ "-c",
+ (
+ "from deeptutor_cli.chat import _read_repl_input; "
+ "print('RESULT=' + repr(_read_repl_input()))"
+ ),
+ ],
+ cwd=project_root,
+ env=env,
+ stdin=slave_fd,
+ stdout=slave_fd,
+ stderr=slave_fd,
+ close_fds=True,
+ )
+
+ output = bytearray()
+ try:
+ deadline = time.monotonic() + 10
+ while b"You>" not in output and time.monotonic() < deadline:
+ readable, _, _ = select.select([master_fd], [], [], 0.1)
+ if readable:
+ output.extend(os.read(master_fd, 4096))
+ assert b"You>" in output
+
+ os.write(master_fd, "能".encode() + b"\x7fok\n")
+ process.wait(timeout=10)
+ while True:
+ readable, _, _ = select.select([master_fd], [], [], 0)
+ if not readable:
+ break
+ try:
+ output.extend(os.read(master_fd, 4096))
+ except OSError:
+ break
+
+ assert process.returncode == 0, output.decode("utf-8", "replace")
+ assert b"RESULT='ok'" in output
+ assert not termios.tcgetattr(slave_fd)[0] & termios.IUTF8
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait()
+ os.close(master_fd)
+ os.close(slave_fd)