diff --git a/ai_chat.py b/ai_chat.py index 923e159..d0fe653 100644 --- a/ai_chat.py +++ b/ai_chat.py @@ -2,14 +2,18 @@ import asyncio import json import logging import os +from time import monotonic from dataclasses import dataclass import httpx from dotenv import load_dotenv from textual.app import App, ComposeResult -from textual.containers import Container, VerticalScroll +from rich.text import Text +from rich.markdown import Markdown +from textual.containers import Container, Horizontal, VerticalScroll from textual.widgets import Header, Footer, Static from textual.binding import Binding +from textual.screen import ModalScreen log = logging.getLogger(__name__) @@ -31,6 +35,28 @@ class ChatMessage: sender: str +class SquareLoadingIndicator(Static): + """A hollow three-by-three square with a rotating highlight.""" + + def on_mount(self) -> None: + self.auto_refresh = 0.15 + + def render(self) -> Text: + active = int(monotonic() / 0.15) % 8 + if self.app.animation_level == "none": + active = 0 + color = self.rich_style.color + result = Text(no_wrap=True) + for row, positions in enumerate(((0, 1, 2), (7, -1, 3), (6, 5, 4))): + if row: + result.append("\n") + for column, position in enumerate(positions): + if column: + result.append(" ") + result.append(" " if position == -1 else "\u25cf", style=f"{'bold' if position == active else 'dim'} {color.name if color else 'cyan'}") + return result + + class MessageBubble(Static): """A chat message bubble that supports streaming updates.""" @@ -44,31 +70,55 @@ class MessageBubble(Static): self.styles.border = ("round", "green") self._content_widget = Static(message.content, classes="bubble-content", markup=False) self._streaming = False + self._waiting_widget = Horizontal( + SquareLoadingIndicator(), + Static("Waiting for response...", markup=False, classes="waiting-label"), + classes="response-waiting", + ) + self._waiting_widget.display = False + self._render_content() + + def _render_content(self) -> None: + # Keep the raw source in message.content for subsequent API requests. + content = self.message.content + self._content_widget.update( + Markdown(content, code_theme="monokai") + if self.message.role == "assistant" else content + ) + + def set_waiting(self, waiting: bool) -> None: + self._waiting_widget.display = waiting + self._content_widget.display = bool(self.message.content.strip()) or not waiting def compose(self) -> ComposeResult: yield self._content_widget + yield self._waiting_widget def set_content(self, content: str) -> None: """Set the full content (non-streaming).""" self.message.content = content - self._content_widget.update(content) + self._render_content() + self.set_waiting(False) self.refresh() def append_content(self, delta: str) -> None: """Append content for streaming.""" self.message.content += delta - self._content_widget.update(self.message.content) + self._render_content() + if self.message.content.strip(): + self.set_waiting(False) self.refresh() def start_streaming(self) -> None: """Mark as streaming.""" self._streaming = True - self._content_widget.update("") + self.set_waiting(True) self.refresh() def end_streaming(self) -> None: """Mark streaming as complete.""" self._streaming = False + self.set_waiting(False) self.refresh() @@ -81,7 +131,6 @@ class ChatContainer(VerticalScroll): """Add a new message and return its bubble for streaming.""" bubble = MessageBubble(message) self.mount(bubble) - self.call_after_refresh(self.scroll_end, animate=False) self.messages.append(message) self.refresh() return bubble @@ -93,10 +142,42 @@ class ChatContainer(VerticalScroll): bubbles = self.query(MessageBubble) if bubbles: bubbles.last().set_content(content) - self.scroll_end(animate=False) self.refresh() +class ControlsHelp(ModalScreen): + BINDINGS = [Binding("escape,f1", "dismiss", "Close")] + DEFAULT_CSS = """ + ControlsHelp { align: center middle; } + #controls-help { + width: 64; + max-width: 95%; + height: auto; + padding: 1 2; + border: round $primary; + background: $surface; + } + """ + + def compose(self) -> ComposeResult: + yield Static( + "[bold]Reading controls[/bold]\n\n" + "Mouse wheel / Up / Down: scroll\n" + "Page Up / Page Down: scroll a page\n" + "Home: oldest message\n" + "End: latest message and resume following\n\n" + "Scrolling up pauses automatic following.\n\n" + "[bold]Zoom (Windows Terminal)[/bold]\n" + "Ctrl + Plus: larger text\n" + "Ctrl + Minus: smaller text\n" + "Ctrl + 0: reset font size\n\n" + "Font size is controlled by your terminal.\n" + "Other terminals may use different shortcuts.\n\n" + "Escape / F1: close help", + id="controls-help", + ) + + class AIChatApp(App): CSS = """ Screen { @@ -115,6 +196,24 @@ class AIChatApp(App): width: 100%; } + .response-waiting { + height: 3; + align-vertical: middle; + } + + .response-waiting SquareLoadingIndicator { + width: 5; + height: 3; + margin: 0 2 0 1; + color: $primary; + } + + .response-waiting .waiting-label { + width: 1fr; + height: 3; + content-align: left middle; + } + MessageBubble { margin: 1 0; width: 100%; @@ -130,6 +229,13 @@ class AIChatApp(App): BINDINGS = [ Binding("ctrl+c", "quit", "Quit"), + Binding("f1", "controls_help", "Help / Zoom"), + Binding("pageup", "chat_scroll('page_up')", "Page up", priority=True), + Binding("pagedown", "chat_scroll('page_down')", "Page down", priority=True), + Binding("home", "chat_scroll('home')", "Oldest", priority=True), + Binding("end", "chat_scroll('end')", "Latest", priority=True), + Binding("up", "chat_scroll('up')", show=False, priority=True), + Binding("down", "chat_scroll('down')", show=False, priority=True), ] def __init__( @@ -163,8 +269,30 @@ class AIChatApp(App): async def on_mount(self) -> None: self.chat_container = self.query_one(ChatContainer) self.status_bar = self.query_one("#status-bar", Static) + self.chat_container.focus() + self.chat_container.anchor() self.run_worker(self.start_conversation(), exclusive=True) + def action_controls_help(self) -> None: + self.push_screen(ControlsHelp()) + + def action_chat_scroll(self, direction: str) -> None: + if isinstance(self.screen, ControlsHelp): + return + chat = self.chat_container + if direction == "end": + chat.anchor() + elif direction == "home": + chat.scroll_home(animate=False) + elif direction == "page_up": + chat.scroll_page_up(animate=False) + elif direction == "page_down": + chat.scroll_page_down(animate=False) + elif direction == "up": + chat.scroll_up(animate=False) + elif direction == "down": + chat.scroll_down(animate=False) + async def start_conversation(self) -> None: self._is_running = True self.update_status(f"Starting conversation... AI 1 ({self.ai1.name}) begins") @@ -194,8 +322,12 @@ class AIChatApp(App): await self._try_streaming(current_ai, history, bubble) except Exception as stream_error: self.update_status(f"Streaming failed, trying non-streaming... ({stream_error})") - full_response = await self.call_ai(current_ai, history) - bubble.set_content(full_response) + bubble.set_waiting(True) + try: + full_response = await self.call_ai(current_ai, history) + bubble.set_content(full_response) + finally: + bubble.set_waiting(False) except Exception as error: error_msg = f"Error: {error}" self.chat_container.add_message(ChatMessage("system", error_msg, "System")) @@ -216,7 +348,6 @@ class AIChatApp(App): async for chunk in self.stream_ai(ai, history): full_response += chunk bubble.append_content(chunk) - self.chat_container.call_after_refresh(self.chat_container.scroll_end, animate=False) await asyncio.sleep(0) if not full_response.strip(): raise ValueError("Empty response from API") diff --git a/requirements.txt b/requirements.txt index dacb934..73b4972 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,3 @@ -textual>=0.52.0 +textual>=8.2.8 httpx>=0.27.0 python-dotenv>=1.0.0 \ No newline at end of file diff --git a/test_ai_chat.py b/test_ai_chat.py index 19f3cd2..38ae93e 100644 --- a/test_ai_chat.py +++ b/test_ai_chat.py @@ -6,9 +6,12 @@ import io import os from unittest.mock import patch +from rich.console import Console +from rich.markdown import Markdown + import httpx -from ai_chat import AIChatApp, AIConfig, MessageBubble, main +from ai_chat import AIChatApp, AIConfig, MessageBubble, ChatMessage, ControlsHelp, main class ChatTests(unittest.IsolatedAsyncioTestCase): @@ -39,7 +42,8 @@ class ChatTests(unittest.IsolatedAsyncioTestCase): self.assertEqual([m['role'] for m in requests[1]['messages']], ['system', 'user', 'user']) self.assertEqual([m['role'] for m in requests[2]['messages']], ['system', 'user', 'assistant', 'user']) self.assertEqual(len(app.query(MessageBubble)), 4) - self.assertEqual(str(app.query(MessageBubble).last()._content_widget.render()), '[bold]hello[/bold]') + self.assertIsInstance(app.query(MessageBubble).last()._content_widget.content, Markdown) + self.assertEqual(app.messages[-1].content, '[bold]hello[/bold]') self.assertTrue(app.client.is_closed) async def test_partial_stream_fallback_reuses_bubble(self): @@ -104,6 +108,92 @@ class ChatTests(unittest.IsolatedAsyncioTestCase): self.assertIn('Empty response', str(app.status_bar.render())) self.assertEqual(app.current_turn, 0) + async def test_scrolling_preserves_reading_position_and_resumes(self): + app = await self.make_app(lambda request: httpx.Response(500)) + async def idle(): + pass + app.start_conversation = idle + async with app.run_test(size=(100, 30)) as pilot: + chat = app.chat_container + bubble = chat.add_message(ChatMessage("assistant", "line\n\n" * 100, "AI 1")) + await pilot.pause() + self.assertGreater(chat.max_scroll_y, 0) + self.assertEqual(chat.scroll_y, chat.max_scroll_y) + await pilot.press('pageup') + position = chat.scroll_y + self.assertLess(position, chat.max_scroll_y) + bubble.append_content("new line\n\n" * 30) + await pilot.pause() + self.assertEqual(chat.scroll_y, position) + chat.add_message(ChatMessage("assistant", "next reply\n\n" * 30, "AI 2")) + await pilot.pause() + self.assertEqual(chat.scroll_y, position) + await pilot.press('home') + self.assertEqual(chat.scroll_y, 0) + await pilot.press('down') + self.assertGreater(chat.scroll_y, 0) + await pilot.press('end') + self.assertEqual(chat.scroll_y, chat.max_scroll_y) + chat.update_last_message("more lines\n\n" * 80) + await pilot.pause() + self.assertEqual(chat.scroll_y, chat.max_scroll_y) + await pilot.resize_terminal(70, 24) + await pilot.pause() + self.assertEqual(chat.scroll_y, chat.max_scroll_y) + await pilot.press('f1') + self.assertIsInstance(app.screen, ControlsHelp) + await pilot.press('escape') + self.assertNotIsInstance(app.screen, ControlsHelp) + + async def test_markdown_and_waiting_during_stream(self): + app = await self.make_app(lambda request: httpx.Response(500)) + first_chunk = asyncio.Event() + finish = asyncio.Event() + source = "# Heading\n\n**bold** and `code`\n\n- item\n\n```python\nprint(1)\n```" + async def stream(ai, history): + await first_chunk.wait() + yield source + await finish.wait() + app.stream_ai = stream + async with app.run_test() as pilot: + bubble = app.query(MessageBubble).last() + self.assertTrue(bubble._waiting_widget.display) + self.assertFalse(bubble._content_widget.display) + first_chunk.set() + await pilot.pause() + self.assertFalse(bubble._waiting_widget.display) + self.assertTrue(bubble._content_widget.display) + output = io.StringIO() + Console(file=output, width=80, force_terminal=False).print(bubble._content_widget.content) + rendered = output.getvalue() + self.assertIn('Heading', rendered) + self.assertIn('print(1)', rendered) + self.assertNotIn('**bold**', rendered) + self.assertNotIn('```', rendered) + self.assertEqual(bubble.message.content, source) + finish.set() + await self.wait_finished(app, pilot) + self.assertFalse(bubble._waiting_widget.display) + + async def test_waiting_during_fallback_and_error(self): + fallback_started = asyncio.Event() + finish = asyncio.Event() + async def handler(request): + if json.loads(request.content).get('stream'): + return httpx.Response(200, text='data: [DONE]\n\n') + fallback_started.set() + await finish.wait() + return httpx.Response(500, text='failed') + app = await self.make_app(handler) + async with app.run_test() as pilot: + await asyncio.wait_for(fallback_started.wait(), 2) + bubble = app.query(MessageBubble).last() + self.assertTrue(bubble._waiting_widget.display) + finish.set() + await self.wait_finished(app, pilot) + self.assertFalse(bubble._waiting_widget.display) + self.assertEqual(app.messages[-1].role, 'system') + class CommandLineTests(unittest.TestCase): def test_invalid_environment_turns_reports_usage_error(self):