Skip to content

🔍 Code Quality Report - 2026-09-28 #830

Open

Description

@github-actions

Weekly Code Quality Report - 2026-09-28

This is an automated report generated by the weekly code quality workflow.

Code Quality Analysis Report

Generated: 2026-09-28
Codebase: OpenHands CLI (openhands_cli/)
Files Analyzed: 248


Executive Summary

The OpenHands CLI codebase demonstrates solid architecture with clear module boundaries between acp_impl/, tui/, and auth/. Pyright reports 0 type errors, indicating good baseline type safety. However, the analysis identified several areas for improvement:

Category Critical High Medium Low
Type Checking 0 4 12 14
State Management 0 3 2 3
Separation of Concerns 0 3 4 -
Code Duplication (ACP/TUI) 0 2 4 -
Total 0 12 22 17

Key Findings:

  1. 78 uses of Any type that could be more specific (particularly for API responses and MCP configs)
  2. Significant prop drilling - state and runners passed through 7+ controller classes
  3. UI/presentation mixed with business logic in auth/api_client.py and auth/device_flow.py
  4. Major code duplication in tool title/kind computation between ACP and TUI implementations

1. Type Checking Issues

1.1 Critical Issues

None - Pyright reports 0 errors, 0 warnings.

1.2 Missing Type Hints (4 instances)

File Line Function/Parameter Recommendation
tui/panels/mcp_side_panel.py 212 first_server_spec, second_server_spec StdioMCPServer | RemoteMCPServer | dict[str, Any]
tui/widgets/richlog_visualizer.py 236 func Callable[..., Any]
tui/widgets/richlog_visualizer.py 550 event Appropriate SDK event type
tui/widgets/user_input/single_line_input.py 69 event Key from textual.events

1.3 Type Improvement Opportunities

High Priority: External API/SDK Boundaries (33 instances)

MCP Server Configurations (10+ uses across codebase)

# Current
mcp_servers: dict[str, dict[str, Any]]

# Recommended: Create TypedDict
class MCPServerConfig(TypedDict):
    command: str | None
    args: list[str] | None
    env: dict[str, str] | None
    url: str | None

API Client Responses (auth/api_client.py - 12 instances)

# Current
def get_user_info() -> dict[str, Any]: ...
def get_user_settings() -> dict[str, Any]: ...

# Recommended: Define TypedDicts
class UserInfo(TypedDict):
    email: str
    name: str | None
    ...

class UserSettings(TypedDict):
    llm_model: str | None
    agent: str | None
    ...

LiteLLM Tool Calls (acp_impl/events/token_streamer.py)

# Line 242 - Currently Any
def _handle_tool_call_streaming(self, tool_call: Any) -> None:

# Recommended: Import from LiteLLM or create Protocol

Medium Priority: Internal State (12 instances)

Critic Features (tui/utils/critic/refinement.py - 6 instances)

# Current
def _format_feature_for_prompt(feature: dict[str, Any]) -> str:

# Recommended
class CriticFeature(TypedDict):
    display_name: str
    probability: float
    name: str

Low Priority: Framework Conventions (14 instances)

Textual CSS/reactive attributes follow framework conventions and don't require explicit type hints:

  • CSS_PATH = "settings_screen.tcss"
  • collapsed = reactive(True)

Consider converting CompletionType to proper Enum:

# Current (tui/widgets/user_input/autocomplete_dropdown.py:11-13)
class CompletionType:
    COMMAND = "command"
    FILE = "file"
    NONE = "none"

# Recommended
class CompletionType(str, Enum):
    COMMAND = "command"
    FILE = "file"
    NONE = "none"

2. State Management Issues

2.1 Current State Architecture

The codebase uses a reactive state management pattern in the TUI with ConversationContainer as the single source of truth. The stores (agent_store.py, prompt_history.py) properly use Pydantic models for validation.

Positive patterns:

  • ✅ Pydantic BaseModel for settings (CriticSettings, CliSettings, LLMEnvOverrides)
  • ✅ TypedDict for data structures (PromptHistoryEntry)
  • ✅ No mutable default arguments found
  • ✅ Thread-safe state updates via call_from_thread()

2.2 Problems Identified

High Priority

1. Global agent_store Singleton (tui/modals/settings/utils.py:14)

agent_store = AgentStore()
  • Impact: Shared mutable state across all imports, complicates testing and state isolation
  • Recommendation: Use dependency injection or a factory pattern

2. Deep Prop Drilling (tui/core/conversation_manager.py:91-133)

The state and runners objects are passed to 7+ controller classes:

Controller state runners Other deps
RunnerRegistry ✓ - factory, message_pump
ConfirmationPolicyService ✓ ✓ -
RefinementController ✓ ✓ post_message
UserMessageController ✓ ✓ run_worker
ConversationCrudController ✓ ✓ store, notify
ConversationSwitchController ✓ ✓ notify, post_message
ConfirmationFlowController ✓ ✓ policy_service
  • Recommendation: Create a ControllerContext dataclass to bundle shared dependencies

3. Scattered Local Caches

Multiple widgets maintain separate caches that can drift from the source of truth:

Widget Cache Source
history_side_panel.py:129 _local_rows: list[ConversationMetadata] Store
plan_side_panel.py:57 _task_list: list[TaskItem] Disk
input_field.py:174 _history_cache: list[str] PromptHistoryStore
richlog_visualizer.py:121 _pending_actions: dict Events

Medium Priority

4. Module-Level Computed State (tui/modals/settings/choices.py:62)

provider_options = get_provider_options()  # Computed at import time
  • Impact: Won't reflect runtime changes without reimport
  • Recommendation: Use a factory function called at point of use

5. Multiple Session Tracking Dicts (ACP agents)

# base_agent.py
self._active_sessions: dict[str, BaseConversation] = {}
self._running_tasks: dict[str, asyncio.Task] = {}

# remote_agent.py
self._active_workspaces: dict[str, OpenHandsCloudWorkspace] = {}
  • Risk: These parallel dictionaries could become out of sync

2.3 Recommendations

  1. Replace global singleton with dependency injection:

    # Instead of module-level AgentStore()
    def get_agent_store() -> AgentStore:
        return AgentStore()  # Or cached/scoped instance
  2. Create ControllerContext to reduce prop drilling:

    @dataclass
    class ControllerContext:
        state: ConversationContainer
        runners: RunnerRegistry
        notify: Callable[..., None]
        post_message: Callable[..., None]
        run_worker: Callable[..., None]
  3. Implement reactive data flow from stores to widgets to eliminate cache duplication


3. Separation of Concerns Issues

3.1 Coupled Components

UI/Presentation Mixed with Business Logic

auth/api_client.py - MAJOR VIOLATION (Lines 161-305)

# API client module contains console output
def _print_settings_summary(settings: dict[str, Any]) -> None:
    console_print("  ✓ User settings retrieved", style=OPENHANDS_THEME.success)
    llm_model = settings.get("llm_model", "Not set")
    console_print(f"    LLM Model: {llm_model}", style=OPENHANDS_THEME.secondary)

# Blocking user input in API module!
def _ask_user_consent_for_overwrite(...) -> bool:
    response = input("Do you want to overwrite? (y/N): ")

auth/device_flow.py - UI in Authentication Logic (Lines 162-219)

async def authenticate(self) -> DeviceTokenResponse:
    console_print("Starting OpenHands authentication...", style=OPENHANDS_THEME.accent)
    console_print("\nOpening your web browser...", style=OPENHANDS_THEME.warning)
    try:
        webbrowser.open(verification_url)
        console_print("✓ Browser opened successfully", style=OPENHANDS_THEME.success)
    except Exception as e:
        console_print(f"Could not open browser: {e}", style=OPENHANDS_THEME.warning)

stores/agent_store.py - Console Output in Data Store (Lines 173, 280)

console.print("\nAgent configuration file is corrupted!", style="red", markup=False)

3.2 Mixed Responsibilities (SRP Violations)

auth/api_client.py (374 lines, 6+ responsibilities)

  1. HTTP client for OpenHands API
  2. Settings data transformation
  3. UI presentation
  4. User interaction
  5. Agent configuration creation
  6. Full post-OAuth workflow

stores/agent_store.py (532 lines, 6+ responsibilities)

  1. Agent persistence (load/save)
  2. Environment variable handling
  3. Runtime configuration
  4. Tool resolution
  5. Context building
  6. Critic configuration

3.3 Tight Coupling

setup.py imports TUI component (Line 19)

from openhands_cli.tui.widgets.richlog_visualizer import ConversationVisualizer

The setup module (used by both TUI and ACP) imports a TUI-specific visualizer.

ACP imports auth CLI logic directly (acp_impl/agent/base_agent.py:273-274)

from openhands_cli.auth.device_flow import DeviceFlowError
from openhands_cli.auth.login_command import login_command  # Does console printing!

3.4 Module Boundary Assessment

Module Boundary Quality Notes
acp_impl/ ✅ Good No imports from tui/, clean ACP protocol
tui/ ✅ Good No imports from acp_impl/, well-structured
auth/ ⚠️ Issues Mixed presentation and business logic
stores/ ⚠️ Issues Console output in data layer

3.5 Recommendations

  1. Extract presentation from auth/:

    • Create auth/presenter.py for console output
    • Or move UI to CLI command layer (entrypoint.py)
  2. Split api_client.py into focused modules:

    • api_client.py - Pure API client
    • settings_service.py - Settings transformation
    • agent_setup_service.py - Agent configuration
  3. Remove setup.py TUI dependency:

    • Make visualizer optional/injectable
    • Use a protocol/interface
  4. Create auth interface protocols:

    class AuthPresenter(Protocol):
        def show_progress(self, message: str) -> None: ...
        def show_success(self, message: str) -> None: ...
        def prompt_consent(self, message: str) -> bool: ...

4. Code Duplication (ACP/TUI)

4.1 Duplicated Patterns

MAJOR: Tool Title & Kind Computation (3 locations)

ACP (events/utils.py:146-209)

def get_tool_kind(tool_name: str, *, action: Action | None = None) -> ToolKind:
    if tool_name == "think": return "think"
    if tool_name.startswith("browser"): return "fetch"
    if isinstance(action, FileEditorAction):
        return "read" if action.command == "view" else "edit"
    return TOOL_KIND_MAPPING.get(tool_name, "other")

ACP Streaming (events/tool_state.py:73-177) - Same logic duplicated for streaming

TUI (widgets/richlog_visualizer.py:470-513)

def _build_action_title(self, event: ActionEvent) -> str:
    if isinstance(action, TerminalAction) and action.command:
        cmd = escape_rich_markup(action.command...)
        if summary: return f"{agent_prefix}[bold]{summary}[/bold][dim]: $ {cmd}[/dim]"

HIGH: Confirmation Mode Definitions

ACP (confirmation.py:25-44)

ConfirmationMode = Literal["always-ask", "always-approve", "llm-approve"]
CONFIRMATION_MODES: dict[ConfirmationMode, dict[str, str]] = {
    "always-ask": {"short": "Ask for permission...", "long": "..."},
    ...
}

TUI (confirmation_modal.py:18-22)

POLICY_DISPLAY_NAMES: dict[type[ConfirmationPolicyBase], str] = {
    NeverConfirm: "Always approve actions (no confirmation)",
    AlwaysConfirm: "Confirm every action",
    ...
}

MEDIUM: Conversation Execution Loop

ACP (runner.py:27-76) and TUI (conversation_runner.py:140-195) both implement similar confirmation-check-run loops.

MEDIUM: Metrics/Status Line Formatting

ACP (events/utils.py:29-60)

def _format_status_line(usage: TokenUsage, cost: float) -> str:
    parts = [f"↑ input {input_tokens}", f"cache hit {cache_rate}", ...]

TUI (widgets/status_line.py:200-240)

def _format_metrics_display(self) -> str:
    token_details = f"↑ {abbreviate_number(input_tokens)} ↓ {abbreviate_number(output_tokens)}"

4.2 What's Already Shared (openhands_cli/shared/)

✅ delegate_formatter.py - format_delegate_title()
✅ rich_utils.py - escape_rich_markup()
✅ conversation_summary.py - extract_conversation_summary()
✅ slash_commands.py - parse_slash_command()
✅ user_actions/types.py - UserConfirmation, ConfirmationResult
✅ utils.py - abbreviate_number(), format_cost()

4.3 Recommendations: New Shared Modules

Proposed Module Contents Eliminates Duplication In
shared/tool_display.py get_tool_kind(), get_tool_title() ACP events/utils.py, events/tool_state.py, TUI richlog_visualizer.py
shared/confirmation_modes.py Unified mode definitions/descriptions ACP confirmation.py, TUI confirmation_modal.py
shared/conversation_executor.py Core confirmation loop logic ACP runner.py, TUI conversation_runner.py
shared/metrics_formatter.py Status line formatting ACP events/utils.py, TUI status_line.py

5. Low-Hanging Fruit

Quick wins that can be addressed with minimal effort:

Issue Location Effort Impact
Add missing type hints (4 params) Various Trivial Medium
Convert CompletionType to Enum autocomplete_dropdown.py:11-13 Trivial Low
Create MCPServerConfig TypedDict New file in shared/ Small High
Extract get_tool_kind/title to shared shared/tool_display.py Small High
Create UserInfo TypedDict auth/api_client.py Small Medium
Replace global agent_store tui/modals/settings/utils.py Small Medium
Move console output from agent_store.py stores/agent_store.py:173,280 Trivial Medium
Create ControllerContext dataclass tui/core/ Medium High
Split api_client.py responsibilities auth/api_client.py Medium High
Extract auth presentation layer auth/ Medium High

6. Statistics

By Category

Category Issues Found
Missing parameter types 4
Any types to improve 78
Untyped class attributes 30
Global mutable state 4
Prop drilling patterns 1 (7+ controllers)
Local cache duplication 4
SRP violations 2 major
UI/business mixing 3 files
Tight coupling 2 instances
Code duplication (ACP/TUI) 6 patterns

By Severity

Severity Count
Critical 0
High 12
Medium 22
Low 17

7. Prioritized Action Items

Immediate (This Sprint)

  1. Add missing type hints to 4 function parameters

    • Effort: 30 minutes
    • Files: mcp_side_panel.py, richlog_visualizer.py, single_line_input.py
  2. Create MCPServerConfig TypedDict in shared/

    • Effort: 1 hour
    • Impact: Improves type safety across 10+ uses
  3. Extract get_tool_kind() and get_tool_title() to shared/tool_display.py

    • Effort: 2 hours
    • Impact: Eliminates major code duplication
  4. Move console output from agent_store.py to caller

    • Effort: 30 minutes
    • Impact: Clean separation of concerns

Short-Term (Next 2 Sprints)

  1. Create API response TypedDicts (UserInfo, UserSettings, etc.)

    • Effort: 2 hours
    • Files: auth/api_client.py
  2. Replace global agent_store singleton with dependency injection

    • Effort: 2 hours
    • Files: tui/modals/settings/utils.py
  3. Create shared/confirmation_modes.py with unified definitions

    • Effort: 2 hours
    • Impact: Eliminates duplication, improves consistency
  4. Create ControllerContext dataclass to reduce prop drilling

    • Effort: 4 hours
    • Files: tui/core/conversation_manager.py and controllers

Medium-Term (Next Quarter)

  1. Extract presentation from auth/ module

    • Effort: 1 day
    • Create auth/presenter.py or move UI to command layer
  2. Split api_client.py into focused modules

    • Effort: 1 day
    • Create separate files for API, settings, agent setup
  3. Create shared/conversation_executor.py for execution loop

    • Effort: 4 hours
    • Unify ACP and TUI confirmation handling
  4. Remove TUI dependency from setup.py

    • Effort: 2 hours
    • Make visualizer optional/injectable

Appendix: Files Requiring Attention

High Priority Files

  • auth/api_client.py - SRP violation, UI mixing (374 lines)
  • acp_impl/events/utils.py - Tool display duplication
  • tui/widgets/richlog_visualizer.py - Tool display duplication
  • tui/core/conversation_manager.py - Prop drilling

Medium Priority Files

  • stores/agent_store.py - Console output, 6+ responsibilities (532 lines)
  • auth/device_flow.py - UI in auth logic
  • acp_impl/confirmation.py - Duplicated mode definitions
  • tui/modals/settings/utils.py - Global singleton

Files with Good Patterns (Reference)

  • shared/delegate_formatter.py - Clean shared utility
  • shared/slash_commands.py - Clean shared utility
  • stores/cli_settings.py - Proper Pydantic models
  • tui/core/state.py - Reactive state pattern

Workflow Run: View Details

Categories Analyzed:

  • 🔍 Type checking and type hints
  • 📦 State management patterns
  • 🔀 Separation of concerns
  • 🔁 Code duplication between ACP and TUI

Next Steps:

  • Review the findings above
  • PRs for low-hanging fruit may be automatically created
  • Create specific issues for larger refactoring items

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions