Skip to content
Repos

blackcat

Python 59.2 KB1400 lines Opens in site

Directory Raw Download

"""Tests for the Textual TUI harness (skipped without the tui extra).

Pilot tests drive :class:`BlackCatApp` headless; bridge tests assert the
event stream without an app. Everything runs offline (echo provider,
tmp files, synthetic events).
"""

from __future__ import annotations

# retoor <retoor@molodetz.nl>
import asyncio
import html
import os
import re
import tempfile
import unittest
from contextlib import asynccontextmanager
from pathlib import Path
from types import SimpleNamespace

from blackcat.tui.quality import RenderContract

try:
    from blackcat.tui import cards as T
    from blackcat.tui.app import BlackCatApp, BlackCatCommands
    from blackcat.tui.bridge import TUIBot, UIEvent
    from blackcat.tui.chrome import (
        CostsView,
        DiffView,
        PendingImages,
        PromptBox,
        SubmitPrompt,
    )
    from blackcat.tui.theme import THEMES
    HAS_TEXTUAL = True
except ImportError:
    HAS_TEXTUAL = False


def _echo_kwargs(**extra):
    kwargs = {"provider": "echo"}
    kwargs.update(extra)
    return kwargs


@asynccontextmanager
async def booted_app(**bot_kwargs):
    """Yield (app, pilot) with the splash dismissed."""
    app = BlackCatApp(bot_kwargs=_echo_kwargs(**bot_kwargs))
    async with app.run_test(size=(120, 40)) as pilot:
        await pilot.press("escape")
        await pilot.pause()
        yield app, pilot


async def wait_card(app, seq, timeout=10.0):
    """Wait until card ``seq`` reaches a terminal status."""
    import time
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        card = app._cards.get(seq)
        if card is not None and card.status in ("ok", "failed"):
            return card
        await asyncio.sleep(0.05)
    raise AssertionError("card %d never finished: %r" % (
        seq, getattr(app._cards.get(seq), "status", None)))



@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestBridge(unittest.IsolatedAsyncioTestCase):
    async def test_prompt_emits_turn_events(self):
        events = []
        bot = TUIBot(provider="echo", emit=events.append)
        self.addAsyncCleanup(bot.aclose)
        await bot.prompt("hi")
        kinds = [e.kind for e in events]
        self.assertEqual(kinds, ["turn_start", "turn_done"])
        self.assertEqual(events[1].payload["reply"], "echo: hi")

    async def test_run_tool_emits_card_events(self):
        from blackcat.fstate import FileState
        from blackcat.tools import FileTools
        events = []
        with tempfile.TemporaryDirectory() as tmp:
            path = os.path.join(tmp, "a.txt")
            with open(path, "w", encoding="utf-8") as fh:
                fh.write("hello\n")
            bot = TUIBot(provider="echo",
                         tools=FileTools(FileState(tmp)),
                         emit=events.append)
            self.addAsyncCleanup(bot.aclose)
            out = await bot.run_tool("read", path="a.txt")
        self.assertTrue(out["ok"])
        kinds = [e.kind for e in events]
        self.assertEqual(kinds, ["tool_start", "tool_done"])
        self.assertEqual(events[0].payload["name"], "read")
        self.assertTrue(events[1].payload["result"]["ok"])
        self.assertGreaterEqual(events[1].payload["elapsed_ms"], 0.0)

    async def test_converge_sub_events(self):
        events = []

        class _Chat:
            model = "m"

            async def chat(self, messages, **kwargs):
                return {"choices": [{"message": {"content":
                            '{"claims": []}'}}], "usage": {}}

        class _RS:
            async def search(self, query, count=10):
                return {"results": [
                    {"title": "T", "url": "https://a.org",
                     "summary": "s"}],
                    "fallback_provider": "rsearch"}

        bot = TUIBot(provider="deepseek", api_key="k",
                     emit=events.append)
        self.addAsyncCleanup(bot.aclose)
        bot._client = _Chat()
        bot._rsearch = _RS()
        out = await bot.run_tool("iterative_evidence_convergence",
                                 topic="t", max_iterations=1,
                                 min_iterations=1)
        self.assertTrue(out["ok"])
        kinds = [e.kind for e in events]
        self.assertIn("converge_query", kinds)
        self.assertIn("converge_extract", kinds)
        self.assertEqual(kinds[0], "tool_start")
        self.assertEqual(kinds[-1], "tool_done")

    async def test_deep_research_sub_events(self):
        from blackcat.client import DeepSeekError
        events = []
        bot = TUIBot(provider="echo", emit=events.append)
        self.addAsyncCleanup(bot.aclose)

        async def _search(query, count=10):
            return {"results": [
                {"title": "T", "url": "https://a.org/x",
                 "summary": "s"}]}

        async def _fetch(url):
            return {"url": url, "content": "word " * 200}

        async def _stealth_fail(url):
            raise DeepSeekError("stealthii down")

        bot.search = _search
        bot.fetch = _fetch
        bot._stealth.fetch = _stealth_fail
        out = await bot.run_tool("deep_research", topic="t",
                                 max_queries=1, max_sources=2)
        self.assertTrue(out["ok"])
        kinds = [e.kind for e in events]
        self.assertEqual(kinds[0], "tool_start")
        self.assertEqual(kinds[-1], "tool_done")
        for kind in ("research_plan", "research_query",
                     "research_ranked", "research_fetch",
                     "research_fetch_attempt", "research_synth"):
            self.assertIn(kind, kinds)
        fetch_event = next(e for e in events
                           if e.kind == "research_fetch")
        self.assertEqual(fetch_event.payload["seq"], 1)
        self.assertEqual(fetch_event.payload["method"], "provider")

    async def test_note_and_compact_events(self):
        events = []
        bot = TUIBot(provider="echo", emit=events.append)
        self.addAsyncCleanup(bot.aclose)
        bot.note("remember this")
        await bot.prompt("hi")
        await bot.compact()
        kinds = [e.kind for e in events]
        self.assertIn("note", kinds)
        self.assertIn("compact", kinds)

    async def test_emit_never_breaks_bot(self):
        def _boom(event):
            raise RuntimeError("ui exploded")

        bot = TUIBot(provider="echo", emit=_boom)
        self.addAsyncCleanup(bot.aclose)
        self.assertEqual(await bot.prompt("hi"), "echo: hi")


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestCardsUnit(unittest.TestCase):
    def test_factory_covers_every_tool(self):
        from blackcat.agent import TOOL_NAMES
        for name in TOOL_NAMES:
            card = T.make_card(name, 1, {})
            self.assertIsInstance(card, T.ToolCard)
            self.assertIsNone(card.alias_for)
        self.assertIsInstance(T.make_card("write", 1, {}),
                              T.WriteCard)
        self.assertEqual(T.make_card("write", 1, {}).alias_for,
                         "write_file")
        converge = T.make_card("converge_on_claim", 1, {})
        self.assertIsInstance(converge, T.ConvergeCard)
        self.assertEqual(converge.alias_for,
                         "iterative_evidence_convergence")
        self.assertIsInstance(T.make_card("nope", 1, {}),
                              T.GenericCard)

    def test_glyph_tables_complete(self):
        for key in T.GLYPHS:
            self.assertIn(key, T.ASCII_GLYPHS)

    def test_glyphset_owns_ascii_flag(self):
        self.assertFalse(T.GlyphSet.ascii_mode)
        try:
            self.assertTrue(T.GlyphSet.set_ascii(True))
            self.assertTrue(T.GlyphSet.ascii_mode)
            self.assertEqual(T.GlyphSet.get("ok"), "[ok]")
            self.assertEqual(T.glyph("ok"), "[ok]")
        finally:
            T.GlyphSet.set_ascii(False)
        self.assertEqual(T.GlyphSet.get("ok"), "✔")

    def test_card_factory_registry(self):
        self.assertIn("deep_research", T.CardFactory.known_tools())
        card = T.CardFactory.create("write", 1, {})
        self.assertIsInstance(card, T.WriteCard)
        self.assertEqual(card.alias_for, "write_file")
        self.assertIsInstance(
            T.CardFactory.create("nope", 1, {}), T.GenericCard)

    def test_card_text_shorten(self):
        self.assertEqual(
            T.CardText.shorten("  a   b  ", 99), "a b")

    def test_card_text_plain_never_parses_markup(self):
        from textual.widgets import Static
        row = T.CardText.plain("[notice] [=weird, x=1]", "code-row")
        self.assertIsInstance(row, Static)
        self.assertIn("[notice]", str(row.render()))
        self.assertEqual(str(T.CardText.plain(None).render()), "")
        self.assertTrue(
            T.CardText.shorten("x" * 200, 10).endswith("…"))

    def test_chrome_helpers_are_classes(self):
        from blackcat.tui.chrome import Gradient, Thumbnail
        painted = Gradient.paint_text("AB")
        self.assertEqual(painted.plain, "AB")
        self.assertIsInstance(Thumbnail.for_path("pic.png"),
                              T.Widget)

    def test_launcher_builds_bot_kwargs(self):
        from blackcat.tui import TuiLauncher
        launcher = TuiLauncher(provider="echo",
                               initial_prompt="hi")
        self.assertEqual(
            launcher._bot_kwargs["provider"], "echo")
        self.assertEqual(launcher._initial_prompt, "hi")

    def test_themes_register(self):
        self.assertEqual(len(THEMES), 3)
        names = sorted(t.name for t in THEMES)
        self.assertEqual(names, ["alley-cat", "matrix-alley",
                                 "milk-bowl"])



def _card_cases():
    read_result = {"ok": True, "path": "a.py", "offset": 1,
                   "shown": 2, "total_lines": 2,
                   "lines": ["1:ab|def f():", "2:cd|    pass"],
                   "truncated": False}
    grep_result = {"ok": True, "pattern": "f(", "backend": "rg",
                   "hits": [{"file": "a.py", "line": 1,
                             "text": "def f():"}],
                   "truncated": False}
    outline_py = {"ok": True, "path": "a.py", "language": "python",
                  "nodes": [
                      {"kind": "class", "name": "C", "line": 1,
                       "end": 9},
                      {"kind": "function", "name": "C.m",
                       "line": 2, "args": ["self"]}],
                  "total": 2}
    outline_md = {"ok": True, "path": "r.md", "language": "markdown",
                  "nodes": [{"name": "Title", "line": 1, "level": 1}],
                  "total": 1}
    edit_result = {"ok": True, "path": "a.py", "matched": "x",
                   "replacements": 1, "ranges": [[1, 1]]}
    multi_result = {"ok": True, "path": "a.py", "edits": 2,
                    "summaries": [{"index": 0, "replacements": 1},
                                  {"index": 1, "replacements": 1}]}
    write_result = {"ok": True, "path": "n.txt", "created": True,
                    "lines": 2}
    patch_result = {"ok": True, "files": [
        {"path": "a.py", "op": "update", "hunks": 1}]}
    search_result = {"ok": True, "query": "q", "results": [
        {"title": "T", "url": "https://a.org", "summary": "s",
         "date": "2026-01-01", "source_provider": "brave"}],
        "fallback_provider": "rsearch",
        "fallback_source": "brave"}
    fetch_result = {"ok": True, "url": "https://a.org",
                    "content": "# Hi\n\nok"}
    converge_result = {"ok": True, "topic": "t", "conclusion": "yes",
                       "confidence": 0.91, "iterations": 2,
                       "evidence_count": 3,
                       "supporting_evidence": [
                           {"text": "e1", "reliability": 0.9}],
                       "counter_evidence": [],
                       "state_summary": {"claims": 1,
                                         "evidence_items": 3,
                                         "contradictions": 0},
                       "costs": {"total_usd": 0.001, "calls": 4}}
    scholar_result = {"ok": True, "query": "q", "results": [
        {"title": "P", "url": "https://arxiv.org/a",
         "summary": "s", "date": "2025",
         "authors": ["Ann", "Bo"], "citations": 12,
         "source_provider": "arxiv"}]}
    repo_result = {"ok": True, "query": "q", "results": [
        {"path": "a.py", "line": 3, "snippet": "x = 1",
         "score": 0.8}], "indexed_files": 9}
    return [
        ("read", {"path": "a.py"}, read_result, T.ReadCard, "ok",
         "2 lines"),
        ("grep", {"pattern": "f("}, grep_result, T.GrepCard, "ok",
         "1 hit"),
        ("outline", {"path": "a.py"}, outline_py, T.OutlineCard,
         "ok", "2 symbol"),
        ("outline", {"path": "r.md"}, outline_md, T.OutlineCard,
         "ok", "markdown"),
        ("edit", {"path": "a.py", "old_string": "x",
                  "new_string": "y"}, edit_result, T.EditCard, "ok",
         "1 replacement"),
        ("multi_edit", {"path": "a.py", "edits": [
            {"old_string": "a", "new_string": "b"},
            {"old_string": "c", "new_string": "d"}]},
         multi_result, T.MultiEditCard, "ok", "2/2"),
        ("write_file", {"path": "n.txt", "content": "a\nb"},
         write_result, T.WriteCard, "ok", "created"),
        ("apply_patch", {"patch_text": "*** Begin Patch\n"},
         patch_result, T.PatchCard, "ok", "1 hunk"),
        ("search", {"query": "q"}, search_result, T.SearchCard,
         "ok", "1 result"),
        ("search", {"query": "q"},
         dict(search_result, fallback_provider="searxng"),
         T.SearchCard, "ok", "1 result"),
        ("fetch", {"url": "https://a.org"}, fetch_result,
         T.FetchCard, "ok", "DeepSeek Fetch"),
        ("fetch", {"url": "https://a.org"},
         dict(fetch_result, fallback_provider="jina"),
         T.FetchCard, "ok", "Jina"),
        ("fetch", {"url": "https://a.org"},
         {"ok": True, "url": "https://a.org", "content": "  "},
         T.FetchCard,
         "ok", "empty page"),
        ("iterative_evidence_convergence", {"topic": "t"},
         converge_result, T.ConvergeCard, "ok", "0.91"),
        ("converge_on_claim", {"topic": "t"}, converge_result,
         T.ConvergeCard, "ok", "0.91"),
        ("deep_research", {"topic": "t"},
         {"ok": True, "topic": "t", "confidence": 0.72,
          "claims": [{"text": "c1", "sources": [1],
                      "confidence": "high"}],
          "sources": [], "unknowns": [], "report": "# R",
          "stats": {"claims": 1, "fetched": 2}},
         T.DeepResearchCard, "ok", "72%"),
        ("scholar", {"query": "q"}, scholar_result, T.ScholarCard,
         "ok", "1 paper"),
        ("repo_search", {"query": "q"}, repo_result, T.RepoCard,
         "ok", "1 hit"),
        ("bash", {"command": "echo hi"},
         {"ok": True, "exit_code": 0, "code": "ok", "stdout": "hi\n",
          "stderr": "", "duration_ms": 12, "cwd": ".",
          "truncated": False, "stdout_bytes": 3, "stderr_bytes": 0,
          "timed_out": False, "redactions": []},
         T.BashCard, "ok", "exit 0"),
        ("browse", {"task": "find the price",
                    "url": "https://a.org/"},
         {"ok": True, "task": "find the price", "answer": "42",
          "visited": ["https://a.org/"], "steps": 3,
          "headed": False},
         T.BrowseCard, "ok", "1 page(s)"),
        ("browse", {"task": "find the price", "headed": True},
         {"ok": False, "code": "browse_failed",
          "error": "no display"},
         T.BrowseCard, "failed", "browse_failed"),
        ("download", {"urls": ["https://a.org/a.bin",
                               "https://a.org/b.bin"],
                      "dest": "dl"},
         {"ok": True, "code": "ok", "dest": "dl",
          "files": [
              {"ok": True, "code": "ok",
               "url": "https://a.org/a.bin", "path": "dl/a.bin",
               "bytes": 12, "method": "stealthii"},
              {"ok": True, "code": "skipped",
               "url": "https://a.org/b.bin", "path": "dl/b.bin",
               "bytes": 7, "method": "direct",
               "note": "exists; pass overwrite=true to replace"}],
          "saved": 1, "skipped": 1, "failed": 0, "bytes": 19},
         T.DownloadCard, "ok", "1 saved"),
        ("download", {"urls": []},
         {"ok": False, "code": "bad_args",
          "error": "urls must be a non-empty list"},
         T.DownloadCard, "failed", "bad_args"),
        ("bash", {"command": "exit 1"},
         {"ok": False, "exit_code": 1, "code": "nonzero_exit",
          "stdout": "", "stderr": "boom", "duration_ms": 9, "cwd": ".",
          "truncated": False, "stdout_bytes": 0, "stderr_bytes": 4,
          "timed_out": False, "redactions": []},
         T.BashCard, "failed", "exit 1"),
        ("bash", {"command": "sleep 99", "timeout_ms": 1000},
         {"ok": False, "exit_code": -15, "code": "timed_out",
          "stdout": "part", "stderr": "", "duration_ms": 1000,
          "cwd": ".", "truncated": False, "stdout_bytes": 4,
          "stderr_bytes": 0, "timed_out": True, "redactions": [],
          "error": "timed out after 1000ms"},
         T.BashCard, "failed", "timed out"),
        ("bash", {"command": "pwd", "cwd": "/tmp"},
         {"ok": False, "code": "security",
          "error": "path escapes workspace root"},
         T.BashCard, "failed", "security"),
        ("write", {"path": "n.txt", "content": "x"}, write_result,
         T.WriteCard, "ok", "created"),
        ("nope", {}, {"ok": False, "code": "unknown_tool",
                      "error": "unknown tool 'nope'"},
         T.GenericCard, "failed", "unknown_tool"),
        ("read", {"path": "missing.txt"},
         {"ok": False, "code": "io", "error": "no such file"},
         T.ReadCard, "failed", "io"),
        ("edit", {"path": "a.py", "old_string": "x",
                  "new_string": "y"},
         {"ok": False, "code": "no_match",
          "error": "not found",
          "suggestions": [{"lines": [1, 1]}]},
         T.EditCard, "failed", "no_match"),
    ]


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestCardMatrix(unittest.IsolatedAsyncioTestCase):
    async def test_every_card_renders(self):
        async with booted_app() as (app, pilot):
            for index, (name, args, result, cls, status,
                        summary_bit) in enumerate(_card_cases()):
                with self.subTest(tool=name, status=status):
                    seq = 100 + index
                    app.post_message(UIEvent(
                        "tool_start",
                        {"seq": seq, "name": name, "args": args}))
                    await pilot.pause()
                    card = app._cards.get(seq)
                    self.assertIsInstance(card, cls)
                    self.assertEqual(card.status, "running")
                    app.post_message(UIEvent(
                        "tool_done",
                        {"seq": seq, "name": name, "args": args,
                         "result": result, "elapsed_ms": 3.0,
                         "cost_usd": 0.0}))
                    await pilot.pause()
                    self.assertEqual(card.status, status)
                    self.assertIn(summary_bit, card.summary)

    async def test_fetch_card_live_while_running(self):
        async with booted_app() as (app, pilot):
            app.post_message(UIEvent(
                "tool_start",
                {"seq": 77, "name": "fetch",
                 "args": {"url": "https://example.org/slow"}}))
            await pilot.pause()
            await asyncio.sleep(0.25)
            await pilot.pause()
            card = app._cards[77]
            self.assertEqual(card.status, "running")
            self.assertGreaterEqual(len(card.body.children), 3)

            def body_text():
                parts = []
                for child in card.body.children:
                    try:
                        parts.append(str(child.render()))
                    except Exception:
                        parts.append("")
                return " ".join(parts)

            first = body_text()
            self.assertIn("https://example.org/slow", first)
            self.assertIn("awaiting response", first)
            await asyncio.sleep(0.25)
            await pilot.pause()
            self.assertNotEqual(first, body_text())
            app.post_message(UIEvent(
                "tool_done",
                {"seq": 77, "name": "fetch",
                 "args": {"url": "https://example.org/slow"},
                 "result": {"ok": True,
                            "url": "https://example.org/slow",
                            "content": "# Page\nhello fetch"},
                 "elapsed_ms": 5.0, "cost_usd": 0.0}))
            await pilot.pause()
            self.assertEqual(card.status, "ok")
            self.assertNotIn("awaiting response", body_text())

    async def test_bash_card_streams_live(self):
        async with booted_app() as (app, pilot):
            app.post_message(UIEvent(
                "tool_start",
                {"seq": 78, "name": "bash",
                 "args": {"command": "echo hi"}}))
            await pilot.pause()
            card = app._cards[78]
            self.assertIsInstance(card, T.BashCard)
            self.assertEqual(card.status, "running")
            app.post_message(UIEvent(
                "bash_chunk",
                {"seq": 78, "stream": "stdout", "text": "hel"}))
            app.post_message(UIEvent(
                "bash_chunk",
                {"seq": 78, "stream": "stdout", "text": "lo\n"}))
            await pilot.pause()
            self.assertEqual(card._live_text, "hello\n")
            self.assertIn("hello", str(card._live_row.render()))
            app.post_message(UIEvent(
                "tool_done",
                {"seq": 78, "name": "bash",
                 "args": {"command": "echo hi"},
                 "result": {"ok": True, "exit_code": 0, "code": "ok",
                            "stdout": "hello\n", "stderr": "",
                            "duration_ms": 4, "cwd": ".",
                            "truncated": False, "stdout_bytes": 6,
                            "stderr_bytes": 0, "timed_out": False,
                            "redactions": []},
                 "elapsed_ms": 4.0, "cost_usd": 0.0}))
            await pilot.pause()
            self.assertEqual(card.status, "ok")
            self.assertIn("exit 0", card.summary)

    async def test_bracket_payload_renders_literally(self):
        stdout = ('{"common_name":"leeuw008.nl",'
                  '"name_value":"*.leeuw008.nl\\\\nleeuw008.nl",'
                  '"id":29884906865,'
                  '"issuer":"[=Google Trust Services, CN=WE1",'
                  '"serial":"18fda3a3176097670eaa84ecd8123dc6"}\n'
                  '[notice] [=Google Trust Services, CN=WE1]\n')
        args = {"command": "curl https://crt.sh/?q=leeuw008.nl"}
        result = {"ok": True, "exit_code": 0, "code": "ok",
                  "stdout": stdout, "stderr": "", "duration_ms": 9,
                  "cwd": ".", "truncated": False,
                  "stdout_bytes": len(stdout), "stderr_bytes": 0,
                  "timed_out": False, "redactions": []}
        async with booted_app() as (app, pilot):
            app.post_message(UIEvent(
                "tool_start",
                {"seq": 82, "name": "bash", "args": args}))
            app.post_message(UIEvent(
                "tool_done",
                {"seq": 82, "name": "bash", "args": args,
                 "result": result, "elapsed_ms": 9.0,
                 "cost_usd": 0.0}))
            await pilot.pause()
            await asyncio.sleep(0.5)
            await pilot.pause()
            card = app._cards[82]
            self.assertIsInstance(card, T.BashCard)
            self.assertEqual(card.status, "ok")
            texts = [str(child.render()) for child in
                     card.body.children]
            self.assertTrue(any("leeuw008.nl" in text
                                for text in texts))
            self.assertTrue(any("[notice]" in text
                                for text in texts))

    async def test_bash_chunk_without_card_is_ignored(self):
        async with booted_app() as (app, pilot):
            app.post_message(UIEvent(
                "bash_chunk",
                {"seq": 999, "stream": "stdout", "text": "x"}))
            await pilot.pause()

    async def test_download_card_lands_files_live(self):
        async with booted_app() as (app, pilot):
            args = {"urls": ["https://a.org/a.bin",
                             "https://a.org/b.bin"],
                    "dest": "dl"}
            app.post_message(UIEvent(
                "tool_start",
                {"seq": 81, "name": "download", "args": args}))
            await pilot.pause()
            card = app._cards[81]
            self.assertIsInstance(card, T.DownloadCard)
            self.assertEqual(card.status, "running")
            app.post_message(UIEvent(
                "download_file",
                {"seq": 81, "url": "https://a.org/a.bin",
                 "row": {"ok": True, "code": "ok",
                         "url": "https://a.org/a.bin",
                         "path": "dl/a.bin", "bytes": 12,
                         "method": "stealthii"}}))
            await pilot.pause()
            texts = [str(child.render()) for child in
                     card.body.children]
            self.assertTrue(any("a.bin" in text and "12B" in text
                                for text in texts))
            app.post_message(UIEvent(
                "tool_done",
                {"seq": 81, "name": "download", "args": args,
                 "result": {"ok": True, "code": "ok", "dest": "dl",
                            "files": [
                                {"ok": True, "code": "ok",
                                 "url": "https://a.org/a.bin",
                                 "path": "dl/a.bin", "bytes": 12,
                                 "method": "stealthii"}],
                            "saved": 1, "skipped": 0, "failed": 0,
                            "bytes": 12},
                 "elapsed_ms": 6.0, "cost_usd": 0.0}))
            await pilot.pause()
            self.assertEqual(card.status, "ok")
            self.assertIn("1 saved", card.summary)

    async def test_converge_live_queries(self):
        async with booted_app() as (app, pilot):
            app.post_message(UIEvent(
                "tool_start",
                {"seq": 5, "name": "iterative_evidence_convergence",
                 "args": {"topic": "t", "max_iterations": 3}}))
            await pilot.pause()
            card = app._cards[5]
            self.assertIsInstance(card, T.ConvergeCard)
            app.post_message(UIEvent(
                "converge_query",
                {"seq": 5, "query": "q1", "count": 5,
                 "results": 4}))
            app.post_message(UIEvent(
                "converge_extract",
                {"seq": 5, "fresh": 2, "claims": 1}))
            await pilot.pause()
            self.assertEqual(card._queries, 1)
            self.assertEqual(card._extracts, 1)
            self.assertIn("1 queries", card.summary)

    async def test_deep_research_live_events(self):
        async with booted_app() as (app, pilot):
            app.post_message(UIEvent(
                "tool_start",
                {"seq": 7, "name": "deep_research",
                 "args": {"topic": "t"}}))
            await pilot.pause()
            card = app._cards[7]
            self.assertIsInstance(card, T.DeepResearchCard)
            app.post_message(UIEvent(
                "research_plan",
                {"seq": 7, "topic": "t", "queries": ["t", "t data"]}))
            app.post_message(UIEvent(
                "research_query",
                {"seq": 7, "query": "t", "results": 4}))
            app.post_message(UIEvent(
                "research_ranked",
                {"seq": 7, "dropped": 1, "sources": [
                    {"n": 1, "title": "S", "url": "https://a.org",
                     "domain": "a.org", "tier": 2, "score": 3.5}]}))
            app.post_message(UIEvent(
                "research_fetch",
                {"seq": 7, "n": 1, "url": "https://a.org",
                 "domain": "a.org", "ok": True, "method": "jina",
                 "chars": 900, "claims": 2,
                 "attempts": [{"method": "provider", "ok": False},
                              {"method": "jina", "ok": True}]}))
            app.post_message(UIEvent(
                "research_synth",
                {"seq": 7, "claims": 2, "confidence": 0.7}))
            await pilot.pause()
            self.assertEqual(card._n_queries, 1)
            self.assertEqual(card._n_fetched, 1)
            self.assertEqual(card._stage, 3)
            self.assertIn("writing report", card.summary)

    async def test_deep_research_attempt_is_live(self):
        async with booted_app() as (app, pilot):
            app.post_message(UIEvent(
                "tool_start",
                {"seq": 8, "name": "deep_research",
                 "args": {"topic": "t"}}))
            await pilot.pause()
            card = app._cards[8]
            self.assertIn("planning subqueries",
                          str(card._plan_hint.render()))
            app.post_message(UIEvent(
                "research_plan",
                {"seq": 8, "topic": "t", "queries": ["t"]}))
            app.post_message(UIEvent(
                "research_ranked",
                {"seq": 8, "dropped": 0, "sources": [
                    {"n": 1, "title": "S", "url": "https://a.org",
                     "domain": "a.org", "tier": 2, "score": 3.5}]}))
            app.post_message(UIEvent(
                "research_fetch_attempt",
                {"seq": 8, "n": 1, "url": "https://a.org",
                 "method": "jina", "state": "start"}))
            await pilot.pause()
            row = card._source_rows[1]
            self.assertIn("fetching via jina", str(row.render()))
            self.assertIn(1, card._inflight)
            app.post_message(UIEvent(
                "research_fetch_attempt",
                {"seq": 8, "n": 1, "url": "https://a.org",
                 "method": "jina", "state": "done", "ok": False,
                 "error": "jina timeout after 60s"}))
            await pilot.pause()
            self.assertIn("trying next", str(row.render()))

    async def test_ui_event_failure_is_visible(self):
        async with booted_app() as (app, pilot):
            def boom(payload):
                raise RuntimeError("kaboom")

            app._ev_research_plan = boom
            app.post_message(UIEvent(
                "research_plan", {"seq": 1, "queries": []}))
            await pilot.pause()
            texts = [str(w.render())
                     for w in app.query_one("#transcript").children]
            self.assertTrue(any("ui event research_plan failed"
                                in t for t in texts), texts)

    async def test_read_more_button(self):
        lines = ["%d:hh|line %d" % (i, i) for i in range(1, 71)]
        result = {"ok": True, "path": "big.py", "offset": 1,
                  "shown": 70, "total_lines": 70, "lines": lines,
                  "truncated": False}
        async with booted_app() as (app, pilot):
            app.post_message(UIEvent(
                "tool_start",
                {"seq": 9, "name": "read",
                 "args": {"path": "big.py"}}))
            app.post_message(UIEvent(
                "tool_done",
                {"seq": 9, "name": "read", "args": {"path": "big.py"},
                 "result": result, "elapsed_ms": 1.0,
                 "cost_usd": 0.0}))
            card = None
            buttons = []
            for _ in range(100):
                await pilot.pause(0.2)
                card = app._cards.get(9)
                if card is None:
                    continue
                buttons = [b for b in card.query("Button")
                           if (b.id or "").startswith("more-")]
                if len(buttons) == 1:
                    break
            self.assertEqual(len(buttons), 1)
            app.query_one("#more-9").scroll_visible()
            await pilot.pause(0.5)
            before = len(list(card.body.children))
            await pilot.click("#more-9")
            await pilot.pause()
            after = len(list(card.body.children))
            self.assertGreater(after, before)


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestTurn(unittest.IsolatedAsyncioTestCase):
    async def test_echo_turn(self):
        async with booted_app() as (app, pilot):
            app.post_message(SubmitPrompt("hello", []))
            await pilot.pause(1.5)
            users = list(app.query("UserBubble"))
            bots = list(app.query("AssistantBubble"))
            self.assertEqual(len(users), 1)
            self.assertEqual(users[0]._text, "hello")
            self.assertEqual(len(bots), 1)
            self.assertEqual(bots[0]._full, "echo: hello")
            self.assertIn("done", app.query_one("#status").text)
            box = app.query_one("#prompt", PromptBox)
            self.assertEqual(box.prompt_history, ["hello"])

    async def test_busy_rejects_second_turn(self):
        async with booted_app() as (app, pilot):
            app._busy = True
            app.post_message(SubmitPrompt("hello", []))
            await pilot.pause()
            self.assertEqual(list(app.query("UserBubble")), [])

    async def test_prompt_keys(self):
        async with booted_app() as (app, pilot):
            box = app.query_one("#prompt", PromptBox)
            box.focus()
            await pilot.pause()
            await pilot.press(*"ab")
            await pilot.press("shift+tab")
            self.assertEqual(box.text, "ab\n")
            await pilot.press("enter")
            await pilot.pause(1.5)
            users = list(app.query("UserBubble"))
            self.assertEqual(len(users), 1)
            self.assertEqual(users[0]._text, "ab")
            await pilot.press(*"xy")
            await pilot.press("enter")
            await pilot.pause(1.5)
            box.focus()
            await pilot.pause()
            await pilot.press("up")
            self.assertEqual(box.text, "xy")
            await pilot.press("up")
            self.assertEqual(box.text, "ab")
            await pilot.press("down")
            self.assertEqual(box.text, "xy")


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestFileToolFlow(unittest.IsolatedAsyncioTestCase):
    async def test_write_read_edit_grep_outline_patch(self):
        with tempfile.TemporaryDirectory() as tmp:
            async with booted_app(tools_root=tmp) as (app, pilot):
                app._approval_mode = "auto"
                app._tool_worker(
                    "write_file",
                    {"path": "calc.py",
                     "content": "def f():\n    return 1\n"})
                card = await wait_card(app, 1)
                self.assertEqual(card.status, "ok")
                app._tool_worker("read", {"path": "calc.py"})
                card = await wait_card(app, 2)
                self.assertEqual(card.status, "ok")
                self.assertIn("2 lines", card.summary)
                app._tool_worker(
                    "edit", {"path": "calc.py",
                             "old_string": "    return 1",
                             "new_string": "    return 2"})
                card = await wait_card(app, 3)
                self.assertEqual(card.status, "ok")
                app._tool_worker(
                    "multi_edit",
                    {"path": "calc.py",
                     "edits": [{"old_string": "def f():",
                                "new_string": "def g():"},
                               {"old_string": "    return 2",
                                "new_string": "    return 3"}]})
                card = await wait_card(app, 4)
                self.assertEqual(card.status, "ok")
                self.assertIn("2/2", card.summary)
                app._tool_worker("grep", {"pattern": "return",
                                          "path": "."})
                card = await wait_card(app, 5)
                self.assertEqual(card.status, "ok")
                app._tool_worker("outline", {"path": "calc.py"})
                card = await wait_card(app, 6)
                self.assertEqual(card.status, "ok")
                patch = ("*** Begin Patch\n"
                         "*** Update File: calc.py\n"
                         "@@\n"
                         " def g():\n"
                         "-    return 3\n"
                         "+    return 4\n"
                         "*** End Patch\n")
                app._tool_worker("apply_patch",
                                 {"patch_text": patch})
                card = await wait_card(app, 7)
                self.assertEqual(card.status, "ok")
                with open(os.path.join(tmp, "calc.py"),
                          encoding="utf-8") as fh:
                    self.assertIn("return 4", fh.read())
                await pilot.pause()
                from blackcat.tui.chrome import LeftRail
                rail = app.query_one("#left-rail", LeftRail)
                self.assertIn("calc.py", rail.touched)

    async def test_tool_done_before_mount_settles(self):
        async with booted_app() as (app, pilot):
            app._ev_tool_start({"seq": 1, "name": "outline",
                                "args": {"path": "calc.py"}})
            app._ev_tool_done({"seq": 1, "name": "outline",
                               "args": {"path": "calc.py"},
                               "result": {"ok": True, "nodes": [],
                                          "language": "python"},
                               "elapsed_ms": 1.0, "cost_usd": 0.0})
            card = await wait_card(app, 1)
            self.assertEqual(card.status, "ok")
            self.assertIn("0 symbol(s)", card.summary)


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestApproval(unittest.IsolatedAsyncioTestCase):
    async def _run_write(self, pilot, app, choice):
        task = asyncio.ensure_future(
            app._bot.run_tool("write_file", path="n.txt",
                              content="hi"))
        for _ in range(200):
            card = app._cards.get(1)
            if card is not None and card.status == "confirming":
                break
            await asyncio.sleep(0.05)
        else:
            raise AssertionError("no approval card appeared")
        box = app.query_one("#prompt", PromptBox)
        self.assertTrue(box.disabled)
        await pilot.press(choice)
        return await asyncio.wait_for(task, 10.0)

    async def test_approve_writes_file(self):
        with tempfile.TemporaryDirectory() as tmp:
            async with booted_app(tools_root=tmp) as (app, pilot):
                result = await self._run_write(pilot, app, "y")
                self.assertTrue(result["ok"])
                await pilot.pause()
                self.assertTrue(os.path.exists(
                    os.path.join(tmp, "n.txt")))
                self.assertEqual(app._cards[1].status, "ok")
                box = app.query_one("#prompt", PromptBox)
                self.assertFalse(box.disabled)

    async def test_deny_writes_nothing(self):
        with tempfile.TemporaryDirectory() as tmp:
            async with booted_app(tools_root=tmp) as (app, pilot):
                result = await self._run_write(pilot, app, "n")
                self.assertFalse(result["ok"])
                self.assertEqual(result["code"], "rejected")
                self.assertFalse(os.path.exists(
                    os.path.join(tmp, "n.txt")))

    async def test_always_flips_mode(self):
        with tempfile.TemporaryDirectory() as tmp:
            async with booted_app(tools_root=tmp) as (app, pilot):
                result = await self._run_write(pilot, app, "a")
                self.assertTrue(result["ok"])
                await pilot.pause()
                self.assertEqual(app._approval_mode, "auto")


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestInitialPrompt(unittest.IsolatedAsyncioTestCase):
    async def test_initial_prompt_runs_first_turn(self):
        app = BlackCatApp(bot_kwargs=_echo_kwargs(),
                          initial_prompt="hello tui")
        async with app.run_test(size=(120, 40)) as pilot:
            await pilot.press("escape")
            for _ in range(200):
                if len(app._bot.messages) >= 2 and not app._busy:
                    break
                await asyncio.sleep(0.05)
            self.assertEqual(app._bot.messages[0]["content"],
                             "hello tui")
            self.assertEqual(app._bot.messages[1]["content"],
                             "echo: hello tui")

    async def test_initial_prompt_exits_when_turn_done(self):
        app = BlackCatApp(bot_kwargs=_echo_kwargs(),
                          initial_prompt="hello tui")
        async with app.run_test(size=(120, 40)) as pilot:
            await pilot.press("escape")
            for _ in range(300):
                if not app.is_running:
                    break
                await asyncio.sleep(0.05)
            self.assertFalse(app.is_running)
            self.assertEqual(app._bot.messages[1]["content"],
                             "echo: hello tui")

    async def test_no_initial_prompt_stays_open(self):
        async with booted_app() as (app, pilot):
            app.post_message(SubmitPrompt("hi", []))
            for _ in range(200):
                if len(app._bot.messages) >= 2 and not app._busy:
                    break
                await asyncio.sleep(0.05)
            await asyncio.sleep(0.3)
            await pilot.pause()
            self.assertTrue(app.is_running)


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestRunTuiWiring(unittest.TestCase):
    def test_run_tui_silences_streams_and_passes_prompt(self):
        import logging
        from unittest import mock as _mock

        from blackcat.tui import run_tui
        logger = logging.getLogger("blackcat")
        handler = logging.StreamHandler()
        logger.addHandler(handler)
        captured = {}

        class _FakeApp:
            def __init__(self, bot_kwargs=None, initial_prompt=None):
                captured["bot_kwargs"] = bot_kwargs
                captured["initial_prompt"] = initial_prompt

            def run(self):
                captured["ran"] = True

        try:
            with _mock.patch("blackcat.tui.app.BlackCatApp", _FakeApp):
                code = run_tui(provider="echo",
                               initial_prompt="do the thing")
        finally:
            if handler in logger.handlers:
                logger.removeHandler(handler)
        self.assertEqual(code, 0)
        self.assertTrue(captured["ran"])
        self.assertEqual(captured["initial_prompt"], "do the thing")
        streams = [h for h in logger.handlers
                   if isinstance(h, logging.StreamHandler)
                   and not isinstance(h, logging.FileHandler)]
        self.assertEqual(streams, [])


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestYoloTui(unittest.IsolatedAsyncioTestCase):
    async def test_yolo_write_needs_no_approval(self):
        with tempfile.TemporaryDirectory() as tmp:
            async with booted_app(tools_root=tmp, yolo=True) as (app, pilot):
                self.assertTrue(app._bot.yolo)
                self.assertEqual(app._approval_mode, "auto")
                result = await asyncio.wait_for(asyncio.ensure_future(
                    app._bot.run_tool("write_file", path="n.txt",
                                      content="hi")), 10.0)
                self.assertTrue(result["ok"])
                self.assertTrue(os.path.exists(
                    os.path.join(tmp, "n.txt")))
                card = await wait_card(app, 1)
                self.assertEqual(card.status, "ok")


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestChrome(unittest.IsolatedAsyncioTestCase):
    async def test_tab_keys(self):
        async with booted_app() as (app, pilot):
            await pilot.press("escape")
            await pilot.press("d")
            await pilot.pause()
            from textual.widgets import TabbedContent
            tabs = app.query_one("#right-panel", TabbedContent)
            self.assertEqual(tabs.active, app._tab_ids["Diff"])
            await pilot.press("c")
            await pilot.pause()
            self.assertEqual(tabs.active, app._tab_ids["Costs"])

    async def test_theme_and_ascii(self):
        async with booted_app() as (app, pilot):
            self.assertEqual(app.theme, "alley-cat")
            await pilot.press("escape")
            await pilot.press("t")
            await pilot.pause()
            self.assertEqual(app.theme, "milk-bowl")
            try:
                app.action_toggle_ascii()
                self.assertTrue(T.GlyphSet.ascii_mode)
                self.assertEqual(T.glyph("ok"), "[ok]")
            finally:
                app.action_toggle_ascii()
                self.assertFalse(T.GlyphSet.ascii_mode)

    async def test_slash_commands(self):
        async with booted_app() as (app, pilot):
            app.post_message(SubmitPrompt("/costs", []))
            await pilot.pause()
            from textual.widgets import TabbedContent
            tabs = app.query_one("#right-panel", TabbedContent)
            self.assertEqual(tabs.active, app._tab_ids["Costs"])
            app.post_message(SubmitPrompt("/scholar black holes",
                                          []))
            await pilot.pause(1.5)
            scholars = [c for c in app._cards.values()
                        if isinstance(c, T.ScholarCard)]
            self.assertEqual(len(scholars), 1)
            self.assertEqual(scholars[0].status, "ok")
            app.post_message(SubmitPrompt("/nope", []))
            await pilot.pause()

    async def test_new_session_resets(self):
        async with booted_app() as (app, pilot):
            app.post_message(SubmitPrompt("hello", []))
            await pilot.pause(1.5)
            self.assertTrue(list(app.query("UserBubble")))
            from blackcat.tui.chrome import NewSession
            app.post_message(NewSession())
            await pilot.pause()
            self.assertEqual(list(app.query("UserBubble")), [])
            self.assertEqual(list(app.query("AssistantBubble")), [])

    async def test_attach_flow(self):
        async with booted_app() as (app, pilot):
            app.action_attach()
            await pilot.pause()
            await pilot.press(*"/tmp/x.png")
            await pilot.press("enter")
            await pilot.pause()
            pending = app.query_one("#pending", PendingImages)
            self.assertEqual(pending.paths, ["/tmp/x.png"])

    async def test_palette_commands(self):
        async with booted_app() as (app, pilot):
            provider = BlackCatCommands(app.screen)
            hits = [hit async for hit in provider.search("theme")]
            self.assertTrue(hits)
            for hit in hits:
                if "theme" in str(hit.match_display):
                    hit.command()
                    break
            await pilot.pause()
            self.assertEqual(app.theme, "milk-bowl")
            hits = [hit async for hit in
                    provider.search("no-such-command-xyz")]
            self.assertEqual(hits, [])

    async def test_mascot_moods(self):
        async with booted_app() as (app, pilot):
            from blackcat.tui.chrome import HeaderBar
            mascot = app.query_one(HeaderBar).mascot
            mascot.set_mood("error")
            await pilot.pause()
            self.assertIn("✖", str(mascot.render()))
            mascot.set_mood("idle")
            await pilot.pause()
            self.assertNotIn("✖", str(mascot.render()))


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestRenderContract(unittest.TestCase):
    def test_pure_helpers_need_no_app(self):
        self.assertTrue(RenderContract.is_blank("   "))
        self.assertTrue(RenderContract.is_blank(None))
        self.assertFalse(RenderContract.is_blank("x"))
        self.assertEqual(RenderContract.header_violations(None),
                         ["missing header"])
        self.assertEqual(RenderContract.body_violations(None),
                         ["missing body"])

    def test_bubble_contract_without_widgets(self):
        self.assertEqual(RenderContract.check_bubble(
            SimpleNamespace(_full="")), ["empty reply"])
        self.assertEqual(RenderContract.check_bubble(
            SimpleNamespace(_full="hi")), [])

    def test_status_row_classes(self):
        self.assertTrue(RenderContract.is_fallback(
            SimpleNamespace(has_class=lambda
                            name: name == "quality-fallback")))
        self.assertFalse(RenderContract.is_fallback(
            SimpleNamespace(has_class=lambda name: False)))


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestCardSeal(unittest.IsolatedAsyncioTestCase):
    async def test_mount_crash_still_renders(self):
        from blackcat.tui.chrome import Transcript
        async with booted_app() as (app, pilot):
            transcript = app.query_one(Transcript)
            mounted = []
            for name in T.CardFactory.known_tools():
                card = T.make_card(name, 1, {})

                def _boom() -> None:
                    raise RuntimeError("build blew up")

                card.build_running = _boom
                transcript.mount(card)
                mounted.append(card)
            await pilot.pause()
            await pilot.wait_for_scheduled_animations()
            await pilot.pause()
            for card in mounted:
                with self.subTest(tool=card.tool_name):
                    self.assertEqual(
                        RenderContract.check_card(card), [])

    async def test_running_cards_never_empty(self):
        args = {"read": {"path": "a.py"},
                "grep": {"pattern": "x", "path": "."},
                "outline": {"path": "a.py"},
                "edit": {"path": "a.py", "old_string": "x",
                         "new_string": "y"},
                "multi_edit": {"path": "a.py", "edits": [
                    {"old_string": "a", "new_string": "b"}]},
                "write_file": {"path": "n.txt", "content": "hi"},
                "write": {"path": "n.txt", "content": "hi"},
                "apply_patch": {"patch_text": "*** Begin Patch\n"},
                "search": {"query": "q"},
                "fetch": {"url": "https://example.org/slow"},
                "iterative_evidence_convergence": {"topic": "t"},
                "converge_on_claim": {"topic": "t"},
                "deep_research": {"topic": "t"},
                "scholar": {"query": "q"},
                "repo_search": {"query": "q"},
                "bash": {"command": "echo hi"}}
        async with booted_app() as (app, pilot):
            for seq, name in enumerate(T.CardFactory.known_tools(),
                                       start=1):
                app.post_message(UIEvent(
                    "tool_start",
                    {"seq": seq, "name": name,
                     "args": args.get(name, {})}))
            await pilot.pause()
            for seq, name in enumerate(T.CardFactory.known_tools(),
                                       start=1):
                with self.subTest(tool=name):
                    card = app._cards[seq]
                    self.assertEqual(
                        RenderContract.header_violations(
                            card.header), [])
                    self.assertEqual(
                        RenderContract.body_violations(
                            card.body), [])
                    self.assertEqual(card.seal(), [])

    async def test_done_empty_results_stay_explicit(self):
        cases = [
            ("grep", {"pattern": "x", "path": "."},
             {"ok": True, "hits": [], "backend": "rg"}),
            ("search", {"query": "q"},
             {"ok": True, "query": "q", "results": []}),
            ("fetch", {"url": "https://a.org"},
             {"ok": True, "url": "https://a.org",
              "content": "  "}),
            ("repo_search", {"query": "q"},
             {"ok": True, "query": "q", "results": [],
              "indexed_files": 0}),
            ("read", {"path": "missing.txt"},
             {"ok": False, "code": "io", "error": "nope"}),
        ]
        async with booted_app() as (app, pilot):
            for seq, (name, tool_args, _result) in enumerate(
                    cases, start=1):
                app.post_message(UIEvent(
                    "tool_start",
                    {"seq": seq, "name": name, "args": tool_args}))
            await pilot.pause()
            for seq, (name, tool_args,
                      result) in enumerate(cases, start=1):
                app.post_message(UIEvent(
                    "tool_done",
                    {"seq": seq, "name": name, "args": tool_args,
                     "result": result, "elapsed_ms": 3.0,
                     "cost_usd": 0.0}))
            for seq, (name, _a, _r) in enumerate(cases, start=1):
                with self.subTest(tool=name):
                    card = await wait_card(app, seq)
                    await asyncio.sleep(0.35)
                    await pilot.pause()
                    self.assertEqual(
                        RenderContract.check_card(card), [])
                    leftovers = [
                        c for c in card.body.children
                        if c.has_class("quality-fallback")
                        and c.display]
                    self.assertEqual(leftovers, [])

    async def test_effect_chips_leave_no_trace(self):
        async with booted_app() as (app, pilot):
            mid = app.query_one("#middle").region.height
            app._rain("+$0.0001")
            await pilot.pause()
            self.assertEqual(
                app.query_one("#middle").region.height, mid)
            await asyncio.sleep(1.6)
            await pilot.pause()
            leftovers = [c for c in app.screen.children
                         if type(c).__name__ == "Label"]
            self.assertEqual(leftovers, [])
            self.assertEqual(
                app.query_one("#middle").region.height, mid)

    async def test_confetti_leaves_no_trace(self):
        async with booted_app() as (app, pilot):
            mid = app.query_one("#middle").region.height
            app._confetti()
            await pilot.pause()
            bits = [c for c in app.screen.children
                    if type(c).__name__ == "Label"]
            self.assertEqual(len(bits), 24)
            self.assertEqual(
                app.query_one("#middle").region.height, mid)
            await asyncio.sleep(2.8)
            await pilot.pause()
            leftovers = [c for c in app.screen.children
                         if type(c).__name__ == "Label"]
            self.assertEqual(leftovers, [])
            self.assertEqual(
                app.query_one("#middle").region.height, mid)

    async def test_prompt_row_static_across_collapse(self):
        async with booted_app() as (app, pilot):
            for seq in range(1, 13):
                app.post_message(UIEvent(
                    "tool_start",
                    {"seq": seq, "name": "fetch",
                     "args": {"url": "https://example.org/%d"
                              % seq}}))
            await pilot.pause()
            await asyncio.sleep(0.5)
            await pilot.pause()
            prompt = app.query_one("#prompt-row")
            y_before = prompt.region.y
            mid_before = app.query_one("#middle").region.height
            for seq in range(1, 13):
                app.post_message(UIEvent(
                    "tool_done",
                    {"seq": seq, "name": "fetch",
                     "args": {"url": "https://example.org/%d"
                              % seq},
                     "result": {
                         "ok": True,
                         "url": "https://example.org/%d" % seq,
                         "content": "# T\ntext"},
                     "elapsed_ms": 5.0, "cost_usd": 0.0}))
            await pilot.pause()
            await asyncio.sleep(0.6)
            await pilot.pause()
            self.assertEqual(
                app.query_one("#prompt-row").region.y, y_before)
            self.assertEqual(
                app.query_one("#middle").region.height, mid_before)

    async def test_watchdog_repairs_blanked_card(self):
        async with booted_app() as (app, pilot):
            app.post_message(UIEvent(
                "tool_start",
                {"seq": 1, "name": "grep",
                 "args": {"pattern": "x", "path": "."}}))
            await pilot.pause()
            card = app._cards[1]
            card.header.update("")
            card.status_row.display = False
            self.assertEqual(
                RenderContract.check_card(card),
                ["empty header", "empty body"])
            app._audit_cards()
            self.assertEqual(RenderContract.check_card(card), [])
            self.assertNotEqual(
                str(card.header.render()).strip(), "")

    @staticmethod
    def painted_words(path):
        texts = []
        svg = Path(path).read_text()
        for chunk in re.findall(r"<text\b.*?</text>", svg, re.S):
            words = html.unescape(
                re.sub(r"<[^>]+>", "", chunk)).replace(" ", " ")
            words = " ".join(words.split())
            if words:
                texts.append(words)
        return "\n".join(texts)


@unittest.skipUnless(HAS_TEXTUAL, "tui extra unavailable")
class TestPaintContract(unittest.IsolatedAsyncioTestCase):
    async def test_cards_paint_their_headers(self):
        kinds = {
            "read": {"path": "a.py"},
            "grep": {"pattern": "x", "path": "."},
            "search": {"query": "q"},
            "fetch": {"url": "https://example.org/slow"},
        }
        async with booted_app() as (app, pilot):
            seq = 0
            for _round in range(3):
                for name, args in kinds.items():
                    seq += 1
                    app.post_message(UIEvent(
                        "tool_start",
                        {"seq": seq, "name": name, "args": args}))
                await pilot.pause()
                for done in range(seq - 3, seq + 1):
                    name = list(kinds)[(done - 1) % 4]
                    app.post_message(UIEvent(
                        "tool_done",
                        {"seq": done, "name": name,
                         "args": kinds[name],
                         "result": {"ok": True},
                         "elapsed_ms": 3.0, "cost_usd": 0.0}))
                await pilot.pause()
            await pilot.wait_for_scheduled_animations()
            await pilot.pause()
            handle, shot = tempfile.mkstemp(suffix=".svg")
            try:
                os.close(handle)
                app.save_screenshot(shot)
                words = TestCardSeal.painted_words(shot)
            finally:
                os.remove(shot)
            for name in kinds:
                with self.subTest(tool=name):
                    self.assertIn(name, words)

    async def test_chrome_empty_states(self):
        from textual.widgets import TextArea
        async with booted_app() as (app, pilot):
            diff = app.query_one(DiffView)
            area = diff.query_one("#diff-area", TextArea)
            self.assertFalse(area.show_line_numbers)
            diff.add_diff("a.py", "x", "y")
            await pilot.pause()
            self.assertTrue(area.show_line_numbers)
            diff.clear()
            await pilot.pause()
            self.assertFalse(area.show_line_numbers)
            total = app.query_one(CostsView).query_one(
                "#costs-total")
            self.assertNotEqual(
                str(total.render()).strip(), "")


if __name__ == "__main__":
    unittest.main()
41.9ms