session.spec.ts 31 KB

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