Skip to content

fix(claude): stop counting base64 attachments as raw characters in token estimates - #983

Open
DevMello wants to merge 3 commits into
lidge-jun:devfrom
DevMello:fix/count-tokens-attachments
Open

fix(claude): stop counting base64 attachments as raw characters in token estimates#983
DevMello wants to merge 3 commits into
lidge-jun:devfrom
DevMello:fix/count-tokens-attachments

Conversation

@DevMello

@DevMello DevMello commented Aug 4, 2026

Copy link
Copy Markdown

Summary

  • count_tokens estimated base64 attachments as raw characters: a 2MB pasted screenshot reported ~680k input tokens instead of a real cost around 1.6k.
  • Attachment sources are now priced per attachment (sniffed pixel dimensions / 750, else decoded bytes / 512, min 256) at both the count_tokens endpoint and the cursor/kiro usage-log floor. Text-only bodies estimate exactly as before.

Verification

  • bun run typecheck && bun run lint:gui && bun run test && bun run privacy:scan
  • 5 new tests: endpoint bound for a 512KB image, PNG dimension pricing, tool_result nesting, text-only and text-document parity.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed.
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.

Summary by CodeRabbit

  • Improvements

    • Improved token estimates for image and document attachments, including base64-encoded content.
    • Image dimensions and document types now contribute more accurately to token counts.
    • Usage reporting and token-count results are more consistent for multimodal requests.
    • Text-only requests continue to use existing token estimation behavior.
  • Bug Fixes

    • Prevented encoded attachments from inflating token counts based solely on encoded character length.
    • Corrected handling of base64 padding and nested document attachments.
    • Preserved accurate counting for text content, tool inputs, and schemas.

@github-actions github-actions Bot added the bug Something isn't working label Aug 4, 2026
@coderabbitai

coderabbitai Bot commented Aug 4, 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: ASSERTIVE

Plan: Pro Plus

Run ID: 6bf02d5a-4821-4467-a69e-a2576b882fbc

📥 Commits

Reviewing files that changed from the base of the PR and between 3b78fdd and 1ad2be0.

📒 Files selected for processing (2)
  • src/server/claude-messages.ts
  • tests/claude-messages-endpoint.test.ts

📝 Walkthrough

Walkthrough

Claude request token estimation now treats base64 image and document attachments as bounded data. It uses image dimensions or decoded byte size. Ordinary text remains character-estimated. Routed usage logging and /count_tokens use the new estimator.

Changes

Claude token estimation

Layer / File(s) Summary
Attachment-aware estimator and integrations
src/server/claude-messages.ts
estimateClaudeRequestTokens separates base64 attachments from serialized text. Image attachments use sniffImageDimensions; other attachments use decoded byte size. Nested tool_result.content is handled recursively. Routed usage logging and /count_tokens use the estimator.
Estimator behavior coverage
tests/claude-messages-endpoint.test.ts
Tests cover bounded image estimates, dimension-based pricing, nested PDF data, base64 padding, tool_use.input, tool schemas, text documents, and text-only parity with estimateTokens. A helper creates dimensioned PNG data.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CountTokens as /count_tokens
  participant UsageLogging as Routed usage logging
  participant Estimator as estimateClaudeRequestTokens
  participant ImageSniffer as sniffImageDimensions
  participant TextEstimator as estimateTokens
  CountTokens->>Estimator: request content and modelId
  UsageLogging->>Estimator: system, messages, tools, and modelId
  Estimator->>ImageSniffer: inspect base64 image data
  ImageSniffer-->>Estimator: image dimensions
  Estimator->>TextEstimator: estimate text and adjusted content
  TextEstimator-->>Estimator: token estimate
  Estimator-->>CountTokens: estimated token count
  Estimator-->>UsageLogging: estimated token count
Loading

Possibly related PRs

Suggested reviewers: ingwannu, wibias, lidge-jun

🚥 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 clearly and concisely describes the main change: excluding base64 attachments from raw-character token estimates.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@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.

Actionable comments posted: 1

🤖 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/server/claude-messages.ts`:
- Line 869: Update the decoded-size calculation in the attachment token
estimator to remove trailing base64 padding characters before converting encoded
length to bytes, so a padded 131,072-byte payload estimates 256 tokens. Add a
focused regression test alongside the existing attachment-related tests covering
that exact padded payload and expected token count.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 3c7b18fa-fd1d-4eac-a461-619c523d1e12

📥 Commits

Reviewing files that changed from the base of the PR and between 5d2973c and a6dc37a.

📒 Files selected for processing (2)
  • src/server/claude-messages.ts
  • tests/claude-messages-endpoint.test.ts

Comment thread src/server/claude-messages.ts Outdated

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a6dc37aee0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/claude-messages.ts Outdated
Comment on lines +890 to +892
if (source.type === "base64" && typeof source.data === "string") {
attachmentTokens += estimateBase64AttachmentTokens(source.data);
return { ...(entry as Record<string, unknown>), data: "" };

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restrict stripping to attachment source objects

When a Claude history contains an assistant tool_use.input (or another non-attachment JSON object) with fields like {type: "base64", data: "..."}, this branch treats it as an image/document source and removes the string from the estimate. The translator later serializes tool_use.input as function_call arguments, so that base64 text is still sent to routed providers; count_tokens and the cursor/kiro usage-log floor can therefore undercount large tool arguments by orders of magnitude. Limit the special handling to actual Anthropic attachment source objects under image/document blocks.

Useful? React with 👍 / 👎.

@Wibias
Wibias marked this pull request as draft August 4, 2026 04:48
@DevMello
DevMello marked this pull request as ready for review August 4, 2026 05:44

@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.

Actionable comments posted: 1

🤖 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/server/claude-messages.ts`:
- Around line 892-902: Restrict the attachment-processing logic around the
visible image/document branch to Claude protocol content-block containers,
including nested tool_result.content, and do not recurse into arbitrary
tool_use.input values. Preserve attachment token estimation and data redaction
only for genuine content blocks. Add a focused regression test alongside the
existing claude-messages tests using a complete attachment-shaped object in
tool_use.input and assert it uses the normal serialized-text estimate.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: d5dd6c5c-bb5c-4215-976e-73d0bf1bcd15

📥 Commits

Reviewing files that changed from the base of the PR and between a6dc37a and 3b78fdd.

📒 Files selected for processing (2)
  • src/server/claude-messages.ts
  • tests/claude-messages-endpoint.test.ts

Comment thread src/server/claude-messages.ts Outdated

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3b78fddf6b

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/server/claude-messages.ts Outdated
Comment on lines +894 to +897
if (block.type === "image" || block.type === "document") {
const source = block.source as { type?: unknown; data?: unknown } | undefined;
if (source && typeof source === "object" && source.type === "base64" && typeof source.data === "string") {
attachmentTokens += estimateBase64AttachmentTokens(source.data);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve attachment-shaped tool-use arguments

With an assistant tool_use.input that contains an object shaped like {type:"image", source:{type:"base64", data:"..."}} (or the same shape inside a tool schema/example), this global replacer still strips the payload and charges the bounded attachment estimate. Those objects are not Anthropic content attachments: assistantMessageToItems serializes tool_use.input into function_call.arguments, and toolsToResponses forwards tool schemas, so the base64 text is still replayed to routed providers. The fresh code still walks the whole messages/tools trees without tracking whether the match is actually inside message/tool_result content, so /count_tokens and the cursor/kiro usage-log floor can undercount large tool arguments by orders of magnitude.

Useful? React with 👍 / 👎.

@DevMello
DevMello marked this pull request as draft August 4, 2026 06:12
@DevMello
DevMello marked this pull request as ready for review August 4, 2026 06:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant