Skip to content

Compact oversized chat context for provider windows - #1280

Merged
i386 merged 5 commits into
mainfrom
agent/console-context-compaction
Aug 24, 2026
Merged

Compact oversized chat context for provider windows#1280
i386 merged 5 commits into
mainfrom
agent/console-context-compaction

Conversation

@i386

@i386 i386 commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

Summary

Apple system models expose a 4096-token context window. The console can send a persisted conversation plus its system prompt that exceeds that window, causing the router to reject the request before it reaches the Apple sidecar with:

no context-compatible target for model 'apple/system' can fit approximately ... tokens

This PR adds one targeted recovery path:

  • Detect only the context-specific 503 response.
  • Retry once with the newest conversation turns that fit a conservative serialized-request budget.
  • Keep the full conversation visible locally; only the retry payload is compacted.
  • Leave unrelated 503 responses unchanged.

Follow-up to #1277.

Validation

  • pnpm exec prettier --check src/features/chat/api/mesh-connection.ts src/features/chat/api/mesh-connection.test.ts
  • pnpm exec vitest run src/features/chat/api/mesh-connection.test.ts (14 passed)
  • pnpm exec tsc -b --pretty false
  • git diff --check

Notes

This is intentionally a separate PR from the model-route retry change. It addresses the 503 context-admission failure observed with apple/system and applies to any provider reporting the same router error.

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of oversized conversations by retrying with progressively compacted input when no compatible context is available.
    • Preserves the latest conversation turn while removing older content as needed to meet request size limits.
    • Supports multibyte text within the configured 14,000-byte limit.
    • Reuses uploaded attachments during retries to avoid unnecessary re-uploads.
    • Continues streaming responses when retries succeed and retains existing retry behavior for other temporary connection issues.

@coderabbitai

coderabbitai Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3262cd19-1729-44de-88fa-d266ade636af

📥 Commits

Reviewing files that changed from the base of the PR and between 6dd1e01 and 0cff72b.

📒 Files selected for processing (3)
  • crates/mesh-llm-ui/src/features/chat/api/build-input.ts
  • crates/mesh-llm-ui/src/features/chat/api/mesh-connection.test.ts
  • crates/mesh-llm-ui/src/features/chat/api/mesh-connection.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/mesh-llm-ui/src/features/chat/api/mesh-connection.test.ts
  • crates/mesh-llm-ui/src/features/chat/api/mesh-connection.ts

Included review availability: Your plan includes up to 8 reviews per rolling hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The chat request pipeline caches attachment uploads, detects matching context-route 503 responses, compacts conversations to 14,000 UTF-8 bytes, and retries once. Tests cover turn retention, multibyte text, streaming, and attachment token reuse.

Changes

Context compaction and attachment reuse

Layer / File(s) Summary
Attachment upload cache
crates/mesh-llm-ui/src/features/chat/api/build-input.ts
Input builders share an attachment upload cache. Matching data sources reuse completed or in-flight uploads. Failed uploads are removed from the cache.
Compacted request construction
crates/mesh-llm-ui/src/features/chat/api/mesh-connection.ts
The client detects matching context-route 503 responses and builds a request from recent user-started message subsets under 14,000 UTF-8 bytes.
Retry handling and recovery validation
crates/mesh-llm-ui/src/features/chat/api/mesh-connection.ts, crates/mesh-llm-ui/src/features/chat/api/mesh-connection.test.ts
The client performs one context-compaction retry while retaining existing model-route retry handling. Tests verify turn retention, byte limits, streamed output, and attachment token reuse.

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

Merge Risk: ⚪ Minimal · up to 0cff7

The PR adds a targeted context-compaction retry while preserving the full local conversation and leaving unrelated failures unchanged; no actionable merge-blocking risk remains after normal checks and review.

Sequence Diagram(s)

sequenceDiagram
  participant MeshConnection
  participant InputBuilder
  participant ContextRoute
  participant StreamConsumer
  MeshConnection->>InputBuilder: Build request with shared attachment cache
  InputBuilder-->>MeshConnection: Return Responses input
  MeshConnection->>ContextRoute: Send conversation request
  ContextRoute-->>MeshConnection: Return 503 context-route rejection
  MeshConnection->>MeshConnection: Build compacted request
  MeshConnection->>ContextRoute: Retry with compacted request
  ContextRoute-->>StreamConsumer: Stream response
Loading

Possibly related PRs

  • Mesh-LLM/mesh-llm#1277: Both changes modify mesh-connection.ts and its tests to handle one-time retries for specific HTTP errors.

Suggested reviewers: michaelneale, ndizazzo

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

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.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: compacting oversized chat context for provider context-window limits.
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 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch agent/console-context-compaction

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.

@coderabbitai coderabbitai Bot left a comment

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.

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 `@crates/mesh-llm-ui/src/features/chat/api/mesh-connection.ts`:
- Around line 111-112: Update the retry-body size check in the
buildResponsesInput flow to measure the UTF-8 byte length of the serialized
candidate, not JSON.stringify(candidate).length, before accepting it. Add a
regression test using multibyte text and assert the compacted serialized body is
at most CONTEXT_COMPACTION_RETRY_BODY_BYTES (14,000 bytes).
🪄 Autofix

✅ Autofix completed


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3c737881-9972-4ecb-bbea-adabece54ce5

📥 Commits

Reviewing files that changed from the base of the PR and between 767edfb and ffdeb3e.

📒 Files selected for processing (2)
  • crates/mesh-llm-ui/src/features/chat/api/mesh-connection.test.ts
  • crates/mesh-llm-ui/src/features/chat/api/mesh-connection.ts

Comment thread crates/mesh-llm-ui/src/features/chat/api/mesh-connection.ts Outdated
@coderabbitai

coderabbitai Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Fixes Applied Successfully

Fixed 2 file(s) based on 1 unresolved review comment.

Files modified:

  • crates/mesh-llm-ui/src/features/chat/api/mesh-connection.test.ts
  • crates/mesh-llm-ui/src/features/chat/api/mesh-connection.ts

Commit: 6d65a846eaf3603a231a4a9ddcdab63861760a18

The changes have been pushed to the agent/console-context-compaction branch.

Time taken: 4m 41s

Fixed 2 file(s) based on 1 unresolved review comment.

Co-authored-by: CodeRabbit <noreply@coderabbit.ai>

@ndizazzo ndizazzo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for keeping this recovery path narrowly scoped. The error matching and UTF-8 measurement are heading in the right direction, but I found three cases that need addressing before this is safe to merge: the new multibyte test currently fails, candidate construction can repeat attachment uploads, and compaction can split a user/assistant turn. I reproduced the focused test failure locally (1 failed, 14 passed); typecheck and the production build both pass.

Comment thread crates/mesh-llm-ui/src/features/chat/api/mesh-connection.ts
Comment thread crates/mesh-llm-ui/src/features/chat/api/mesh-connection.ts Outdated
Comment thread crates/mesh-llm-ui/src/features/chat/api/mesh-connection.test.ts Outdated
@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@i386

i386 commented Aug 18, 2026

Copy link
Copy Markdown
Collaborator Author

@ndizazzo this is ready

@ndizazzo
ndizazzo self-requested a review August 18, 2026 08:28

@ndizazzo ndizazzo left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-reviewed after the latest commits (6dd1e01, 0cff72b). All three change requests from my prior review are addressed:

  • Turn-boundary split: compactResponsesInput now only starts a candidate at a role: 'user' message, so a retry can no longer detach an assistant reply from the user turn that produced it.
  • Repeated attachment uploads: buildResponsesInput now threads a shared AttachmentUploadCache through all compaction probes and the final selected candidate, keyed by mime type + filename + base64 value, with cache eviction on upload failure. A new test asserts /api/objects is called exactly once across the probe-and-retry flow.
  • Failing multibyte fixture: scaled down so one retained turn fits the 14 KB budget while the full history still exceeds it, still exercising UTF-8 vs UTF-16 measurement.

Verified locally on the PR head (0cff72b):

  • pnpm exec vitest run src/features/chat/api/mesh-connection.test.ts → 19/19 passing (was 1 failing/14 passing)
  • pnpm exec tsc -b --pretty false → clean
  • pnpm exec prettier --check on the touched files → clean

Resolved the three addressed threads. No further issues found — approving.

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has not been updated in at least 5 days. It will be closed after 7 days of inactivity to keep the active review queue current. Please update it within 2 days if the changes are still moving forward.

@github-actions github-actions Bot added the stale label Aug 24, 2026
@i386
i386 merged commit 7d14945 into main Aug 24, 2026
45 checks passed
@i386
i386 deleted the agent/console-context-compaction branch August 24, 2026 06:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants