Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

fix: add Array.isArray() validation in favoriteTopic to prevent TypeError (#12188)

Varun Chawla3d99e7ed774a
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 8c923b558fd..fc493c55cfd 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -262,6 +262,196 @@ describe('topic action', () => {
expect(updateFavoriteSpy).toHaveBeenCalledWith(topicId, { favorite: favState });
expect(refreshTopicSpy).toHaveBeenCalled();
});
+
+ // Regression tests for issue #12072
+ it('should handle non-array groups in SWR cache without throwing TypeError', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const topicId = 'topic-id';
+ const favState = true;
+ const activeAgentId = 'test-agent';
+
+ await act(async () => {
+ useChatStore.setState({ activeAgentId });
+ });
+
+ const updateFavoriteSpy = vi
+ .spyOn(topicService, 'updateTopic')
+ .mockResolvedValue(undefined as any);
+
+ // Mock mutate to receive a non-array value (malformed cache)
+ (mutate as Mock).mockImplementation(async (_key, updateFn) => {
+ if (typeof updateFn === 'function') {
+ // Pass non-array values to test defensive checks
+ const testCases = [
+ null,
+ undefined,
+ 'string-instead-of-array',
+ { wrongStructure: true },
+ 42,
+ ];
+
+ for (const malformedData of testCases) {
+ const result = updateFn(malformedData);
+ // Should return the malformed data as-is without throwing
+ expect(result).toBe(malformedData);
+ }
+ }
+ });
+
+ // Should not throw TypeError when cache has malformed data
+ await act(async () => {
+ await expect(result.current.favoriteTopic(topicId, favState)).resolves.not.toThrow();
+ });
+
+ expect(updateFavoriteSpy).toHaveBeenCalledWith(topicId, { favorite: favState });
+ });
+
+ it('should handle groups with non-array topics field without throwing TypeError', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const topicId = 'topic-id';
+ const favState = true;
+ const activeAgentId = 'test-agent';
+
+ await act(async () => {
+ useChatStore.setState({ activeAgentId });
+ });
+
+ const updateFavoriteSpy = vi
+ .spyOn(topicService, 'updateTopic')
+ .mockResolvedValue(undefined as any);
+
+ // Mock mutate to test groups with malformed topics field
+ (mutate as Mock).mockImplementation(async (_key, updateFn) => {
+ if (typeof updateFn === 'function') {
+ // Test groups where topics is not an array
+ const malformedGroups = [
+ {
+ cronJob: {},
+ cronJobId: 'job-1',
+ topics: null, // topics is null
+ },
+ {
+ cronJob: {},
+ cronJobId: 'job-2',
+ topics: undefined, // topics is undefined
+ },
+ {
+ cronJob: {},
+ cronJobId: 'job-3',
+ topics: 'not-an-array', // topics is a string
+ },
+ {
+ cronJob: {},
+ cronJobId: 'job-4',
+ topics: { id: 'malformed' }, // topics is an object
+ },
+ ];
+
+ const result = updateFn(malformedGroups);
+
+ // When no topic matches, the function returns original groups unchanged
+ // The important thing is it doesn't throw a TypeError on .map()
+ expect(result).toBe(malformedGroups);
+ }
+ });
+
+ // Should not throw TypeError when groups have malformed topics
+ await act(async () => {
+ await expect(result.current.favoriteTopic(topicId, favState)).resolves.not.toThrow();
+ });
+
+ expect(updateFavoriteSpy).toHaveBeenCalledWith(topicId, { favorite: favState });
+ });
+
+ it('should correctly update favorite state in well-formed cache data', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const topicId = 'topic-to-favorite';
+ const favState = true;
+ const activeAgentId = 'test-agent';
+
+ await act(async () => {
+ useChatStore.setState({ activeAgentId });
+ });
+
+ const updateFavoriteSpy = vi
+ .spyOn(topicService, 'updateTopic')
+ .mockResolvedValue(undefined as any);
+
+ // Mock mutate to test correct behavior with well-formed data
+ (mutate as Mock).mockImplementation(async (_key, updateFn) => {
+ if (typeof updateFn === 'function') {
+ const wellFormedGroups = [
+ {
+ cronJob: {},
+ cronJobId: 'job-1',
+ topics: [
+ { id: 'other-topic', favorite: false, title: 'Other' },
+ { id: topicId, favorite: false, title: 'Target' },
+ ],
+ },
+ ];
+
+ const result = updateFn(wellFormedGroups);
+
+ // Should return updated array with favorite state changed
+ expect(Array.isArray(result)).toBe(true);
+ const updatedTopic = result[0].topics.find((t: any) => t.id === topicId);
+ expect(updatedTopic).toBeDefined();
+ expect(updatedTopic.favorite).toBe(favState);
+
+ // Other topics should remain unchanged
+ const otherTopic = result[0].topics.find((t: any) => t.id === 'other-topic');
+ expect(otherTopic.favorite).toBe(false);
+ }
+ });
+
+ await act(async () => {
+ await result.current.favoriteTopic(topicId, favState);
+ });
+
+ expect(updateFavoriteSpy).toHaveBeenCalledWith(topicId, { favorite: favState });
+ });
+
+ it('should return original groups when no updates are needed', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const topicId = 'topic-already-favorited';
+ const favState = true;
+ const activeAgentId = 'test-agent';
+
+ await act(async () => {
+ useChatStore.setState({ activeAgentId });
+ });
+
+ const updateFavoriteSpy = vi
+ .spyOn(topicService, 'updateTopic')
+ .mockResolvedValue(undefined as any);
+
+ // Mock mutate to test no-op scenario
+ (mutate as Mock).mockImplementation(async (_key, updateFn) => {
+ if (typeof updateFn === 'function') {
+ const originalGroups = [
+ {
+ cronJob: {},
+ cronJobId: 'job-1',
+ topics: [
+ { id: topicId, favorite: true, title: 'Already Favorited' }, // Already has the target state
+ ],
+ },
+ ];
+
+ const result = updateFn(originalGroups);
+
+ // Should return the same reference when no updates are made
+ expect(result).toBe(originalGroups);
+ }
+ });
+
+ await act(async () => {
+ await result.current.favoriteTopic(topicId, favState);
+ });
+
+ expect(updateFavoriteSpy).toHaveBeenCalledWith(topicId, { favorite: favState });
+ });
});
describe('useFetchTopics', () => {
it('should fetch topics for a given session id', async () => {
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 8478f40451a..0dddaeed736 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -302,18 +302,20 @@ export const chatTopic: StateCreator<
await mutate(
['cronTopicsWithJobInfo', activeAgentId],
(groups?: CronTopicsGroupWithJobInfo[]) => {
- if (!groups) return groups;
+ if (!Array.isArray(groups)) return groups;
let updated = false;
const next = groups.map((group) => {
let groupUpdated = false;
- const topics = group.topics.map((topic) => {
- if (topic.id !== id) return topic;
- if (topic.favorite === favorite) return topic;
- groupUpdated = true;
- updated = true;
- return { ...topic, favorite };
- });
+ const topics = Array.isArray(group.topics)
+ ? group.topics.map((topic) => {
+ if (topic.id !== id) return topic;
+ if (topic.favorite === favorite) return topic;
+ groupUpdated = true;
+ updated = true;
+ return { ...topic, favorite };
+ })
+ : [];
return groupUpdated ? { ...group, topics } : group;
});