Skip to content

fix(agent): preserve failed context#1608

Merged
zerob13 merged 2 commits into
devfrom
feat/add-failed-msg-in-context
May 11, 2026
Merged

fix(agent): preserve failed context#1608
zerob13 merged 2 commits into
devfrom
feat/add-failed-msg-in-context

Conversation

@zerob13
Copy link
Copy Markdown
Collaborator

@zerob13 zerob13 commented May 11, 2026

Summary

  • include assistant error/cancel messages in future agent context
  • convert stored error blocks into readable failure/cancel summaries
  • keep settled tool call replay and compaction history aligned with context building

Tests

  • pnpm run format
  • pnpm run i18n
  • pnpm run lint
  • pnpm exec vitest --config vitest.config.ts test/main/presenter/agentRuntimePresenter/contextBuilder.test.ts test/main/presenter/agentRuntimePresenter/compactionService.test.ts --run
  • pnpm run typecheck

Summary by CodeRabbit

  • New Features

    • Failed assistant messages and readable failure/cancellation summaries are preserved and included in subsequent turns and resume contexts.
    • History selection now consistently includes eligible assistant error records for context and compaction.
  • Documentation

    • Added spec, plan, and task docs describing failed-message context preservation and acceptance criteria.
  • Tests

    • Added focused tests covering error/cancel handling, partial assistant content, replayed tool results, and compaction behavior.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 11, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 638f58ad-8ae8-4218-adbc-a65ce37ed322

📥 Commits

Reviewing files that changed from the base of the PR and between 3bd0a52 and 74cd635.

📒 Files selected for processing (2)
  • src/main/presenter/agentRuntimePresenter/compactionService.ts
  • test/main/presenter/agentRuntimePresenter/compactionService.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/presenter/agentRuntimePresenter/compactionService.ts

📝 Walkthrough

Walkthrough

This PR preserves failed message context to help agents recover from errors. It introduces an eligibility predicate to classify context-eligible records (sent user messages and assistant error messages), formats error reasons into readable summaries, integrates these summaries into chat message conversion and compaction logic, and updates history selection across context building, compaction, and runtime components.

Changes

Failed Message Context Preservation

Layer / File(s) Summary
Planning and Specification
docs/issues/failed-message-context/plan.md, docs/issues/failed-message-context/spec.md, docs/issues/failed-message-context/tasks.md
Documents the plan for preserving failed message context, acceptance criteria, task checklist, and compatibility expectations.
Error Handling Constants and Eligibility Predicate
src/main/presenter/agentRuntimePresenter/contextBuilder.ts
Introduces UNKNOWN_ASSISTANT_ERROR and KNOWN_ERROR_REASON_TEXT constants; exports isContextHistoryRecord predicate to classify eligible context records (sent user, assistant error; excluding pending, user error).
Error Summary Formatting Utilities
src/main/presenter/agentRuntimePresenter/contextBuilder.ts
Exports normalizeAssistantErrorReason, formatAssistantErrorSummary, buildAssistantErrorSummary, and appendAssistantTextContent helpers to convert error codes to readable text and merge error summaries with existing content.
Message Record Conversion with Error Summaries
src/main/presenter/agentRuntimePresenter/contextBuilder.ts
Updates recordToChatMessages to compute error summaries from assistant blocks and record status, then append them into assistant message content (preserving reasoning as configured) and as standalone messages after tool calls.
Context Building History Selection
src/main/presenter/agentRuntimePresenter/contextBuilder.ts
Updates buildContext and buildResumeContext to filter candidate history using isContextHistoryRecord instead of status === 'sent'.
Compaction Service Error Handling and History Selection
src/main/presenter/agentRuntimePresenter/compactionService.ts
Uses isContextHistoryRecord for history filtering in prepareForNextUserTurn, prepareForResumeTurn, and prepareForContextPressureRecovery; extends serializeAssistantRecord to append formatted error summaries.
Runtime Presenter History Selection
src/main/presenter/agentRuntimePresenter/index.ts
Updates AgentRuntimePresenter.processMessage to use isContextHistoryRecord for determining historyRecords.
Compaction Service Test Coverage
test/main/presenter/agentRuntimePresenter/compactionService.test.ts
Extends test helpers (makeUserRecord, makeAssistantRecord, makeAssistantErrorRecord) and adds test cases verifying assistant error records are included in history context while user-error records are excluded.
Context Building Test Coverage
test/main/presenter/agentRuntimePresenter/contextBuilder.test.ts
Adds mock helpers and test cases verifying error records are converted into readable summaries, user-error messages filtered, partial content preserved, and settled tool calls replayed before terminal error context.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant DB as MessageStore
  participant Presenter as recordToChatMessages
  participant Formatter as formatAssistantErrorSummary
  participant Compactor as prepareCompaction
  User->>DB: prior assistant/error records persisted
  DB->>Presenter: fetch candidate records (isContextHistoryRecord)
  Presenter->>Formatter: extract & format error reasons
  Formatter-->>Presenter: formatted summary
  Presenter->>Compactor: pass history (with appended error summaries)
  Compactor-->>Presenter: compaction result / serialized assistant text
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 When agents stumble, their tales now survive—
Error-filled messages, beautifully alive!
I tuck failed lines into the next-turn song,
So future steps remember what went wrong. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.26% 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 'fix(agent): preserve failed context' directly summarizes the main objective of including assistant error and cancel messages in future agent context.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/add-failed-msg-in-context

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

@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

🤖 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/main/presenter/agentRuntimePresenter/compactionService.ts`:
- Around line 184-187: serializeAssistantRecord currently only pushes a failure
summary when formatAssistantErrorSummary(errorMessages) returns a value, causing
compaction to omit failure context for records where record.status === 'error'
but no explicit error blocks exist; update serializeAssistantRecord so that
after computing errorSummary from formatAssistantErrorSummary(errorMessages) you
check if record.status === 'error' and errorSummary is falsy, then push the same
"unknown failure" fallback used by recordToChatMessages (or construct an
equivalent assistant:error summary) into lines to keep compaction output in sync
with runtime context.
🪄 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

Run ID: 69fd93b1-d486-403c-b166-40a0fafd6dc4

📥 Commits

Reviewing files that changed from the base of the PR and between d8810fd and 3bd0a52.

📒 Files selected for processing (8)
  • docs/issues/failed-message-context/plan.md
  • docs/issues/failed-message-context/spec.md
  • docs/issues/failed-message-context/tasks.md
  • src/main/presenter/agentRuntimePresenter/compactionService.ts
  • src/main/presenter/agentRuntimePresenter/contextBuilder.ts
  • src/main/presenter/agentRuntimePresenter/index.ts
  • test/main/presenter/agentRuntimePresenter/compactionService.test.ts
  • test/main/presenter/agentRuntimePresenter/contextBuilder.test.ts

Comment thread src/main/presenter/agentRuntimePresenter/compactionService.ts
@zerob13 zerob13 merged commit 8f70338 into dev May 11, 2026
3 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

Development

Successfully merging this pull request may close these issues.

1 participant