session.spec.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. it('reads session-authorized attachment bytes and keeps the opaque id on the wire', async () => {
  221. const { api, session } = makeSession()
  222. const result = await session.readAttachment('attachment-1' as never)
  223. expect(result).toEqual({
  224. ok: true,
  225. value: {
  226. attachment: { attachmentId: 'a', mediaType: 'image/png', bytes: 1, width: 1, height: 1 },
  227. data: Uint8Array.of(0),
  228. },
  229. })
  230. expect(api.callsOf('session.attachment')).toEqual([{
  231. sessionId: SID, attachmentId: 'attachment-1',
  232. }])
  233. })
  234. })
  235. describe('pending interactions', () => {
  236. it('adds approval/question on requested and removes them on resolved', async () => {
  237. const { session } = makeSession()
  238. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  239. session.handleMuxEnvelope('rq' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  240. expect(session.getSnapshot().pending.map(p => p.kind).sort()).toEqual(['approval', 'question'])
  241. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap1' as never, outcome: 'approved' as never })
  242. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq' as never, outcome: 'answered' })
  243. expect(session.getSnapshot().pending).toEqual([])
  244. })
  245. })
  246. describe('remaining branches', () => {
  247. it('prompt transport throw folds to internal promptError', async () => {
  248. const { api, session } = makeSession()
  249. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  250. const result = await session.prompt([{ type: 'text', text: 'x' }], 'queue')
  251. expect(result.ok).toBe(false)
  252. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'internal', message: 'prompt wire down' } })
  253. })
  254. it('cancel business error also lands op=stop promptError', async () => {
  255. const { api, session } = makeSession()
  256. api.onCancel = () => Promise.resolve(err({ code: 'agent-busy', message: 'nope', details: { reason: 'r' } }))
  257. await session.cancel()
  258. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'agent-busy' } })
  259. })
  260. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  261. const { api, session } = makeSession()
  262. await session.loadOlder() // cold: no-op, zero calls
  263. expect(api.calls).toEqual([])
  264. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  265. await session.open()
  266. // err result: window unchanged
  267. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  268. await session.loadOlder()
  269. expect(session.getSnapshot().nodes).toHaveLength(2)
  270. expect(session.getSnapshot().hasMore).toBe(true)
  271. // empty page: hasMore adopts the response
  272. api.onHistory = () => histResponse([], false)
  273. await session.loadOlder()
  274. expect(session.getSnapshot().hasMore).toBe(false)
  275. // hasMore false now: further loadOlder is a guard no-op
  276. const calls = api.calls.length
  277. await session.loadOlder()
  278. expect(api.calls.length).toBe(calls)
  279. // throw path: fail-soft with console.error
  280. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  281. try {
  282. await session.resync()
  283. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  284. await session.resync()
  285. api.onHistory = () => Promise.reject(new Error('page wire down'))
  286. await session.loadOlder()
  287. expect(errorSpy).toHaveBeenCalled()
  288. expect(session.getSnapshot().loadingOlder).toBe(false)
  289. } finally {
  290. errorSpy.mockRestore()
  291. }
  292. })
  293. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  294. const { api, session } = makeSession()
  295. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  296. let notified = 0
  297. const unsubscribe = session.subscribe(() => { notified++ })
  298. await session.open()
  299. await new Promise(resolve => setTimeout(resolve, 0))
  300. expect(notified).toBeGreaterThan(0)
  301. const seen = notified
  302. unsubscribe()
  303. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  304. await new Promise(resolve => setTimeout(resolve, 0))
  305. expect(notified).toBe(seen)
  306. })
  307. it('subscribed baseline past the window tail triggers the second stitch pull in doOpen', async () => {
  308. const { api, session } = makeSession()
  309. const full = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  310. let call = 0
  311. api.onHistory = () => {
  312. call++
  313. return histResponse(call === 1 ? plainTurn(0, 0, 'a', 'b') : full)
  314. }
  315. // Baseline arrives before open: lastSeq 11 > first page tail 5 → doOpen repulls once.
  316. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  317. await session.open()
  318. expect(call).toBe(2)
  319. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  320. })
  321. it('a failed second stitch pull keeps the first window and still opens', async () => {
  322. const { api, session } = makeSession()
  323. let call = 0
  324. api.onHistory = () => {
  325. call++
  326. return call === 1
  327. ? histResponse(plainTurn(0, 0, 'a', 'b'))
  328. : Promise.resolve(err({ code: 'internal', message: 'stitch pull down', details: {} }))
  329. }
  330. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  331. await session.open()
  332. expect(call).toBe(2)
  333. const snapshot = session.getSnapshot()
  334. expect(snapshot.openState).toBe('open') // stitch-pull failure is not an open failure
  335. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3]) // first window kept
  336. })
  337. it('approval frame with callId/reason keeps the optional fields; duplicate resolved is a no-op', () => {
  338. const { session } = makeSession()
  339. session.handleMuxEnvelope('ra' as never, {
  340. type: 'approval/requested', sessionId: SID, approvalId: 'ap2' as never, toolName: 'rm', callId: 'c1' as never, reason: '危险',
  341. })
  342. expect(session.getSnapshot().pending[0]).toMatchObject({ kind: 'approval', callId: 'c1', reason: '危险' })
  343. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  344. session.handleMuxEnvelope('rx2' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  345. session.handleMuxEnvelope('ry2' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'never-was' as never, outcome: 'cancelled' })
  346. expect(session.getSnapshot().pending).toEqual([])
  347. })
  348. it('ignores unknown mux frame types and repeated running flips (documented defaults)', () => {
  349. const { session } = makeSession()
  350. const before = session.getSnapshot()
  351. session.handleMuxEnvelope('rz' as never, { type: 'future/frame' } as never)
  352. session.handleRunning(false) // already false: dedup branch
  353. expect(session.getSnapshot()).toBe(before)
  354. session.handleRemoved()
  355. expect(session.getSnapshot().removed).toBe(true)
  356. })
  357. it('drops live events while cold/error (no window upkeep)', async () => {
  358. const { api, session } = makeSession()
  359. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '冷态帧') })
  360. expect(session.getSnapshot().nodes).toEqual([])
  361. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  362. await session.open()
  363. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '错态帧') })
  364. expect(session.getSnapshot().nodes).toEqual([])
  365. })
  366. it('repairGap failure logs and clears stitching; concurrent gaps coalesce into one repair', async () => {
  367. const { api, session } = makeSession()
  368. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  369. await session.open()
  370. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  371. let repairs = 0
  372. api.onHistory = () => {
  373. repairs++
  374. return gate.promise
  375. }
  376. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  377. try {
  378. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞一') })
  379. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(10, '洞二') }) // stitching: detours, no second repair
  380. expect(repairs).toBe(1)
  381. gate.reject(new Error('repair wire down'))
  382. await vi.waitFor(() => { expect(errorSpy).toHaveBeenCalled() })
  383. // Window unchanged; a later successful repull still lands the buffered frames.
  384. expect(session.getSnapshot().nodes).toHaveLength(2)
  385. } finally {
  386. errorSpy.mockRestore()
  387. }
  388. })
  389. it('freezes only content-bearing partials; a content-free partial is dropped outright', async () => {
  390. const { api, session } = makeSession()
  391. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  392. await session.open()
  393. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  394. feed(ev.turnStart(6, 1))
  395. feed(ev.chunkStart(7, 1)) // empty text block only, no delta
  396. feed(ev.turnEnd(8, 1, 'cancelled'))
  397. const snapshot = session.getSnapshot()
  398. expect(snapshot.partial).toBeNull()
  399. expect(snapshot.nodes.filter(n => n.kind === 'assistant' && (n as { interrupted?: true }).interrupted)).toEqual([])
  400. })
  401. it('turn/end sweeps only same-turn open calls; other turns keep running', async () => {
  402. const { api, session } = makeSession()
  403. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  404. await session.open()
  405. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  406. feed(ev.turnStart(6, 1))
  407. feed(ev.toolCall(7, 1, 'turn1-call', 'echo', '{}'))
  408. feed(ev.toolCall(8, 2, 'turn2-call', 'echo', '{}')) // stray call attributed to a later turn
  409. feed(ev.turnEnd(9, 1, 'cancelled'))
  410. const snapshot = session.getSnapshot()
  411. expect(snapshot.runningCalls.map(c => c.callId)).toEqual(['turn2-call'])
  412. expect(snapshot.nodes.at(-1)).toMatchObject({ kind: 'tool-result', callId: 'turn1-call', isError: true })
  413. })
  414. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  415. const { api, session } = makeSession()
  416. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  417. api.onHistory = () => stale.promise
  418. const opening = session.open()
  419. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  420. const resynced = session.resync()
  421. stale.reject(new Error('stale wire'))
  422. await Promise.all([opening, resynced])
  423. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  424. })
  425. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  426. const { api, session } = makeSession()
  427. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  428. api.onHistory = () => stale.promise
  429. const opening = session.open()
  430. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  431. const resynced = session.resync()
  432. stale.resolve(ok({ events: entries(plainTurn(0, 0, '旧', '代')) as never[], hasMore: false })) // success, but its generation is gone
  433. await Promise.all([opening, resynced])
  434. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9]) // only the fresh generation's window
  435. })
  436. it('drops a stale stitch pull (second doOpen fetch) superseded mid-flight by resync', async () => {
  437. const { api, session } = makeSession()
  438. const secondPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  439. let call = 0
  440. api.onHistory = () => {
  441. call++
  442. if (call === 1) return histResponse(plainTurn(0, 0, 'a', 'b')) // first page: tail 5
  443. if (call === 2) return secondPull.promise // gap-stitch pull: held
  444. return histResponse(plainTurn(6, 1, 'c', 'd'))
  445. }
  446. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  447. const opening = session.open() // triggers the second pull, which parks
  448. await vi.waitFor(() => { expect(call).toBe(2) })
  449. const resynced = session.resync()
  450. secondPull.resolve(ok({ events: entries([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]) as never[], hasMore: false }))
  451. await Promise.all([opening, resynced])
  452. expect(session.getSnapshot().openState).toBe('open')
  453. })
  454. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  455. const { api, session } = makeSession()
  456. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  457. await session.open()
  458. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  459. api.onHistory = () => repairPull.promise
  460. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞') }) // starts repairGap
  461. api.onHistory = () => histResponse(plainTurn(6, 1, 'c', 'd'))
  462. const resynced = session.resync() // bumps the generation
  463. repairPull.resolve(ok({ events: entries(plainTurn(0, 0, '旧', '页')) as never[], hasMore: false })) // repair result: stale, dropped
  464. await resynced
  465. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9])
  466. })
  467. it('successful cancel leaves no promptError; tool/result for an unknown callId is a no-op', async () => {
  468. const { api, session } = makeSession()
  469. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  470. await session.open()
  471. const result = await session.cancel()
  472. expect(result.ok).toBe(true)
  473. expect(session.getSnapshot().promptError).toBeNull()
  474. const callsBefore = session.getSnapshot().runningCalls
  475. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.toolResult(6, 0, 'never-called', 'x') })
  476. expect(session.getSnapshot().runningCalls).toBe(callsBefore) // callsRev untouched: same reference
  477. })
  478. it('freezes a tool-call-only partial (visible through the non-text arm)', async () => {
  479. const { api, session } = makeSession()
  480. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  481. await session.open()
  482. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  483. feed(ev.turnStart(6, 1))
  484. feed(at(7, { type: 'assistant/chunk', data: { turn: 1, step: 0, chunk: { type: 'tool-call-delta', index: 0, id: 'c1', name: 'echo', argumentsDelta: '{' } } }))
  485. feed(ev.turnEnd(8, 1, 'cancelled'))
  486. const frozen = session.getSnapshot().nodes.at(-1)
  487. expect(frozen).toMatchObject({ kind: 'assistant', interrupted: true, blocks: [{ kind: 'tool-call', callId: 'c1' }] })
  488. })
  489. it('dispose is a reserved no-op on resident instances', () => {
  490. const { session } = makeSession()
  491. expect(() => { session.dispose() }).not.toThrow()
  492. })
  493. it('carries mux-frame views into runningCalls and tool-result nodes, and history-entry views through open', async () => {
  494. const { api, session } = makeSession()
  495. const callView = { for: 'call', view: { card: 'generic', title: '历史卡' } }
  496. api.onHistory = () => Promise.resolve(ok({
  497. events: [
  498. ...entries(plainTurn(0, 0, 'a', 'b')),
  499. { event: ev.toolCall(6, 1, 'h1', 'bash', '{}'), view: callView },
  500. { event: ev.toolResult(7, 1, 'h1', 'done'), view: { for: 'result', view: { card: 'generic', title: '历史果' } } },
  501. ] as never[],
  502. hasMore: false,
  503. }))
  504. await session.open()
  505. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  506. kind: 'tool-result', callView: { title: '历史卡' }, resultView: { title: '历史果' },
  507. })
  508. // Live path: the frame's view slot reaches runningCalls, then the result node.
  509. session.handleMuxEnvelope('rv1' as never, {
  510. type: 'session/event', sessionId: SID, event: ev.toolCall(8, 2, 'l1', 'write', '{}'),
  511. view: { for: 'call', view: { card: 'generic', title: '直播卡' } },
  512. } as never)
  513. expect(session.getSnapshot().runningCalls).toMatchObject([{ callId: 'l1', callView: { title: '直播卡' } }])
  514. session.handleMuxEnvelope('rv2' as never, {
  515. type: 'session/event', sessionId: SID, event: ev.toolResult(9, 2, 'l1', 'ok'),
  516. view: { for: 'result', view: { card: 'generic', title: '直播果' } },
  517. } as never)
  518. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  519. kind: 'tool-result', callView: { title: '直播卡' }, resultView: { title: '直播果' },
  520. })
  521. })
  522. })
  523. describe('resync', () => {
  524. it('rebuilds the window and clears pending; cold instances no-op', async () => {
  525. const { api, session } = makeSession()
  526. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  527. await session.open()
  528. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  529. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')])
  530. await session.resync()
  531. const snapshot = session.getSnapshot()
  532. expect(snapshot.openState).toBe('open')
  533. expect(snapshot.pending).toEqual([]) // baseline replay re-sends still-pending frames
  534. expect(snapshot.nodes).toHaveLength(4)
  535. const cold = makeSession()
  536. await cold.session.resync()
  537. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  538. })
  539. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  540. const { api, session } = makeSession()
  541. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  542. api.onHistory = () => stale.promise
  543. const firstOpen = session.open()
  544. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  545. const resynced = session.resync()
  546. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  547. await firstOpen
  548. await resynced
  549. const snapshot = session.getSnapshot()
  550. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  551. expect(snapshot.nodes.map(n => n.seq)).toEqual([7, 9])
  552. })
  553. })
  554. describe('reference stability (the memo contract)', () => {
  555. it('keeps unchanged node references across an append and swaps the snapshot object', async () => {
  556. const { api, session } = makeSession()
  557. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  558. await session.open()
  559. const before = session.getSnapshot()
  560. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(6, '追加') })
  561. const after = session.getSnapshot()
  562. expect(after).not.toBe(before) // top-level swap on change
  563. expect(after.nodes[0]).toBe(before.nodes[0]) // untouched nodes keep identity
  564. expect(after.nodes[1]).toBe(before.nodes[1])
  565. expect(after.nodes).toHaveLength(3)
  566. // No change → same snapshot reference.
  567. expect(session.getSnapshot()).toBe(after)
  568. })
  569. it('keeps untouched substructure arrays identical across unrelated changes (revision counters)', async () => {
  570. const { api, session } = makeSession()
  571. api.onHistory = () => histResponse(plainTurn(0, 0, '底', '座'))
  572. await session.open()
  573. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  574. feed(ev.turnStart(6, 1))
  575. feed(ev.toolCall(7, 1, 'c1', 'echo', '{}'))
  576. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  577. const before = session.getSnapshot()
  578. // A chunk storm touches partial/nodes only: runningCalls and pending must keep identity.
  579. feed(ev.chunkStart(8, 1))
  580. feed(ev.chunkText(9, 1, '与工具无关的流式'))
  581. const after = session.getSnapshot()
  582. expect(after).not.toBe(before)
  583. expect(after.runningCalls).toBe(before.runningCalls)
  584. expect(after.pending).toBe(before.pending)
  585. // And a mutation on the tracked domain swaps that array.
  586. feed(ev.toolResult(10, 1, 'c1', 'ECHO'))
  587. const resolved = session.getSnapshot()
  588. expect(resolved.runningCalls).not.toBe(after.runningCalls)
  589. expect(resolved.pending).toBe(after.pending)
  590. })
  591. })