smt
This commit is contained in:
1 parent
2ad5d1711c
commit
696322dde2
3 files changed
+143
-4
No files matched your search
@@ -7,3 +7,5 @@ __pycache__/
|
|||||||
.venv/
|
.venv/
|
||||||
venv/
|
venv/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
|
|
||||||
|
screenshots/
|
||||||
+120
-3
@@ -2,16 +2,21 @@ import asyncio
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import io
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
from time import monotonic
|
from time import monotonic
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from textual.app import App, ComposeResult
|
from textual.app import App, ComposeResult
|
||||||
|
from rich.console import Console
|
||||||
|
from rich.panel import Panel
|
||||||
from rich.text import Text
|
from rich.text import Text
|
||||||
from rich.markdown import Markdown
|
from rich.markdown import Markdown
|
||||||
from textual.containers import Container, Horizontal, VerticalScroll
|
from textual.containers import Container, Horizontal, VerticalScroll
|
||||||
from textual.widgets import Header, Footer, Static
|
from textual.widgets import Header, Footer, Static, Button
|
||||||
from textual.binding import Binding
|
from textual.binding import Binding
|
||||||
from textual.screen import ModalScreen
|
from textual.screen import ModalScreen
|
||||||
|
|
||||||
@@ -164,6 +169,7 @@ class ControlsHelp(ModalScreen):
|
|||||||
"[bold]Reading controls[/bold]\n\n"
|
"[bold]Reading controls[/bold]\n\n"
|
||||||
"Mouse wheel / Up / Down: scroll\n"
|
"Mouse wheel / Up / Down: scroll\n"
|
||||||
"Page Up / Page Down: scroll a page\n"
|
"Page Up / Page Down: scroll a page\n"
|
||||||
|
"S / F2: save visible screen or full conversation\n"
|
||||||
"Home: oldest message\n"
|
"Home: oldest message\n"
|
||||||
"End: latest message and resume following\n\n"
|
"End: latest message and resume following\n\n"
|
||||||
"Scrolling up pauses automatic following.\n\n"
|
"Scrolling up pauses automatic following.\n\n"
|
||||||
@@ -178,12 +184,49 @@ class ControlsHelp(ModalScreen):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ScreenshotOptions(ModalScreen[str | None]):
|
||||||
|
BINDINGS = [
|
||||||
|
Binding("escape", "dismiss(None)", "Cancel"),
|
||||||
|
Binding("f", "dismiss('full')", "Full conversation"),
|
||||||
|
Binding("v", "dismiss('visible')", "Visible screen"),
|
||||||
|
]
|
||||||
|
DEFAULT_CSS = """
|
||||||
|
ScreenshotOptions { align: center middle; }
|
||||||
|
#screenshot-options {
|
||||||
|
width: 58;
|
||||||
|
max-width: 95%;
|
||||||
|
height: auto;
|
||||||
|
padding: 1 2;
|
||||||
|
border: round $primary;
|
||||||
|
background: $surface;
|
||||||
|
}
|
||||||
|
#screenshot-options Button { width: 100%; margin-top: 1; }
|
||||||
|
"""
|
||||||
|
|
||||||
|
def compose(self) -> ComposeResult:
|
||||||
|
with Container(id="screenshot-options"):
|
||||||
|
yield Static("[bold]Save screenshot[/bold]\nSVG images are saved in screenshots/.")
|
||||||
|
yield Button("Full conversation (F)", id="full", variant="primary")
|
||||||
|
yield Button("Visible screen (V)", id="visible")
|
||||||
|
yield Button("Cancel", id="cancel")
|
||||||
|
|
||||||
|
def on_button_pressed(self, event: Button.Pressed) -> None:
|
||||||
|
self.dismiss(None if event.button.id == "cancel" else event.button.id)
|
||||||
|
|
||||||
|
|
||||||
class AIChatApp(App):
|
class AIChatApp(App):
|
||||||
CSS = """
|
CSS = """
|
||||||
Screen {
|
Screen {
|
||||||
background: $surface;
|
background: $surface;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#elapsed-time {
|
||||||
|
height: 1;
|
||||||
|
padding: 0 1;
|
||||||
|
text-align: right;
|
||||||
|
background: $surface-darken-1;
|
||||||
|
}
|
||||||
|
|
||||||
#chat-container {
|
#chat-container {
|
||||||
height: 1fr;
|
height: 1fr;
|
||||||
border: solid $primary;
|
border: solid $primary;
|
||||||
@@ -220,6 +263,13 @@ class AIChatApp(App):
|
|||||||
min-height: 3;
|
min-height: 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#turn-counter {
|
||||||
|
height: 1;
|
||||||
|
padding: 0 1;
|
||||||
|
background: $surface-darken-1;
|
||||||
|
text-style: bold;
|
||||||
|
}
|
||||||
|
|
||||||
#status-bar {
|
#status-bar {
|
||||||
height: 3;
|
height: 3;
|
||||||
padding: 0 1;
|
padding: 0 1;
|
||||||
@@ -230,6 +280,8 @@ class AIChatApp(App):
|
|||||||
BINDINGS = [
|
BINDINGS = [
|
||||||
Binding("ctrl+c", "quit", "Quit"),
|
Binding("ctrl+c", "quit", "Quit"),
|
||||||
Binding("f1", "controls_help", "Help / Zoom"),
|
Binding("f1", "controls_help", "Help / Zoom"),
|
||||||
|
Binding("s", "screenshot_options", "Screenshot", priority=True),
|
||||||
|
Binding("f2", "screenshot_options", show=False, priority=True),
|
||||||
Binding("pageup", "chat_scroll('page_up')", "Page up", priority=True),
|
Binding("pageup", "chat_scroll('page_up')", "Page up", priority=True),
|
||||||
Binding("pagedown", "chat_scroll('page_down')", "Page down", priority=True),
|
Binding("pagedown", "chat_scroll('page_down')", "Page down", priority=True),
|
||||||
Binding("home", "chat_scroll('home')", "Oldest", priority=True),
|
Binding("home", "chat_scroll('home')", "Oldest", priority=True),
|
||||||
@@ -254,13 +306,17 @@ class AIChatApp(App):
|
|||||||
self.max_turns = max_turns
|
self.max_turns = max_turns
|
||||||
self.messages: list[ChatMessage] = []
|
self.messages: list[ChatMessage] = []
|
||||||
self.current_turn = 0
|
self.current_turn = 0
|
||||||
|
self._started_at: float | None = None
|
||||||
|
self._ended_at: float | None = None
|
||||||
self._is_running = False
|
self._is_running = False
|
||||||
self.client = httpx.AsyncClient(timeout=120.0)
|
self.client = httpx.AsyncClient(timeout=120.0)
|
||||||
|
|
||||||
def compose(self) -> ComposeResult:
|
def compose(self) -> ComposeResult:
|
||||||
yield Header(show_clock=True)
|
yield Header(show_clock=True)
|
||||||
yield Container(
|
yield Container(
|
||||||
|
Static("Elapsed: 00:00:00", id="elapsed-time", markup=False),
|
||||||
ChatContainer(id="chat-container"),
|
ChatContainer(id="chat-container"),
|
||||||
|
Static(f"Turns completed: 0 / {self.max_turns}", id="turn-counter", markup=False),
|
||||||
Static(id="status-bar", markup=False),
|
Static(id="status-bar", markup=False),
|
||||||
id="main-container"
|
id="main-container"
|
||||||
)
|
)
|
||||||
@@ -269,15 +325,56 @@ class AIChatApp(App):
|
|||||||
async def on_mount(self) -> None:
|
async def on_mount(self) -> None:
|
||||||
self.chat_container = self.query_one(ChatContainer)
|
self.chat_container = self.query_one(ChatContainer)
|
||||||
self.status_bar = self.query_one("#status-bar", Static)
|
self.status_bar = self.query_one("#status-bar", Static)
|
||||||
|
self.turn_counter = self.query_one("#turn-counter", Static)
|
||||||
|
self.elapsed_time = self.query_one("#elapsed-time", Static)
|
||||||
self.chat_container.focus()
|
self.chat_container.focus()
|
||||||
self.chat_container.anchor()
|
self.chat_container.anchor()
|
||||||
self.run_worker(self.start_conversation(), exclusive=True)
|
self.run_worker(self.start_conversation(), exclusive=True)
|
||||||
|
|
||||||
|
def action_screenshot_options(self) -> None:
|
||||||
|
if not isinstance(self.screen, ScreenshotOptions):
|
||||||
|
self.push_screen(ScreenshotOptions(), self._screenshot_selected)
|
||||||
|
|
||||||
|
def _screenshot_selected(self, choice: str | None) -> None:
|
||||||
|
if choice is not None:
|
||||||
|
# Capture after the modal has been removed from the screen.
|
||||||
|
self.call_after_refresh(self._save_conversation_screenshot, choice)
|
||||||
|
|
||||||
|
def export_conversation_screenshot(self) -> str:
|
||||||
|
"""Render all messages without the viewport's scrolling/clipping."""
|
||||||
|
console = Console(
|
||||||
|
width=max(40, self.size.width), file=io.StringIO(),
|
||||||
|
record=True, force_terminal=True, color_system="truecolor",
|
||||||
|
)
|
||||||
|
for message in self.messages:
|
||||||
|
content = Markdown(message.content, code_theme="monokai") if message.role == "assistant" else Text(message.content)
|
||||||
|
console.print(Panel(
|
||||||
|
content, title=Text(message.sender),
|
||||||
|
border_style="blue" if message.sender == "AI 1" else "green",
|
||||||
|
padding=(1, 1),
|
||||||
|
))
|
||||||
|
return console.export_svg(title="AI conversation")
|
||||||
|
|
||||||
|
def _save_conversation_screenshot(self, choice: str) -> None:
|
||||||
|
try:
|
||||||
|
directory = Path("screenshots")
|
||||||
|
directory.mkdir(exist_ok=True)
|
||||||
|
filename = f"conversation-{choice}-{datetime.now():%Y%m%d-%H%M%S-%f}.svg"
|
||||||
|
path = directory / filename
|
||||||
|
if choice == "full":
|
||||||
|
path.write_text(self.export_conversation_screenshot(), encoding="utf-8")
|
||||||
|
else:
|
||||||
|
self.save_screenshot(filename=filename, path=str(directory))
|
||||||
|
except (OSError, ValueError) as error:
|
||||||
|
self.notify(f"Could not save screenshot: {error}", severity="error")
|
||||||
|
else:
|
||||||
|
self.notify(f"Screenshot saved: {path.resolve()}", timeout=10)
|
||||||
|
|
||||||
def action_controls_help(self) -> None:
|
def action_controls_help(self) -> None:
|
||||||
self.push_screen(ControlsHelp())
|
self.push_screen(ControlsHelp())
|
||||||
|
|
||||||
def action_chat_scroll(self, direction: str) -> None:
|
def action_chat_scroll(self, direction: str) -> None:
|
||||||
if isinstance(self.screen, ControlsHelp):
|
if isinstance(self.screen, (ControlsHelp, ScreenshotOptions)):
|
||||||
return
|
return
|
||||||
chat = self.chat_container
|
chat = self.chat_container
|
||||||
if direction == "end":
|
if direction == "end":
|
||||||
@@ -295,11 +392,28 @@ class AIChatApp(App):
|
|||||||
|
|
||||||
async def start_conversation(self) -> None:
|
async def start_conversation(self) -> None:
|
||||||
self._is_running = True
|
self._is_running = True
|
||||||
|
self._started_at = monotonic()
|
||||||
|
self._ended_at = None
|
||||||
|
elapsed_timer = self.set_interval(1, self.update_elapsed_time)
|
||||||
self.update_status(f"Starting conversation... AI 1 ({self.ai1.name}) begins")
|
self.update_status(f"Starting conversation... AI 1 ({self.ai1.name}) begins")
|
||||||
|
|
||||||
self.chat_container.messages = self.messages
|
self.chat_container.messages = self.messages
|
||||||
self.chat_container.add_message(ChatMessage("user", self.initial_prompt, "System"))
|
self.chat_container.add_message(ChatMessage("user", self.initial_prompt, "System"))
|
||||||
await self.run_conversation_loop()
|
try:
|
||||||
|
await self.run_conversation_loop()
|
||||||
|
finally:
|
||||||
|
self._ended_at = monotonic()
|
||||||
|
elapsed_timer.stop()
|
||||||
|
self.update_elapsed_time()
|
||||||
|
|
||||||
|
def update_elapsed_time(self) -> None:
|
||||||
|
if self._started_at is None:
|
||||||
|
return
|
||||||
|
end = self._ended_at if self._ended_at is not None else monotonic()
|
||||||
|
seconds = max(0, int(end - self._started_at))
|
||||||
|
hours, remainder = divmod(seconds, 3600)
|
||||||
|
minutes, seconds = divmod(remainder, 60)
|
||||||
|
self.elapsed_time.update(f"Elapsed: {hours:02d}:{minutes:02d}:{seconds:02d}")
|
||||||
|
|
||||||
def history_for(self, sender: str) -> list[dict]:
|
def history_for(self, sender: str) -> list[dict]:
|
||||||
"""Describe each turn from the responding model's perspective."""
|
"""Describe each turn from the responding model's perspective."""
|
||||||
@@ -334,6 +448,9 @@ class AIChatApp(App):
|
|||||||
self.update_status(error_msg)
|
self.update_status(error_msg)
|
||||||
return
|
return
|
||||||
self.current_turn += 1
|
self.current_turn += 1
|
||||||
|
self.turn_counter.update(
|
||||||
|
f"Turns completed: {self.current_turn} / {self.max_turns}"
|
||||||
|
)
|
||||||
if self.current_turn < self.max_turns:
|
if self.current_turn < self.max_turns:
|
||||||
await asyncio.sleep(0.5)
|
await asyncio.sleep(0.5)
|
||||||
self.update_status("Conversation ended. Press Ctrl+C to quit.")
|
self.update_status("Conversation ended. Press Ctrl+C to quit.")
|
||||||
|
|||||||
+21
-1
@@ -11,7 +11,7 @@ from rich.markdown import Markdown
|
|||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
from ai_chat import AIChatApp, AIConfig, MessageBubble, ChatMessage, ControlsHelp, main
|
from ai_chat import AIChatApp, AIConfig, MessageBubble, ChatMessage, ControlsHelp, ScreenshotOptions, main
|
||||||
|
|
||||||
|
|
||||||
class ChatTests(unittest.IsolatedAsyncioTestCase):
|
class ChatTests(unittest.IsolatedAsyncioTestCase):
|
||||||
@@ -194,6 +194,26 @@ class ChatTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
self.assertFalse(bubble._waiting_widget.display)
|
self.assertFalse(bubble._waiting_widget.display)
|
||||||
self.assertEqual(app.messages[-1].role, 'system')
|
self.assertEqual(app.messages[-1].role, 'system')
|
||||||
|
|
||||||
|
async def test_screenshot_menu_stays_open_when_turn_finishes(self):
|
||||||
|
app = await self.make_app(lambda request: httpx.Response(500))
|
||||||
|
finish = asyncio.Event()
|
||||||
|
async def stream(ai, history):
|
||||||
|
await finish.wait()
|
||||||
|
yield "Complete"
|
||||||
|
app.stream_ai = stream
|
||||||
|
async with app.run_test() as pilot:
|
||||||
|
await pilot.press('s')
|
||||||
|
self.assertIsInstance(app.screen, ScreenshotOptions)
|
||||||
|
self.assertGreater(app.screen.query_one('#full').region.height, 0)
|
||||||
|
finish.set()
|
||||||
|
await self.wait_finished(app, pilot)
|
||||||
|
self.assertEqual(app.current_turn, 1)
|
||||||
|
self.assertEqual(app.turn_counter.content, 'Turns completed: 1 / 1')
|
||||||
|
self.assertIsInstance(app.screen, ScreenshotOptions)
|
||||||
|
await pilot.press('escape', 'f2')
|
||||||
|
self.assertIsInstance(app.screen, ScreenshotOptions)
|
||||||
|
await pilot.press('escape')
|
||||||
|
|
||||||
|
|
||||||
class CommandLineTests(unittest.TestCase):
|
class CommandLineTests(unittest.TestCase):
|
||||||
def test_invalid_environment_turns_reports_usage_error(self):
|
def test_invalid_environment_turns_reports_usage_error(self):
|
||||||
|
|||||||
Reference in new issue
Block a user