session.spec.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /**
  2. * Session orchestration: drive the object through contract calls and injected
  3. * frames (open → prompt → stream → finalize → cancel → resync) and assert the
  4. * ConversationSnapshot it settles into. Reference stability is asserted with
  5. * toBe/not.toBe — it is the React.memo/uSES contract, equal-value output is not
  6. * enough.
  7. */
  8. import { describe, expect, it, vi } from 'vitest'
  9. import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
  10. import type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
  11. import { Session } from '../src/client/sessions/session.ts'
  12. import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
  13. import { entries, ev, plainTurn } from './event-script.ts'
  14. const at = (seq: number, e: Record<string, unknown>): SessionEvent =>
  15. ({ seq, time: 1_700_000_000_000 + seq, ...e }) as unknown as SessionEvent
  16. const SID = 'fk-s1' as SessionId
  17. function makeSession(api = new FakeApiClient()): { api: FakeApiClient; session: Session } {
  18. return { api, session: new Session(SID, api) }
  19. }
  20. function histResponse(events: SessionEvent[], hasMore = false) {
  21. // history now returns HistoryEntry[] ({event, view?}); these tests are view-less.
  22. return Promise.resolve(ok({ events: entries(events) as never[], hasMore }))
  23. }
  24. describe('open', () => {
  25. it('installs the tail page: cold → loading → open with window and nodes in place', async () => {
  26. const { api, session } = makeSession()
  27. const page = plainTurn(10, 3, '问', '答')
  28. api.onHistory = () => histResponse(page, true)
  29. expect(session.getSnapshot().openState).toBe('cold')
  30. const opening = session.open()
  31. expect(session.getSnapshot().openState).toBe('loading')
  32. await opening
  33. const snapshot = session.getSnapshot()
  34. expect(snapshot.openState).toBe('open')
  35. expect(snapshot.hasMore).toBe(true)
  36. expect(snapshot.nodes.map(n => n.kind)).toEqual(['user', 'assistant'])
  37. })
  38. it('is idempotent: concurrent opens share one history call, reopening when open is a no-op', async () => {
  39. const { api, session } = makeSession()
  40. await Promise.all([session.open(), session.open()])
  41. await session.open()
  42. expect(api.callsOf('session.history')).toHaveLength(1)
  43. })
  44. it('lands an error result in openState=error with the RpcError kept', async () => {
  45. const { api, session } = makeSession()
  46. api.onHistory = () => Promise.resolve(err({ code: 'session-not-found', message: 'gone', details: { sessionId: SID } }))
  47. await session.open()
  48. const snapshot = session.getSnapshot()
  49. expect(snapshot.openState).toBe('error')
  50. expect(snapshot.openError?.code).toBe('session-not-found')
  51. })
  52. it('folds a transport throw into openState=error / internal', async () => {
  53. const { api, session } = makeSession()
  54. api.onHistory = () => Promise.reject(new Error('socket died'))
  55. await session.open()
  56. expect(session.getSnapshot().openState).toBe('error')
  57. expect(session.getSnapshot().openError).toMatchObject({ code: 'internal', message: 'socket died' })
  58. })
  59. it('stitches live frames arriving while history is pending, dropping the page overlap', async () => {
  60. const { api, session } = makeSession()
  61. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  62. api.onHistory = () => gate.promise
  63. const opening = session.open()
  64. // Three live frames land mid-open; seq 15 overlaps the page tail (page covers 10..15).
  65. const page = plainTurn(10, 0, '早', '安')
  66. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.turnStart(15, 1) })
  67. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(16, '插进来的') })
  68. gate.resolve(ok({ events: entries(page) as never[], hasMore: false }))
  69. await opening
  70. const seqs = session.getSnapshot().nodes.map(n => n.seq)
  71. // Overlapping seq-15 frame (== page tail turn/end) was dropped; 16 appended once.
  72. expect(seqs).toEqual([11, 13, 16])
  73. })
  74. })
  75. describe('live event path', () => {
  76. async function opened(events: SessionEvent[] = plainTurn(0, 0, 'a', 'b')) {
  77. const { api, session } = makeSession()
  78. api.onHistory = () => histResponse(events)
  79. await session.open()
  80. return { api, session }
  81. }
  82. it('drops replayed frames at or below the window tail', async () => {
  83. const { session } = await opened()
  84. const before = session.getSnapshot()
  85. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(3, '重放') })
  86. await Promise.resolve()
  87. expect(session.getSnapshot().nodes).toEqual(before.nodes)
  88. })
  89. it('accumulates chunks into partial, then finalize swaps partial out as the node lands', async () => {
  90. const { session } = await opened()
  91. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  92. feed(ev.turnStart(6, 1))
  93. feed(ev.user(7, '流式问'))
  94. feed(ev.chunkStart(8, 1))
  95. feed(ev.chunkText(9, 1, '半截'))
  96. let snapshot = session.getSnapshot()
  97. expect(snapshot.partial).toMatchObject({ turn: 1, blocks: [{ kind: 'text', text: '半截' }] })
  98. feed(ev.chunkText(10, 1, '回复'))
  99. expect(session.getSnapshot().partial?.blocks).toEqual([{ kind: 'text', text: '半截回复' }])
  100. feed(ev.assistant(11, 1, '半截回复'))
  101. feed(ev.turnEnd(12, 1))
  102. snapshot = session.getSnapshot()
  103. expect(snapshot.partial).toBeNull()
  104. const last = snapshot.nodes.at(-1)
  105. expect(last).toMatchObject({ kind: 'assistant', blocks: [{ kind: 'text', text: '半截回复' }] })
  106. expect((last as { interrupted?: true }).interrupted).toBeUndefined()
  107. })
  108. it('freezes an unfinalized partial into an interrupted node on turn/end (cancel path)', async () => {
  109. const { session } = await opened()
  110. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  111. feed(ev.turnStart(6, 1))
  112. feed(ev.user(7, '要被打断的'))
  113. feed(ev.chunkStart(8, 1))
  114. feed(ev.chunkText(9, 1, '说到一半'))
  115. feed(ev.turnEnd(10, 1, 'cancelled')) // no assistant/message ever arrives
  116. const snapshot = session.getSnapshot()
  117. expect(snapshot.partial).toBeNull()
  118. const frozen = snapshot.nodes.at(-1)
  119. expect(frozen).toMatchObject({ kind: 'assistant', interrupted: true, blocks: [{ kind: 'text', text: '说到一半' }] })
  120. // Ordered inside the flow: after the user message (seq 7), before any later turn.
  121. expect((frozen as { seq: number }).seq).toBeGreaterThan(7)
  122. })
  123. it('tracks tool calls in runningCalls and converts orphans to interrupted tool-result cards on turn/end', async () => {
  124. const { session } = await opened()
  125. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  126. feed(ev.turnStart(6, 1))
  127. feed(ev.toolCall(7, 1, 'c1', 'echo', '{"a":1}'))
  128. expect(session.getSnapshot().runningCalls).toMatchObject([{ callId: 'c1', name: 'echo' }])
  129. feed(ev.toolResult(8, 1, 'c1', 'ECHO'))
  130. expect(session.getSnapshot().runningCalls).toEqual([])
  131. // Second call never resolves: turn/end freezes it as an error card.
  132. feed(ev.toolCall(9, 1, 'c2', 'slow_tool', '{}'))
  133. feed(ev.turnEnd(10, 1, 'cancelled'))
  134. const snapshot = session.getSnapshot()
  135. expect(snapshot.runningCalls).toEqual([])
  136. expect(snapshot.nodes.at(-1)).toMatchObject({
  137. kind: 'tool-result', callId: 'c2', isError: true, error: { code: 'interrupted' },
  138. })
  139. })
  140. it('repairs a seq gap by repulling the tail page instead of appending a hole', async () => {
  141. const { api, session } = await opened(plainTurn(0, 0, 'a', 'b')) // tail seq = 5
  142. const repaired = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  143. api.onHistory = () => histResponse(repaired)
  144. // seq 9 with tail 5 → gap; the event detours to the buffer and one history refetch fires.
  145. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.assistant(9, 1, 'd') })
  146. await vi.waitFor(() => {
  147. expect(api.callsOf('session.history').length).toBe(2)
  148. })
  149. await Promise.resolve()
  150. const seqs = session.getSnapshot().nodes.map(n => n.seq)
  151. expect(seqs).toEqual([1, 3, 7, 9]) // both turns' user/assistant, no hole, no duplicate 9
  152. })
  153. })
  154. describe('paging', () => {
  155. it('prepends an older page and keeps seq continuity', async () => {
  156. const older = plainTurn(0, 0, '旧问', '旧答')
  157. const newer = plainTurn(6, 1, '新问', '新答')
  158. const { api, session } = makeSession()
  159. api.onHistory = payload => payload.beforeSeq === undefined
  160. ? histResponse(newer, true)
  161. : histResponse(older, false)
  162. await session.open()
  163. await session.loadOlder()
  164. const snapshot = session.getSnapshot()
  165. expect(api.callsOf('session.history')).toMatchObject([{}, { beforeSeq: 6 }].map(p => ({ sessionId: SID, ...p })))
  166. expect(snapshot.hasMore).toBe(false)
  167. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  168. })
  169. it('drops a discontinuous older page fail-soft (window unchanged, hasMore cleared)', async () => {
  170. const { api, session } = makeSession()
  171. api.onHistory = payload => payload.beforeSeq === undefined
  172. ? histResponse(plainTurn(10, 1, '新', '页'), true)
  173. : histResponse(plainTurn(0, 0, '断', '层'), true) // tail seq 5, but baseSeq is 10 → hole
  174. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  175. try {
  176. await session.open()
  177. const nodesBefore = session.getSnapshot().nodes
  178. await session.loadOlder()
  179. const snapshot = session.getSnapshot()
  180. expect(snapshot.nodes).toEqual(nodesBefore)
  181. expect(snapshot.hasMore).toBe(false)
  182. } finally {
  183. errorSpy.mockRestore()
  184. }
  185. })
  186. it('ignores loadOlder while one is in flight (single request)', async () => {
  187. const { api, session } = makeSession()
  188. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  189. await session.open()
  190. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  191. api.onHistory = () => gate.promise
  192. const first = session.loadOlder()
  193. const second = session.loadOlder()
  194. gate.resolve(ok({ events: entries(plainTurn(0, 0, 'a', 'b')) as never[], hasMore: false }))
  195. await Promise.all([first, second])
  196. expect(api.callsOf('session.history')).toHaveLength(2) // open + one page, not two
  197. })
  198. })
  199. describe('prompt and cancel errors', () => {
  200. it('sends content through session.prompt with the mode passed through', async () => {
  201. const { api, session } = makeSession()
  202. const result = await session.prompt([{ type: 'text', text: '要发的' }], 'queue')
  203. expect(result.ok).toBe(true)
  204. expect(api.callsOf('session.prompt')).toMatchObject([{ sessionId: SID, mode: 'queue', content: [{ type: 'text', text: '要发的' }] }])
  205. })
  206. it('business failure lands in promptError with op=send', async () => {
  207. const { api, session } = makeSession()
  208. api.onPrompt = () => Promise.resolve(err({ code: 'agent-busy', message: 'busy', details: { reason: 'x' } }))
  209. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue')
  210. expect(result.ok).toBe(false)
  211. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'agent-busy' } })
  212. })
  213. it('lands cancel failures in promptError with op=stop', async () => {
  214. const { api, session } = makeSession()
  215. api.onCancel = () => Promise.reject(new Error('cancel transport down'))
  216. const result = await session.cancel()
  217. expect(result.ok).toBe(false)
  218. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'internal' } })
  219. })
  220. })
  221. describe('pending interactions', () => {
  222. it('adds approval/question on requested and removes them on resolved', async () => {
  223. const { session } = makeSession()
  224. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  225. session.handleMuxEnvelope('rq' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  226. expect(session.getSnapshot().pending.map(p => p.kind).sort()).toEqual(['approval', 'question'])
  227. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap1' as never, outcome: 'approved' as never })
  228. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq' as never, outcome: 'answered' })
  229. expect(session.getSnapshot().pending).toEqual([])
  230. })
  231. it('mints waits whose respond() backfills the requested rpcId into the client-response envelope', async () => {
  232. const { api, session } = makeSession()
  233. session.handleMuxEnvelope('rq-answer' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  234. const wait = session.getSnapshot().pending[0]!
  235. expect(wait).toMatchObject({ kind: 'question', key: 'q:rq-answer', sessionId: SID, payload: { questions: [] } })
  236. const receipt = await wait.respond({
  237. ok: true,
  238. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  239. })
  240. expect(receipt).toEqual({ accepted: true })
  241. expect(api.callsOf('respond')).toEqual([{
  242. type: 'client-response', rpcId: 'rq-answer',
  243. result: {
  244. ok: true,
  245. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  246. },
  247. }])
  248. })
  249. it('settles the wait on the authoritative resolved frame: respond() then throws synchronously', async () => {
  250. const { api, session } = makeSession()
  251. session.handleMuxEnvelope('rq1' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  252. const wait = session.getSnapshot().pending[0]!
  253. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq1' as never, outcome: 'answered' })
  254. expect(session.getSnapshot().pending).toEqual([])
  255. expect(() => wait.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } }))
  256. .toThrow('already settled')
  257. expect(api.callsOf('respond')).toEqual([])
  258. })
  259. })
  260. describe('remaining branches', () => {
  261. it('prompt transport throw folds to internal promptError', async () => {
  262. const { api, session } = makeSession()
  263. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  264. const result = await session.prompt([{ type: 'text', text: 'x' }], 'queue')
  265. expect(result.ok).toBe(false)
  266. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'internal', message: 'prompt wire down' } })
  267. })
  268. it('cancel business error also lands op=stop promptError', async () => {
  269. const { api, session } = makeSession()
  270. api.onCancel = () => Promise.resolve(err({ code: 'agent-busy', message: 'nope', details: { reason: 'r' } }))
  271. await session.cancel()
  272. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'agent-busy' } })
  273. })
  274. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  275. const { api, session } = makeSession()
  276. await session.loadOlder() // cold: no-op, zero calls
  277. expect(api.calls).toEqual([])
  278. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  279. await session.open()
  280. // err result: window unchanged
  281. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  282. await session.loadOlder()
  283. expect(session.getSnapshot().nodes).toHaveLength(2)
  284. expect(session.getSnapshot().hasMore).toBe(true)
  285. // empty page: hasMore adopts the response
  286. api.onHistory = () => histResponse([], false)
  287. await session.loadOlder()
  288. expect(session.getSnapshot().hasMore).toBe(false)
  289. // hasMore false now: further loadOlder is a guard no-op
  290. const calls = api.calls.length
  291. await session.loadOlder()
  292. expect(api.calls.length).toBe(calls)
  293. // throw path: fail-soft with console.error
  294. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  295. try {
  296. await session.resync()
  297. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  298. await session.resync()
  299. api.onHistory = () => Promise.reject(new Error('page wire down'))
  300. await session.loadOlder()
  301. expect(errorSpy).toHaveBeenCalled()
  302. expect(session.getSnapshot().loadingOlder).toBe(false)
  303. } finally {
  304. errorSpy.mockRestore()
  305. }
  306. })
  307. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  308. const { api, session } = makeSession()
  309. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  310. let notified = 0
  311. const unsubscribe = session.subscribe(() => { notified++ })
  312. await session.open()
  313. await new Promise(resolve => setTimeout(resolve, 0))
  314. expect(notified).toBeGreaterThan(0)
  315. const seen = notified
  316. unsubscribe()
  317. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  318. await new Promise(resolve => setTimeout(resolve, 0))
  319. expect(notified).toBe(seen)
  320. })
  321. it('subscribed baseline past the window tail triggers the second stitch pull in doOpen', async () => {
  322. const { api, session } = makeSession()
  323. const full = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  324. let call = 0
  325. api.onHistory = () => {
  326. call++
  327. return histResponse(call === 1 ? plainTurn(0, 0, 'a', 'b') : full)
  328. }
  329. // Baseline arrives before open: lastSeq 11 > first page tail 5 → doOpen repulls once.
  330. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  331. await session.open()
  332. expect(call).toBe(2)
  333. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  334. })
  335. it('a failed second stitch pull keeps the first window and still opens', async () => {
  336. const { api, session } = makeSession()
  337. let call = 0
  338. api.onHistory = () => {
  339. call++
  340. return call === 1
  341. ? histResponse(plainTurn(0, 0, 'a', 'b'))
  342. : Promise.resolve(err({ code: 'internal', message: 'stitch pull down', details: {} }))
  343. }
  344. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  345. await session.open()
  346. expect(call).toBe(2)
  347. const snapshot = session.getSnapshot()
  348. expect(snapshot.openState).toBe('open') // stitch-pull failure is not an open failure
  349. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3]) // first window kept
  350. })
  351. it('approval frame with callId/reason keeps the optional fields; duplicate resolved is a no-op', () => {
  352. const { session } = makeSession()
  353. session.handleMuxEnvelope('ra' as never, {
  354. type: 'approval/requested', sessionId: SID, approvalId: 'ap2' as never, toolName: 'rm', callId: 'c1' as never, reason: '危险',
  355. })
  356. expect(session.getSnapshot().pending[0]).toMatchObject({ kind: 'approval', payload: { callId: 'c1', reason: '危险' } })
  357. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  358. session.handleMuxEnvelope('rx2' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  359. session.handleMuxEnvelope('ry2' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'never-was' as never, outcome: 'cancelled' })
  360. expect(session.getSnapshot().pending).toEqual([])
  361. })
  362. it('ignores unknown mux frame types and repeated running flips (documented defaults)', () => {
  363. const { session } = makeSession()
  364. const before = session.getSnapshot()
  365. session.handleMuxEnvelope('rz' as never, { type: 'future/frame' } as never)
  366. session.handleRunning(false) // already false: dedup branch
  367. expect(session.getSnapshot()).toBe(before)
  368. session.handleRemoved()
  369. expect(session.getSnapshot().removed).toBe(true)
  370. })
  371. it('drops live events while cold/error (no window upkeep)', async () => {
  372. const { api, session } = makeSession()
  373. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '冷态帧') })
  374. expect(session.getSnapshot().nodes).toEqual([])
  375. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  376. await session.open()
  377. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '错态帧') })
  378. expect(session.getSnapshot().nodes).toEqual([])
  379. })
  380. it('repairGap failure logs and clears stitching; concurrent gaps coalesce into one repair', async () => {
  381. const { api, session } = makeSession()
  382. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  383. await session.open()
  384. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  385. let repairs = 0
  386. api.onHistory = () => {
  387. repairs++
  388. return gate.promise
  389. }
  390. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  391. try {
  392. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞一') })
  393. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(10, '洞二') }) // stitching: detours, no second repair
  394. expect(repairs).toBe(1)
  395. gate.reject(new Error('repair wire down'))
  396. await vi.waitFor(() => { expect(errorSpy).toHaveBeenCalled() })
  397. // Window unchanged; a later successful repull still lands the buffered frames.
  398. expect(session.getSnapshot().nodes).toHaveLength(2)
  399. } finally {
  400. errorSpy.mockRestore()
  401. }
  402. })
  403. it('freezes only content-bearing partials; a content-free partial is dropped outright', async () => {
  404. const { api, session } = makeSession()
  405. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  406. await session.open()
  407. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  408. feed(ev.turnStart(6, 1))
  409. feed(ev.chunkStart(7, 1)) // empty text block only, no delta
  410. feed(ev.turnEnd(8, 1, 'cancelled'))
  411. const snapshot = session.getSnapshot()
  412. expect(snapshot.partial).toBeNull()
  413. expect(snapshot.nodes.filter(n => n.kind === 'assistant' && (n as { interrupted?: true }).interrupted)).toEqual([])
  414. })
  415. it('turn/end sweeps only same-turn open calls; other turns keep running', async () => {
  416. const { api, session } = makeSession()
  417. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  418. await session.open()
  419. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  420. feed(ev.turnStart(6, 1))
  421. feed(ev.toolCall(7, 1, 'turn1-call', 'echo', '{}'))
  422. feed(ev.toolCall(8, 2, 'turn2-call', 'echo', '{}')) // stray call attributed to a later turn
  423. feed(ev.turnEnd(9, 1, 'cancelled'))
  424. const snapshot = session.getSnapshot()
  425. expect(snapshot.runningCalls.map(c => c.callId)).toEqual(['turn2-call'])
  426. expect(snapshot.nodes.at(-1)).toMatchObject({ kind: 'tool-result', callId: 'turn1-call', isError: true })
  427. })
  428. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  429. const { api, session } = makeSession()
  430. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  431. api.onHistory = () => stale.promise
  432. const opening = session.open()
  433. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  434. const resynced = session.resync()
  435. stale.reject(new Error('stale wire'))
  436. await Promise.all([opening, resynced])
  437. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  438. })
  439. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  440. const { api, session } = makeSession()
  441. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  442. api.onHistory = () => stale.promise
  443. const opening = session.open()
  444. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  445. const resynced = session.resync()
  446. stale.resolve(ok({ events: entries(plainTurn(0, 0, '旧', '代')) as never[], hasMore: false })) // success, but its generation is gone
  447. await Promise.all([opening, resynced])
  448. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9]) // only the fresh generation's window
  449. })
  450. it('drops a stale stitch pull (second doOpen fetch) superseded mid-flight by resync', async () => {
  451. const { api, session } = makeSession()
  452. const secondPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  453. let call = 0
  454. api.onHistory = () => {
  455. call++
  456. if (call === 1) return histResponse(plainTurn(0, 0, 'a', 'b')) // first page: tail 5
  457. if (call === 2) return secondPull.promise // gap-stitch pull: held
  458. return histResponse(plainTurn(6, 1, 'c', 'd'))
  459. }
  460. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  461. const opening = session.open() // triggers the second pull, which parks
  462. await vi.waitFor(() => { expect(call).toBe(2) })
  463. const resynced = session.resync()
  464. secondPull.resolve(ok({ events: entries([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]) as never[], hasMore: false }))
  465. await Promise.all([opening, resynced])
  466. expect(session.getSnapshot().openState).toBe('open')
  467. })
  468. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  469. const { api, session } = makeSession()
  470. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  471. await session.open()
  472. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  473. api.onHistory = () => repairPull.promise
  474. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞') }) // starts repairGap
  475. api.onHistory = () => histResponse(plainTurn(6, 1, 'c', 'd'))
  476. const resynced = session.resync() // bumps the generation
  477. repairPull.resolve(ok({ events: entries(plainTurn(0, 0, '旧', '页')) as never[], hasMore: false })) // repair result: stale, dropped
  478. await resynced
  479. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9])
  480. })
  481. it('successful cancel leaves no promptError; tool/result for an unknown callId is a no-op', async () => {
  482. const { api, session } = makeSession()
  483. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  484. await session.open()
  485. const result = await session.cancel()
  486. expect(result.ok).toBe(true)
  487. expect(session.getSnapshot().promptError).toBeNull()
  488. const callsBefore = session.getSnapshot().runningCalls
  489. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.toolResult(6, 0, 'never-called', 'x') })
  490. expect(session.getSnapshot().runningCalls).toBe(callsBefore) // callsRev untouched: same reference
  491. })
  492. it('freezes a tool-call-only partial (visible through the non-text arm)', async () => {
  493. const { api, session } = makeSession()
  494. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  495. await session.open()
  496. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  497. feed(ev.turnStart(6, 1))
  498. feed(at(7, { type: 'assistant/chunk', data: { turn: 1, step: 0, chunk: { type: 'tool-call-delta', index: 0, id: 'c1', name: 'echo', argumentsDelta: '{' } } }))
  499. feed(ev.turnEnd(8, 1, 'cancelled'))
  500. const frozen = session.getSnapshot().nodes.at(-1)
  501. expect(frozen).toMatchObject({ kind: 'assistant', interrupted: true, blocks: [{ kind: 'tool-call', callId: 'c1' }] })
  502. })
  503. it('dispose is a reserved no-op on resident instances', () => {
  504. const { session } = makeSession()
  505. expect(() => { session.dispose() }).not.toThrow()
  506. })
  507. it('carries mux-frame views into runningCalls and tool-result nodes, and history-entry views through open', async () => {
  508. const { api, session } = makeSession()
  509. const callView = { for: 'call', view: { card: 'generic', title: '历史卡' } }
  510. api.onHistory = () => Promise.resolve(ok({
  511. events: [
  512. ...entries(plainTurn(0, 0, 'a', 'b')),
  513. { event: ev.toolCall(6, 1, 'h1', 'bash', '{}'), view: callView },
  514. { event: ev.toolResult(7, 1, 'h1', 'done'), view: { for: 'result', view: { card: 'generic', title: '历史果' } } },
  515. ] as never[],
  516. hasMore: false,
  517. }))
  518. await session.open()
  519. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  520. kind: 'tool-result', callView: { title: '历史卡' }, resultView: { title: '历史果' },
  521. })
  522. // Live path: the frame's view slot reaches runningCalls, then the result node.
  523. session.handleMuxEnvelope('rv1' as never, {
  524. type: 'session/event', sessionId: SID, event: ev.toolCall(8, 2, 'l1', 'write', '{}'),
  525. view: { for: 'call', view: { card: 'generic', title: '直播卡' } },
  526. } as never)
  527. expect(session.getSnapshot().runningCalls).toMatchObject([{ callId: 'l1', callView: { title: '直播卡' } }])
  528. session.handleMuxEnvelope('rv2' as never, {
  529. type: 'session/event', sessionId: SID, event: ev.toolResult(9, 2, 'l1', 'ok'),
  530. view: { for: 'result', view: { card: 'generic', title: '直播果' } },
  531. } as never)
  532. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  533. kind: 'tool-result', callView: { title: '直播卡' }, resultView: { title: '直播果' },
  534. })
  535. })
  536. })
  537. describe('resync', () => {
  538. it('rebuilds the window and clears pending; cold instances no-op', async () => {
  539. const { api, session } = makeSession()
  540. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  541. await session.open()
  542. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  543. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')])
  544. await session.resync()
  545. const snapshot = session.getSnapshot()
  546. expect(snapshot.openState).toBe('open')
  547. expect(snapshot.pending).toEqual([]) // baseline replay re-sends still-pending frames
  548. expect(snapshot.nodes).toHaveLength(4)
  549. const cold = makeSession()
  550. await cold.session.resync()
  551. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  552. })
  553. it('re-mints a replayed requested frame as a fresh wait with the same key (old reference superseded)', async () => {
  554. const { api, session } = makeSession()
  555. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  556. await session.open()
  557. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  558. const before = session.getSnapshot().pending[0]!
  559. await session.resync()
  560. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  561. const after = session.getSnapshot().pending[0]!
  562. expect(after).not.toBe(before)
  563. expect(after.key).toBe(before.key)
  564. // Superseded ≠ settled: an in-flight respond on the stale reference still reaches the host.
  565. await before.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } })
  566. expect(api.callsOf('respond')).toMatchObject([{ rpcId: 'rq-replay' }])
  567. })
  568. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  569. const { api, session } = makeSession()
  570. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  571. api.onHistory = () => stale.promise
  572. const firstOpen = session.open()
  573. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  574. const resynced = session.resync()
  575. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  576. await firstOpen
  577. await resynced
  578. const snapshot = session.getSnapshot()
  579. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  580. expect(snapshot.nodes.map(n => n.seq)).toEqual([7, 9])
  581. })
  582. })
  583. describe('reference stability (the memo contract)', () => {
  584. it('keeps unchanged node references across an append and swaps the snapshot object', async () => {
  585. const { api, session } = makeSession()
  586. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  587. await session.open()
  588. const before = session.getSnapshot()
  589. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(6, '追加') })
  590. const after = session.getSnapshot()
  591. expect(after).not.toBe(before) // top-level swap on change
  592. expect(after.nodes[0]).toBe(before.nodes[0]) // untouched nodes keep identity
  593. expect(after.nodes[1]).toBe(before.nodes[1])
  594. expect(after.nodes).toHaveLength(3)
  595. // No change → same snapshot reference.
  596. expect(session.getSnapshot()).toBe(after)
  597. })
  598. it('keeps untouched substructure arrays identical across unrelated changes (revision counters)', async () => {
  599. const { api, session } = makeSession()
  600. api.onHistory = () => histResponse(plainTurn(0, 0, '底', '座'))
  601. await session.open()
  602. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  603. feed(ev.turnStart(6, 1))
  604. feed(ev.toolCall(7, 1, 'c1', 'echo', '{}'))
  605. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  606. const before = session.getSnapshot()
  607. // A chunk storm touches partial/nodes only: runningCalls and pending must keep identity.
  608. feed(ev.chunkStart(8, 1))
  609. feed(ev.chunkText(9, 1, '与工具无关的流式'))
  610. const after = session.getSnapshot()
  611. expect(after).not.toBe(before)
  612. expect(after.runningCalls).toBe(before.runningCalls)
  613. expect(after.pending).toBe(before.pending)
  614. // And a mutation on the tracked domain swaps that array.
  615. feed(ev.toolResult(10, 1, 'c1', 'ECHO'))
  616. const resolved = session.getSnapshot()
  617. expect(resolved.runningCalls).not.toBe(after.runningCalls)
  618. expect(resolved.pending).toBe(after.pending)
  619. })
  620. })