|
| 1 | +/** |
| 2 | + * @vitest-environment jsdom |
| 3 | + */ |
| 4 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 5 | + |
| 6 | +vi.hoisted(() => { |
| 7 | + const legacyNewestFirst = { |
| 8 | + state: { |
| 9 | + messages: [ |
| 10 | + { |
| 11 | + id: 'msg-2', |
| 12 | + content: 'response', |
| 13 | + workflowId: 'wf-1', |
| 14 | + type: 'workflow', |
| 15 | + timestamp: '2026-07-13T00:00:00.000Z', |
| 16 | + }, |
| 17 | + { |
| 18 | + id: 'msg-1', |
| 19 | + content: 'hi', |
| 20 | + workflowId: 'wf-1', |
| 21 | + type: 'user', |
| 22 | + timestamp: '2026-07-13T00:00:00.000Z', |
| 23 | + }, |
| 24 | + ], |
| 25 | + }, |
| 26 | + version: 0, |
| 27 | + } |
| 28 | + window.localStorage.setItem('chat-store', JSON.stringify(legacyNewestFirst)) |
| 29 | +}) |
| 30 | + |
| 31 | +import { useChatStore } from '@/stores/chat/store' |
| 32 | + |
| 33 | +describe('chat store message ordering', () => { |
| 34 | + it('migrates v0 persisted messages from newest-first to insertion order', () => { |
| 35 | + const messages = useChatStore.getState().messages |
| 36 | + expect(messages.map((m) => m.id)).toEqual(['msg-1', 'msg-2']) |
| 37 | + }) |
| 38 | + |
| 39 | + describe('addMessage', () => { |
| 40 | + beforeEach(() => { |
| 41 | + useChatStore.setState({ messages: [] }) |
| 42 | + }) |
| 43 | + |
| 44 | + it('appends messages so insertion order is conversation order, even with identical timestamps', () => { |
| 45 | + const { addMessage } = useChatStore.getState() |
| 46 | + const timestamp = new Date().toISOString() |
| 47 | + |
| 48 | + addMessage({ content: 'hi', workflowId: 'wf-1', type: 'user', timestamp } as any) |
| 49 | + addMessage({ content: '', workflowId: 'wf-1', type: 'workflow', timestamp } as any) |
| 50 | + |
| 51 | + const types = useChatStore.getState().messages.map((m) => m.type) |
| 52 | + expect(types).toEqual(['user', 'workflow']) |
| 53 | + }) |
| 54 | + |
| 55 | + it('keeps only the most recent messages when trimming to the cap', () => { |
| 56 | + const { addMessage } = useChatStore.getState() |
| 57 | + |
| 58 | + for (let i = 0; i < 55; i++) { |
| 59 | + addMessage({ content: `m${i}`, workflowId: 'wf-1', type: 'user' }) |
| 60 | + } |
| 61 | + |
| 62 | + const messages = useChatStore.getState().messages |
| 63 | + expect(messages).toHaveLength(50) |
| 64 | + expect(messages[0].content).toBe('m5') |
| 65 | + expect(messages[messages.length - 1].content).toBe('m54') |
| 66 | + }) |
| 67 | + }) |
| 68 | +}) |
0 commit comments