chatCacheRoutes.test.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. // @vitest-environment node
  2. import { mkdtempSync, rmSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import request from 'supertest'
  6. import { afterEach, describe, expect, it, vi } from 'vitest'
  7. import { createApplication, type ApplicationRuntime } from '../../src/server/app.js'
  8. import type { ServerConfig } from '../../src/server/config.js'
  9. const homes: string[] = []
  10. const runtimes: ApplicationRuntime[] = []
  11. const host = '127.0.0.1:15300'
  12. const origin = `http://${host}`
  13. function cookie(response: request.Response): string {
  14. const values = response.headers['set-cookie'] as unknown as string[] | undefined
  15. return (values ?? []).map(value => value.split(';', 1)[0]).join('; ')
  16. }
  17. function config(home: string): ServerConfig {
  18. return {
  19. host: '127.0.0.1', port: 15300, upstream: new URL('http://127.0.0.1:19119'),
  20. allowedHosts: new Set(), home, mediaRoot: home, attachmentsRoot: home, imagesRoot: home,
  21. mediaOwner: 'test', allowInsecureLan: false, insecureLan: false, production: false,
  22. chatCacheMode: 'prefer-local',
  23. }
  24. }
  25. afterEach(() => {
  26. for (const runtime of runtimes.splice(0)) runtime.close()
  27. for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true })
  28. })
  29. describe('source=web chat cache routes', () => {
  30. it('serves warm and restarted chat reads locally while history stays upstream-only', async () => {
  31. const home = mkdtempSync(join(tmpdir(), 'yaoyao-chat-cache-routes-')); homes.push(home)
  32. const counts = { list: 0, detail: 0, messages: 0, history: 0, media: 0 }
  33. const mediaPath = '/Users/test/.hermes/profiles/default/images/result.png'
  34. const fetchImpl = vi.fn<typeof fetch>(async (input, init) => {
  35. const url = new URL(String(input))
  36. const headers = new Headers(init?.headers)
  37. if (url.pathname === '/api/status') return Response.json({ auth_required: false })
  38. if (url.pathname === '/') return new Response('<script>window.__HERMES_SESSION_TOKEN__="cache-token-1234567890123456";</script>')
  39. if (headers.get('x-hermes-session-token') !== 'cache-token-1234567890123456') return Response.json({}, { status: 401 })
  40. if (url.pathname === '/api/profiles') return Response.json({ profiles: [{ name: 'default', is_default: true }] })
  41. if (url.pathname === '/api/sessions' && url.searchParams.get('source') === 'web') {
  42. counts.list++
  43. return Response.json({ sessions: [{ id: 'session-web', profile: 'default', source: 'web', title: '持久会话' }] })
  44. }
  45. if (url.pathname === '/api/profiles/sessions' && url.searchParams.get('exclude_sources')?.includes('web')) {
  46. counts.history++
  47. return Response.json({ sessions: [{ id: 'history-only', source: 'telegram', title: '只读历史' }] })
  48. }
  49. if (url.pathname === '/api/sessions/session-web/messages') {
  50. counts.messages++
  51. return Response.json({
  52. session: { id: 'session-web', profile: 'default', source: 'web', title: '持久会话' },
  53. messages: [{ id: 'message-1', role: 'assistant', content: `持久消息\n![结果](${mediaPath})` }],
  54. pagination: { total: 1, returned: 1, offset: 0, limit: 100, hasMore: false },
  55. })
  56. }
  57. if (url.pathname === '/api/files/download') {
  58. counts.media++
  59. expect(url.searchParams.get('path')).toBe(mediaPath)
  60. return new Response('png-bytes', { headers: { 'content-type': 'image/png' } })
  61. }
  62. if (url.pathname === '/api/sessions/session-web') {
  63. counts.detail++
  64. return Response.json({ id: 'session-web', profile: 'default', source: 'web', title: '持久会话' })
  65. }
  66. return Response.json({ error: 'missing fixture' }, { status: 404 })
  67. })
  68. const first = createApplication({ config: config(home), fetchImpl }); runtimes.push(first)
  69. const agent = request.agent(first.app.callback())
  70. const boot = await agent.get('/api/app/bootstrap').set('Host', host).expect(200)
  71. const setup = await agent.post('/api/app/setup').set('Host', host).set('Origin', origin)
  72. .set('X-CSRF-Token', boot.body.csrfToken).send({ username: 'owner', password: 'fixture-password' }).expect(200)
  73. const sessionCookie = cookie(setup)
  74. const listPath = '/api/app/sessions?view=chat&profile=default&limit=100'
  75. await agent.get(listPath).set('Host', host).expect('X-Yaoyao-Data-Source', 'upstream').expect(200)
  76. await agent.get(listPath).set('Host', host).expect('X-Yaoyao-Data-Source', 'local').expect(200)
  77. await agent.get(listPath).set('Host', host).set('X-Yaoyao-Cache', 'bypass')
  78. .expect('X-Yaoyao-Data-Source', 'upstream').expect(200)
  79. const messagesPath = '/api/app/sessions/session-web/messages?profile=default&offset=0&limit=100'
  80. await agent.get(messagesPath).set('Host', host).expect('X-Yaoyao-Data-Source', 'upstream').expect(200)
  81. const cachedMessages = await agent.get(messagesPath).set('Host', host)
  82. .expect('X-Yaoyao-Data-Source', 'local').expect(200)
  83. expect(cachedMessages.body.messages[0].content).toContain('持久消息')
  84. await agent.get(mediaPath).set('Host', host).expect('X-Yaoyao-Data-Source', 'upstream').expect(200)
  85. const cachedMedia = await agent.get(mediaPath).set('Host', host)
  86. .expect('X-Yaoyao-Data-Source', 'local').expect(200)
  87. expect(Buffer.from(cachedMedia.body).toString()).toBe('png-bytes')
  88. const rangedMedia = await agent.get(mediaPath).set('Host', host).set('Range', 'bytes=0-2')
  89. .expect('X-Yaoyao-Data-Source', 'local').expect('Content-Range', 'bytes 0-2/9').expect(206)
  90. expect(Buffer.from(rangedMedia.body).toString()).toBe('png')
  91. await agent.get('/api/app/sessions?view=history').set('Host', host).expect(200)
  92. await agent.get('/api/app/sessions?view=history').set('Host', host).expect(200)
  93. expect(counts).toMatchObject({ list: 2, messages: 1, history: 1, media: 1 })
  94. const historySnapshots = first.chatCache!.store.db.prepare("SELECT COUNT(*) count FROM chat_snapshots WHERE kind='history'").get() as { count: number }
  95. expect(historySnapshots.count).toBe(0)
  96. first.close(); runtimes.splice(runtimes.indexOf(first), 1)
  97. const offlineFetch = vi.fn<typeof fetch>(async () => { throw new Error('9119 offline') })
  98. const restarted = createApplication({ config: config(home), fetchImpl: offlineFetch }); runtimes.push(restarted)
  99. const offlineList = await request(restarted.app.callback()).get(listPath).set('Host', host).set('Cookie', sessionCookie)
  100. .expect('X-Yaoyao-Data-Source', 'local').expect(200)
  101. expect(offlineList.body.sessions[0].title).toBe('持久会话')
  102. const offlineMessages = await request(restarted.app.callback()).get(messagesPath).set('Host', host).set('Cookie', sessionCookie)
  103. .expect('X-Yaoyao-Data-Source', 'local').expect(200)
  104. expect(offlineMessages.body.messages[0].content).toContain('持久消息')
  105. const offlineMedia = await request(restarted.app.callback()).get(mediaPath).set('Host', host).set('Cookie', sessionCookie)
  106. .expect('X-Yaoyao-Data-Source', 'local').expect(200)
  107. expect(Buffer.from(offlineMedia.body).toString()).toBe('png-bytes')
  108. expect(offlineFetch).not.toHaveBeenCalled()
  109. await request(restarted.app.callback()).get('/api/app/sessions?view=history').set('Host', host).set('Cookie', sessionCookie)
  110. .expect(502)
  111. expect(offlineFetch).toHaveBeenCalled()
  112. })
  113. })