diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e630db..14cc96f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,19 +6,18 @@ | --- | --- | | `run_example.py` | Entry point that calls `ai_chat.main()` | | `ai_chat.py` | CLI, Textual UI, conversation loop, API requests, exports, and statistics | -| `settings.py` | Load and save `sloppy.json` connections and selections | | `test_ai_chat.py` | Unit and Textual integration tests with mock HTTP responses | | `.env.example` | Example runtime configuration | ## Conversation and request flow -`main()` loads `.env`, parses CLI overrides, validates the prompt and turn count, and creates `AIChatApp`. The app optionally opens the connection picker, then starts the conversation. AI 1 and AI 2 alternate for at most `max_turns` replies. +`main()` loads `.env`, parses CLI overrides, validates the connections, prompt, and turn count, and creates `AIChatApp`. AI 1 and AI 2 alternate for at most `max_turns` replies. For each reply, `history_for()` presents the current speaker's earlier replies as `assistant` messages and the other speaker's replies as `user` messages. It keeps the original topic and recent messages within a 12,000-character request-history budget. The full conversation remains in the UI and exports. Requests go to `{base_url}/chat/completions` with the speaker's system prompt, model ID, temperature `0.7`, and `max_tokens` of `2000`. Streaming reads server-sent `data:` events, requests usage reporting, and requires a final `[DONE]` event. If a stream fails, is incomplete, or is empty, the app attempts a regular JSON completion. Transport and empty-response failures receive up to two retries. The same message bubble is reused during fallback; partial stream content is cleared before the fallback request and cannot enter later conversation history. -`settings.py` validates the shape and field types of loaded settings. It writes JSON through an exclusively created temporary file and atomic replace, and removes its own temporary file if the write fails. On Unix, newly written settings are private to the current user (`0600`). Use an `env:VARIABLE` API-key reference for hosted-provider secrets. `.env`, `sloppy.json`, screenshots, and transcripts are ignored by Git. +`.env`, screenshots, and transcripts are ignored by Git. ## Tests @@ -28,4 +27,4 @@ After installing `requirements.txt`, run: python -m unittest discover -v ``` -The suite covers CLI and settings behavior, streaming and fallback, speaker roles and bounded history, UI controls, statistics, and transcript export. It uses `httpx.MockTransport` and Textual's test pilot, so no live model server is needed. +The suite covers CLI behavior, streaming and fallback, speaker roles and bounded history, UI controls, statistics, and transcript export. It uses `httpx.MockTransport` and Textual's test pilot, so no live model server is needed. diff --git a/README.md b/README.md index 858e3a6..bbeae3f 100644 --- a/README.md +++ b/README.md @@ -24,33 +24,12 @@ python run_example.py --help `.env` accepts `AI1_NAME`, `AI1_BASE_URL`, `AI1_API_KEY`, `AI1_MODEL`, and `AI1_SYSTEM_PROMPT`, plus matching `AI2_*` variables. `INITIAL_PROMPT` is required. `MAX_TURNS` defaults to 20 and must be positive. Set each base URL to an API root such as `http://localhost:11434/v1`; Sloppy appends `/chat/completions`. -Command-line options `--ai1-name`, `--ai1-url`, `--ai1-key`, `--ai1-model`, `--ai1-prompt` and matching `--ai2-*` options override `.env` values for a run. When any connection option is supplied, both connections need a base URL and API key after applying defaults. Prefer environment variables over command-line arguments for hosted-provider secrets, since command-line values can enter shell history. - -Press **Ctrl+M** to add, edit, delete, and select saved connections. Use **Back** to leave the picker without saving; if you leave it at launch, press **Ctrl+M** to reopen it. Connections are stored in `sloppy.json` in the current working directory: - -```json -{ - "models": { - "local": { - "name": "Local Llama", - "base_url": "http://localhost:11434/v1", - "api_key": "env:LOCAL_API_KEY", - "model": "llama3", - "system_prompt": "You are a helpful assistant." - } - }, - "selected": {"ai1": "local", "ai2": "local"} -} -``` - -Set `LOCAL_API_KEY` in the process environment when using `env:LOCAL_API_KEY`. The app resolves it when selecting the connection. You can select the current `.env` connection for either speaker. `.env` values are reread on launch and are never copied into `sloppy.json`. With complete `.env` connections and no `sloppy.json`, the conversation starts directly; otherwise a picker opens. Changes to speaker selection during a conversation apply on the next run. +Command-line options `--ai1-name`, `--ai1-url`, `--ai1-key`, `--ai1-model`, `--ai1-prompt` and matching `--ai2-*` options override `.env` values for a run. Both connections need a base URL and API key after applying defaults. Prefer environment variables over command-line arguments for hosted-provider secrets, since command-line values can enter shell history. ## Controls and exports | Key | Action | | --- | --- | -| Ctrl+M | Connections and speaker selection | -| Ctrl+P | Command palette | | F1 | Reading controls | | S or F2 | Sharing menu | | Mouse wheel, Up / Down, Page Up / Page Down | Scroll | @@ -63,9 +42,7 @@ The sharing menu saves the full conversation or visible screen as SVG in `screen ## Troubleshooting -- **No connection in the picker:** Complete the base URL and key in `.env`, or add a saved connection with **Ctrl+M**. -- **Missing API key:** Set the environment variable named by a saved `env:NAME` reference before launch. +- **Missing connection:** Complete the base URL and key in `.env` or supply them with CLI arguments. - **API error:** Check the API root, model ID, server availability, and credentials. A failed or incomplete stream falls back to a non-streaming request; transport and empty-response failures receive up to two retries. -- **Invalid settings:** Fix malformed `sloppy.json` in the current working directory. `models` and `selected` must be objects; connection fields and selections must be strings. The error identifies the invalid field. See [CONTRIBUTING.md](CONTRIBUTING.md) for code structure and tests. diff --git a/ai_chat.py b/ai_chat.py index a390997..3680501 100644 --- a/ai_chat.py +++ b/ai_chat.py @@ -18,7 +18,7 @@ from rich.console import Group from rich.text import Text from rich.markdown import Markdown from textual.containers import Container, Horizontal, VerticalScroll -from textual.widgets import Header, Footer, Static, Button, Input, Select, Label +from textual.widgets import Header, Footer, Static, Button from textual.binding import Binding from textual.screen import ModalScreen @@ -66,7 +66,7 @@ class SquareLoadingIndicator(Static): class MessageBubble(Static): """A chat message bubble that supports streaming updates.""" - + def __init__(self, message: ChatMessage, **kwargs): super().__init__(**kwargs) self.message = message @@ -218,133 +218,12 @@ class ScreenshotOptions(ModalScreen[str | None]): self.dismiss(None if event.button.id == "cancel" else event.button.id) -class ModelSettings(ModalScreen[tuple[AIConfig, AIConfig] | None]): - """Choose the two speakers and maintain saved OpenAI-compatible connections.""" - - BINDINGS = [Binding("escape", "dismiss(None)", "Close")] - DEFAULT_CSS = """ - ModelSettings { align: center middle; } - #model-settings { width: 76; max-width: 95%; height: auto; max-height: 95%; - padding: 1 2; border: round $primary; background: $surface; overflow-y: auto; } - #model-settings Input, #model-settings Select { margin-bottom: 1; } - #model-actions Button { margin-right: 1; } - """ - - def __init__(self, path: Path, initial_ai1: AIConfig, initial_ai2: AIConfig): - super().__init__() - self.path = path - self.initial = (initial_ai1, initial_ai2) - from settings import load_settings - self.settings = load_settings(path) - - def compose(self) -> ComposeResult: - with VerticalScroll(id="model-settings"): - yield Static("[bold]Models and connections[/bold] • saved in sloppy.json") - yield Button("Back (Esc)", id="back-models") - yield Label("AI 1") - yield Select([], id="ai1-select", allow_blank=True) - yield Label("AI 2") - yield Select([], id="ai2-select", allow_blank=True) - yield Static("[bold]Add or edit a connection[/bold]") - yield Input(placeholder="Connection ID (e.g. local-llama)", id="connection-id") - yield Input(placeholder="Display name", id="model-name") - yield Input(placeholder="Base URL, e.g. http://localhost:11434/v1", id="base-url") - yield Input(placeholder="API key (or env:VARIABLE)", id="api-key", password=True) - yield Input(placeholder="Model ID", id="model-id") - yield Input(placeholder="System prompt", id="system-prompt") - with Horizontal(id="model-actions"): - yield Button("Save connection", id="save-model", variant="primary") - yield Button("Delete connection", id="delete-model") - yield Button("Use selected models", id="use-models", variant="success") - - def on_mount(self) -> None: - self.refresh_choices() - - def refresh_choices(self) -> None: - options = [(f"{key}: {value.get('name', key)} ({value.get('model', '')})", key) - for key, value in self.settings['models'].items()] - for slot, config in zip(('ai1', 'ai2'), self.initial): - if config.base_url and config.api_key: - options.append((f"{slot.upper()} from .env ({config.model})", f"env:{slot}")) - for slot in ('ai1', 'ai2'): - select = self.query_one(f"#{slot}-select", Select) - select.set_options(options) - chosen = self.settings['selected'].get(slot) - if chosen in self.settings['models'] or (chosen == f"env:{slot}" and chosen in [value for _, value in options]): - select.value = chosen - elif f"env:{slot}" in [value for _, value in options]: - select.value = f"env:{slot}" - - def on_select_changed(self, event: Select.Changed) -> None: - if event.select.id not in ('ai1-select', 'ai2-select'): - return - identifier = event.value - if not isinstance(identifier, str) or identifier not in self.settings['models']: - return - from settings import model_from_settings - values = model_from_settings(self.settings, identifier) - for widget_id, value in (('connection-id', identifier), ('model-name', values['name']), - ('base-url', values['base_url']), ('api-key', values['api_key']), - ('model-id', values['model']), ('system-prompt', values['system_prompt'])): - self.query_one(f"#{widget_id}", Input).value = value - - def on_button_pressed(self, event: Button.Pressed) -> None: - from settings import model_from_settings, save_settings, store_model - action = event.button.id - if action == 'back-models': - self.dismiss(None) - return - identifier = self.query_one('#connection-id', Input).value.strip() - try: - if action == 'save-model': - config = AIConfig( - self.query_one('#model-name', Input).value.strip(), - self.query_one('#base-url', Input).value.strip(), - self.query_one('#api-key', Input).value.strip(), - self.query_one('#model-id', Input).value.strip(), - self.query_one('#system-prompt', Input).value or 'You are a helpful assistant.', - ) - store_model(self.settings, identifier, config) - save_settings(self.settings, self.path) - self.refresh_choices() - self.notify(f"Saved {identifier}") - elif action == 'delete-model': - if identifier not in self.settings['models']: - raise ValueError('Select or enter an existing connection ID') - del self.settings['models'][identifier] - for slot in ('ai1', 'ai2'): - if self.settings['selected'].get(slot) == identifier: - self.settings['selected'][slot] = '' - save_settings(self.settings, self.path) - self.refresh_choices() - self.notify(f"Deleted {identifier}") - elif action == 'use-models': - identifiers = [self.query_one(f'#{slot}-select', Select).value for slot in ('ai1', 'ai2')] - valid = [set(self.settings['models']) | ({f'env:{slot}'} if config.base_url and config.api_key else set()) - for slot, config in zip(('ai1', 'ai2'), self.initial)] - if any(value not in choices for value, choices in zip(identifiers, valid)): - raise ValueError('Select a connection for each AI') - self.settings['selected'] = dict(zip(('ai1', 'ai2'), identifiers)) - save_settings(self.settings, self.path) - models = [self.initial[index] if value == f'env:ai{index + 1}' - else AIConfig(**model_from_settings(self.settings, value)) - for index, value in enumerate(identifiers)] - for model in models: - if model.api_key.startswith('env:'): - model.api_key = os.getenv(model.api_key[4:], '') - if not model.api_key: - raise ValueError(f'API key missing for {model.name}') - self.dismiss((models[0], models[1])) - except (OSError, ValueError) as error: - self.notify(str(error), severity='error') - - class AIChatApp(App): CSS = """ Screen { background: $surface; } - + #elapsed-time { height: 1; padding: 0 1; @@ -358,12 +237,12 @@ class AIChatApp(App): margin: 1; padding: 1; } - + .bubble-content { padding: 1; width: 100%; } - + .response-waiting { height: 3; align-vertical: middle; @@ -387,7 +266,7 @@ class AIChatApp(App): width: 100%; min-height: 3; } - + #conversation-stats { height: auto; padding: 0 1; @@ -412,8 +291,6 @@ class AIChatApp(App): BINDINGS = [ Binding("ctrl+c", "quit", "Quit"), - Binding("ctrl+p", "command_palette", "Commands"), - Binding("ctrl+m", "model_settings", "Models"), Binding("f1", "controls_help", "Help / Zoom"), Binding("s", "screenshot_options", "Screenshot", priority=True), Binding("f2", "screenshot_options", show=False, priority=True), @@ -431,16 +308,10 @@ class AIChatApp(App): ai2_config: AIConfig, initial_prompt: str, max_turns: int = 20, - settings_path: Path | None = None, - choose_models: bool = False, - env_models: tuple[AIConfig, AIConfig] | None = None, ): super().__init__() if max_turns < 1: raise ValueError("max_turns must be positive") - self.settings_path = settings_path - self.choose_models = choose_models - self.env_models = env_models or (ai1_config, ai2_config) self.ai1 = ai1_config self.ai2 = ai2_config self.initial_prompt = initial_prompt @@ -483,31 +354,7 @@ class AIChatApp(App): self.elapsed_time = self.query_one("#elapsed-time", Static) self.chat_container.focus() self.chat_container.anchor() - if self.choose_models and self.settings_path: - self.action_model_settings() - else: - self.run_worker(self.start_conversation(), exclusive=True) - - def action_model_settings(self) -> None: - if self.settings_path and not isinstance(self.screen, ModelSettings): - try: - self.push_screen(ModelSettings(self.settings_path, *self.env_models), self._models_selected) - except (OSError, ValueError, json.JSONDecodeError) as error: - self.notify(f"Could not load settings: {error}", severity="error") - - def _models_selected(self, models: tuple[AIConfig, AIConfig] | None) -> None: - if models is None: - if not self.messages: - self.update_status("No conversation started. Press Ctrl+M to choose models.") - return - if self._is_running: - self.notify("Saved selection applies to the next conversation") - return - self.ai1, self.ai2 = models - if not self.messages: - self.run_worker(self.start_conversation(), exclusive=True) - else: - self.notify("Saved selection applies to the next conversation") + self.run_worker(self.start_conversation(), exclusive=True) def action_screenshot_options(self) -> None: if not isinstance(self.screen, ScreenshotOptions): @@ -599,7 +446,7 @@ class AIChatApp(App): 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.chat_container.messages = self.messages self.chat_container.add_message(ChatMessage("user", self.initial_prompt, "System")) try: @@ -812,21 +659,21 @@ class AIChatApp(App): async def call_ai(self, ai: AIConfig, history: list[dict]) -> str: """Non-streaming fallback.""" messages = [{"role": "system", "content": ai.system_prompt}] + history - + payload = { "model": ai.model, "messages": messages, "temperature": 0.7, "max_tokens": 2000, } - + headers = { "Authorization": f"Bearer {ai.api_key}", "Content-Type": "application/json", } - + url = f"{ai.base_url.rstrip('/')}/chat/completions" - + self.begin_response_metrics() try: return await self._call_ai_response(url, payload, headers) @@ -837,7 +684,7 @@ class AIChatApp(App): response = await self.client.post(url, json=payload, headers=headers) if response.status_code != 200: raise Exception(f"API Error {response.status_code}: {response.text}") - + data = response.json() self.record_usage(data.get("usage")) if "error" in data: @@ -851,7 +698,7 @@ class AIChatApp(App): async def stream_ai(self, ai: AIConfig, history: list[dict]): """Stream response from AI using SSE.""" messages = [{"role": "system", "content": ai.system_prompt}] + history - + payload = { "model": ai.model, "messages": messages, @@ -860,23 +707,23 @@ class AIChatApp(App): "stream": True, "stream_options": {"include_usage": True}, } - + headers = { "Authorization": f"Bearer {ai.api_key}", "Content-Type": "application/json", "Accept": "text/event-stream", } - + url = f"{ai.base_url.rstrip('/')}/chat/completions" - + log.debug(f"Streaming request to {url} with model {ai.model}") - + async with self.client.stream("POST", url, json=payload, headers=headers) as response: log.debug(f"Response status: {response.status_code}") if response.status_code != 200: error_body = await response.aread() raise Exception(f"API Error {response.status_code}: {error_body.decode(errors='replace')}") - + done = False async for line in response.aiter_lines(): if not line.startswith("data:"): @@ -911,10 +758,10 @@ class AIChatApp(App): def load_config() -> tuple[AIConfig, AIConfig, str, str]: load_dotenv() - + def get_env(key: str, default: str = "") -> str: return os.getenv(key, default) - + ai1 = AIConfig( name=get_env("AI1_NAME", "AI 1"), base_url=get_env("AI1_BASE_URL", ""), @@ -922,7 +769,7 @@ def load_config() -> tuple[AIConfig, AIConfig, str, str]: model=get_env("AI1_MODEL", "gpt-3.5-turbo"), system_prompt=get_env("AI1_SYSTEM_PROMPT", "You are a helpful assistant."), ) - + ai2 = AIConfig( name=get_env("AI2_NAME", "AI 2"), base_url=get_env("AI2_BASE_URL", ""), @@ -930,61 +777,63 @@ def load_config() -> tuple[AIConfig, AIConfig, str, str]: model=get_env("AI2_MODEL", "gpt-3.5-turbo"), system_prompt=get_env("AI2_SYSTEM_PROMPT", "You are a helpful assistant."), ) - + prompt = get_env("INITIAL_PROMPT", "") turns = get_env("MAX_TURNS", "20") - + return ai1, ai2, prompt, turns def main(): import argparse - + # Load from .env first ai1_env, ai2_env, prompt_env, turns_env = load_config() - + parser = argparse.ArgumentParser(description="Two AI models conversation TUI with streaming") parser.add_argument("--ai1-name", default=ai1_env.name, help="Name for AI 1") parser.add_argument("--ai1-url", default=ai1_env.base_url, help="Base URL for AI 1 (OpenAI-compatible)") parser.add_argument("--ai1-key", default=ai1_env.api_key, help="API key for AI 1") parser.add_argument("--ai1-model", default=ai1_env.model, help="Model for AI 1") parser.add_argument("--ai1-prompt", default=ai1_env.system_prompt, help="System prompt for AI 1") - + parser.add_argument("--ai2-name", default=ai2_env.name, help="Name for AI 2") parser.add_argument("--ai2-url", default=ai2_env.base_url, help="Base URL for AI 2 (OpenAI-compatible)") parser.add_argument("--ai2-key", default=ai2_env.api_key, help="API key for AI 2") parser.add_argument("--ai2-model", default=ai2_env.model, help="Model for AI 2") parser.add_argument("--ai2-prompt", default=ai2_env.system_prompt, help="System prompt for AI 2") - + parser.add_argument("--prompt", default=prompt_env, help="Initial prompt for AI 1 to start") parser.add_argument("--turns", type=int, default=turns_env, help="Maximum conversation turns") - + args = parser.parse_args() - + + if not args.ai1_url or not args.ai1_key: + parser.error("AI1_BASE_URL and AI1_API_KEY required (set in .env or via --ai1-url/--ai1-key)") + if not args.ai2_url or not args.ai2_key: + parser.error("AI2_BASE_URL and AI2_API_KEY required (set in .env or via --ai2-url/--ai2-key)") if args.turns < 1: parser.error("--turns / MAX_TURNS must be positive") if not args.prompt.strip(): parser.error("INITIAL_PROMPT required (set in .env or via --prompt)") - ai1 = AIConfig(args.ai1_name, args.ai1_url, args.ai1_key, args.ai1_model, args.ai1_prompt) - ai2 = AIConfig(args.ai2_name, args.ai2_url, args.ai2_key, args.ai2_model, args.ai2_prompt) - from settings import DEFAULT_PATH, load_settings - try: - load_settings(DEFAULT_PATH) - except (OSError, ValueError, json.JSONDecodeError) as error: - parser.error(f"Could not load sloppy.json: {error}") - import sys - explicit_models = any(arg.startswith(("--ai1-", "--ai2-")) for arg in sys.argv[1:]) - if explicit_models: - ai1 = AIConfig(args.ai1_name, args.ai1_url, args.ai1_key, args.ai1_model, args.ai1_prompt) - ai2 = AIConfig(args.ai2_name, args.ai2_url, args.ai2_key, args.ai2_model, args.ai2_prompt) - if not all((ai1.base_url, ai1.api_key, ai2.base_url, ai2.api_key)): - parser.error("Both AI connections need a base URL and API key") - env_ready = all((ai1.base_url, ai1.api_key, ai2.base_url, ai2.api_key)) - app = AIChatApp(ai1, ai2, args.prompt, args.turns, - settings_path=DEFAULT_PATH, - choose_models=not explicit_models and (DEFAULT_PATH.exists() or not env_ready), - env_models=(ai1_env, ai2_env)) + ai1 = AIConfig( + name=args.ai1_name, + base_url=args.ai1_url, + api_key=args.ai1_key, + model=args.ai1_model, + system_prompt=args.ai1_prompt, + ) + + ai2 = AIConfig( + name=args.ai2_name, + base_url=args.ai2_url, + api_key=args.ai2_key, + model=args.ai2_model, + system_prompt=args.ai2_prompt, + ) + + app = AIChatApp(ai1, ai2, args.prompt, args.turns) app.run() diff --git a/settings.py b/settings.py deleted file mode 100644 index 17aa4d1..0000000 --- a/settings.py +++ /dev/null @@ -1,63 +0,0 @@ -import json -import os -from dataclasses import asdict -from pathlib import Path - - -DEFAULT_PATH = Path('sloppy.json') - - -def load_settings(path=DEFAULT_PATH): - path = Path(path) - if not path.exists(): - return {'models': {}, 'selected': {'ai1': '', 'ai2': ''}} - data = json.loads(path.read_text(encoding='utf-8')) - if not isinstance(data, dict) or not isinstance(data.get('models', {}), dict): - raise ValueError('sloppy.json must contain a models object') - data.setdefault('models', {}) - data.setdefault('selected', {'ai1': '', 'ai2': ''}) - if not isinstance(data['selected'], dict): - raise ValueError('sloppy.json selected must be an object') - for slot, value in data['selected'].items(): - if not isinstance(slot, str) or not isinstance(value, str): - raise ValueError(f'sloppy.json selected.{slot} must be a string') - for identifier, values in data['models'].items(): - if not isinstance(identifier, str) or not isinstance(values, dict): - raise ValueError(f'sloppy.json models.{identifier} must be an object') - for field in ('name', 'base_url', 'api_key', 'model', 'system_prompt'): - if field in values and not isinstance(values[field], str): - raise ValueError(f'sloppy.json models.{identifier}.{field} must be a string') - return data - - -def save_settings(data, path=DEFAULT_PATH): - path = Path(path) - temporary = path.with_name(path.name + '.tmp') - flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL - if hasattr(os, 'O_BINARY'): - flags |= os.O_BINARY - created = False - try: - descriptor = os.open(temporary, flags, 0o600) - created = True - with os.fdopen(descriptor, 'w', encoding='utf-8') as output: - output.write(json.dumps(data, indent=2, ensure_ascii=False) + '\n') - os.replace(temporary, path) - except BaseException: - if created: - temporary.unlink(missing_ok=True) - raise - - -def model_from_settings(data, identifier): - values = data['models'][identifier] - return {key: values.get(key, default) for key, default in ( - ('name', identifier), ('base_url', ''), ('api_key', ''), - ('model', ''), ('system_prompt', 'You are a helpful assistant.'))} - - -def store_model(data, identifier, config): - identifier = identifier.strip() - if not identifier or not all((config.name.strip(), config.base_url.strip(), config.model.strip())): - raise ValueError('ID, name, base URL, and model are required') - data['models'][identifier] = asdict(config) diff --git a/test_ai_chat.py b/test_ai_chat.py index fb29401..a678b4b 100644 --- a/test_ai_chat.py +++ b/test_ai_chat.py @@ -4,19 +4,14 @@ import unittest import contextlib import io import os -import tempfile -import stat -from pathlib import Path from unittest.mock import patch from rich.console import Console from rich.markdown import Markdown -from textual.widgets import Button import httpx -from ai_chat import AIChatApp, AIConfig, MessageBubble, ChatMessage, ControlsHelp, ScreenshotOptions, ModelSettings, main -from settings import load_settings, save_settings, store_model, model_from_settings +from ai_chat import AIChatApp, AIConfig, MessageBubble, ChatMessage, ControlsHelp, ScreenshotOptions, main class ChatTests(unittest.IsolatedAsyncioTestCase): @@ -200,32 +195,6 @@ class ChatTests(unittest.IsolatedAsyncioTestCase): self.assertEqual([m.content for m in app.messages], ['Start here', 'complete reply', 'second reply']) self.assertNotIn('partial secret', json.dumps(requests[2])) - async def test_invalid_settings_picker_reports_error_and_chat_remains_usable(self): - app = await self.make_app(lambda request: httpx.Response(200, text='data: {"choices":[{"delta":{"content":"working"}}]}\n\ndata: [DONE]\n\n')) - with tempfile.TemporaryDirectory() as directory: - app.settings_path = Path(directory) / 'sloppy.json' - app.settings_path.write_text('{"models": {"x": null}}', encoding='utf-8') - async with app.run_test() as pilot: - with patch.object(app, 'notify') as notify: - app.action_model_settings() - self.assertIn('models.x', notify.call_args.args[0]) - await self.wait_finished(app, pilot) - self.assertEqual(app.messages[-1].content, 'working') - - async def test_back_exits_model_picker_without_saving(self): - app = await self.make_app(lambda request: httpx.Response(500)) - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / 'sloppy.json' - app.settings_path = path - app.choose_models = True - async with app.run_test() as pilot: - self.assertIsInstance(app.screen, ModelSettings) - app.screen.query_one('#back-models', Button).press() - await pilot.pause() - self.assertNotIsInstance(app.screen, ModelSettings) - self.assertFalse(path.exists()) - self.assertIn('Ctrl+M', str(app.status_bar.render())) - async def test_empty_stream_uses_fallback(self): calls = [] def handler(request): @@ -401,70 +370,32 @@ class ChatTests(unittest.IsolatedAsyncioTestCase): class CommandLineTests(unittest.TestCase): - def test_settings_validation_identifies_invalid_fields(self): - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / 'sloppy.json' - for data, field in [ - ({'models': {}, 'selected': None}, 'selected'), - ({'models': {'x': None}}, 'models.x'), - ({'models': {'x': {'api_key': None}}}, 'models.x.api_key'), - ({'models': {}, 'selected': {'ai1': None}}, 'selected.ai1'), - ]: - path.write_text(json.dumps(data), encoding='utf-8') - with self.subTest(field=field), self.assertRaisesRegex(ValueError, field.replace('.', r'\.')): - load_settings(path) - path.write_text(json.dumps({'models': {'x': {'model': 'm'}}}), encoding='utf-8') - self.assertEqual(load_settings(path)['selected'], {'ai1': '', 'ai2': ''}) - - @unittest.skipIf(os.name == 'nt', 'Unix file modes only') - def test_settings_temp_is_private_and_failure_cleans_up(self): - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / 'sloppy.json' - for existing in (False, True): - if existing: - path.write_text('old', encoding='utf-8') - path.chmod(0o644) - original_replace = os.replace - def inspect_replace(source, destination): - self.assertEqual(stat.S_IMODE(source.stat().st_mode), 0o600) - self.assertIn('secret', source.read_text(encoding='utf-8')) - original_replace(source, destination) - with patch('settings.os.replace', side_effect=inspect_replace): - save_settings({'api_key': 'secret'}, path) - self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600) - with patch('settings.os.replace', side_effect=OSError('replace failed')): - with self.assertRaisesRegex(OSError, 'replace failed'): - save_settings({'api_key': 'secret'}, path) - self.assertFalse(path.with_name('sloppy.json.tmp').exists()) - - def test_env_only_starts_without_picker_or_json_import(self): + def test_env_connections_start_directly(self): variables = { 'AI1_BASE_URL': 'http://one.test/v1', 'AI1_API_KEY': 'one-key', 'AI2_BASE_URL': 'http://two.test/v1', 'AI2_API_KEY': 'two-key', 'INITIAL_PROMPT': 'Discuss this', 'MAX_TURNS': '2', } - with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, variables), \ - patch('sys.argv', ['ai_chat.py']), patch('ai_chat.AIChatApp.run', autospec=True) as run: - original = os.getcwd() - try: - os.chdir(directory) - main() - self.assertFalse(Path('sloppy.json').exists()) - finally: - os.chdir(original) - self.assertFalse(run.call_args.args[0].choose_models) + with patch.dict(os.environ, variables), patch('sys.argv', ['ai_chat.py']), \ + patch('ai_chat.AIChatApp.run', autospec=True) as run: + main() + app = run.call_args.args[0] + self.assertEqual(app.ai1.base_url, variables['AI1_BASE_URL']) + self.assertEqual(app.ai2.api_key, variables['AI2_API_KEY']) - def test_model_settings_round_trip(self): - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / 'sloppy.json' - settings = load_settings(path) - store_model(settings, 'local', AIConfig('Local', 'http://localhost:11434/v1', - 'env:LOCAL_KEY', 'llama3')) - settings['selected'] = {'ai1': 'local', 'ai2': 'local'} - save_settings(settings, path) - loaded = load_settings(path) - self.assertEqual(loaded['selected']['ai2'], 'local') - self.assertEqual(model_from_settings(loaded, 'local')['api_key'], 'env:LOCAL_KEY') + def test_cli_model_overrides_environment(self): + variables = { + 'AI1_BASE_URL': 'http://one.test/v1', 'AI1_API_KEY': 'one-key', + 'AI2_BASE_URL': 'http://two.test/v1', 'AI2_API_KEY': 'two-key', + 'INITIAL_PROMPT': 'Discuss this', + } + with patch.dict(os.environ, variables), \ + patch('sys.argv', ['ai_chat.py', '--ai1-model', 'different', '--ai2-url', 'http://other.test/v1']), \ + patch('ai_chat.AIChatApp.run', autospec=True) as run: + main() + app = run.call_args.args[0] + self.assertEqual(app.ai1.model, 'different') + self.assertEqual(app.ai2.base_url, 'http://other.test/v1') def test_invalid_environment_turns_reports_usage_error(self): with patch.dict(os.environ, {"MAX_TURNS": "invalid"}), patch('sys.argv', ['ai_chat.py']):