chatStore.test.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import { describe, expect, it } from 'vitest'
  2. import type { ChatMessage, ChatRouteState, RpcEventFrame } from '@shared/types'
  3. import { applyChatEvent, mergeChatMessages } from '@/utils/messageReducer'
  4. function message(id: string, content = '相同内容', clientMessageId?: string): ChatMessage {
  5. return {
  6. id, sessionId: 'session-1', profile: 'yaoyao', role: 'user', content,
  7. clientMessageId, timestamp: 1, stage: 'settled',
  8. }
  9. }
  10. function state(): ChatRouteState {
  11. return {
  12. route: { profile: 'yaoyao', sessionId: 'session-1' }, messages: [], historySynced: true,
  13. hasMoreBefore: false, loadedMessageCount: 0, messageTotal: 0, isLoadingHistory: false,
  14. isStreaming: false, isQueued: false, generation: 1,
  15. }
  16. }
  17. function event(type: string, payload: Record<string, unknown>, sessionId = 'session-1'): RpcEventFrame['params'] {
  18. return { type, session_id: sessionId, profile: 'yaoyao', payload: payload as never }
  19. }
  20. describe('chat message reducer', () => {
  21. it('preserves repeated user text when server identities differ', () => {
  22. const merged = mergeChatMessages([message('one')], [message('two')])
  23. expect(merged).toHaveLength(2)
  24. expect(merged.map(item => item.content)).toEqual(['相同内容', '相同内容'])
  25. })
  26. it('reconciles an optimistic row only by client message identity', () => {
  27. const optimistic = { ...message('local', 'hello', 'client-1'), stage: 'pending' as const }
  28. const persisted = { ...message('server-1', 'hello', 'client-1'), serverMessageId: 'server-1' }
  29. const merged = mergeChatMessages([optimistic], [persisted])
  30. expect(merged).toHaveLength(1)
  31. expect(merged[0].id).toBe('server-1')
  32. expect(merged[0].stage).toBe('settled')
  33. })
  34. it('keeps history and a realtime assistant reply in chronological order', () => {
  35. const optimistic = { ...message('local-user', '新问题', 'client-1'), timestamp: 30, stage: 'pending' as const }
  36. const older = { ...message('history-user', '旧问题'), timestamp: 10, sequence: 10 }
  37. const newer = {
  38. ...message('history-answer', '旧回答'), role: 'assistant' as const, timestamp: 20, sequence: 11,
  39. }
  40. const streamed = {
  41. ...message('stream-answer', '新回答'), role: 'assistant' as const, timestamp: 31, stage: 'streaming' as const, isStreaming: true,
  42. }
  43. const merged = mergeChatMessages([optimistic], [newer, older], 'snapshot')
  44. expect(mergeChatMessages(merged, [streamed]).map(item => item.id)).toEqual([
  45. 'history-user', 'history-answer', 'local-user', 'stream-answer',
  46. ])
  47. })
  48. it('replaces a cached iOS marker with an attachment-only normalized message', () => {
  49. const cached = message('ios-file', '[用户附加文件:车位.pdf]\n@file:`attachments/车位.pdf`')
  50. const normalized = {
  51. ...message('ios-file', ''),
  52. attachments: [{ id: 'ios-file:0', name: '车位.pdf', mimeType: 'application/pdf', size: 0, kind: 'pdf' as const, url: '/attachments/车位.pdf' }],
  53. }
  54. const merged = mergeChatMessages([cached], [normalized])
  55. expect(merged[0]).toMatchObject({ content: '', attachments: [expect.objectContaining({ name: '车位.pdf' })] })
  56. })
  57. it('ignores events attributed to another route', () => {
  58. const original = state()
  59. const reduced = applyChatEvent(original, event('message.delta', { delta: 'wrong' }, 'session-2'))
  60. expect(reduced).toBe(original)
  61. expect(reduced.messages).toEqual([])
  62. })
  63. it('uses terminal authoritative output to repair missed deltas', () => {
  64. let current = applyChatEvent(state(), event('message.start', { message_id: 'assistant-1' }))
  65. current = applyChatEvent(current, event('message.delta', { message_id: 'assistant-1', delta: '少量' }))
  66. current = applyChatEvent(current, event('message.complete', {
  67. message_id: 'assistant-1', text: '完整最终回答', authoritative_output: true,
  68. usage: { input: 10, output: 20, total: 30 },
  69. }))
  70. expect(current.messages).toHaveLength(1)
  71. expect(current.messages[0].content).toBe('完整最终回答')
  72. expect(current.messages[0].stage).toBe('settled')
  73. expect(current.usage?.totalTokens).toBe(30)
  74. })
  75. it('treats message.complete status=error as a failed terminal row', () => {
  76. let current = applyChatEvent(state(), event('message.start', { message_id: 'assistant-1' }))
  77. current = applyChatEvent(current, event('message.complete', {
  78. message_id: 'assistant-1', status: 'error', text: '工具执行失败', error: 'permission denied',
  79. }))
  80. expect(current.messages[0]).toMatchObject({ stage: 'failed', isStreaming: false })
  81. expect(current.error).toContain('permission denied')
  82. })
  83. it('maps the current 9119 context usage field names', () => {
  84. const current = applyChatEvent(state(), event('session.usage', {
  85. input: 10, output: 20, total: 30, context_used: 12_500, context_max: 114_688, context_percent: 10.9,
  86. }))
  87. expect(current.usage).toMatchObject({ contextTokens: 12_500, contextLimit: 114_688, percentUsed: 10.9 })
  88. })
  89. it('tracks approval and clarification independently', () => {
  90. let current = applyChatEvent(state(), event('approval.request', { request_id: 'approval-1', message: '允许吗?' }))
  91. current = applyChatEvent(current, event('clarify.request', { request_id: 'clarify-1', question: '选哪个?' }))
  92. expect(current.pendingApproval?.id).toBe('approval-1')
  93. expect(current.pendingClarification?.id).toBe('clarify-1')
  94. current = applyChatEvent(current, event('approval.resolved', {}))
  95. expect(current.pendingApproval).toBeUndefined()
  96. expect(current.pendingClarification?.id).toBe('clarify-1')
  97. })
  98. })