Skip to content

fix: correlate tool calls by the SDK's toolUseID and keep subagent text out of canonical history - #118

Merged
saucam merged 2 commits into
mainfrom
fix/tool-correlation-canonical-history
Jul 6, 2026
Merged

fix: correlate tool calls by the SDK's toolUseID and keep subagent text out of canonical history#118
saucam merged 2 commits into
mainfrom
fix/tool-correlation-canonical-history

Conversation

@saucam

@saucam saucam commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

Summary

Fixes the two High-severity provider-layer correctness bugs from the July audit — both in the Claude provider's event pipeline, so they ship as one PR.

#81 — PreToolUse↔canUseTool FIFO desync

canUseTool reconstructed the tool_use_id by popping a name-keyed FIFO that the PreToolUse hook pushed for every tool call. The SDK skips canUseTool for auto-allowed tools (allowedTools, project permissions.allow), so any allow rule left a stale queue head. The next gated call popped the wrong entry, mis-correlating every later tool call in the session (tool_start with the wrong sdkToolUseId → orphaned tool_complete → tools stuck "running" forever, output attached to the wrong message). Entries for always-allowed tools were never popped, so the map also grew unboundedly.

The SDK passes the real toolUseID (and agentID) directly to canUseTool — this PR uses those and deletes the FIFO entirely. No queue, no desync, no unbounded growth.

#82 — cross-provider canonical history corruption

Two halves:

  • Subagent assistant text was emitted indistinguishably from primary text, so it streamed into the primary assistant message and into the canonical history (a subagent text_done could even clobber the primary message mid-stream).
  • CanonicalHistoryAccumulator assigned each text_done, so a normal agentic turn (text → tool → text → final text) kept only the last block — all interleaved reasoning vanished from the history handed to the next provider on a model switch.

