Skip to content

refactor: consolidate app runtime and selector architecture#6

Merged
yanmxa merged 1 commit intomainfrom
codex-refactor
Apr 5, 2026
Merged

refactor: consolidate app runtime and selector architecture#6
yanmxa merged 1 commit intomainfrom
codex-refactor

Conversation

@yanmxa
Copy link
Copy Markdown
Owner

@yanmxa yanmxa commented Apr 5, 2026

Summary

  • consolidate shared tool execution, streaming, completion, and compaction runtime paths across and
  • split oversized app selector, input, render, and initialization modules into focused files with clearer ownership boundaries
  • add regression coverage around executor overrides, runtime request builders, selector behavior, stream startup, and shared helper semantics

Testing

  • env GOCACHE=/tmp/gocache go test ./internal/message ./internal/core ./internal/app ./internal/...

Summary by CodeRabbit

Release Notes

  • Refactor

    • Reorganized internal execution orchestration for improved maintainability and testability.
    • Restructured tool result rendering with specialized handlers for different tool types.
    • Refactored plugin selector UI logic into focused modules for actions, navigation, and keymap handling.
    • Improved provider and model selection workflows with cleaner state management.
    • Converted global progress tracking to instance-scoped implementation.
  • Bug Fixes

    • Fixed tool hook payload handling in certain execution paths.

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @yanmxa, your pull request is larger than the review limit of 150000 diff characters

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 5, 2026

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR performs extensive modularization and abstraction refactoring across the codebase. Key changes include splitting agent executor orchestration into focused helpers, decomposing handler input logic into specialized files, extracting core loop utilities into separate modules, refactoring tool execution to use prepared-call abstractions, modularizing UI component logic (plugin and provider selectors), introducing runtime interfaces and request builders, centralizing routing/modal handling, and removing global progress hub state.

Changes

