Skip to content

armgit / kong

Public Imported from GitHub
0

The world's first agentic reverse engineer.

add TUI app and widgets for interactive analysis display

Amruthf14f0cf6882e
diff --git a/kong/tui/__init__.py b/kong/tui/__init__.py
new file mode 100644
index 0000000..ebb87db
--- /dev/null
+++ b/kong/tui/__init__.py
@@ -0,0 +1 @@
+"""Kong TUI package."""
diff --git a/kong/tui/app.py b/kong/tui/app.py
new file mode 100644
index 0000000..d324405
--- /dev/null
+++ b/kong/tui/app.py
@@ -0,0 +1,143 @@
+"""Main Textual application for Kong TUI."""
+
+from __future__ import annotations
+
+import time
+
+from textual.app import App, ComposeResult
+from textual.binding import Binding
+from textual.message import Message
+
+from kong.agent.events import Event, EventType, Phase
+from kong.agent.supervisor import Supervisor
+from kong.tui.widgets import AgentLog, BinaryHeader, ProgressWidget, StatusBar
+
+EVENT_STYLES: dict[EventType, str] = {
+ EventType.PHASE_START: "bold cyan",
+ EventType.PHASE_COMPLETE: "bold green",
+ EventType.FUNCTION_COMPLETE: "green",
+ EventType.FUNCTION_SKIPPED: "dim",
+ EventType.FUNCTION_ERROR: "red",
+ EventType.RUN_ERROR: "bold red",
+ EventType.RUN_COMPLETE: "bold green",
+ EventType.DEOBFUSCATION_DETECTED: "magenta",
+ EventType.DEOBFUSCATION_COMPLETE: "magenta",
+ EventType.EXPORT_FILE: "cyan",
+ EventType.CLEANUP_TYPE_CREATED: "blue",
+}
+
+
+class AgentEvent(Message):
+ """Bridges supervisor events from worker thread to Textual message system."""
+
+ def __init__(self, event: Event) -> None:
+ super().__init__()
+ self.event = event
+
+
+class KongApp(App):
+ """Kong analysis TUI."""
+
+ CSS = """
+ Screen { layout: vertical; }
+ #header { height: 1; padding: 0 1; background: $primary; color: $text; }
+ """
+
+ BINDINGS = [
+ Binding("p", "toggle_pause", "Pause/Resume"),
+ Binding("q", "quit_app", "Quit"),
+ Binding("e", "export_now", "Export Now"),
+ ]
+
+ def __init__(self, supervisor: Supervisor) -> None:
+ super().__init__()
+ self.supervisor = supervisor
+ self._start_time: float = 0.0
+ self._completed: int = 0
+ self._total: int = 0
+
+ def compose(self) -> ComposeResult:
+ yield BinaryHeader(id="header")
+ yield ProgressWidget()
+ yield AgentLog()
+ yield StatusBar()
+
+ def on_mount(self) -> None:
+ self._start_time = time.time()
+ self.supervisor.on_event(self._on_supervisor_event)
+ self.run_worker(self._run_analysis, thread=True)
+ self.set_interval(1, self._tick)
+
+ def _on_supervisor_event(self, event: Event) -> None:
+ self.call_from_thread(self.post_message, AgentEvent(event))
+
+ def _run_analysis(self) -> None:
+ self.supervisor.run()
+
+ def on_agent_event(self, message: AgentEvent) -> None:
+ event = message.event
+ progress = self.query_one(ProgressWidget)
+ log = self.query_one(AgentLog)
+
+ if event.type == EventType.RUN_START:
+ pass
+
+ if event.type == EventType.TRIAGE_FUNCTIONS_ENUMERATED:
+ binary_data = event.data.get("binary_info", {})
+ header = self.query_one(BinaryHeader)
+ header.set_info(
+ name=self.supervisor.binary_info.name if self.supervisor.binary_info else "unknown",
+ arch=binary_data.get("arch", ""),
+ fmt=binary_data.get("format", ""),
+ compiler=binary_data.get("compiler", ""),
+ )
+ self._total = event.data.get("total", 0)
+ progress.update_progress(self._completed, self._total)
+
+ if event.type == EventType.PHASE_START:
+ phase_name = event.phase.value if event.phase else "unknown"
+ progress.update_phase(phase_name.capitalize())
+
+ if event.type in (EventType.FUNCTION_COMPLETE, EventType.FUNCTION_SKIPPED):
+ self._completed += 1
+ progress.update_progress(self._completed, self._total)
+ stats = self.supervisor.stats
+ progress.update_confidence(
+ stats.high_confidence,
+ stats.medium_confidence,
+ stats.low_confidence,
+ )
+
+ style = EVENT_STYLES.get(event.type, "")
+ log.log_event(event.message, style=style)
+
+ def _tick(self) -> None:
+ elapsed = time.time() - self._start_time if self._start_time else 0.0
+ llm_calls = self.supervisor.stats.llm_calls
+ cost = 0.0
+ llm_client = getattr(self.supervisor, "llm_client", None)
+ if llm_client is not None and hasattr(llm_client, "total_cost_usd"):
+ cost = llm_client.total_cost_usd
+ status_bar = self.query_one(StatusBar)
+ status_bar.update_status(
+ elapsed=elapsed,
+ llm_calls=llm_calls,
+ cost=cost,
+ paused=self.supervisor._paused,
+ )
+
+ def action_toggle_pause(self) -> None:
+ if self.supervisor._paused:
+ self.supervisor.resume()
+ else:
+ self.supervisor.pause()
+
+ def action_quit_app(self) -> None:
+ self.supervisor.pause()
+ self.exit()
+
+ def action_export_now(self) -> None:
+ self.run_worker(self._run_export, thread=True)
+
+ def _run_export(self) -> None:
+ self.supervisor._run_export()
diff --git a/kong/tui/widgets.py b/kong/tui/widgets.py
new file mode 100644
index 0000000..918e0f5
--- /dev/null
+++ b/kong/tui/widgets.py
@@ -0,0 +1,131 @@
+"""Custom Textual widgets for the Kong TUI."""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+from rich.text import Text
+from textual.reactive import reactive
+from textual.widget import Widget
+from textual.widgets import RichLog, Static
+
+
+class BinaryHeader(Static):
+ """One-line binary info display."""
+
+ DEFAULT_CSS = """
+ BinaryHeader {
+ height: 1;
+ padding: 0 1;
+ background: $primary;
+ color: $text;
+ }
+ """
+
+ _content: str = ""
+
+ def set_info(self, name: str, arch: str, fmt: str, compiler: str) -> None:
+ self._content = f"Binary: {name} | {arch} {fmt} | {compiler}"
+ self.update(self._content)
+
+
+class ProgressWidget(Widget):
+ """Phase indicator with progress bar and confidence breakdown."""
+
+ DEFAULT_CSS = """
+ ProgressWidget {
+ height: 3;
+ padding: 0 1;
+ }
+ """
+
+ phase_name: reactive[str] = reactive("Initializing")
+ completed: reactive[int] = reactive(0)
+ total: reactive[int] = reactive(0)
+ high: reactive[int] = reactive(0)
+ medium: reactive[int] = reactive(0)
+ low: reactive[int] = reactive(0)
+
+ def update_phase(self, name: str) -> None:
+ self.phase_name = name
+
+ def update_progress(self, completed: int, total: int) -> None:
+ self.completed = completed
+ self.total = total
+
+ def update_confidence(self, high: int, medium: int, low: int) -> None:
+ self.high = high
+ self.medium = medium
+ self.low = low
+
+ def render(self) -> Text:
+ bar_width = 30
+ pct = (self.completed / self.total * 100) if self.total > 0 else 0
+ filled = int(bar_width * self.completed / self.total) if self.total > 0 else 0
+ bar = "█" * filled + "░" * (bar_width - filled)
+
+ line1 = f"Phase: {self.phase_name} {bar} {self.completed}/{self.total} ({pct:.0f}%)"
+
+ line2 = Text()
+ line2.append("Confidence: ")
+ line2.append("■■■", style="green")
+ line2.append(f" {self.high} high ")
+ line2.append("■■", style="yellow")
+ line2.append(f" {self.medium} med ")
+ line2.append("■", style="red")
+ line2.append(f" {self.low} low")
+
+ result = Text(line1 + "\n")
+ result.append(line2)
+ return result
+
+
+class AgentLog(RichLog):
+ """Scrollable event log with timestamps."""
+
+ DEFAULT_CSS = """
+ AgentLog {
+ height: 1fr;
+ border: solid $primary;
+ }
+ """
+
+ def log_event(self, message: str, style: str = "") -> None:
+ timestamp = datetime.now().strftime("%H:%M:%S")
+ text = Text(f"[{timestamp}] {message}")
+ if style:
+ text.stylize(style)
+ self.write(text)
+
+
+class StatusBar(Static):
+ """Footer with keybinds and status info."""
+
+ DEFAULT_CSS = """
+ StatusBar {
+ height: 1;
+ dock: bottom;
+ background: $surface;
+ padding: 0 1;
+ }
+ """
+
+ _content: str = ""
+
+ def update_status(
+ self,
+ elapsed: float,
+ llm_calls: int,
+ cost: float,
+ paused: bool,
+ ) -> None:
+ minutes = int(elapsed // 60)
+ seconds = int(elapsed % 60)
+ text = (
+ f"[p]ause [q]uit [e]xport now "
+ f"LLM: {llm_calls} | ${cost:.4f} | {minutes}m {seconds:02d}s"
+ )
+ if paused:
+ text += " PAUSED"
+ self._content = text
+ self.update(self._content)
diff --git a/tests/test_tui.py b/tests/test_tui.py
new file mode 100644
index 0000000..8a525a9
--- /dev/null
+++ b/tests/test_tui.py
@@ -0,0 +1,138 @@
+"""Tests for TUI widgets and app."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, create_autospec
+
+from textual.app import App
+from textual.widget import Widget
+from textual.widgets import RichLog, Static
+
+from kong.agent.supervisor import Supervisor
+from kong.tui.app import EVENT_STYLES, AgentEvent, KongApp
+from kong.tui.widgets import AgentLog, BinaryHeader, ProgressWidget, StatusBar
+
+
+class TestBinaryHeader:
+ def test_is_static_subclass(self) -> None:
+ widget = BinaryHeader()
+ assert isinstance(widget, Static)
+
+ def test_set_info_formats_correctly(self) -> None:
+ widget = BinaryHeader()
+ widget.set_info(
+ name="test.bin",
+ arch="x86_64",
+ fmt="ELF",
+ compiler="GCC",
+ )
+ expected = "Binary: test.bin | x86_64 ELF | GCC"
+ assert widget._content == expected
+
+
+class TestProgressWidget:
+ def test_is_widget_subclass(self) -> None:
+ widget = ProgressWidget()
+ assert isinstance(widget, Widget)
+
+ def test_default_reactive_values(self) -> None:
+ widget = ProgressWidget()
+ assert widget.phase_name == "Initializing"
+ assert widget.completed == 0
+ assert widget.total == 0
+ assert widget.high == 0
+ assert widget.medium == 0
+ assert widget.low == 0
+
+ def test_update_phase(self) -> None:
+ widget = ProgressWidget()
+ widget.update_phase("Analysis")
+ assert widget.phase_name == "Analysis"
+
+ def test_update_progress(self) -> None:
+ widget = ProgressWidget()
+ widget.update_progress(5, 10)
+ assert widget.completed == 5
+ assert widget.total == 10
+
+ def test_update_confidence(self) -> None:
+ widget = ProgressWidget()
+ widget.update_confidence(3, 2, 1)
+ assert widget.high == 3
+ assert widget.medium == 2
+ assert widget.low == 1
+
+
+class TestAgentLog:
+ def test_is_richlog_subclass(self) -> None:
+ widget = AgentLog()
+ assert isinstance(widget, RichLog)
+
+
+class TestStatusBar:
+ def test_is_static_subclass(self) -> None:
+ widget = StatusBar()
+ assert isinstance(widget, Static)
+
+ def test_update_status_formats_correctly(self) -> None:
+ widget = StatusBar()
+ widget.update_status(elapsed=125.0, llm_calls=10, cost=0.0523, paused=False)
+ content = widget._content
+ assert "LLM: 10" in content
+ assert "$0.0523" in content
+ assert "2m 05s" in content
+ assert "PAUSED" not in content
+
+ def test_update_status_paused(self) -> None:
+ widget = StatusBar()
+ widget.update_status(elapsed=60.0, llm_calls=5, cost=0.01, paused=True)
+ content = widget._content
+ assert "PAUSED" in content
+
+
+class TestKongApp:
+ def test_is_app_subclass(self) -> None:
+ supervisor = create_autospec(Supervisor, instance=True)
+ supervisor._paused = False
+ supervisor.stats = MagicMock()
+ supervisor.stats.llm_calls = 0
+ app = KongApp(supervisor)
+ assert isinstance(app, App)
+
+ def test_stores_supervisor(self) -> None:
+ supervisor = create_autospec(Supervisor, instance=True)
+ supervisor._paused = False
+ supervisor.stats = MagicMock()
+ supervisor.stats.llm_calls = 0
+ app = KongApp(supervisor)
+ assert app.supervisor is supervisor
+
+
+class TestEventStyles:
+ def test_event_styles_is_dict(self) -> None:
+ assert isinstance(EVENT_STYLES, dict)
+
+ def test_event_styles_has_expected_keys(self) -> None:
+ from kong.agent.events import EventType
+ expected_keys = {
+ EventType.PHASE_START,
+ EventType.PHASE_COMPLETE,
+ EventType.FUNCTION_COMPLETE,
+ EventType.FUNCTION_SKIPPED,
+ EventType.FUNCTION_ERROR,
+ EventType.RUN_ERROR,
+ EventType.RUN_COMPLETE,
+ EventType.DEOBFUSCATION_DETECTED,
+ EventType.DEOBFUSCATION_COMPLETE,
+ EventType.EXPORT_FILE,
+ EventType.CLEANUP_TYPE_CREATED,
+ }
+ assert expected_keys.issubset(EVENT_STYLES.keys())
+
+
+class TestAgentEvent:
+ def test_agent_event_wraps_event(self) -> None:
+ from kong.agent.events import Event, EventType
+ event = Event(type=EventType.RUN_START, message="test")
+ msg = AgentEvent(event)
+ assert msg.event is event