Skip to content

🐛 fix: adjust historyCount calculation to include accurate user messages#13051

Merged
arvinxx merged 1 commit into
lobehub:canaryfrom
sxjeru:31777
Mar 20, 2026
Merged

🐛 fix: adjust historyCount calculation to include accurate user messages#13051
arvinxx merged 1 commit into
lobehub:canaryfrom
sxjeru:31777

Conversation

@sxjeru

@sxjeru sxjeru commented Mar 17, 2026

Copy link
Copy Markdown
Contributor

💻 Change Type

  • ✨ feat
  • 🐛 fix
  • ♻️ refactor
  • 💄 style
  • 👷 build
  • ⚡️ perf
  • ✅ test
  • 📝 docs
  • 🔨 chore

🔗 Related Issue

🔀 Description of Change

目前当附带历史消息数为 0 时,实际会携带 3 条 message ,包括 system + 最近一条 assistance + user

理论上不应该携带任何 assistance 消息才对。

包括设为 1 时会携带两条历史消息。

🧪 How to Test

  • Tested locally
  • Added/updated tests
  • No tests needed

📸 Screenshots / Videos

Before After
... ...

📝 Additional Information

Summary by Sourcery

Adjust chat history trimming logic so historyCount represents only prior messages and ensure the current user message is always included once.

Bug Fixes:

  • Correct the historyCount calculation so that a configured value of 0 no longer includes assistant history messages.
  • Fix message selection when historyCount is enabled to avoid sending extra historical exchanges beyond the configured limit.

Tests:

  • Add unit tests to verify behavior for enabled historyCount with a positive value, enabled historyCount with 0, and disabled historyCount, ensuring the correct number of messages are sent to the LLM.

Copilot AI review requested due to automatic review settings March 17, 2026 03:14
@vercel

vercel Bot commented Mar 17, 2026

Copy link
Copy Markdown

@sxjeru is attempting to deploy a commit to the LobeHub OSS Team on Vercel.

A member of the Team first needs to authorize it.

@sourcery-ai

sourcery-ai Bot commented Mar 17, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Adjusts how historyCount is interpreted so it represents only prior history messages, with the current user message added separately, and adds tests to verify correct message selection behavior under different historyCount configurations.

Sequence diagram for historyCount-based message preparation

sequenceDiagram
  actor User
  participant UI
  participant ChatService
  participant AgentRuntimeService
  participant ContextEngineering
  participant LLMProvider

  User->>UI: Submit current user message
  UI->>ChatService: createAssistantMessage(messages, model, provider, resolvedAgentConfig)
  ChatService->>ContextEngineering: buildLlmMessages(enableHistoryCount, historyCount + 1, inputTemplate, messages)
  ContextEngineering-->>ChatService: llmMessages (system date + selected history + current user)
  ChatService->>LLMProvider: getChatCompletion(llmMessages)
  LLMProvider-->>ChatService: assistant response

  User->>AgentRuntimeService: Trigger agent runtime chat
  AgentRuntimeService->>ContextEngineering: buildLlmMessages(enableHistoryCount, historyCount + 1, inputTemplate, messages)
  ContextEngineering-->>AgentRuntimeService: llmMessages (system date + selected history + current user)
  AgentRuntimeService->>LLMProvider: getChatCompletion(llmMessages)
  LLMProvider-->>AgentRuntimeService: assistant response
Loading

Class diagram for ChatService and AgentRuntimeService historyCount usage

classDiagram
  class ChatService {
    +createAssistantMessage(messages, model, provider, resolvedAgentConfig)
    +getChatCompletion(request)
  }

  class AgentRuntimeService {
    +runWithContextEngineering(dataMessages, agentStoreState, chatConfig, modelRuntimeConfig)
  }

  class ContextEngineering {
    +buildLlmMessages(enableHistoryCount, historyCount, inputTemplate, messages, modelRuntimeConfig)
  }

  ChatService --> ContextEngineering : uses historyCount_plus_1
  AgentRuntimeService --> ContextEngineering : uses historyCount_plus_1
Loading

Flow diagram for message selection with historyCount

flowchart TD
  A[Start createAssistantMessage] --> B[Add system date message]
  B --> C[Check enableHistoryCount]

  C -->|false| D[Include all user and assistant messages]
  D --> Z[Send messages to LLM]

  C -->|true| E[Read historyCount]
  E -->|0| F[Select only current user message]
  F --> Z

  E -->|>0| G[Select last historyCount user and assistant messages]
  G --> H[Append current user message]
  H --> Z[Send messages to LLM]