Cohort / File(s) Summary
Agent Executor Refactoring
internal/agent/executor.go, internal/agent/executor_run.go, internal/agent/executor_test.go
Split Executor.Run() into discrete helper methods (prepareRun, attachRunContext, logRunStart, executePreparedRun, buildCancelledAgentResult, buildAgentResult). Moved request validation, workspace prep, loop construction, logging, and result assembly into new unexported helpers. Centralized display-name selection and updated system-prompt generation to accept resolved permission mode. Added new test file with three unit tests validating run-config overrides, permission-mode resolution, and cancellation result handling.
Handler Input Splitting
internal/app/handler_input.go, internal/app/handler_input_runtime.go, internal/app/handler_input_submit.go, internal/app/handler_input_window.go
Decomposed large handler_input.go (−263 lines) by extracting stream/tool cancellation (handler_input_runtime.go), submit/exit/prompt-hook logic (handler_input_submit.go), and window-resize/reflow handling (handler_input_window.go). Removed inline submission, skill invocation, image pasting, and window handlers from main file; logic relocated to focused modules.
Tool Execution & Preparation
internal/app/tool/run.go, internal/app/tool/state.go, internal/tool/call.go, internal/tool/execute.go, internal/tool/execute_test.go
Introduced PreparedToolCall abstraction to encapsulate parsed params, resolved tool, and MCP-flag; refactored execution paths to call coretool.PrepareToolCall() once and reuse prepared result. Added Begin() and Context() helpers to ExecState for centralized context lifecycle. Updated permission/interaction checks and error handling to use prepared call. Added two new unit tests for prepared-tool behavior.
Core Loop Utilities Extraction
internal/core/compact.go, internal/core/completion.go, internal/core/stream_collect.go, internal/core/core.go, internal/core/core_test.go
Extracted compaction decision logic (compact.go), completion routing (completion.go), and stream chunk collection (stream_collect.go) from core.go. Updated core to use new predicates CanCompactMessages, ShouldCompactPromptTooLong. Refactored runTool to accept PreparedToolCall. Added new constants AutoCompactResumePrompt and minMessagesForCompaction. Added tests for compaction predicates and hook-response preservation.
Plugin Selector UI Modularization
internal/app/plugin/model.go, internal/app/plugin/actions.go, internal/app/plugin/keymap.go, internal/app/plugin/load.go, internal/app/plugin/navigation.go, internal/app/plugin/reset.go, internal/app/plugin/model_test.go
Decomposed model.go (−657 lines) into focused modules: action execution (actions.go), keypress handling (keymap.go), state resets (reset.go), and navigation/filtering (navigation.go). Refactored load.go to call reset helpers. Added comprehensive unit tests validating cancel behavior, keypress handling, and tab switching. Main model file now contains only core state and New()/IsActive().
Provider Selector UI Modularization
internal/app/provider/model.go, internal/app/provider/load.go, internal/app/provider/navigation.go, internal/app/provider/select.go, internal/app/provider/reset.go, internal/app/provider/model_test.go
Similar decomposition to plugin selector: removed implementations from model.go (−291 lines), split into navigation (navigation.go), selection logic (select.go), state resets (reset.go). Updated load.go to use reset helpers. Added unit tests validating cancel, back-navigation, tab switching, keypress, and selection behavior.
App Runtime Abstractions
internal/app/runtime_conversation.go, internal/app/runtime_requests.go, internal/app/stream_runtime.go
Converted conversationRuntime from concrete struct to interface with SuggestPromptCmd, FetchTokenLimitsCmd, CompactCmd, StartStream. Added defaultConversationRuntime implementation and streamRequest/streamStartResult types. New runtime_requests.go adds helper methods (buildPromptSuggestionRequest, buildTokenLimitFetchRequest, buildCompactRequest). New stream_runtime.go adds buildStreamRequest and startConversationStream helpers.
Handler Context Updates
internal/app/handler_approval.go, internal/app/handler_mode.go, internal/app/handler_provider.go
Updated multiple handlers to use m.tool.Context() instead of m.tool.Ctx and to call m.tool.Begin() for context lifecycle. handler_provider.go extracted duplicate connection-refresh logic into refreshProviderConnection helper.
Stream & Tool Result Handling
internal/app/handler_stream.go, internal/app/handler_tool.go, internal/app/handler_tool_persist.go, internal/app/handler_tool_progress.go, internal/app/handler_tool_plugin.go
Refactored stream completion into modular decision logic (applyCompletedStreamState, handleCompletionDecision, handleCompletionToolCalls, finalizeCompletedTurn). Extracted tool-result side effects and message appending into helpers. Added new files for tool overflow persistence, progress handling, and plugin installation.
Command Handler Refactoring
internal/app/handler_command.go, internal/app/handler_command_test.go
Extracted builtin command handlers from anonymous closures into named functions (handleInitCommand, handleMemoryCommand, etc.). Added module-level builtinCommandHandlers map. Extracted command dispatch, exit handling, and unknown-command formatting into helpers. Added tests validating handler registry, exit behavior, and unknown-command handling.
Loop Builder & Model Configuration
internal/app/loop_builder.go, internal/app/model.go, internal/app/model_init.go
New loop_builder.go provides buildLoopClient, buildLoopSystem, buildLoopToolSet, and related helpers. Updated model.go to delegate loop configuration to these builders, removing inline logic. Refactored model_init.go to extract state initialization into dedicated helpers (newProviderState, newSessionState, etc.).
Routing & Modal Management
internal/app/routing.go, internal/app/view.go, internal/app/update.go, internal/app/prompt_suggest.go
New routing.go centralizes feature-update routing via routeFeatureUpdate() and overlay-selector rendering via renderOverlaySelector(). update.go delegates feature dispatch to routing. view.go now uses renderOverlaySelector() and renderActiveModal() for full-screen rendering. prompt_suggest.go delegates request building to helper.
Output Progress Management
internal/app/output/model.go, internal/app/output/update.go, internal/app/output/update_test.go
Removed automatic hub creation in New() constructor; now accepts optional nil hub. Removed progressHub() lazy-initializer helper; inlined nil checks directly in progress methods. Added tests validating progress handling and drain behavior with nil hub.
Progress Hub Removal
internal/ui/progress/progress.go
Removed global DefaultHub and package-level helper functions (Send, SendForAgent, Check, Drain). Shifted to explicit instance-based hub usage throughout codebase.
Tool Rendering Refactoring
internal/app/render/message_tool.go, internal/app/render/message_tool_inline.go, internal/app/render/message_tool_agent.go, internal/app/render/message_tool_parse.go
Removed inline tool-result rendering from message_tool.go (−494 lines). New message_tool_inline.go provides dispatched rendering for tools/skills. New message_tool_agent.go provides specialized agent/task result rendering. New message_tool_parse.go provides parsing and formatting helpers (skill content, field extraction, label formatting, result sizing).
Message Helpers
internal/message/message.go, internal/message/message_test.go
Added LastAssistantContent and LastAssistantChatContent helpers to scan messages for most-recent non-empty assistant response. Added corresponding unit tests.
Compact Handler & Documentation
internal/app/handler_compact.go, docs/architecture-review-roadmap.md, internal/app/update_test.go
Updated handler_compact.go to use request builders and core compaction predicates. Added "Implemented In This Iteration" section to architecture roadmap documenting refactors. Added 398 lines of comprehensive update tests validating submit gating, image handling, exit request detection, selector ordering, request construction, loop assembly, modal priority, and thinking detection.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • PR #4: Implements overlapping refactoring of agent executor orchestration, selector/modal routing, runtime abstractions, tool preparation, and TUI/core reorganization.
  • PR #3: Overlaps in consolidating runtime interfaces, stream utilities, tool execution abstractions, progress hub removal, and cross-cutting refactoring patterns.

Poem

🐰 A rabbit hops through modules neat,
Where handlers split in rhythmic beat,
Tool calls now prepared with care,
Streams and selectors everywhere!
Abstract runtimes, focused files—
Code refactored with rabbit smiles! 🏃‍♂️✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately summarizes the primary refactoring work: consolidating runtime architecture and splitting selector/input modules into smaller, focused files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex-refactor

@yanmxa yanmxa merged commit 643be3b into main Apr 5, 2026
2 of 4 checks passed
@yanmxa yanmxa deleted the codex-refactor branch April 21, 2026 07:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant