chatCache.test.ts 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. // @vitest-environment node
  2. import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import { DatabaseSync } from 'node:sqlite'
  6. import { afterEach, describe, expect, it, vi } from 'vitest'
  7. import { ChatCacheCoordinator, ChatCacheStore, chatCacheKey } from '../../src/server/chatCache.js'
  8. import type { UpstreamServiceSession } from '../../src/server/localAuth.js'
  9. import type { UpstreamResponse } from '../../src/server/upstream.js'
  10. const homes: string[] = []
  11. const owner = 'owner-1'
  12. const profile = 'default'
  13. const sessionID = 'session-web'
  14. function response(value: unknown, status = 200, contentType = 'application/json'): UpstreamResponse {
  15. return { status, headers: new Headers({ 'content-type': contentType }), body: Buffer.from(typeof value === 'string' ? value : JSON.stringify(value)) }
  16. }
  17. function fixture() {
  18. const home = mkdtempSync(join(tmpdir(), 'yaoyao-chat-cache-'))
  19. homes.push(home)
  20. const store = new ChatCacheStore(home)
  21. const upstream = { request: vi.fn() } as unknown as UpstreamServiceSession
  22. return { home, store, coordinator: new ChatCacheCoordinator(store, upstream, 'prefer-local') }
  23. }
  24. afterEach(() => {
  25. for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true })
  26. })
  27. describe('durable source=web chat cache', () => {
  28. it.each(['prefer-local', 'shadow', 'upstream-only'] as const)(
  29. 'preserves sessions and cached files after repeated read 404s in %s mode', async mode => {
  30. const f = fixture()
  31. const coordinator = new ChatCacheCoordinator(f.store, f.coordinator.upstream, mode)
  32. const sourcePath = '/tmp/final-report.png'
  33. try {
  34. f.store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'web' })
  35. f.store.putSnapshot(owner, 'tail', 'messages', profile, sessionID, response({
  36. messages: [{ id: 'latest', role: 'assistant', content: `![报告](${sourcePath})` }],
  37. pagination: { total: 2, offset: 0, has_more: true },
  38. }))
  39. f.store.storeAttachment(owner, sourcePath, response('report-bytes', 200, 'image/png'))
  40. const asset = f.store.attachment(owner, sourcePath)!
  41. const changed = vi.fn()
  42. coordinator.onSynchronized = changed
  43. const result = await coordinator.messages(owner, 'older', profile, sessionID, 1, 1, async () => {
  44. f.store.recordCommand(owner, profile, sessionID, 'prompt.submit', { text: '新消息' })
  45. return response({ detail: 'Session not found' }, 404)
  46. })
  47. expect(result.response.status).toBe(404)
  48. expect(f.store.ownsSession(owner, profile, sessionID)).toBe(true)
  49. expect(JSON.parse(f.store.messagePage(owner, profile, sessionID, 0, 1)!.response.body.toString()).messages)
  50. .toEqual([expect.objectContaining({ id: 'latest' })])
  51. expect(readFileSync(asset.localPath, 'utf8')).toBe('report-bytes')
  52. expect(changed).not.toHaveBeenCalled()
  53. await coordinator.messages(owner, 'older', profile, sessionID, 1, 1,
  54. async () => response({ detail: 'Session not found' }, 404))
  55. expect(f.store.ownsSession(owner, profile, sessionID)).toBe(true)
  56. expect(readFileSync(asset.localPath, 'utf8')).toBe('report-bytes')
  57. expect(changed).not.toHaveBeenCalled()
  58. } finally { f.store.close() }
  59. },
  60. )
  61. it('serves older cached sessions without probing or automatically cleaning them', async () => {
  62. const f = fixture()
  63. try {
  64. f.store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'web' })
  65. f.store.putSnapshot(owner, 'detail', 'detail', profile, sessionID, response({ id: sessionID, title: '保留' }))
  66. f.store.db.prepare('UPDATE chat_sessions SET owned_at=?').run(Date.now() - 120_000)
  67. const load = vi.fn(async () => response({ sessions: [], total: 0 }))
  68. vi.mocked(f.coordinator.upstream.request).mockResolvedValue(response({}, 404))
  69. const result = await f.coordinator.read(owner, 'list', 'list', profile, undefined, load, true)
  70. expect(result.source).toBe('local')
  71. expect(JSON.parse(result.response.body.toString()).sessions).toContainEqual(expect.objectContaining({ id: sessionID }))
  72. expect(load).not.toHaveBeenCalled()
  73. expect(f.coordinator.upstream.request).not.toHaveBeenCalled()
  74. expect(f.store.ownsSession(owner, profile, sessionID)).toBe(true)
  75. } finally { f.store.close() }
  76. })
  77. it('retains a cached session when reconciliation receives a 404', async () => {
  78. const f = fixture()
  79. f.store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'web' })
  80. f.store.putSnapshot(owner, 'detail', 'detail', profile, sessionID, response({ id: sessionID, title: 'ghost' }))
  81. vi.mocked(f.coordinator.upstream.request).mockResolvedValue(response({ detail: 'Session not found' }, 404))
  82. await expect(f.coordinator.reconcile(owner, profile, sessionID)).rejects.toThrow('Unable to synchronize conversation metadata')
  83. expect(f.store.ownsSession(owner, profile, sessionID)).toBe(true)
  84. expect(f.store.localDetail(owner, profile, sessionID)).toBeDefined()
  85. f.store.close()
  86. })
  87. it('keeps acknowledged flags across aliases and rejects a deleted session sync', () => {
  88. const f = fixture()
  89. f.store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'web' })
  90. f.store.putSnapshot(owner, 'detail', 'detail', profile, sessionID, response({ id: sessionID, is_pinned: false }))
  91. const revision = f.store.revision(owner, profile, sessionID)
  92. f.store.recordSessionPatch(owner, profile, sessionID, { pinned: true })
  93. expect(JSON.parse(f.store.localDetail(owner, profile, sessionID)!.response.body.toString()).pinned).toBe(true)
  94. expect(f.store.applySync(owner, profile, sessionID, revision, [], false)).toBe(false)
  95. f.store.deleteSession(owner, profile, sessionID)
  96. expect(f.store.applySync(owner, profile, sessionID, 0, [], true)).toBe(false)
  97. f.store.close()
  98. })
  99. it('keeps session metadata when message envelopes only contain session_id and advances activity from messages', () => {
  100. const f = fixture()
  101. f.store.recordRoute(owner, profile, sessionID, 'runtime-web')
  102. f.store.putSnapshot(owner, 'detail', 'detail', profile, sessionID, response({
  103. id: sessionID, profile, source: 'ios', title: '准备 GPT-6 详细 Markdown 文档',
  104. started_at: 1_788_661_637, last_active: 1_788_661_640, pinned: true, message_count: 1,
  105. }))
  106. f.store.putSnapshot(owner, 'tail', 'messages', profile, sessionID, response({
  107. session_id: sessionID, model: 'test-model',
  108. messages: [{ id: 'latest', timestamp: 1_788_663_697.824613, role: 'assistant', content: '完成' }],
  109. pagination: { total: 2, offset: 0 },
  110. }))
  111. f.store.putSnapshot(owner, 'older', 'messages', profile, sessionID, response({
  112. session_id: sessionID,
  113. messages: [{ id: 'first', timestamp: 1_788_661_640_000, role: 'user', content: '开始' }],
  114. pagination: { total: 2, offset: 1 },
  115. }))
  116. const summary = JSON.parse(f.store.localDetail(owner, profile, sessionID)!.response.body.toString())
  117. expect(summary).toMatchObject({
  118. id: sessionID, profile, source: 'ios', title: '准备 GPT-6 详细 Markdown 文档',
  119. started_at: 1_788_661_637, last_active: 1_788_663_697.824613,
  120. pinned: true, model: 'test-model', message_count: 2,
  121. })
  122. expect(summary).not.toHaveProperty('messages')
  123. expect(summary).not.toHaveProperty('pagination')
  124. f.store.close()
  125. })
  126. it('repairs overwritten summaries on restart using message time instead of cache refresh time', () => {
  127. const f = fixture()
  128. f.store.recordRoute(owner, profile, sessionID, 'runtime-web')
  129. f.store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'ios' })
  130. f.store.putSnapshot(owner, 'messages', 'messages', profile, sessionID, response({
  131. session_id: sessionID,
  132. messages: [
  133. { id: 'first', timestamp: '2026-09-06T03:00:00Z', role: 'user', content: '开始' },
  134. { id: 'last', timestamp: 1_788_663_697.824613, role: 'assistant', content: '完成' },
  135. ],
  136. pagination: { total: 2, offset: 0 },
  137. }))
  138. f.store.db.prepare(`UPDATE chat_sessions SET data=?,owned_at=?,last_synced_at=?
  139. WHERE owner=? AND profile=? AND session_id=?`).run(JSON.stringify({
  140. session_id: sessionID, title: '准备 GPT-6 详细 Markdown 文档', model: 'test-model',
  141. messages: [], pagination: { total: 2 },
  142. }), 1_788_661_637_003, 1_900_000_000_000, owner, profile, sessionID)
  143. f.store.db.prepare("DELETE FROM chat_meta WHERE key='session-activity-v1'").run()
  144. f.store.close()
  145. const restored = new ChatCacheStore(f.home)
  146. const summary = JSON.parse(restored.localList(owner, profile, {}).body.toString()).sessions[0]
  147. expect(summary).toMatchObject({
  148. id: sessionID, source: 'ios', title: '准备 GPT-6 详细 Markdown 文档',
  149. started_at: 1_788_663_600, last_active: 1_788_663_697.824613, message_count: 2,
  150. })
  151. expect(summary).not.toHaveProperty('messages')
  152. expect(summary).not.toHaveProperty('pagination')
  153. restored.close()
  154. const again = new ChatCacheStore(f.home)
  155. expect(JSON.parse(again.localList(owner, profile, {}).body.toString()).sessions[0]).toEqual(summary)
  156. again.close()
  157. })
  158. it('orders owned conversations by real time across seconds and milliseconds', () => {
  159. const f = fixture()
  160. for (const [id, activity] of [['older', 1_788_561_050_759], ['newer', 1_788_663_697.824613]] as const) {
  161. f.store.recordRoute(owner, profile, id, `runtime-${id}`)
  162. f.store.putSnapshot(owner, id, 'detail', profile, id, response({ id, last_active: activity }))
  163. }
  164. expect(JSON.parse(f.store.localList(owner, profile, {}).body.toString()).sessions.map((s: { id: string }) => s.id))
  165. .toEqual(['newer', 'older'])
  166. f.store.close()
  167. })
  168. it('hydrates all owned list metadata before paging and keeps upstream activity aliases authoritative', async () => {
  169. const f = fixture()
  170. const sessions = Array.from({ length: 103 }, (_, index) => ({
  171. id: `owned-${index}`, profile, source: 'web', title: `Conversation ${index}`,
  172. started_at: 1_700_000_000 - index, last_active_at: 1_700_000_100 - index,
  173. message_count: 0, pinned: index === 102,
  174. }))
  175. for (const session of sessions) {
  176. f.store.recordCommand(owner, profile, session.id, 'session.create', { source: 'web' })
  177. }
  178. const load = vi.fn(async () => response({ sessions: [
  179. { id: 'unowned-history', profile, source: 'web', title: 'Private native history' }, ...sessions,
  180. ] }))
  181. const first = await f.coordinator.read(owner, 'first', 'list', profile, undefined, load, true, { limit: 100 })
  182. const firstPage = JSON.parse(first.response.body.toString())
  183. expect(firstPage.sessions[0]).toMatchObject({ id: 'owned-102', last_active: sessions[102]!.last_active_at })
  184. expect(firstPage.sessions[1]).toMatchObject({ id: 'owned-0', last_active: sessions[0]!.last_active_at })
  185. expect(f.store.needsListMetadata(owner, profile)).toBe(false)
  186. const second = await f.coordinator.read(owner, 'second', 'list', profile, undefined, load, true, { offset: 100, limit: 100 })
  187. expect(second.source).toBe('local')
  188. expect(load).toHaveBeenCalledTimes(1)
  189. const secondPage = JSON.parse(second.response.body.toString())
  190. const ids = [...firstPage.sessions, ...secondPage.sessions].map((session: { id: string }) => session.id)
  191. expect(ids).toEqual(['owned-102', ...sessions.slice(0, 102).map(session => session.id)])
  192. expect(f.store.snapshot(owner, 'first')!.response.body.toString()).not.toContain('unowned-history')
  193. expect(f.store.localDetail(owner, profile, 'unowned-history')).toBeUndefined()
  194. f.store.close()
  195. })
  196. it('serves a warm list without a second 9119 request and survives restart', async () => {
  197. const f = fixture()
  198. f.store.recordRoute(owner, profile, sessionID, 'runtime-web')
  199. f.store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'web' })
  200. const search = new URLSearchParams({ source: 'web', profile })
  201. const key = chatCacheKey('list', profile, undefined, search)
  202. const load = vi.fn(async () => response({ sessions: [{ id: sessionID, profile, source: 'web', title: '本地会话' }] }))
  203. f.store.putSnapshot(owner, 'seed-detail', 'detail', profile, sessionID, response({ id: sessionID, profile, title: '本地会话', message_count: 0 }))
  204. const first = await f.coordinator.read(owner, key, 'list', profile, undefined, load, true)
  205. const second = await f.coordinator.read(owner, key, 'list', profile, undefined, load, true)
  206. expect(first.source).toBe('local')
  207. expect(second.source).toBe('local')
  208. expect(load).not.toHaveBeenCalled()
  209. f.store.close()
  210. const restored = new ChatCacheStore(f.home)
  211. const cached = restored.localList(owner, profile, {})
  212. expect(JSON.parse(cached.body.toString()).sessions[0].title).toBe('本地会话')
  213. restored.close()
  214. })
  215. it('reprojects a pre-ownership list snapshot after restart before serving it', async () => {
  216. const f = fixture()
  217. const search = new URLSearchParams({ profile, offset: '0', limit: '100' })
  218. const key = chatCacheKey('list', profile, undefined, search)
  219. f.store.recordRoute(owner, profile, sessionID, 'runtime-web')
  220. f.store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'ios' })
  221. f.store.putSnapshot(owner, key, 'list', profile, undefined, response({
  222. sessions: [{ id: sessionID, profile, source: 'ios', title: '旧快照标题' }],
  223. total: 1,
  224. }), true)
  225. f.store.db.prepare(`UPDATE chat_sessions SET authoritative_title=NULL,authoritative_title_at=0
  226. WHERE owner=? AND profile=? AND session_id=?`).run(owner, profile, sessionID)
  227. expect(JSON.parse(f.store.snapshot(owner, key)!.response.body.toString()).sessions[0].owned)
  228. .toBeUndefined()
  229. f.store.close()
  230. const restored = new ChatCacheStore(f.home)
  231. expect(restored.snapshot(owner, key)?.state).toBe('stale')
  232. expect((restored.db.prepare(`SELECT authoritative_title FROM chat_sessions
  233. WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, sessionID) as { authoritative_title: string }).authoritative_title)
  234. .toBe('旧快照标题')
  235. const coordinator = new ChatCacheCoordinator(
  236. restored,
  237. { request: vi.fn() } as unknown as UpstreamServiceSession,
  238. 'prefer-local',
  239. )
  240. const projected = await coordinator.read(
  241. owner,
  242. key,
  243. 'list',
  244. profile,
  245. undefined,
  246. async () => { throw new Error('9119 offline') },
  247. true,
  248. { offset: 0, limit: 100 },
  249. )
  250. expect(projected).toMatchObject({ source: 'local', state: 'current' })
  251. expect(JSON.parse(projected.response.body.toString()).sessions[0]).toMatchObject({
  252. id: sessionID,
  253. source: 'ios',
  254. owned: true,
  255. })
  256. restored.close()
  257. })
  258. it('adopts the released v0.3.26 registry once without using source for later membership', () => {
  259. const home = mkdtempSync(join(tmpdir(), 'yaoyao-v026-registry-'))
  260. homes.push(home)
  261. const legacy = new DatabaseSync(join(home, 'chat-cache.sqlite3'))
  262. legacy.exec(`CREATE TABLE chat_sessions(
  263. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
  264. runtime_id TEXT, source TEXT NOT NULL, data TEXT NOT NULL,
  265. sync_state TEXT NOT NULL DEFAULT 'stale', complete INTEGER NOT NULL DEFAULT 0,
  266. last_event_seq INTEGER NOT NULL DEFAULT 0, last_synced_at INTEGER NOT NULL,
  267. PRIMARY KEY(owner,profile,session_id))`)
  268. legacy.prepare(`INSERT INTO chat_sessions(
  269. owner,profile,session_id,runtime_id,source,data,sync_state,complete,last_event_seq,last_synced_at
  270. ) VALUES(?,?,?,?,?,?,?,?,?,?)`).run(
  271. owner,
  272. profile,
  273. 'v026-session',
  274. null,
  275. 'web',
  276. JSON.stringify({ id: 'v026-session', profile, source: 'web', title: '已发布旧会话' }),
  277. 'current',
  278. 0,
  279. 0,
  280. 1_000,
  281. )
  282. legacy.close()
  283. const migrated = new ChatCacheStore(home, owner)
  284. expect(migrated.ownsSession(owner, profile, 'v026-session')).toBe(true)
  285. expect(migrated.db.prepare(`SELECT ownership_evidence FROM chat_sessions
  286. WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, 'v026-session'))
  287. .toMatchObject({ ownership_evidence: 'legacy-single-user' })
  288. expect(migrated.putSnapshot(owner, 'new-source-row', 'detail', profile, 'new-source-row',
  289. response({ id: 'new-source-row', profile, source: 'web', title: '未登记新历史' }))).toBe(false)
  290. expect(migrated.ownsSession(owner, profile, 'new-source-row')).toBe(false)
  291. migrated.close()
  292. })
  293. it('does not adopt ambiguous multi-owner legacy cache rows without command evidence', () => {
  294. const home = mkdtempSync(join(tmpdir(), 'yaoyao-v026-multi-owner-'))
  295. homes.push(home)
  296. const legacy = new DatabaseSync(join(home, 'chat-cache.sqlite3'))
  297. legacy.exec(`CREATE TABLE chat_sessions(
  298. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
  299. runtime_id TEXT, source TEXT NOT NULL, data TEXT NOT NULL,
  300. sync_state TEXT NOT NULL DEFAULT 'stale', complete INTEGER NOT NULL DEFAULT 0,
  301. last_event_seq INTEGER NOT NULL DEFAULT 0, last_synced_at INTEGER NOT NULL,
  302. PRIMARY KEY(owner,profile,session_id));
  303. CREATE TABLE chat_events(
  304. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
  305. event_seq INTEGER NOT NULL, event_type TEXT NOT NULL, payload TEXT NOT NULL,
  306. received_at INTEGER NOT NULL, PRIMARY KEY(owner,profile,session_id,event_seq,event_type));`)
  307. const insertSession = legacy.prepare(`INSERT INTO chat_sessions(
  308. owner,profile,session_id,runtime_id,source,data,sync_state,complete,last_event_seq,last_synced_at
  309. ) VALUES(?,?,?,?,?,?,?,?,?,?)`)
  310. for (const [legacyOwner, id] of [
  311. ['owner-a', 'evidenced'],
  312. ['owner-a', 'source-only-a'],
  313. ['owner-b', 'source-only-b'],
  314. ] as const) {
  315. insertSession.run(
  316. legacyOwner,
  317. profile,
  318. id,
  319. null,
  320. 'web',
  321. JSON.stringify({ id, profile, source: 'web', title: id }),
  322. 'current',
  323. 0,
  324. 0,
  325. 1_000,
  326. )
  327. }
  328. legacy.prepare(`INSERT INTO chat_events(
  329. owner,profile,session_id,event_seq,event_type,payload,received_at
  330. ) VALUES(?,?,?,?,?,?,?)`).run(
  331. 'owner-a', profile, 'evidenced', 1, 'command:session.create', '{}', 900,
  332. )
  333. legacy.close()
  334. const migrated = new ChatCacheStore(home, 'owner-a')
  335. expect(migrated.ownsSession('owner-a', profile, 'evidenced')).toBe(true)
  336. expect(migrated.ownsSession('owner-a', profile, 'source-only-a')).toBe(false)
  337. expect(migrated.ownsSession('owner-b', profile, 'source-only-b')).toBe(false)
  338. migrated.close()
  339. })
  340. it('does not adopt one cached owner when the sole local user has another id', () => {
  341. const home = mkdtempSync(join(tmpdir(), 'yaoyao-v026-owner-mismatch-'))
  342. homes.push(home)
  343. const legacy = new DatabaseSync(join(home, 'chat-cache.sqlite3'))
  344. legacy.exec(`CREATE TABLE chat_sessions(
  345. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
  346. runtime_id TEXT, source TEXT NOT NULL, data TEXT NOT NULL,
  347. sync_state TEXT NOT NULL DEFAULT 'stale', complete INTEGER NOT NULL DEFAULT 0,
  348. last_event_seq INTEGER NOT NULL DEFAULT 0, last_synced_at INTEGER NOT NULL,
  349. PRIMARY KEY(owner,profile,session_id))`)
  350. legacy.prepare(`INSERT INTO chat_sessions(
  351. owner,profile,session_id,runtime_id,source,data,sync_state,complete,last_event_seq,last_synced_at
  352. ) VALUES(?,?,?,?,?,?,?,?,?,?)`).run(
  353. 'cached-old-user', profile, 'source-only', null, 'web',
  354. JSON.stringify({ id: 'source-only', profile, source: 'web', title: '旧缓存' }),
  355. 'current', 0, 0, 1_000,
  356. )
  357. legacy.close()
  358. const migrated = new ChatCacheStore(home, 'current-sole-user')
  359. expect(migrated.ownsSession('cached-old-user', profile, 'source-only')).toBe(false)
  360. migrated.close()
  361. })
  362. it('re-enters ownership migration when columns exist but the completion marker is missing', () => {
  363. const home = mkdtempSync(join(tmpdir(), 'yaoyao-v026-interrupted-migration-'))
  364. homes.push(home)
  365. const interrupted = new DatabaseSync(join(home, 'chat-cache.sqlite3'))
  366. interrupted.exec(`CREATE TABLE chat_sessions(
  367. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
  368. runtime_id TEXT, source TEXT NOT NULL, data TEXT NOT NULL,
  369. authoritative_title TEXT, authoritative_title_at INTEGER NOT NULL DEFAULT 0,
  370. owned_at INTEGER, ownership_evidence TEXT,
  371. sync_state TEXT NOT NULL DEFAULT 'stale', complete INTEGER NOT NULL DEFAULT 0,
  372. last_event_seq INTEGER NOT NULL DEFAULT 0, last_synced_at INTEGER NOT NULL,
  373. PRIMARY KEY(owner,profile,session_id))`)
  374. interrupted.prepare(`INSERT INTO chat_sessions(
  375. owner,profile,session_id,runtime_id,source,data,sync_state,complete,last_event_seq,last_synced_at
  376. ) VALUES(?,?,?,?,?,?,?,?,?,?)`).run(
  377. owner, profile, 'interrupted-row', null, 'web',
  378. JSON.stringify({ id: 'interrupted-row', profile, source: 'web', title: '可恢复旧会话' }),
  379. 'current', 0, 0, 1_000,
  380. )
  381. interrupted.close()
  382. const recovered = new ChatCacheStore(home, owner)
  383. expect(recovered.ownsSession(owner, profile, 'interrupted-row')).toBe(true)
  384. expect(recovered.db.prepare("SELECT value FROM chat_meta WHERE key='ownership-registry-v1'").get())
  385. .toMatchObject({ value: 'complete' })
  386. recovered.close()
  387. })
  388. it('materializes complete message pages and keeps owners isolated', () => {
  389. const f = fixture()
  390. f.store.recordRoute(owner, profile, sessionID, 'runtime-web')
  391. f.store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'web' })
  392. f.store.putSnapshot(owner, 'detail', 'detail', profile, sessionID,
  393. response({ id: sessionID, profile, source: 'web', title: '对话' }))
  394. f.store.putSnapshot(owner, 'messages', 'messages', profile, sessionID, response({
  395. session: { id: sessionID, profile, source: 'web', title: '对话' },
  396. messages: [
  397. { id: 'm1', role: 'user', content: '开始' },
  398. { id: 'm2', role: 'assistant', content: '完成' },
  399. ],
  400. pagination: { total: 2, returned: 2, offset: 0, limit: 100, hasMore: false },
  401. }))
  402. const page = f.store.messagePage(owner, profile, sessionID, 0, 100)
  403. const payload = JSON.parse(page!.response.body.toString())
  404. expect(payload.session_id).toBe(sessionID)
  405. expect(payload.pagination).toMatchObject({ total: 2, returned: 2, offset: 0, limit: 100, has_more: false })
  406. expect(payload.messages.map((item: { id: string }) => item.id)).toEqual(['m1', 'm2'])
  407. expect(f.store.messagePage('another-owner', profile, sessionID, 0, 100)).toBeUndefined()
  408. f.store.close()
  409. })
  410. it('never persists unregistered history regardless of source metadata', () => {
  411. const f = fixture()
  412. expect(f.store.putSnapshot(owner, 'history', 'detail', profile, 'history-1',
  413. response({ id: 'history-1', profile, source: 'telegram', title: '历史' }))).toBe(false)
  414. expect(f.store.putSnapshot(owner, 'unowned-web', 'detail', profile, 'unowned-web',
  415. response({ id: 'unowned-web', profile, source: 'web', title: '未登记 Web 历史' }))).toBe(false)
  416. expect(f.store.snapshot(owner, 'history')).toBeUndefined()
  417. expect(f.store.snapshot(owner, 'unowned-web')).toBeUndefined()
  418. f.store.close()
  419. })
  420. it('marks event gaps stale, deduplicates events, and falls back while 9119 is offline', async () => {
  421. const f = fixture()
  422. const key = 'detail-key'
  423. f.store.recordRoute(owner, profile, sessionID, 'runtime-1')
  424. f.store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'web' })
  425. f.store.putSnapshot(owner, key, 'detail', profile, sessionID,
  426. response({ id: sessionID, profile, source: 'web', title: '稳定内容' }))
  427. const frame = { type: 'message.delta', seq: 2, payload: { text: '增量' } }
  428. f.store.recordEvent(owner, profile, sessionID, frame)
  429. f.store.recordEvent(owner, profile, sessionID, frame)
  430. const count = f.store.db.prepare("SELECT COUNT(*) count FROM chat_events WHERE event_type='message.delta'").get() as { count: number }
  431. expect(count.count).toBe(1)
  432. expect(f.store.ownsSession(owner, profile, sessionID)).toBe(true)
  433. expect(f.store.ownsSession('another-owner', profile, sessionID)).toBe(false)
  434. const route = f.store.db.prepare('SELECT runtime_id FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
  435. .get(owner, profile, sessionID) as { runtime_id: string }
  436. expect(route.runtime_id).toBe('runtime-1')
  437. const fallback = await f.coordinator.read(owner, key, 'detail', profile, sessionID,
  438. async () => { throw new Error('9119 offline') })
  439. expect(fallback).toMatchObject({ source: 'local', state: 'stale' })
  440. const serverFailure = await f.coordinator.read(owner, key, 'detail', profile, sessionID,
  441. async () => response({ error: 'unavailable' }, 503))
  442. expect(serverFailure).toMatchObject({ source: 'local', state: 'stale' })
  443. f.store.close()
  444. })
  445. it.each(['session.title', 'session.title.updated'])(
  446. 'projects %s into the owned summary without changing source metadata',
  447. (eventType) => {
  448. const f = fixture()
  449. const ownedSessionID = `owned-${eventType}`
  450. const listKey = chatCacheKey('list', profile, undefined, new URLSearchParams({ source: 'web', profile }))
  451. f.store.recordRoute(owner, profile, ownedSessionID, 'runtime-owned')
  452. f.store.recordCommand(owner, profile, ownedSessionID, 'session.create', { source: 'ios' })
  453. f.store.putSnapshot(owner, listKey, 'list', profile, undefined, response({ sessions: [] }), true)
  454. f.store.recordEvent(owner, profile, ownedSessionID, {
  455. type: eventType,
  456. payload: { session_id: ownedSessionID, title: '服务端生成的标题' },
  457. })
  458. expect(f.store.snapshot(owner, listKey)?.state).toBe('stale')
  459. const merged = f.store.mergeOwnedSessionsIntoList(owner, profile, response({ sessions: [], total: 0 }))
  460. expect(JSON.parse(merged.body.toString()).sessions).toContainEqual(expect.objectContaining({
  461. id: ownedSessionID,
  462. profile,
  463. source: 'ios',
  464. owned: true,
  465. title: '服务端生成的标题',
  466. }))
  467. const staleList = f.store.mergeOwnedSessionsIntoList(owner, profile, response({ sessions: [{
  468. id: ownedSessionID, profile, source: 'ios', title: '新对话',
  469. }] }))
  470. expect(JSON.parse(staleList.body.toString()).sessions[0].title).toBe('服务端生成的标题')
  471. const titleVersion = f.store.db.prepare(`SELECT authoritative_title_at FROM chat_sessions
  472. WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, ownedSessionID) as { authoritative_title_at: number }
  473. expect(f.store.putSnapshot(owner, 'delayed-detail', 'detail', profile, ownedSessionID,
  474. response({ id: ownedSessionID, profile, source: 'ios', title: '迟到的旧标题' }), false,
  475. titleVersion.authoritative_title_at - 1)).toBe(true)
  476. const afterDelayedDetail = f.store.markSessionOwnership(owner, profile, ownedSessionID,
  477. response({ id: ownedSessionID, profile, source: 'ios', title: '迟到的旧标题' }))
  478. expect(JSON.parse(afterDelayedDetail.body.toString()).title).toBe('服务端生成的标题')
  479. expect(f.store.putSnapshot(owner, 'newer-detail', 'detail', profile, ownedSessionID,
  480. response({ id: ownedSessionID, profile, source: 'ios', title: '后续详情标题' }), false,
  481. titleVersion.authoritative_title_at + 1)).toBe(true)
  482. expect(f.store.putSnapshot(owner, 'regressed-detail', 'detail', profile, ownedSessionID,
  483. response({ id: ownedSessionID, profile, source: 'ios', title: '新对话' }))).toBe(true)
  484. const afterDetail = f.store.markSessionOwnership(owner, profile, ownedSessionID,
  485. response({ id: ownedSessionID, profile, source: 'ios', title: '新对话' }))
  486. expect(JSON.parse(afterDetail.body.toString()).title).toBe('后续详情标题')
  487. f.store.close()
  488. },
  489. )
  490. it('accepts detail and messages for a registered session regardless of source metadata', () => {
  491. const f = fixture()
  492. const ownedSessionID = 'owned-ios-session'
  493. f.store.recordRoute(owner, profile, ownedSessionID, 'runtime-owned')
  494. f.store.recordCommand(owner, profile, ownedSessionID, 'session.create', { source: 'ios' })
  495. expect(f.store.putSnapshot(owner, 'owned-detail', 'detail', profile, ownedSessionID,
  496. response({ id: ownedSessionID, profile, source: 'ios', title: 'iOS 权威标题' }))).toBe(true)
  497. expect(f.store.putSnapshot(owner, 'owned-messages', 'messages', profile, ownedSessionID, response({
  498. session: { id: ownedSessionID, profile, source: 'ios', title: 'iOS 权威标题' },
  499. messages: [{ id: 'm-ios', role: 'assistant', content: '已同步' }],
  500. pagination: { total: 1, returned: 1, offset: 0, limit: 100, hasMore: false },
  501. }))).toBe(true)
  502. const page = f.store.messagePage(owner, profile, ownedSessionID, 0, 100)
  503. expect(JSON.parse(page!.response.body.toString())).toMatchObject({
  504. session_id: ownedSessionID,
  505. session: { source: 'ios', title: 'iOS 权威标题' },
  506. messages: [{ id: 'm-ios' }],
  507. })
  508. f.store.close()
  509. })
  510. it('caches only attachment paths discovered in source=web messages', () => {
  511. const f = fixture()
  512. f.store.recordRoute(owner, profile, sessionID, 'runtime-web')
  513. f.store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'web' })
  514. const sourcePath = '/Users/test/.hermes/profiles/default/images/result.png'
  515. f.store.putSnapshot(owner, 'messages', 'messages', profile, sessionID, response({
  516. session: { id: sessionID, profile, source: 'web' },
  517. messages: [{ id: 'm1', role: 'assistant', content: `![结果](${sourcePath})` }],
  518. pagination: { total: 1, offset: 0, hasMore: false },
  519. }))
  520. expect(f.store.knowsAttachment(owner, sourcePath)).toBe(true)
  521. const bytes = response('image-data', 200, 'image/png')
  522. expect(f.store.storeAttachment(owner, sourcePath, bytes)).toBeTruthy()
  523. expect(f.store.attachment(owner, sourcePath)?.mimeType).toBe('image/png')
  524. expect(f.store.knowsAttachment(owner, '/Users/test/history.png')).toBe(false)
  525. f.store.close()
  526. })
  527. it('supports shadow and upstream-only rollback modes', async () => {
  528. const home = mkdtempSync(join(tmpdir(), 'yaoyao-chat-cache-modes-')); homes.push(home)
  529. const store = new ChatCacheStore(home)
  530. const upstream = { request: vi.fn() } as unknown as UpstreamServiceSession
  531. store.recordRoute(owner, profile, sessionID, 'runtime-web')
  532. store.recordCommand(owner, profile, sessionID, 'session.create', { source: 'web' })
  533. const load = vi.fn(async () => response({ sessions: [{ id: sessionID, profile, source: 'web' }] }))
  534. const search = new URLSearchParams({ source: 'web' })
  535. const key = chatCacheKey('list', profile, undefined, search)
  536. const shadow = new ChatCacheCoordinator(store, upstream, 'shadow')
  537. await shadow.read(owner, key, 'list', profile, undefined, load, true)
  538. await shadow.read(owner, key, 'list', profile, undefined, load, true)
  539. expect(load).toHaveBeenCalledTimes(2)
  540. const upstreamOnly = new ChatCacheCoordinator(store, upstream, 'upstream-only')
  541. const upstreamResult = await upstreamOnly.read(owner, key, 'list', profile, undefined, load, true)
  542. expect(load).toHaveBeenCalledTimes(3)
  543. expect(JSON.parse(upstreamResult.response.body.toString()).sessions).toEqual([
  544. expect.objectContaining({ id: sessionID, owned: true }),
  545. ])
  546. upstreamOnly.route(owner, profile, 'upstream-only-created', 'runtime-upstream-only')
  547. expect(store.ownsSession(owner, profile, 'upstream-only-created')).toBe(true)
  548. store.close()
  549. })
  550. it('paginates the complete owner registry before slicing regardless of mixed upstream history', () => {
  551. const f = fixture()
  552. for (let index = 0; index < 15; index++) {
  553. const id = `owned-${index}`
  554. const source = index % 2 ? 'ios' : 'web'
  555. f.store.recordRoute(owner, profile, id, `runtime-${index}`)
  556. f.store.recordCommand(owner, profile, id, 'session.create', { source })
  557. expect(f.store.putSnapshot(owner, `detail-${index}`, 'detail', profile, id, response({
  558. id,
  559. profile,
  560. source,
  561. title: `Owned ${index}`,
  562. last_active: 1_000 + index,
  563. }))).toBe(true)
  564. }
  565. const upstreamSessions = [
  566. ...Array.from({ length: 40 }, (_, index) => ({
  567. id: `unowned-${index}`,
  568. profile,
  569. source: index % 2 ? 'ios' : 'web',
  570. title: `Unowned ${index}`,
  571. last_active: 10_000 + index,
  572. })),
  573. ...Array.from({ length: 15 }, (_, index) => ({
  574. id: `owned-${index}`,
  575. profile,
  576. source: index % 2 ? 'ios' : 'web',
  577. title: '新对话',
  578. last_active: 1_000 + index,
  579. })),
  580. ]
  581. const merged = f.store.mergeOwnedSessionsIntoList(
  582. owner,
  583. profile,
  584. response({ sessions: upstreamSessions, total: upstreamSessions.length }),
  585. { offset: 5, limit: 4, archived: 'exclude' },
  586. )
  587. const payload = JSON.parse(merged.body.toString())
  588. expect(payload).toMatchObject({ total: 15, offset: 5, limit: 4 })
  589. expect(payload.sessions.map((session: { id: string }) => session.id))
  590. .toEqual(['owned-9', 'owned-8', 'owned-7', 'owned-6'])
  591. expect(payload.sessions.every((session: { owned?: boolean }) => session.owned === true)).toBe(true)
  592. const history = f.store.excludeOwnedSessionsFromList(
  593. owner,
  594. profile,
  595. response({ sessions: upstreamSessions, total: upstreamSessions.length }),
  596. { offset: 7, limit: 5 },
  597. )
  598. const historyPayload = JSON.parse(history.body.toString())
  599. expect(historyPayload).toMatchObject({ total: 40, offset: 7, limit: 5 })
  600. expect(historyPayload.sessions.map((session: { id: string }) => session.id))
  601. .toEqual(['unowned-7', 'unowned-8', 'unowned-9', 'unowned-10', 'unowned-11'])
  602. expect(historyPayload.sessions.some((session: { source: string }) => session.source === 'web')).toBe(true)
  603. f.store.close()
  604. })
  605. it('keeps an old pinned owned session on the first page after registry projection', () => {
  606. const f = fixture()
  607. for (let index = 0; index < 101; index++) {
  608. const id = `owned-${index}`
  609. f.store.recordRoute(owner, profile, id, `runtime-${index}`)
  610. f.store.recordCommand(owner, profile, id, 'session.create', { source: 'ios' })
  611. expect(f.store.putSnapshot(owner, `detail-${index}`, 'detail', profile, id, response({
  612. id,
  613. profile,
  614. source: 'ios',
  615. title: `Owned ${index}`,
  616. last_active: 1_000 + index,
  617. pinned: index === 0,
  618. }))).toBe(true)
  619. }
  620. const merged = f.store.mergeOwnedSessionsIntoList(
  621. owner,
  622. profile,
  623. response({ sessions: [], total: 0 }),
  624. { offset: 0, limit: 100, archived: 'exclude' },
  625. )
  626. const payload = JSON.parse(merged.body.toString())
  627. expect(payload).toMatchObject({ total: 101, offset: 0, limit: 100 })
  628. expect(payload.sessions).toHaveLength(100)
  629. expect(payload.sessions[0]).toMatchObject({ id: 'owned-0', pinned: true, owned: true })
  630. expect(payload.sessions.map((session: { id: string }) => session.id)).not.toContain('owned-1')
  631. f.store.close()
  632. })
  633. })
  634. describe('local history and bounded tail synchronization', () => {
  635. function cached(count = 1_000) {
  636. const f = fixture()
  637. f.store.recordRoute(owner, profile, sessionID, 'runtime')
  638. const rows = Array.from({ length: count }, (_, i) => ({ id: `row-${i}`, role: i % 2 ? 'assistant' : 'user', content: `message ${i}` }))
  639. const summary = { id: sessionID, profile, title: 'cached', message_count: count }
  640. f.store.putSnapshot(owner, 'seed', 'messages', profile, sessionID, response({ session: summary, messages: rows,
  641. pagination: { total: count, offset: 0, has_more: false } }))
  642. return { ...f, rows, summary }
  643. }
  644. function upstreamFor(f: ReturnType<typeof cached>, rows: typeof f.rows) {
  645. const request = vi.fn(async (path: string, options: { search: URLSearchParams }) => {
  646. if (!path.endsWith('/messages')) return response({ ...f.summary, message_count: rows.length })
  647. const offset = Number(options.search.get('offset'))
  648. const limit = Number(options.search.get('limit'))
  649. const end = Math.max(0, rows.length - offset), start = Math.max(0, end - limit)
  650. return response({ messages: rows.slice(start, end), pagination: { total: rows.length, offset, has_more: start > 0 } })
  651. })
  652. const coordinator = new ChatCacheCoordinator(f.store, { request } as unknown as UpstreamServiceSession)
  653. return { coordinator, request }
  654. }
  655. it('never rereads stored pages while a new turn invalidates the tail', async () => {
  656. const f = cached()
  657. f.store.recordCommand(owner, profile, sessionID, 'prompt.submit', { text: 'next' })
  658. f.store.recordEvent(owner, profile, sessionID, { type: 'message.delta', seq: 1, payload: { delta: 'new' } })
  659. const load = vi.fn(async () => { throw new Error('must remain local') })
  660. for (let i = 0; i < 20; i++) {
  661. const page = await f.coordinator.messages(owner, `page-${i}`, profile, sessionID, (i % 10) * 100, 100, load)
  662. expect(page.source).toBe('local')
  663. expect(JSON.parse(page.response.body.toString()).messages).toHaveLength(100)
  664. }
  665. expect(load).not.toHaveBeenCalled()
  666. f.store.close()
  667. })
  668. it('persists new rows using one tail page and does not rewrite unchanged history', async () => {
  669. const f = cached()
  670. f.store.db.exec('CREATE TABLE changed_rows(id TEXT); CREATE TRIGGER changed_message AFTER UPDATE ON chat_messages BEGIN INSERT INTO changed_rows VALUES(new.message_id); END')
  671. const rows = [...f.rows, { id: 'new-user', role: 'user', content: 'next' }, { id: 'new-answer', role: 'assistant', content: 'answer' }]
  672. const { coordinator, request } = upstreamFor(f, rows)
  673. coordinator.observe(owner, profile, sessionID, { type: 'message.complete', seq: 1 })
  674. const page = await coordinator.messages(owner, 'last', profile, sessionID, 0, 10, async () => { throw new Error('unexpected read') })
  675. expect(JSON.parse(page.response.body.toString()).messages.at(-1).id).toBe('new-answer')
  676. expect(request.mock.calls.filter(([path]) => path.endsWith('/messages'))).toHaveLength(1)
  677. expect(f.store.db.prepare('SELECT * FROM changed_rows').all()).toEqual([])
  678. expect(f.store.messagePage(owner, profile, sessionID, 902, 100)).toBeDefined()
  679. coordinator.observe(owner, profile, sessionID, { type: 'message.complete', seq: 1 })
  680. expect(request).toHaveBeenCalledTimes(2)
  681. f.store.close()
  682. })
  683. it('fetches only the missing suffix after a replay gap', async () => {
  684. const f = cached()
  685. const rows = [...f.rows, ...Array.from({ length: 130 }, (_, i) => ({ id: `new-${i}`, role: 'assistant', content: 'reply' }))]
  686. const { coordinator, request } = upstreamFor(f, rows)
  687. await coordinator.reconcile(owner, profile, sessionID)
  688. expect(request.mock.calls.filter(([path]) => path.endsWith('/messages'))).toHaveLength(2)
  689. expect(JSON.parse(f.store.messagePage(owner, profile, sessionID, 0, 10)!.response.body.toString()).pagination.total).toBe(1130)
  690. f.store.close()
  691. })
  692. it('refreshes old edits and deletions only when explicitly forced', async () => {
  693. const f = cached()
  694. const rows = f.rows.slice(1).map(row => row.id === 'row-2' ? { ...row, content: 'edited old message' } : row)
  695. const { coordinator, request } = upstreamFor(f, rows)
  696. await expect(coordinator.reconcile(owner, profile, sessionID)).rejects.toThrow('explicit refresh')
  697. expect(JSON.parse(f.store.messagePage(owner, profile, sessionID, 900, 100)!.response.body.toString()).messages[0].id).toBe('row-0')
  698. request.mockClear()
  699. await coordinator.reconcile(owner, profile, sessionID, true)
  700. expect(request.mock.calls.filter(([path]) => path.endsWith('/messages'))).toHaveLength(10)
  701. const page = JSON.parse(f.store.messagePage(owner, profile, sessionID, 899, 100)!.response.body.toString())
  702. expect(page.messages[0].id).toBe('row-1')
  703. expect(page.messages[1].content).toBe('edited old message')
  704. expect(page.pagination.total).toBe(999)
  705. f.store.close()
  706. })
  707. it('does not require a full archive before serving a stored page', async () => {
  708. const f = fixture()
  709. f.store.recordRoute(owner, profile, sessionID, 'runtime')
  710. f.store.putSnapshot(owner, 'tail', 'messages', profile, sessionID, response({ messages: [{ id: 'last', role: 'assistant', content: 'tail' }], pagination: { total: 400, offset: 0, has_more: true } }))
  711. expect(f.store.messagePage(owner, profile, sessionID, 0, 1)).toBeDefined()
  712. expect(f.store.messagePage(owner, profile, sessionID, 1, 100)).toBeUndefined()
  713. f.store.close()
  714. })
  715. it('keeps the previous archive when a forced refresh fails halfway', async () => {
  716. const f = cached()
  717. let calls = 0
  718. const coordinator = new ChatCacheCoordinator(f.store, { request: async (path: string) => {
  719. if (!path.endsWith('/messages')) return response(f.summary)
  720. if (++calls > 1) throw new Error('offline')
  721. return response({ messages: f.rows.slice(-100), pagination: { total: 1000, offset: 0, has_more: true } })
  722. } } as unknown as UpstreamServiceSession)
  723. await expect(coordinator.reconcile(owner, profile, sessionID, true)).rejects.toThrow('offline')
  724. expect(f.store.messagePage(owner, profile, sessionID, 900, 100)).toBeDefined()
  725. f.store.close()
  726. })
  727. it('does not commit an older fetch over a newer event', async () => {
  728. const f = cached()
  729. const { coordinator, request } = upstreamFor(f, f.rows)
  730. const original = request.getMockImplementation()!
  731. request.mockImplementation(async (path, options) => {
  732. const result = await original(path, options)
  733. if (path.endsWith('/messages')) f.store.recordEvent(owner, profile, sessionID, { type: 'message.delta', seq: 2, payload: { delta: 'newer' } })
  734. return result
  735. })
  736. await coordinator.reconcile(owner, profile, sessionID)
  737. expect(f.store.localDetail(owner, profile, sessionID)?.state).toBe('stale')
  738. f.store.close()
  739. })
  740. it('joins an in-flight completion and publishes only after the newest revision commits', async () => {
  741. const f = cached()
  742. const rows = [...f.rows, { id: 'newest', role: 'assistant', content: 'newest reply' }]
  743. const { coordinator, request } = upstreamFor(f, rows)
  744. const original = request.getMockImplementation()!
  745. let release!: () => void
  746. const gate = new Promise<void>(resolve => { release = resolve })
  747. let first = true
  748. request.mockImplementation(async (path, options) => {
  749. if (first) { first = false; await gate }
  750. return original(path, options)
  751. })
  752. const published = vi.fn(() => {
  753. const stored = JSON.parse(f.store.messagePage(owner, profile, sessionID, 0, 1)!.response.body.toString())
  754. expect(stored.messages[0].id).toBe('newest')
  755. })
  756. coordinator.onSynchronized = published
  757. f.store.recordEvent(owner, profile, sessionID, { type: 'message.complete', seq: 1 })
  758. const firstSync = coordinator.reconcile(owner, profile, sessionID)
  759. f.store.recordEvent(owner, profile, sessionID, { type: 'message.complete', seq: 2 })
  760. const latestSync = coordinator.reconcile(owner, profile, sessionID)
  761. release()
  762. await Promise.all([firstSync, latestSync])
  763. expect(published).toHaveBeenCalledTimes(1)
  764. expect(request).toHaveBeenCalledTimes(4)
  765. expect(f.store.localDetail(owner, profile, sessionID)?.state).toBe('current')
  766. f.store.close()
  767. })
  768. it('serves a cached empty conversation without requesting it again', async () => {
  769. const f = cached(0)
  770. const load = vi.fn(async () => { throw new Error('unexpected read') })
  771. const page = await f.coordinator.messages(owner, 'empty', profile, sessionID, 0, 100, load)
  772. expect(page.source).toBe('local')
  773. expect(JSON.parse(page.response.body.toString()).messages).toEqual([])
  774. expect(load).not.toHaveBeenCalled()
  775. f.store.close()
  776. })
  777. })