Skip to content

Refactor core monolith helpers#27

Merged
edelauna merged 6 commits into
Zoo-Code-Org:mainfrom
doctarock:issue-8-monolith-refactor
May 19, 2026
Merged

Refactor core monolith helpers#27
edelauna merged 6 commits into
Zoo-Code-Org:mainfrom
doctarock:issue-8-monolith-refactor

Conversation

@doctarock
Copy link
Copy Markdown
Contributor

@doctarock doctarock commented May 6, 2026

Related GitHub Issue

Refs #8

Description

Extract two low-coupling pieces from the core monolith files while preserving the existing call flow:

  • Move API conversation message shaping from Task.ts into src/core/task/apiConversationHistory.ts
  • Move pending edit operation timeout/state management from ClineProvider.ts into src/core/webview/PendingEditOperationStore.ts

Task and ClineProvider keep orchestrating the same operations, but the focused logic now lives in named collaborators.

Test Procedure

  • pnpm --dir src check-types
  • pnpm --dir src exec vitest run core/task/__tests__/reasoning-preservation.test.ts core/task/__tests__/grounding-sources.test.ts core/webview/__tests__/checkpointRestoreHandler.spec.ts

Notes

This is intentionally scoped to the two extraction candidates called out in #8.

Summary by CodeRabbit

  • Refactor

    • Centralized API conversation message preparation for consistent assistant/user messages.
    • Replaced in-provider pending-edit handling with a dedicated timed pending-edit store; provider updated to use the store.
  • Bug Fixes

    • More reliable validation and rewriting of tool-result IDs and conditional conversion of tool-result content to plain text to preserve context.
  • Tests

    • Added tests for conversation message preparation and pending-edit store behavior.

Review Change Stack

@doctarock doctarock requested a review from hannesrudolph as a code owner May 6, 2026 11:04
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 6, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Extracts API conversation message construction into prepareApiConversationMessage and introduces PendingEditOperationStore for pending-edit lifecycle; Task and ClineProvider now delegate to these new modules and accompanying tests were added.

Changes

API Conversation History Extraction

Layer / File(s) Summary
Dispatcher & types
src/core/task/apiConversationHistory.ts
Adds dispatcher and module-level types/options that select assistant vs user message preparation.
Message preparation logic
src/core/task/apiConversationHistory.ts
prepareApiConversationMessage implements assistant handling (response id, encrypted reasoning, thoughtSignature, reasoning_details, protocol-aware thinking/reasoning blocks) and user handling (effective history, tool_result validation/rewriting, ts).
Content block utilities
src/core/task/apiConversationHistory.ts
prependContentBlock and appendContentBlock normalize and insert content blocks into message.content.
Task integration
src/core/task/Task.ts
addToApiConversationHistory now delegates to prepareApiConversationMessage and pushes its result into apiConversationHistory; imports the helper.
Tests
src/core/task/__tests__/apiConversationHistory.spec.ts
Vitest tests cover Anthropic vs non-Anthropic reasoning formatting, encrypted reasoning, thoughtSignature/reasoning_details, and tool_result id validation and timestamping.

Pending Edit Operation Store

Layer / File(s) Summary
Data model
src/core/webview/PendingEditOperationStore.ts
Adds PendingEditOperation, PendingEditOperationInput, and PendingEditOperationView types representing stored pending edits and internal metadata.
Store implementation
src/core/webview/PendingEditOperationStore.ts
Adds PendingEditOperationStore with set (clones images, schedules auto-clear timeout, logs), get (returns view without internal timer/createdAt and clones images), clear (cancels timeout, removes entry, logs) and clearAll.
ClineProvider integration
src/core/webview/ClineProvider.ts
Replaces in-file Map with PendingEditOperationStore member, updates imports and setPendingEditOperation signature to accept PendingEditOperationInput, and delegates get/clear/clearAll to the store.
Tests
src/core/webview/__tests__/PendingEditOperationStore.spec.ts
Vitest suite verifies overwrite behavior, auto-clear and logging, get privacy and immutability of images, clear return semantics, and clearAll timer cancellation.

Sequence Diagram(s)

sequenceDiagram
  participant Task
  participant prepareApiConversationMessage
  participant apiConversationHistory
  participant ClineProvider
  participant PendingEditOperationStore

  Task->>prepareApiConversationMessage: prepareApiConversationMessage(message, api/context)
  prepareApiConversationMessage-->>Task: ApiMessage (ts,id,content changes)
  Task->>apiConversationHistory: push ApiMessage
  ClineProvider->>PendingEditOperationStore: set(operationId, PendingEditOperationInput)
  PendingEditOperationStore-->>ClineProvider: ack (stored, timeout scheduled)
  Note over PendingEditOperationStore: timeout -> auto-clear -> log
  ClineProvider->>PendingEditOperationStore: clear/clearAll (explicit)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Poem

🐰 I stitched the messages tidy and neat,
Stored pending edits so autos don't cheat.
A hop and a nibble, code trimmed with care,
Task calls the helper, Provider keeps the share.
Hooray — logs and tests keep the burrow fair.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Refactor core monolith helpers' is vague and generic, failing to convey specific details about the extraction of API conversation message shaping and pending edit operations. Consider a more specific title like 'Extract API conversation messaging and pending edit store from core modules' to better describe the main changes.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The description covers the key implementation details, design choices, and test procedure, but is missing several required template sections including Pre-Submission Checklist, Screenshots/Videos, and Documentation Updates sections.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@edelauna edelauna left a comment

Choose a reason for hiding this comment

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

Nice - thanks for taking this on - couple comments based on some opportunities we could take with this refactor.

Comment thread src/core/webview/PendingEditOperationStore.ts
Comment thread src/core/webview/PendingEditOperationStore.ts
Comment thread src/core/task/apiConversationHistory.ts Outdated
Comment thread src/core/webview/PendingEditOperationStore.ts
Comment thread src/core/task/apiConversationHistory.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/core/task/__tests__/apiConversationHistory.spec.ts (1)

5-107: 💤 Low value

Consider adding edge case coverage.

The core paths are well tested. A few additional cases could strengthen coverage:

  • User message when last effective isn't an assistant (verifies tool_resulttext conversion on lines 112-124)
  • Anthropic protocol with reasoning but missing thoughtSignature (falls through to generic reasoning block)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/core/task/__tests__/apiConversationHistory.spec.ts` around lines 5 - 107,
Add two edge-case tests to
src/core/task/__tests__/apiConversationHistory.spec.ts for
prepareApiConversationMessage: (1) a user message containing a tool_result when
the last effective message in apiConversationHistory is not an assistant (e.g.,
it's a user or system) and assert the tool_result is converted into a text block
(type "text") and ts set to Date.now(); (2) an Anthropic apiConfiguration
(apiProvider: "anthropic") where the api object does not provide
getThoughtSignature but reasoning is present, and assert the function falls back
to emitting a generic reasoning block (e.g., { type: "reasoning", text: ... })
rather than a thinking block — reference prepareApiConversationMessage,
getThoughtSignature, tool_result and tool_use to locate the relevant logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/core/webview/PendingEditOperationStore.ts`:
- Around line 30-33: The store is saving and returning the images array by
reference which allows external mutation; when calling operations.set with
operationId and editData (and when creating timeoutId/createdAt) clone the
images array (e.g., replace editData.images with a shallow copy like
[...editData.images] or map-clone items) so the internal store holds its own
copy, and likewise when exposing stored operations (the getters that read from
this.operations) return copies of the images array instead of the original
reference so callers cannot mutate internal state; update the set/save path and
the accessors that return stored operation objects to perform these copies for
the images field.

---

Nitpick comments:
In `@src/core/task/__tests__/apiConversationHistory.spec.ts`:
- Around line 5-107: Add two edge-case tests to
src/core/task/__tests__/apiConversationHistory.spec.ts for
prepareApiConversationMessage: (1) a user message containing a tool_result when
the last effective message in apiConversationHistory is not an assistant (e.g.,
it's a user or system) and assert the tool_result is converted into a text block
(type "text") and ts set to Date.now(); (2) an Anthropic apiConfiguration
(apiProvider: "anthropic") where the api object does not provide
getThoughtSignature but reasoning is present, and assert the function falls back
to emitting a generic reasoning block (e.g., { type: "reasoning", text: ... })
rather than a thinking block — reference prepareApiConversationMessage,
getThoughtSignature, tool_result and tool_use to locate the relevant logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 13150e62-f799-489b-9392-bccec80d5314

📥 Commits

Reviewing files that changed from the base of the PR and between 498a691 and 9da86b1.

📒 Files selected for processing (4)
  • src/core/task/__tests__/apiConversationHistory.spec.ts
  • src/core/task/apiConversationHistory.ts
  • src/core/webview/PendingEditOperationStore.ts
  • src/core/webview/__tests__/PendingEditOperationStore.spec.ts
✅ Files skipped from review due to trivial changes (1)
  • src/core/webview/tests/PendingEditOperationStore.spec.ts

Comment thread src/core/webview/PendingEditOperationStore.ts
Comment thread src/core/task/apiConversationHistory.ts
@doctarock
Copy link
Copy Markdown
Contributor Author

Addressed the reasoning payload-shape comment in 3ecf73d02 by choosing the behavior-preserving path: plain-text reasoning blocks now include summary: [] again, matching the old Task.ts wire shape.

Validation: corepack pnpm --dir src exec vitest run core/task/__tests__/apiConversationHistory.spec.ts passed.

Copy link
Copy Markdown
Contributor

@edelauna edelauna left a comment

Choose a reason for hiding this comment

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

🚀 this is a good start, thanks for taking this on - ci should pass once you merge in the updates

@codecov
Copy link
Copy Markdown

codecov Bot commented May 9, 2026

Codecov Report

❌ Patch coverage is 91.84783% with 15 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/core/task/apiConversationHistory.ts 90.09% 11 Missing ⚠️
src/core/webview/ClineProvider.ts 83.33% 2 Missing ⚠️
src/core/webview/PendingEditOperationStore.ts 96.07% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@edelauna
Copy link
Copy Markdown
Contributor

@doctarock if you can get this merged - then I dont have to manually approve workflow runs for your PRs since you'll no longer be a first time contributor.

Copy link
Copy Markdown
Contributor

@edelauna edelauna left a comment

Choose a reason for hiding this comment

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

Merge #68 into this one.

@edelauna edelauna force-pushed the issue-8-monolith-refactor branch from 5cbe5b2 to 1f5bbb4 Compare May 18, 2026 15:14
Copy link
Copy Markdown
Contributor

@edelauna edelauna left a comment

Choose a reason for hiding this comment

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

Thanks for adding the commit - on re-review had one followup comment.

getResponseId?: () => string | undefined
getEncryptedContent?: () => { encrypted_content: string; id?: string } | undefined
getThoughtSignature?: () => string | undefined
getReasoningDetails?: () => any[] | undefined
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The original Task.ts code called handler.getSummary?.() and fell back to [] — was that method intentionally dropped here because no handler ever returns a non-empty summary? If so, might be worth a brief comment so a future reader knows it was deliberate rather than an accidental omission.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

getSummary was intentionally omitted because no provider implements it and the preserved wire shape is the explicit summary: [] fallback, it does deserve a comment though

@edelauna edelauna added the good first issue Good for newcomers label May 18, 2026
@edelauna edelauna force-pushed the issue-8-monolith-refactor branch from 24574f4 to e9453bf Compare May 19, 2026 13:04
Copy link
Copy Markdown
Contributor

@edelauna edelauna left a comment

Choose a reason for hiding this comment

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

Thanks for doing this, and also documenting it out via issues.

@edelauna edelauna merged commit 7245680 into Zoo-Code-Org:main May 19, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

good first issue Good for newcomers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants