chatCrossClientSync.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  2. import { createPinia, setActivePinia } from 'pinia'
  3. import type { TranscriptSnapshot } from '@shared/chatTranscript'
  4. import type { RpcEventFrame, RealtimeConnectionState } from '@shared/types'
  5. const wire = vi.hoisted(() => ({
  6. event: undefined as ((e: RpcEventFrame['params']) => void) | undefined,
  7. state: undefined as ((s: RealtimeConnectionState) => void) | undefined,
  8. request: vi.fn(),
  9. clients: [] as any[],
  10. owner: 0,
  11. supported: true,
  12. }))
  13. const api = vi.hoisted(() => ({ messages: vi.fn(), sessions: vi.fn() }))
  14. vi.mock('@/api/realtime', () => ({
  15. RpcError: class extends Error {},
  16. ChatRpcSocket: class {
  17. get transcriptSupported() {
  18. return wire.supported
  19. }
  20. onEvent(f: typeof wire.event) {
  21. wire.event = f
  22. }
  23. onState(f: typeof wire.state) {
  24. wire.state = f
  25. }
  26. async connect() {
  27. wire.state?.('ready')
  28. }
  29. close() {}
  30. async request(...args: unknown[]) {
  31. return wire.request(...args)
  32. }
  33. },
  34. }))
  35. vi.mock('@/api/chatTranscript', () => ({
  36. ChatTranscriptClient: class {
  37. close = vi.fn()
  38. loadOlder = vi.fn()
  39. restore = vi.fn()
  40. run = vi.fn()
  41. constructor(
  42. readonly profile: string,
  43. readonly id: string,
  44. readonly changed: (value: TranscriptSnapshot) => Promise<void>,
  45. readonly failed: (error: Error) => void,
  46. ) {
  47. wire.clients.push(this)
  48. }
  49. },
  50. }))
  51. vi.mock('@/api/sessions', () => ({
  52. getMessages: api.messages,
  53. getSessions: api.sessions,
  54. getSession: vi.fn(),
  55. deleteSession: vi.fn(),
  56. getSessionUnread: vi.fn(),
  57. markSessionRead: vi.fn(),
  58. updateSession: vi.fn(),
  59. requestHistorySync: vi.fn(),
  60. }))
  61. vi.mock('@/api/profiles', () => ({ getModels: vi.fn() }))
  62. vi.mock('@/stores/auth', () => ({
  63. useAuthStore: () => ({
  64. user: { id: `v2-viewer-${wire.owner}` },
  65. activeProfile: { name: 'p' },
  66. status: 'authenticated',
  67. isAuthenticated: true,
  68. }),
  69. }))
  70. import { useChatStore } from '@/stores/chat'
  71. import { ScopedCache } from '@/utils/cache'
  72. function session(id = 's', owned = true) {
  73. return {
  74. id,
  75. profile: 'p',
  76. owned,
  77. source: 'web',
  78. title: id,
  79. messageCount: 0,
  80. toolCallCount: 0,
  81. startedAt: 1,
  82. updatedAt: 1,
  83. }
  84. }
  85. function snapshot(messages: any[], id = 's', extra: Partial<TranscriptSnapshot> = {}): TranscriptSnapshot {
  86. return {
  87. protocol: 'ordinary-chat-transcript-v2',
  88. epoch: 'test',
  89. cursor: 1,
  90. profile: 'p',
  91. sessionId: id,
  92. messages,
  93. session: {},
  94. hasOlder: false,
  95. total: messages.length,
  96. state: 'current',
  97. running: false,
  98. queued: false,
  99. ...extra,
  100. }
  101. }
  102. const answer = (content = '规范正文', extra = {}) => ({
  103. id: 'canonical-answer',
  104. seq: 2,
  105. revision: 1,
  106. source_message_id: 'upstream',
  107. turn_id: 'turn',
  108. role: 'assistant',
  109. content,
  110. status: 'complete',
  111. ...extra,
  112. })
  113. function emit(type: string, payload: any = {}) {
  114. wire.event?.({ type, session_id: 'runtime', profile: 'p', payload })
  115. }
  116. describe('ordinary v2 cross-client store', () => {
  117. let chat: ReturnType<typeof useChatStore>
  118. beforeEach(() => {
  119. setActivePinia(createPinia())
  120. wire.owner++
  121. wire.clients = []
  122. wire.supported = true
  123. wire.request
  124. .mockReset()
  125. .mockResolvedValue({ session_id: 'runtime', stored_session_id: 's', running: false })
  126. api.messages.mockReset().mockResolvedValue({ messages: [], total: 0, returned: 0, hasMore: false })
  127. api.sessions.mockReset().mockResolvedValue({ items: [session()] })
  128. chat = useChatStore()
  129. chat.sessions = [session()]
  130. })
  131. afterEach(() => {
  132. chat.disconnect()
  133. vi.useRealTimers()
  134. })
  135. async function open(id = 's') {
  136. await chat.selectSession(id, 'p')
  137. await vi.waitFor(() => expect(wire.clients.some((c) => c.id === id)).toBe(true))
  138. return wire.clients.filter((c) => c.id === id).at(-1)!
  139. }
  140. it.each(['image_path', 'path', 'ref_path'])('preserves uploaded image %s in pending and canonical messages', async field => {
  141. const client = await open()
  142. const paths = ['/home/user/.hermes/images/照片 one.png', '/tmp/photo-two.png']
  143. let uploaded = 0
  144. wire.request.mockImplementation((method: string) => Promise.resolve(
  145. method === 'image.attach_bytes' ? { [field]: paths[uploaded++] } : {},
  146. ))
  147. await chat.send('查看图片', paths.map((_, index) => new File(['image'], `photo-${index}.png`, { type: 'image/png' })))
  148. const submission = wire.request.mock.calls.find(([method]) => method === 'prompt.submit')![1]
  149. expect(submission.text).toBe([
  150. '查看图片',
  151. `[用户附加图片:photo-0.png]\n@image:${paths[0]}\n[screenshot]`,
  152. `[用户附加图片:photo-1.png]\n@image:${paths[1]}\n[screenshot]`,
  153. ].join('\n\n'))
  154. const pending = chat.messages.find(message => message.role === 'user')!
  155. expect(pending.attachments?.map(file => file.path)).toEqual(paths)
  156. const checkDownloads = () => chat.messages[0]!.attachments?.forEach((file, index) => {
  157. const url = new URL(file.url!, 'https://yaoyao.test')
  158. expect(url.pathname).toBe('/api/files/download')
  159. expect(url.searchParams.get('path')).toBe(paths[index])
  160. expect(url.searchParams.get('profile')).toBe('p')
  161. })
  162. checkDownloads()
  163. await client.changed(snapshot([{
  164. id: 'canonical-image', seq: 1, revision: 1, role: 'user', status: 'complete',
  165. client_message_id: pending.clientMessageId, content: submission.text,
  166. }]))
  167. expect(chat.messages).toHaveLength(1)
  168. expect(chat.messages[0]!.content).toBe('查看图片')
  169. expect(chat.messages[0]!.attachments?.map(file => file.path)).toEqual(paths)
  170. checkDownloads()
  171. })
  172. it('does not fabricate an image path when an older upload response omits it', async () => {
  173. await open()
  174. wire.request.mockResolvedValue({})
  175. await chat.send('', [new File(['image'], 'photo.png', { type: 'image/png' })])
  176. const submission = wire.request.mock.calls.find(([method]) => method === 'prompt.submit')![1]
  177. expect(submission.text).toBe('[用户附加图片:photo.png]\n[screenshot]')
  178. expect(chat.messages[0]!.attachments?.[0]?.url).toBeUndefined()
  179. })
  180. it('renders only canonical messages and ignores raw upstream bodies and completions', async () => {
  181. const client = await open()
  182. await client.changed(snapshot([answer('前半', { status: 'streaming' })], 's', { running: true }))
  183. emit('message.delta', { text: '不应追加' })
  184. emit('message.interim', { text: '不应重复' })
  185. emit('message.complete', { text: '不应替换' })
  186. expect(chat.messages.map((m) => m.content)).toEqual(['前半'])
  187. expect(chat.isStreaming).toBe(true)
  188. await client.changed(snapshot([answer('完整正文', { revision: 2 })], 's', { cursor: 2 }))
  189. expect(chat.messages.map((m) => m.content)).toEqual(['完整正文'])
  190. expect(chat.isStreaming).toBe(false)
  191. expect(api.messages).not.toHaveBeenCalled()
  192. })
  193. it('keeps checkpoint state when a usage update replaces the route during outbox persistence', async () => {
  194. const client = await open()
  195. const original = ScopedCache.prototype.set
  196. let entered!: () => void, release!: () => void
  197. const started = new Promise<void>(resolve => { entered = resolve })
  198. const gate = new Promise<void>(resolve => { release = resolve })
  199. const spy = vi.spyOn(ScopedCache.prototype, 'set').mockImplementation(async function(this: ScopedCache<unknown>, scope, key, value, durable) {
  200. if ((this as unknown as { namespace: string }).namespace === 'ordinary-outbox-v2') {
  201. entered()
  202. await gate
  203. }
  204. await original.call(this, scope, key, value, durable)
  205. })
  206. const saving = client.changed(snapshot([answer('正在处理', { status: 'streaming' })], 's', {
  207. running: true, liveStatus: '正在思考', pendingApproval: { request_id: 'approval-1', message: '请确认' },
  208. }))
  209. try {
  210. await started
  211. wire.event?.({ type: 'session.usage', session_id: 's', profile: 'p', payload: { input_tokens: 7 } })
  212. release()
  213. await saving
  214. expect(chat.messages.map(m => m.content)).toEqual(['正在处理'])
  215. expect(chat.isStreaming).toBe(true)
  216. expect(chat.pendingApproval?.id).toBe('approval-1')
  217. expect(chat.contextUsage?.inputTokens).toBe(7)
  218. } finally {
  219. release()
  220. await saving.catch(() => {})
  221. spy.mockRestore()
  222. }
  223. })
  224. it('does not materialize a resume snapshot beside the canonical reply', async () => {
  225. wire.request.mockResolvedValue({
  226. session_id: 'runtime',
  227. stored_session_id: 's',
  228. running: true,
  229. inflight: { assistant: '旧恢复快照' },
  230. })
  231. const client = await open()
  232. await client.changed(snapshot([answer('当前正文')]))
  233. expect(chat.messages.map((m) => m.content)).toEqual(['当前正文'])
  234. expect(chat.messages[0]!.id).toBe('canonical-answer')
  235. })
  236. it('restores tools and pending interactions from the canonical snapshot', async () => {
  237. const client = await open()
  238. await client.changed(
  239. snapshot(
  240. [
  241. answer('', {
  242. status: 'streaming',
  243. tool_calls: [{ id: 'tool', name: 'terminal', status: 'running' }],
  244. }),
  245. ],
  246. 's',
  247. {
  248. running: true,
  249. pendingApproval: { request_id: 'approval', message: '允许执行' },
  250. pendingClarification: { request_id: 'clarify', question: '请选择' },
  251. },
  252. ),
  253. )
  254. expect(chat.messages[0]!.toolCalls?.[0]?.id).toBe('tool')
  255. expect(chat.pendingApproval?.id).toBe('approval')
  256. expect(chat.pendingClarification?.id).toBe('clarify')
  257. await client.changed(
  258. snapshot([answer()], 's', { cursor: 2, pendingApproval: null, pendingClarification: null }),
  259. )
  260. expect(chat.pendingApproval).toBeUndefined()
  261. expect(chat.pendingClarification).toBeUndefined()
  262. })
  263. it('rejects a closed session callback after switching to another conversation', async () => {
  264. const first = await open()
  265. chat.sessions.push(session('second'))
  266. wire.request.mockResolvedValue({ session_id: 'runtime-2', stored_session_id: 'second' })
  267. const second = await open('second')
  268. await second.changed(snapshot([answer('第二个会话')], 'second'))
  269. await first.changed(snapshot([answer('旧回调')]))
  270. expect(chat.activeSessionId).toBe('second')
  271. expect(chat.messages[0]!.content).toBe('第二个会话')
  272. })
  273. it('does not let a late submit receipt re-open a completed turn or duplicate the user', async () => {
  274. const client = await open()
  275. let accept!: (value: any) => void
  276. wire.request.mockImplementation((method: string) =>
  277. method === 'prompt.submit'
  278. ? new Promise((resolve) => {
  279. accept = resolve
  280. })
  281. : Promise.resolve({}),
  282. )
  283. const sending = chat.send('问题')
  284. await vi.waitFor(() => expect(accept).toBeTypeOf('function'))
  285. const local = chat.messages.find((m) => m.role === 'user')!
  286. await client.changed(
  287. snapshot(
  288. [
  289. {
  290. id: 'canonical-user',
  291. seq: 1,
  292. revision: 2,
  293. source_message_id: 'persisted-user',
  294. client_message_id: local.clientMessageId,
  295. role: 'user',
  296. content: '问题',
  297. status: 'complete',
  298. },
  299. answer(),
  300. ],
  301. 's',
  302. { cursor: 3, running: false },
  303. ),
  304. )
  305. accept({ status: 'streaming' })
  306. await sending
  307. expect(chat.messages.filter((m) => m.role === 'user')).toHaveLength(1)
  308. expect(chat.messages[0]!.stage).toBe('settled')
  309. expect(chat.isStreaming).toBe(false)
  310. })
  311. it('keeps a pending local input during a new generation replacement', async () => {
  312. const client = await open()
  313. let reject!: (error: Error) => void
  314. wire.request.mockImplementation((method: string) =>
  315. method === 'prompt.submit'
  316. ? new Promise((_resolve, r) => {
  317. reject = r
  318. })
  319. : Promise.resolve({}),
  320. )
  321. const sending = chat.send('待确认').catch(() => {})
  322. await vi.waitFor(() => expect(reject).toBeTypeOf('function'))
  323. const local = chat.messages[0]!.id
  324. await client.changed(snapshot([answer('历史重建')], 's', { epoch: 'rebuilt' }))
  325. expect(chat.messages.some((m) => m.id === local)).toBe(true)
  326. reject(new Error('connection lost'))
  327. await sending
  328. })
  329. it('uses transcript pagination without requesting legacy message pages', async () => {
  330. const client = await open()
  331. await client.changed(snapshot([answer()], 's', { hasOlder: true }))
  332. await chat.loadOlder()
  333. expect(client.loadOlder).toHaveBeenCalledOnce()
  334. expect(api.messages).not.toHaveBeenCalled()
  335. })
  336. it('requires v2 and never falls back to legacy history for owned chat', async () => {
  337. wire.supported = false
  338. await expect(chat.selectSession('s', 'p')).rejects.toThrow('升级服务端')
  339. expect(api.messages).not.toHaveBeenCalled()
  340. })
  341. it('keeps read-only native history outside the ordinary transcript', async () => {
  342. chat.sessions = [session('s', false)]
  343. await chat.selectSession('s', 'p')
  344. expect(api.messages).toHaveBeenCalledOnce()
  345. expect(wire.request).not.toHaveBeenCalled()
  346. })
  347. })