Text/thinking ProviderEvents now carry parentToolUseId (from the SDK's parent_tool_use_id). Session and the accumulator drop non-primary text/thinking, and text_done blocks append across the turn (reset at turn boundaries). The subagent's work still surfaces via its tool_call messages and the spawning Task tool's result.

Tests

  • provider-claude.test.ts: canUseTool correlates by the SDK-provided id; regression repro for fix: PreToolUse↔canUseTool FIFO desync corrupts tool-call correlation when tools are auto-allowed #81 (auto-allowed PreToolUse followed by a gated call of the same tool name correlates to its own id); deny when no toolUseID; translate-layer tagging for assistant + stream_event messages (primary and subagent).
  • provider-switch.test.ts: interleaved text → tool → text concatenates; subagent text/thinking dropped from canonical history; accumulation resets across turns.
  • session-stream-commit.test.ts (C8): subagent text_delta/text_done/thinking mid-stream never touch the primary message, thinking stream, or scrollback.

bun x tsc --noEmit ✅ · bun run lint ✅ · bun run test 1018 pass / 0 fail ✅

Fixes #81
Fixes #82

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Preserved multiple assistant text segments within a single turn by appending consecutive text_done content instead of overwriting.
    • Prevented subagent text and thinking from being included in the primary conversation stream or replay history during/after streaming.
    • Improved tool-call matching and correlation so tool starts align with the correct SDK tool/agent identifiers, even with interleaved calls.
  • Tests
    • Added regression coverage for subagent isolation, turn-to-turn canonical history reset, and tool-call correlation (including gated vs auto-allowed scenarios).

…xt out of canonical history

Two related provider-layer correctness bugs:

1. Tool-call correlation (#81): canUseTool reconstructed the tool_use_id
   from a name-keyed FIFO fed by the PreToolUse hook. The SDK skips
   canUseTool for auto-allowed tools (allowedTools / project
   permissions.allow), so any allow rule left a stale queue head that the
   next gated call popped — mis-correlating every subsequent tool call —
   and entries for always-allowed tools grew the map unboundedly. The SDK
   passes the real toolUseID (and agentID) to canUseTool directly; use
   them and delete the FIFO entirely.

2. Canonical history corruption (#82): subagent assistant text was
   emitted as primary text, and CanonicalHistoryAccumulator assigned each
   text_done, keeping only the last block of a turn. Text/thinking
   provider events now carry parentToolUseId; Session and the accumulator
   drop non-primary text, and text_done blocks append across a turn so
   interleaved commentary (text → tool → text) survives provider
   switches.

Fixes #81
Fixes #82

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 897a0fd8-ad10-4495-b532-9aba8e07b170

📥 Commits

Reviewing files that changed from the base of the PR and between c3107ae and b887fc2.

📒 Files selected for processing (3)
  • src/daemon/providers/canonical.ts
  • src/daemon/providers/interface.ts
  • src/daemon/session.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/daemon/session.ts
  • src/daemon/providers/canonical.ts

📝 Walkthrough

Walkthrough

Claude tool-call correlation now uses SDK identifiers directly, and provider events carry subagent correlation metadata. Canonical history and session streaming now ignore subagent text/thinking while preserving multi-segment assistant text, with expanded tests covering the new behavior.

Changes

Subagent/tool correlation and history isolation

Layer / File(s) Summary
Provider event correlation fields
src/daemon/providers/interface.ts
text_delta, text_done, thinking_delta, and thinking_done gain optional parentToolUseId; isSubagentEvent ઓળખs non-primary text/thinking events.
ClaudeProvider tool correlation
src/daemon/providers/claude/index.ts
Removes #pendingToolUse, stops queueing in PreToolUse, correlates canUseTool with SDK toolUseID/agentID, and tags translated assistant stream events with parentToolUseId.
Canonical and session filtering
src/daemon/providers/canonical.ts, src/daemon/session.ts
Canonical history skips subagent events and appends repeated text_done blocks; session event handling returns early for subagent output before stream commit.
Regression coverage
src/tests/provider-claude.test.ts, src/tests/provider-switch.test.ts, src/tests/session-stream-commit.test.ts
Tests cover SDK gating, parentToolUseId translation, tool correlation regressions, canonical accumulation, and subagent replay isolation.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • saucam/codeoid#38: Related provider/event and canonical-history changes in the same subagent isolation flow.
  • saucam/codeoid#74: Related session replay handling and scrollback commit behavior around streamed assistant events.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately summarizes the tool-correlation and subagent-history fixes.
Linked Issues check ✅ Passed The PR addresses #81 by using SDK toolUseID/agentID and #82 by filtering subagent events and appending text blocks.
Out of Scope Changes check ✅ Passed The changes and tests stay within the two linked fixes; no unrelated scope is evident.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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 fix/tool-correlation-canonical-history

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


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

@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 77.49%. Comparing base (b2fb7e0) to head (b887fc2).
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #118      +/-   ##
==========================================
+ Coverage   77.47%   77.49%   +0.01%     
==========================================
  Files          85       86       +1     
  Lines       13396    13403       +7     
==========================================
+ Hits        10379    10386       +7     
  Misses       3017     3017              
Flag Coverage Δ
daemon 77.49% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/daemon/providers/canonical.ts 100.00% <100.00%> (ø)
src/daemon/providers/claude/index.ts 97.32% <100.00%> (-0.04%) ⬇️
src/daemon/providers/interface.ts 100.00% <100.00%> (ø)
src/daemon/session.ts 75.68% <100.00%> (+0.03%) ⬆️
🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/daemon/providers/canonical.ts (1)

268-284: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Subagent filter duplicated across canonical.ts and session.ts.

Both CanonicalHistoryAccumulator.handleEvent and Session#handleProviderEvent independently re-implement event.parentToolUseId != null to drop subagent text/thinking. Since Session already filters these events before they ever reach #accumulator.handleEvent (per src/daemon/session.ts lines 2009-2015), the check here exists purely to protect standalone callers (e.g. provider-switch.test.ts). Consider extracting a shared isSubagentEvent(event) helper (or a parentToolUseId type guard) so both call sites can't drift independently as more subagent-aware event types are added.

🤖 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/daemon/providers/canonical.ts` around lines 268 - 284, The subagent-event
filtering logic is duplicated in CanonicalHistoryAccumulator.handleEvent and
Session#handleProviderEvent, both checking event.parentToolUseId != null
separately. Extract a shared helper such as isSubagentEvent(event) or a
parentToolUseId type guard in canonical.ts/session.ts and use it from both call
sites so the filtering stays consistent for text_done, thinking_delta, and any
future subagent-aware event types, while preserving the standalone accumulator
behavior used by tests like provider-switch.test.ts.
🤖 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.

Nitpick comments:
In `@src/daemon/providers/canonical.ts`:
- Around line 268-284: The subagent-event filtering logic is duplicated in
CanonicalHistoryAccumulator.handleEvent and Session#handleProviderEvent, both
checking event.parentToolUseId != null separately. Extract a shared helper such
as isSubagentEvent(event) or a parentToolUseId type guard in
canonical.ts/session.ts and use it from both call sites so the filtering stays
consistent for text_done, thinking_delta, and any future subagent-aware event
types, while preserving the standalone accumulator behavior used by tests like
provider-switch.test.ts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 50a2561d-6d11-48a1-96b1-09f307dd23d4

📥 Commits

Reviewing files that changed from the base of the PR and between b2fb7e0 and c3107ae.

📒 Files selected for processing (7)
  • src/daemon/providers/canonical.ts
  • src/daemon/providers/claude/index.ts
  • src/daemon/providers/interface.ts
  • src/daemon/session.ts
  • src/tests/provider-claude.test.ts
  • src/tests/provider-switch.test.ts
  • src/tests/session-stream-commit.test.ts

The subagent text/thinking filter was re-implemented in both
CanonicalHistoryAccumulator.handleEvent and Session#handleProviderEvent.
Centralize it as isSubagentEvent in providers/interface.ts so the two
call sites can't drift as new subagent-aware event types are added.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@saucam
saucam merged commit 9b1db68 into main Jul 6, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant