chatStore.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import { describe, expect, it } from 'vitest'
  2. import type { ChatMessage, ChatRouteState, RpcEventFrame } from '@shared/types'
  3. import { applyChatEvent, mergeChatMessages } from '@/utils/messageReducer'
  4. import { estimateConversationTokens } from '@/utils/contextUsage'
  5. function message(id: string, content = '相同内容', clientMessageId?: string): ChatMessage {
  6. return {
  7. id, sessionId: 'session-1', profile: 'yaoyao', role: 'user', content,
  8. clientMessageId, timestamp: 1, stage: 'settled',
  9. }
  10. }
  11. function state(): ChatRouteState {
  12. return {
  13. route: { profile: 'yaoyao', sessionId: 'session-1' }, messages: [], historySynced: true,
  14. hasMoreBefore: false, loadedMessageCount: 0, messageTotal: 0, isLoadingHistory: false,
  15. isStreaming: false, isQueued: false, generation: 1,
  16. }
  17. }
  18. function event(type: string, payload: Record<string, unknown>, sessionId = 'session-1'): RpcEventFrame['params'] {
  19. return { type, session_id: sessionId, profile: 'yaoyao', payload: payload as never }
  20. }
  21. describe('chat message reducer', () => {
  22. it('estimates visible conversation tokens when Hermes has no live gauge', () => {
  23. expect(estimateConversationTokens([
  24. message('one', '你好,Hermes!'),
  25. { ...message('two', 'The quick brown fox'), role: 'assistant', reasoning: '检查上下文' },
  26. ])).toBeGreaterThan(0)
  27. })
  28. it('preserves repeated user text when server identities differ', () => {
  29. const merged = mergeChatMessages([message('one')], [message('two')])
  30. expect(merged).toHaveLength(2)
  31. expect(merged.map(item => item.content)).toEqual(['相同内容', '相同内容'])
  32. })
  33. it('reconciles an optimistic row only by client message identity', () => {
  34. const optimistic = { ...message('local', 'hello', 'client-1'), stage: 'pending' as const }
  35. const persisted = { ...message('server-1', 'hello', 'client-1'), serverMessageId: 'server-1' }
  36. const merged = mergeChatMessages([optimistic], [persisted])
  37. expect(merged).toHaveLength(1)
  38. expect(merged[0].id).toBe('server-1')
  39. expect(merged[0].stage).toBe('settled')
  40. })
  41. it.each(['append', 'snapshot', 'prepend'] as const)('repairs both cached echoes when history restores identity (%s)', position => {
  42. const local = { ...message('local', '查看服务器情况', 'client-1'), stage: 'accepted' as const }
  43. const oldHistory = { ...message('1155', '查看服务器情况'), serverMessageId: '1155', timestamp: 2 }
  44. const history = { ...oldHistory, clientMessageId: 'client-1' }
  45. const merged = mergeChatMessages([local, oldHistory], [history], position)
  46. expect(merged).toHaveLength(1)
  47. expect(merged[0]).toMatchObject({ id: '1155', clientMessageId: 'client-1', stage: 'settled', timestamp: 2 })
  48. })
  49. it('keeps persisted identity and delivery state when a peer receipt arrives after history', () => {
  50. const current = state()
  51. current.messages = [{ ...message('1155', '查看服务器情况', 'client-1'), serverMessageId: '1155' }]
  52. const updated = applyChatEvent(current, event('run.peer_user_message', {
  53. message_id: 'user:web:prompt:client-1', client_message_id: 'client-1', text: '查看服务器情况', status: 'accepted',
  54. }))
  55. expect(updated.messages).toHaveLength(1)
  56. expect(updated.messages[0]).toMatchObject({ id: '1155', serverMessageId: '1155', stage: 'settled' })
  57. })
  58. it('retains two separate identical submissions while reconciling both echoes', () => {
  59. const local = ['first', 'second'].map(id => ({ ...message(id, '查看服务器情况', id), stage: 'accepted' as const }))
  60. const history = local.map((row, index) => ({ ...row, id: String(index + 1), serverMessageId: String(index + 1), stage: 'settled' as const }))
  61. expect(mergeChatMessages(local, history, 'snapshot').map(row => [row.id, row.clientMessageId, row.stage]))
  62. .toEqual([['1', 'first', 'settled'], ['2', 'second', 'settled']])
  63. })
  64. it('keeps history and a realtime assistant reply in chronological order', () => {
  65. const optimistic = { ...message('local-user', '新问题', 'client-1'), timestamp: 30, stage: 'pending' as const }
  66. const older = { ...message('history-user', '旧问题'), timestamp: 10, sequence: 10 }
  67. const newer = {
  68. ...message('history-answer', '旧回答'), role: 'assistant' as const, timestamp: 20, sequence: 11,
  69. }
  70. const streamed = {
  71. ...message('stream-answer', '新回答'), role: 'assistant' as const, timestamp: 31, stage: 'streaming' as const, isStreaming: true,
  72. }
  73. const merged = mergeChatMessages([optimistic], [newer, older], 'snapshot')
  74. expect(mergeChatMessages(merged, [streamed]).map(item => item.id)).toEqual([
  75. 'history-user', 'history-answer', 'local-user', 'stream-answer',
  76. ])
  77. })
  78. it('replaces a cached iOS marker with an attachment-only normalized message', () => {
  79. const cached = message('ios-file', '[用户附加文件:车位.pdf]\n@file:`attachments/车位.pdf`')
  80. const normalized = {
  81. ...message('ios-file', ''),
  82. attachments: [{ id: 'ios-file:0', name: '车位.pdf', mimeType: 'application/pdf', size: 0, kind: 'pdf' as const, url: '/attachments/车位.pdf' }],
  83. }
  84. const merged = mergeChatMessages([cached], [normalized])
  85. expect(merged[0]).toMatchObject({ content: '', attachments: [expect.objectContaining({ name: '车位.pdf' })] })
  86. })
  87. it('ignores events attributed to another route', () => {
  88. const original = state()
  89. const reduced = applyChatEvent(original, event('message.delta', { delta: 'wrong' }, 'session-2'))
  90. expect(reduced).toBe(original)
  91. expect(reduced.messages).toEqual([])
  92. })
  93. it('uses terminal authoritative output to repair missed deltas', () => {
  94. let current = applyChatEvent(state(), event('message.start', { message_id: 'assistant-1' }))
  95. current = applyChatEvent(current, event('message.delta', { message_id: 'assistant-1', delta: '少量' }))
  96. current = applyChatEvent(current, event('message.complete', {
  97. message_id: 'assistant-1', text: '完整最终回答', authoritative_output: true,
  98. usage: { input: 10, output: 20, total: 30 },
  99. }))
  100. expect(current.messages).toHaveLength(1)
  101. expect(current.messages[0].content).toBe('完整最终回答')
  102. expect(current.messages[0].stage).toBe('settled')
  103. expect(current.usage?.totalTokens).toBe(30)
  104. })
  105. it('starts a new assistant row after a user prompt when an interrupted row is still marked streaming', () => {
  106. const interrupted = {
  107. ...message('assistant-old', '上一轮残留'), role: 'assistant' as const, timestamp: 20,
  108. stage: 'streaming' as const, isStreaming: true,
  109. }
  110. const prompt = { ...message('user-new', '再试试'), timestamp: 30, stage: 'accepted' as const }
  111. const initial = { ...state(), messages: [interrupted, prompt] }
  112. let current = applyChatEvent(initial, event('run.started', {}))
  113. current = applyChatEvent(current, event('message.delta', { delta: '新一轮回答' }))
  114. expect(current.messages).toHaveLength(3)
  115. expect(current.messages.map(item => item.content)).toEqual(['上一轮残留', '再试试', '新一轮回答'])
  116. expect(current.messages[0]).toMatchObject({ id: 'assistant-old', isStreaming: false })
  117. expect(current.messages[2]).toMatchObject({ role: 'assistant', isStreaming: true })
  118. })
  119. it('promotes a synthetic streaming row to a server message id without duplicating it', () => {
  120. const initial = { ...state(), messages: [{ ...message('user-new', '开始'), timestamp: 30 }] }
  121. let current = applyChatEvent(initial, event('run.started', {}))
  122. current = applyChatEvent(current, event('message.delta', { message_id: 'assistant-new', delta: '回答' }))
  123. expect(current.messages).toHaveLength(2)
  124. expect(current.messages[1]).toMatchObject({ id: 'assistant-new', content: '回答', isStreaming: true })
  125. })
  126. it('seals interim commentary so later streamed text stays at the bottom of the turn', () => {
  127. const initial = { ...state(), messages: [{ ...message('user-new', '检查项目'), timestamp: 100 }] }
  128. let current = applyChatEvent(initial, event('message.start', {}))
  129. current = applyChatEvent(current, event('message.delta', { text: '我先读取配置。', timestamp: 101 }))
  130. current = applyChatEvent(current, event('message.interim', { text: '我先读取配置。', timestamp: 102 }))
  131. current = applyChatEvent(current, event('tool.start', { tool_id: 'tool-1', name: 'read_file' }))
  132. current = applyChatEvent(current, event('tool.complete', { tool_id: 'tool-1', name: 'read_file', result: 'ok' }))
  133. current = applyChatEvent(current, event('message.delta', { text: '配置没有问题。', timestamp: 105 }))
  134. expect(current.messages.map(item => item.content)).toEqual(['检查项目', '我先读取配置。', '配置没有问题。'])
  135. expect(current.messages[1]).toMatchObject({ role: 'assistant', isStreaming: false })
  136. expect(current.messages[2]).toMatchObject({ role: 'assistant', isStreaming: true })
  137. expect(current.messages[2].toolCalls).toEqual([
  138. expect.objectContaining({ id: 'tool-1', status: 'completed' }),
  139. ])
  140. })
  141. it('preserves interim commentary after the final answer completes', () => {
  142. const initial = { ...state(), messages: [{ ...message('user-new', '执行'), timestamp: 100 }] }
  143. let current = applyChatEvent(initial, event('message.start', {}))
  144. current = applyChatEvent(current, event('message.delta', { text: '开始执行。' }))
  145. current = applyChatEvent(current, event('message.interim', { text: '开始执行。' }))
  146. current = applyChatEvent(current, event('message.delta', { text: '执行完成。' }))
  147. current = applyChatEvent(current, event('message.complete', { text: '执行完成。' }))
  148. expect(current.messages.map(item => item.content)).toEqual(['执行', '开始执行。', '执行完成。'])
  149. expect(current.messages.slice(1).every(item => item.isStreaming === false)).toBe(true)
  150. })
  151. it('settles an identical completion onto the sealed interim instead of duplicating it', () => {
  152. const initial = { ...state(), messages: [{ ...message('user-new', '执行'), timestamp: 100 }] }
  153. let current = applyChatEvent(initial, event('message.start', {}))
  154. current = applyChatEvent(current, event('message.delta', { text: '已经完成。' }))
  155. current = applyChatEvent(current, event('message.interim', { text: '已经完成。', already_streamed: true }))
  156. current = applyChatEvent(current, event('message.complete', { text: '已经完成。' }))
  157. expect(current.messages.map(item => item.content)).toEqual(['执行', '已经完成。'])
  158. expect(current.messages[1]).toMatchObject({ stage: 'settled', isStreaming: false })
  159. })
  160. it('treats message.complete status=error as a failed terminal row', () => {
  161. let current = applyChatEvent(state(), event('message.start', { message_id: 'assistant-1' }))
  162. current = applyChatEvent(current, event('message.complete', {
  163. message_id: 'assistant-1', status: 'error', text: '工具执行失败', error: 'permission denied',
  164. }))
  165. expect(current.messages[0]).toMatchObject({ stage: 'failed', isStreaming: false })
  166. expect(current.error).toContain('permission denied')
  167. })
  168. it('maps the current 9119 context usage field names', () => {
  169. const current = applyChatEvent(state(), event('session.usage', {
  170. input: 10, output: 20, total: 30, context_used: 12_500, context_max: 114_688, context_percent: 10.9,
  171. }))
  172. expect(current.usage).toMatchObject({ contextTokens: 12_500, contextLimit: 114_688, percentUsed: 10.9 })
  173. })
  174. it('tracks approval and clarification independently', () => {
  175. let current = applyChatEvent(state(), event('approval.request', { request_id: 'approval-1', message: '允许吗?' }))
  176. current = applyChatEvent(current, event('clarify.request', { request_id: 'clarify-1', question: '选哪个?' }))
  177. expect(current.pendingApproval?.id).toBe('approval-1')
  178. expect(current.pendingClarification?.id).toBe('clarify-1')
  179. current = applyChatEvent(current, event('approval.resolved', {}))
  180. expect(current.pendingApproval).toBeUndefined()
  181. expect(current.pendingClarification?.id).toBe('clarify-1')
  182. })
  183. })