Loading

File-Level Changes

Change Details Files
Reinterpret historyCount as the number of prior history messages and adjust contextEngineering calls to only add the current user message on top of that count.
  • Change historyCount calculation to add 1 instead of 2 when passing to contextEngineering in the agent runtime service.
  • Update inline comments to clarify that historyCount represents history messages and that +1 accounts for the current user message.
src/services/agentRuntime/index.ts
src/services/chat/index.ts
Add unit tests to validate message selection when historyCount is enabled, zero, or disabled.
  • Add tests ensuring historyCount + 1 messages (system + last N history + current user) are sent when historyCount is enabled.
  • Add a test case to ensure only the current user message (plus system message) is sent when historyCount is 0 and enabled.
  • Add a test case verifying that all messages are sent (plus system message) when historyCount is disabled.
src/services/chat/chat.test.ts

Possibly linked issues

  • #0: PR corrects +2 to +1 in historyCount and adds tests, fixing the off‑by‑one history messages bug.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

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

Hey - I've left some high level feedback:

  • The historyCount offset logic (+ 1 for current user) is duplicated in both AgentRuntimeService and ChatService; consider extracting a shared helper or clearly centralizing this calculation so future changes don’t diverge between call sites.
  • In the new historyCount tests, before accessing getChatCompletionSpy.mock.calls[0], consider asserting that the spy was called exactly once to make the tests more robust against future internal changes.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `historyCount` offset logic (`+ 1` for current user) is duplicated in both `AgentRuntimeService` and `ChatService`; consider extracting a shared helper or clearly centralizing this calculation so future changes don’t diverge between call sites.
- In the new `historyCount` tests, before accessing `getChatCompletionSpy.mock.calls[0]`, consider asserting that the spy was called exactly once to make the tests more robust against future internal changes.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copilot AI 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.

Pull request overview

This PR fixes how historyCount is calculated when preparing messages for contextEngineering, so that a configured historyCount represents only historical messages and the request still includes the current user message (without unintentionally pulling in the last assistant message when historyCount = 0).

Changes:

  • Adjust historyCount passed into contextEngineering from + 2 to + 1 (to account for the current user message only).
  • Apply the same fix in both the main ChatService flow and the AgentRuntimeService flow.
  • Add unit tests validating message slicing behavior for enabled/disabled historyCount, including the historyCount = 0 edge case.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
src/services/chat/index.ts Fixes historyCount calculation for chat message preprocessing so 0 history doesn’t include prior assistant messages.
src/services/chat/chat.test.ts Adds tests to assert correct message count/ordering for history enabled/disabled and historyCount = 0.
src/services/agentRuntime/index.ts Keeps agent runtime behavior consistent with ChatService by applying the same historyCount + 1 logic.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@codecov

codecov Bot commented Mar 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.00000% with 1 line in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (canary@44e4f6e). Learn more about missing BASE report.

Additional details and impacted files
@@            Coverage Diff            @@
##             canary   #13051   +/-   ##
=========================================
  Coverage          ?   74.67%           
=========================================
  Files             ?     1488           
  Lines             ?   121964           
  Branches          ?    14086           
=========================================
  Hits              ?    91081           
  Misses            ?    30771           
  Partials          ?      112           
Flag Coverage Δ
app 67.93% <50.00%> (?)
database 98.14% <ø> (?)
packages/agent-runtime 88.64% <ø> (?)
packages/context-engine 84.63% <ø> (?)
packages/conversation-flow 92.37% <ø> (?)
packages/file-loaders 87.02% <ø> (?)
packages/memory-user-memory 66.61% <ø> (?)
packages/model-bank 99.84% <ø> (?)
packages/model-runtime 84.95% <ø> (?)
packages/prompts 74.60% <ø> (?)
packages/python-interpreter 92.90% <ø> (?)
packages/ssrf-safe-fetch 0.00% <ø> (?)
packages/utils 90.09% <ø> (?)
packages/web-crawler 88.81% <ø> (?)

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

Components Coverage Δ
Store 66.21% <0.00%> (?)
Services 50.04% <0.00%> (?)
Server 70.16% <0.00%> (?)
Libs 41.66% <0.00%> (?)
Utils 93.58% <0.00%> (?)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@arvinxx arvinxx merged commit 12280ba into lobehub:canary Mar 20, 2026
20 of 22 checks passed
@lobehubbot

Copy link
Copy Markdown
Member

❤️ Great PR @sxjeru ❤️

The growth of project is inseparable from user feedback and contribution, thanks for your contribution! If you are interesting with the lobehub developer community, please join our discord and then dm @arvinxx or @canisminor1990. They will invite you to our private developer channel. We are talking about the lobe-chat development or sharing ai newsletter around the world.

@sxjeru sxjeru deleted the 31777 branch March 20, 2026 14:03
ONLY-yours added a commit that referenced this pull request Mar 27, 2026
# 🚀 release: 20260326

This release includes **91 commits**. Key updates are below.


- **Agent can now execute background tasks** — Agents can perform
long-running operations without blocking your conversation.
[#13289](#13289)
- **Better error messages** — Redesigned error UI across chat and image
generation with clearer explanations and recovery options.
[#13302](#13302)
- **Smoother topic switching** — No more full page reloads when
switching topics while an agent is responding.
[#13309](#13309)
- **Faster image uploads** — Large images are now automatically
compressed to 1920px before upload, reducing wait times.
[#13224](#13224)
- **Improved knowledge base** — Documents are now properly parsed before
chunking, improving retrieval accuracy.
[#13221](#13221)

### Bot Platform

- **WeChat Bot support** — You can now connect LobeChat to WeChat, in
addition to Discord.
[#13191](#13191)
- **Richer bot responses** — Bots now support custom markdown rendering
and context injection.
[#13294](#13294)
- **New bot commands** — Added `/new` to start fresh conversations and
`/stop` to halt generation.
[#13194](#13194)
- **Discord stability fixes** — Fixed thread creation issues and Redis
connection drops.
[#13228](#13228)
[#13205](#13205)

### Models & Providers

- **GLM-5** is now available in the LobeHub model list.
[#13189](#13189)
- **Coding Plan providers** — Added support for code planning assistant
providers. [#13203](#13203)
- **Tencent Hunyuan 3.0 ImageGen** — New image generation model from
Tencent. [#13166](#13166)
- **Gemini content handling** — Better handling when Gemini blocks
content due to safety filters.
[#13270](#13270)
- **Claude token limits fixed** — Corrected max window tokens for
Anthropic Claude models.
[#13206](#13206)

### Skills & Tools

- **Auto credential injection** — Skills can now automatically request
and use required credentials.
[#13124](#13124)
- **Smarter tool permissions** — Built-in tools skip confirmation for
safe paths like `/tmp`.
[#13232](#13232)
- **Model switcher improvements** — Quick access to provider settings
and visual highlight for default model.
[#13220](#13220)

### Memory

- **Bulk delete memories** — You can now delete all memory entries at
once. [#13161](#13161)
- **Per-agent memory control** — Memory injection now respects
individual agent settings.
[#13265](#13265)

### Desktop App

- **Gateway connection** — Desktop app can now connect to LobeHub
Gateway for enhanced features.
[#13234](#13234)
- **Connection status indicator** — See gateway connection status in the
titlebar. [#13260](#13260)
- **Settings persistence** — Gateway toggle state now persists across
app restarts. [#13300](#13300)

### CLI

- **API key authentication** — CLI now supports API key auth for
programmatic access.
[#13190](#13190)
- **Shell completion** — Tab completion for bash/zsh/fish shells.
[#13164](#13164)
- **Man pages** — Built-in manual pages for CLI commands.
[#13200](#13200)

### Security

- **XSS protection** — Sanitized search result image titles to prevent
script injection.
[#13303](#13303)
- **Workflow hardening** — Fixed potential shell injection in release
automation. [#13319](#13319)
- **Dependency update** — Updated nodemailer to address security
advisory. [#13326](#13326)

### Bug Fixes

- Fixed skill page not redirecting correctly after import.
[#13255](#13255)
[#13261](#13261)
- Fixed token counting in group chats.
[#13247](#13247)
- Fixed editor not resetting when switching to empty pages.
[#13229](#13229)
- Fixed manual tool toggle not working.
[#13218](#13218)
- Fixed Search1API response parsing.
[#13207](#13207)
[#13208](#13208)
- Fixed mobile topic menus rendering issues.
[#12477](#12477)
- Fixed history count calculation for accurate context.
[#13051](#13051)
- Added missing Turkish translations.
[#13196](#13196)

### Credits

Huge thanks to these contributors:

@bakiburakogun @hardy-one @Zhouguanyang @sxjeru @hezhijie0327 @arvinxx
@cy948 @CanisMinor @Innei @lijian @lobehubbot @neko @rdmclin2
@rivertwilight @tjx666
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.

4 participants