session.spec.ts 35 KB

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