Skip to content

fix: prevent ClassCastException in RestAI chat when making consecutive requests#1819

Open
octo-patch wants to merge 1 commit intoCodePhiliaX:mainfrom
octo-patch:fix/issue-1796-1812-restai-cache-classcastexception
Open

fix: prevent ClassCastException in RestAI chat when making consecutive requests#1819
octo-patch wants to merge 1 commit intoCodePhiliaX:mainfrom
octo-patch:fix/issue-1796-1812-restai-cache-classcastexception

Conversation

@octo-patch
Copy link
Copy Markdown

Fixes #1796
Fixes #1812

Problem

When using a custom REST AI provider (chatWithRestAi), making two consecutive
requests to /api/ai/chat causes a ClassCastException and a 500 error on the
second request. Refreshing the page (which generates a new uid) restores
functionality temporarily.

Root cause: chatWithRestAi stores the message history as a JSON string via
JSONUtil.toJsonStr(messages), but getFastChatMessage() later retrieves that
value and casts it directly to List<FastChatMessage>. The cast succeeds on the
first call (cache miss → empty list created), but fails with ClassCastException
on every subsequent call when the cached JSON string is retrieved.

Stack trace from #1796:

java.lang.ClassCastException: class java.lang.String cannot be cast to class java.util.List
    at ai.chat2db.server.web.api.controller.ai.ChatController.getFastChatMessage(ChatController.java:465)
    at ai.chat2db.server.web.api.controller.ai.ChatController.chatWithRestAi(ChatController.java:266)

Solution

  1. Store the List<FastChatMessage> object directly in the cache (removing the
    JSONUtil.toJsonStr() call), consistent with all other AI provider methods.
  2. Add a defensive instanceof List check in getFastChatMessage to avoid
    unchecked casts and handle any stale cache entries gracefully.

Testing

  • Verified the cache write and read types are now consistent for the RestAI path.
  • The instanceof guard ensures stale entries (from previous deployments) fall
    back to a fresh empty list instead of crashing.

…tion (fixes CodePhiliaX#1796, CodePhiliaX#1812)

chatWithRestAi was storing messages as a JSON string via JSONUtil.toJsonStr()
but getFastChatMessage() cast the cached value directly to List<FastChatMessage>.
On the second consecutive request the cast threw a ClassCastException causing a
500 error. Fix: store the List object directly, consistent with other AI providers.
Also add instanceof guard in getFastChatMessage for defensive type safety.

Co-Authored-By: Octopus <liyuan851277048@icloud.com>
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