session.spec.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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, todos?: { content: string; status: 'pending' | 'in_progress' | 'completed' }[]) {
  21. // history now returns HistoryEntry[] ({event, view?}); these tests are view-less.
  22. return Promise.resolve(ok({ events: entries(events) as never[], hasMore, ...todos === undefined ? {} : { todos } }))
  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('folds todo/write into snapshot.todos last-write-wins, live and on window replay', async () => {
  141. const listA = [{ content: '搭骨架', status: 'completed' as const }, { content: '写组件', status: 'in_progress' as const }]
  142. const listB = [{ content: '搭骨架', status: 'completed' as const }, { content: '写组件', status: 'completed' as const }]
  143. const { session } = await opened()
  144. expect(session.getSnapshot().todos).toEqual([])
  145. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  146. feed(ev.todoWrite(6, listA))
  147. expect(session.getSnapshot().todos).toEqual(listA)
  148. feed(ev.todoWrite(7, listB))
  149. expect(session.getSnapshot().todos).toEqual(listB)
  150. // Window replay converges on the same last snapshot (history contains both writes).
  151. const replayed = makeSession()
  152. replayed.api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ev.todoWrite(6, listA), ev.todoWrite(7, listB)])
  153. await replayed.session.open()
  154. expect(replayed.session.getSnapshot().todos).toEqual(listB)
  155. })
  156. it('seeds todos from the tail page projection when the last write precedes the window', async () => {
  157. const list = [{ content: '窗口外的计划', status: 'in_progress' as const }]
  158. // Cold open: the page window carries NO todo/write; the projection rides the response.
  159. const { api, session } = makeSession()
  160. api.onHistory = () => histResponse(plainTurn(100, 9, '问', '答'), true, list)
  161. await session.open()
  162. expect(session.getSnapshot().todos).toEqual(list)
  163. // Paging an older window in must not clear the session-level projection.
  164. api.onHistory = () => histResponse(plainTurn(94, 8, '旧问', '旧答'), false)
  165. await session.loadOlder()
  166. expect(session.getSnapshot().todos).toEqual(list)
  167. // A later live write still overrides the seeded projection.
  168. session.handleMuxEnvelope('r' as never, {
  169. type: 'session/event', sessionId: SID,
  170. event: ev.todoWrite(106, [{ content: '新计划', status: 'pending' as const }]),
  171. })
  172. expect(session.getSnapshot().todos).toEqual([{ content: '新计划', status: 'pending' }])
  173. })
  174. it('repairs a seq gap by repulling the tail page instead of appending a hole', async () => {
  175. const { api, session } = await opened(plainTurn(0, 0, 'a', 'b')) // tail seq = 5
  176. const repaired = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  177. api.onHistory = () => histResponse(repaired)
  178. // seq 9 with tail 5 → gap; the event detours to the buffer and one history refetch fires.
  179. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.assistant(9, 1, 'd') })
  180. await vi.waitFor(() => {
  181. expect(api.callsOf('session.history').length).toBe(2)
  182. })
  183. await Promise.resolve()
  184. const seqs = session.getSnapshot().nodes.map(n => n.seq)
  185. expect(seqs).toEqual([1, 3, 7, 9]) // both turns' user/assistant, no hole, no duplicate 9
  186. })
  187. it('gap repair adopts the repull response projection (a missed todo/write outside the new tail page)', async () => {
  188. const { api, session } = await opened(plainTurn(0, 0, 'a', 'b')) // tail seq = 5
  189. expect(session.getSnapshot().todos).toEqual([])
  190. // The missed range contained a todo/write that the repulled page no longer
  191. // covers; the response's session-level projection is the only carrier.
  192. const current = [{ content: '断线期间写的', status: 'in_progress' as const }]
  193. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(8, 1, 'c', 'd')], false, current)
  194. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.assistant(11, 1, 'd') })
  195. await vi.waitFor(() => {
  196. expect(api.callsOf('session.history').length).toBe(2)
  197. })
  198. await Promise.resolve()
  199. expect(session.getSnapshot().todos).toEqual(current)
  200. })
  201. it('clears the plan when a tail response omits the projection (a write the log never kept)', async () => {
  202. // Live write lands, then the host crashes before persisting it: the
  203. // authoritative log holds no todo/write, so the resync tail response
  204. // carries no projection — an omitted field on a tail request is the empty
  205. // list, not a missing carrier, and the rolled-back plan must disappear.
  206. const { api, session } = await opened(plainTurn(0, 0, 'a', 'b'))
  207. session.handleMuxEnvelope('r' as never, {
  208. type: 'session/event', sessionId: SID,
  209. event: ev.todoWrite(6, [{ content: '丢失的计划', status: 'in_progress' as const }]),
  210. })
  211. expect(session.getSnapshot().todos).toEqual([{ content: '丢失的计划', status: 'in_progress' }])
  212. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  213. await session.resync()
  214. expect(session.getSnapshot().todos).toEqual([])
  215. })
  216. })
  217. describe('paging', () => {
  218. it('prepends an older page and keeps seq continuity', async () => {
  219. const older = plainTurn(0, 0, '旧问', '旧答')
  220. const newer = plainTurn(6, 1, '新问', '新答')
  221. const { api, session } = makeSession()
  222. api.onHistory = payload => payload.beforeSeq === undefined
  223. ? histResponse(newer, true)
  224. : histResponse(older, false)
  225. await session.open()
  226. await session.loadOlder()
  227. const snapshot = session.getSnapshot()
  228. expect(api.callsOf('session.history')).toMatchObject([{}, { beforeSeq: 6 }].map(p => ({ sessionId: SID, ...p })))
  229. expect(snapshot.hasMore).toBe(false)
  230. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  231. })
  232. it('drops a discontinuous older page fail-soft (window unchanged, hasMore cleared)', async () => {
  233. const { api, session } = makeSession()
  234. api.onHistory = payload => payload.beforeSeq === undefined
  235. ? histResponse(plainTurn(10, 1, '新', '页'), true)
  236. : histResponse(plainTurn(0, 0, '断', '层'), true) // tail seq 5, but baseSeq is 10 → hole
  237. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  238. try {
  239. await session.open()
  240. const nodesBefore = session.getSnapshot().nodes
  241. await session.loadOlder()
  242. const snapshot = session.getSnapshot()
  243. expect(snapshot.nodes).toEqual(nodesBefore)
  244. expect(snapshot.hasMore).toBe(false)
  245. } finally {
  246. errorSpy.mockRestore()
  247. }
  248. })
  249. it('ignores loadOlder while one is in flight (single request)', async () => {
  250. const { api, session } = makeSession()
  251. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  252. await session.open()
  253. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  254. api.onHistory = () => gate.promise
  255. const first = session.loadOlder()
  256. const second = session.loadOlder()
  257. gate.resolve(ok({ events: entries(plainTurn(0, 0, 'a', 'b')) as never[], hasMore: false }))
  258. await Promise.all([first, second])
  259. expect(api.callsOf('session.history')).toHaveLength(2) // open + one page, not two
  260. })
  261. })
  262. describe('prompt and cancel errors', () => {
  263. it('sends content through session.prompt; composerPhase steps blank → engaging synchronously at send entry', async () => {
  264. const { api, session } = makeSession()
  265. // The blank → engaging edge fires before the RPC settles: the first-send
  266. // flow reads the phase on the session area's first frame to keep the
  267. // guidance hero from flashing back in.
  268. expect(session.getSnapshot().composerPhase).toBe('blank')
  269. const inFlight = session.prompt([{ type: 'text', text: '要发的' }], 'queue')
  270. expect(session.getSnapshot().composerPhase).toBe('engaging')
  271. const result = await inFlight
  272. expect(result.ok).toBe(true)
  273. // Monotone: settlement alone does not step the phase anywhere.
  274. expect(session.getSnapshot().composerPhase).toBe('engaging')
  275. expect(api.callsOf('session.prompt')).toMatchObject([{ sessionId: SID, mode: 'queue', content: [{ type: 'text', text: '要发的' }] }])
  276. // First content lands (running turn): engaging → active.
  277. session.handleRunning(true)
  278. expect(session.getSnapshot().composerPhase).toBe('active')
  279. })
  280. it('business failure lands in promptError with op=send; the phase stays engaging (retry, no hero bounce)', async () => {
  281. const { api, session } = makeSession()
  282. api.onPrompt = () => Promise.resolve(err({ code: 'agent-busy', message: 'busy', details: { reason: 'x' } }))
  283. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue')
  284. expect(result.ok).toBe(false)
  285. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'agent-busy' } })
  286. // Failed first prompt: composer + error strip is the retry surface —
  287. // blank is unreachable once a send was initiated.
  288. expect(session.getSnapshot().composerPhase).toBe('engaging')
  289. })
  290. it('lands cancel failures in promptError with op=stop', async () => {
  291. const { api, session } = makeSession()
  292. api.onCancel = () => Promise.reject(new Error('cancel transport down'))
  293. const result = await session.cancel()
  294. expect(result.ok).toBe(false)
  295. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'internal' } })
  296. })
  297. })
  298. describe('pending interactions', () => {
  299. it('adds approval/question on requested and removes them on resolved', async () => {
  300. const { session } = makeSession()
  301. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  302. session.handleMuxEnvelope('rq' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  303. expect(session.getSnapshot().pending.map(p => p.kind).sort()).toEqual(['approval', 'question'])
  304. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap1' as never, outcome: 'approved' as never })
  305. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq' as never, outcome: 'answered' })
  306. expect(session.getSnapshot().pending).toEqual([])
  307. })
  308. it('mints waits whose respond() backfills the requested rpcId into the client-response envelope', async () => {
  309. const { api, session } = makeSession()
  310. session.handleMuxEnvelope('rq-answer' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  311. const wait = session.getSnapshot().pending[0]!
  312. expect(wait).toMatchObject({ kind: 'question', key: 'q:rq-answer', sessionId: SID, payload: { questions: [] } })
  313. const receipt = await wait.respond({
  314. ok: true,
  315. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  316. })
  317. expect(receipt).toEqual({ accepted: true })
  318. expect(api.callsOf('respond')).toEqual([{
  319. type: 'client-response', rpcId: 'rq-answer',
  320. result: {
  321. ok: true,
  322. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  323. },
  324. }])
  325. })
  326. it('settles the wait on the authoritative resolved frame: respond() then throws synchronously', async () => {
  327. const { api, session } = makeSession()
  328. session.handleMuxEnvelope('rq1' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  329. const wait = session.getSnapshot().pending[0]!
  330. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq1' as never, outcome: 'answered' })
  331. expect(session.getSnapshot().pending).toEqual([])
  332. expect(() => wait.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } }))
  333. .toThrow('already settled')
  334. expect(api.callsOf('respond')).toEqual([])
  335. })
  336. })
  337. describe('remaining branches', () => {
  338. it('prompt transport throw folds to internal promptError', async () => {
  339. const { api, session } = makeSession()
  340. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  341. const result = await session.prompt([{ type: 'text', text: 'x' }], 'queue')
  342. expect(result.ok).toBe(false)
  343. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'internal', message: 'prompt wire down' } })
  344. })
  345. it('cancel business error also lands op=stop promptError', async () => {
  346. const { api, session } = makeSession()
  347. api.onCancel = () => Promise.resolve(err({ code: 'agent-busy', message: 'nope', details: { reason: 'r' } }))
  348. await session.cancel()
  349. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'agent-busy' } })
  350. })
  351. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  352. const { api, session } = makeSession()
  353. await session.loadOlder() // cold: no-op, zero calls
  354. expect(api.calls).toEqual([])
  355. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  356. await session.open()
  357. // err result: window unchanged
  358. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  359. await session.loadOlder()
  360. expect(session.getSnapshot().nodes).toHaveLength(2)
  361. expect(session.getSnapshot().hasMore).toBe(true)
  362. // empty page: hasMore adopts the response
  363. api.onHistory = () => histResponse([], false)
  364. await session.loadOlder()
  365. expect(session.getSnapshot().hasMore).toBe(false)
  366. // hasMore false now: further loadOlder is a guard no-op
  367. const calls = api.calls.length
  368. await session.loadOlder()
  369. expect(api.calls.length).toBe(calls)
  370. // throw path: fail-soft with console.error
  371. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  372. try {
  373. await session.resync()
  374. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  375. await session.resync()
  376. api.onHistory = () => Promise.reject(new Error('page wire down'))
  377. await session.loadOlder()
  378. expect(errorSpy).toHaveBeenCalled()
  379. expect(session.getSnapshot().loadingOlder).toBe(false)
  380. } finally {
  381. errorSpy.mockRestore()
  382. }
  383. })
  384. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  385. const { api, session } = makeSession()
  386. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  387. let notified = 0
  388. const unsubscribe = session.subscribe(() => { notified++ })
  389. await session.open()
  390. await new Promise(resolve => setTimeout(resolve, 0))
  391. expect(notified).toBeGreaterThan(0)
  392. const seen = notified
  393. unsubscribe()
  394. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  395. await new Promise(resolve => setTimeout(resolve, 0))
  396. expect(notified).toBe(seen)
  397. })
  398. it('subscribed baseline past the window tail triggers the second stitch pull in doOpen', async () => {
  399. const { api, session } = makeSession()
  400. const full = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  401. let call = 0
  402. api.onHistory = () => {
  403. call++
  404. return histResponse(call === 1 ? plainTurn(0, 0, 'a', 'b') : full)
  405. }
  406. // Baseline arrives before open: lastSeq 11 > first page tail 5 → doOpen repulls once.
  407. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  408. await session.open()
  409. expect(call).toBe(2)
  410. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  411. })
  412. it('a failed second stitch pull keeps the first window and still opens', async () => {
  413. const { api, session } = makeSession()
  414. let call = 0
  415. api.onHistory = () => {
  416. call++
  417. return call === 1
  418. ? histResponse(plainTurn(0, 0, 'a', 'b'))
  419. : Promise.resolve(err({ code: 'internal', message: 'stitch pull down', details: {} }))
  420. }
  421. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  422. await session.open()
  423. expect(call).toBe(2)
  424. const snapshot = session.getSnapshot()
  425. expect(snapshot.openState).toBe('open') // stitch-pull failure is not an open failure
  426. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3]) // first window kept
  427. })
  428. it('approval frame with callId/reason keeps the optional fields; duplicate resolved is a no-op', () => {
  429. const { session } = makeSession()
  430. session.handleMuxEnvelope('ra' as never, {
  431. type: 'approval/requested', sessionId: SID, approvalId: 'ap2' as never, toolName: 'rm', callId: 'c1' as never, reason: '危险',
  432. })
  433. expect(session.getSnapshot().pending[0]).toMatchObject({ kind: 'approval', payload: { callId: 'c1', reason: '危险' } })
  434. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  435. session.handleMuxEnvelope('rx2' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  436. session.handleMuxEnvelope('ry2' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'never-was' as never, outcome: 'cancelled' })
  437. expect(session.getSnapshot().pending).toEqual([])
  438. })
  439. it('ignores unknown mux frame types and repeated running flips (documented defaults)', () => {
  440. const { session } = makeSession()
  441. const before = session.getSnapshot()
  442. session.handleMuxEnvelope('rz' as never, { type: 'future/frame' } as never)
  443. session.handleRunning(false) // already false: dedup branch
  444. expect(session.getSnapshot()).toBe(before)
  445. session.handleRemoved()
  446. expect(session.getSnapshot().removed).toBe(true)
  447. })
  448. it('drops live events while cold/error (no window upkeep)', async () => {
  449. const { api, session } = makeSession()
  450. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '冷态帧') })
  451. expect(session.getSnapshot().nodes).toEqual([])
  452. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  453. await session.open()
  454. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '错态帧') })
  455. expect(session.getSnapshot().nodes).toEqual([])
  456. })
  457. it('repairGap failure logs and clears stitching; concurrent gaps coalesce into one repair', async () => {
  458. const { api, session } = makeSession()
  459. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  460. await session.open()
  461. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  462. let repairs = 0
  463. api.onHistory = () => {
  464. repairs++
  465. return gate.promise
  466. }
  467. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  468. try {
  469. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞一') })
  470. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(10, '洞二') }) // stitching: detours, no second repair
  471. expect(repairs).toBe(1)
  472. gate.reject(new Error('repair wire down'))
  473. await vi.waitFor(() => { expect(errorSpy).toHaveBeenCalled() })
  474. // Window unchanged; a later successful repull still lands the buffered frames.
  475. expect(session.getSnapshot().nodes).toHaveLength(2)
  476. } finally {
  477. errorSpy.mockRestore()
  478. }
  479. })
  480. it('freezes only content-bearing partials; a content-free partial is dropped outright', async () => {
  481. const { api, session } = makeSession()
  482. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  483. await session.open()
  484. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  485. feed(ev.turnStart(6, 1))
  486. feed(ev.chunkStart(7, 1)) // empty text block only, no delta
  487. feed(ev.turnEnd(8, 1, 'cancelled'))
  488. const snapshot = session.getSnapshot()
  489. expect(snapshot.partial).toBeNull()
  490. expect(snapshot.nodes.filter(n => n.kind === 'assistant' && (n as { interrupted?: true }).interrupted)).toEqual([])
  491. })
  492. it('turn/end sweeps only same-turn open calls; other turns keep running', async () => {
  493. const { api, session } = makeSession()
  494. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  495. await session.open()
  496. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  497. feed(ev.turnStart(6, 1))
  498. feed(ev.toolCall(7, 1, 'turn1-call', 'echo', '{}'))
  499. feed(ev.toolCall(8, 2, 'turn2-call', 'echo', '{}')) // stray call attributed to a later turn
  500. feed(ev.turnEnd(9, 1, 'cancelled'))
  501. const snapshot = session.getSnapshot()
  502. expect(snapshot.runningCalls.map(c => c.callId)).toEqual(['turn2-call'])
  503. expect(snapshot.nodes.at(-1)).toMatchObject({ kind: 'tool-result', callId: 'turn1-call', isError: true })
  504. })
  505. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  506. const { api, session } = makeSession()
  507. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  508. api.onHistory = () => stale.promise
  509. const opening = session.open()
  510. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  511. const resynced = session.resync()
  512. stale.reject(new Error('stale wire'))
  513. await Promise.all([opening, resynced])
  514. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  515. })
  516. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  517. const { api, session } = makeSession()
  518. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  519. api.onHistory = () => stale.promise
  520. const opening = session.open()
  521. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  522. const resynced = session.resync()
  523. stale.resolve(ok({ events: entries(plainTurn(0, 0, '旧', '代')) as never[], hasMore: false })) // success, but its generation is gone
  524. await Promise.all([opening, resynced])
  525. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9]) // only the fresh generation's window
  526. })
  527. it('drops a stale stitch pull (second doOpen fetch) superseded mid-flight by resync', async () => {
  528. const { api, session } = makeSession()
  529. const secondPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  530. let call = 0
  531. api.onHistory = () => {
  532. call++
  533. if (call === 1) return histResponse(plainTurn(0, 0, 'a', 'b')) // first page: tail 5
  534. if (call === 2) return secondPull.promise // gap-stitch pull: held
  535. return histResponse(plainTurn(6, 1, 'c', 'd'))
  536. }
  537. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  538. const opening = session.open() // triggers the second pull, which parks
  539. await vi.waitFor(() => { expect(call).toBe(2) })
  540. const resynced = session.resync()
  541. secondPull.resolve(ok({ events: entries([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]) as never[], hasMore: false }))
  542. await Promise.all([opening, resynced])
  543. expect(session.getSnapshot().openState).toBe('open')
  544. })
  545. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  546. const { api, session } = makeSession()
  547. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  548. await session.open()
  549. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  550. api.onHistory = () => repairPull.promise
  551. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞') }) // starts repairGap
  552. api.onHistory = () => histResponse(plainTurn(6, 1, 'c', 'd'))
  553. const resynced = session.resync() // bumps the generation
  554. repairPull.resolve(ok({ events: entries(plainTurn(0, 0, '旧', '页')) as never[], hasMore: false })) // repair result: stale, dropped
  555. await resynced
  556. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9])
  557. })
  558. it('successful cancel leaves no promptError; tool/result for an unknown callId is a no-op', async () => {
  559. const { api, session } = makeSession()
  560. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  561. await session.open()
  562. const result = await session.cancel()
  563. expect(result.ok).toBe(true)
  564. expect(session.getSnapshot().promptError).toBeNull()
  565. const callsBefore = session.getSnapshot().runningCalls
  566. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.toolResult(6, 0, 'never-called', 'x') })
  567. expect(session.getSnapshot().runningCalls).toBe(callsBefore) // callsRev untouched: same reference
  568. })
  569. it('freezes a tool-call-only partial (visible through the non-text arm)', async () => {
  570. const { api, session } = makeSession()
  571. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  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(at(7, { type: 'assistant/chunk', data: { turn: 1, step: 0, chunk: { type: 'tool-call-delta', index: 0, id: 'c1', name: 'echo', argumentsDelta: '{' } } }))
  576. feed(ev.turnEnd(8, 1, 'cancelled'))
  577. const frozen = session.getSnapshot().nodes.at(-1)
  578. expect(frozen).toMatchObject({ kind: 'assistant', interrupted: true, blocks: [{ kind: 'tool-call', callId: 'c1' }] })
  579. })
  580. it('dispose is a reserved no-op on resident instances', () => {
  581. const { session } = makeSession()
  582. expect(() => { session.dispose() }).not.toThrow()
  583. })
  584. it('carries mux-frame views into runningCalls and tool-result nodes, and history-entry views through open', async () => {
  585. const { api, session } = makeSession()
  586. const callView = { for: 'call', view: { card: 'generic', title: '历史卡' } }
  587. api.onHistory = () => Promise.resolve(ok({
  588. events: [
  589. ...entries(plainTurn(0, 0, 'a', 'b')),
  590. { event: ev.toolCall(6, 1, 'h1', 'bash', '{}'), view: callView },
  591. { event: ev.toolResult(7, 1, 'h1', 'done'), view: { for: 'result', view: { card: 'generic', title: '历史果' } } },
  592. ] as never[],
  593. hasMore: false,
  594. }))
  595. await session.open()
  596. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  597. kind: 'tool-result', callView: { title: '历史卡' }, resultView: { title: '历史果' },
  598. })
  599. // Live path: the frame's view slot reaches runningCalls, then the result node.
  600. session.handleMuxEnvelope('rv1' as never, {
  601. type: 'session/event', sessionId: SID, event: ev.toolCall(8, 2, 'l1', 'write', '{}'),
  602. view: { for: 'call', view: { card: 'generic', title: '直播卡' } },
  603. } as never)
  604. expect(session.getSnapshot().runningCalls).toMatchObject([{ callId: 'l1', callView: { title: '直播卡' } }])
  605. session.handleMuxEnvelope('rv2' as never, {
  606. type: 'session/event', sessionId: SID, event: ev.toolResult(9, 2, 'l1', 'ok'),
  607. view: { for: 'result', view: { card: 'generic', title: '直播果' } },
  608. } as never)
  609. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  610. kind: 'tool-result', callView: { title: '直播卡' }, resultView: { title: '直播果' },
  611. })
  612. })
  613. })
  614. describe('resync', () => {
  615. it('rebuilds the window and clears pending; cold instances no-op', async () => {
  616. const { api, session } = makeSession()
  617. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  618. await session.open()
  619. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  620. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')])
  621. await session.resync()
  622. const snapshot = session.getSnapshot()
  623. expect(snapshot.openState).toBe('open')
  624. expect(snapshot.pending).toEqual([]) // baseline replay re-sends still-pending frames
  625. expect(snapshot.nodes).toHaveLength(4)
  626. const cold = makeSession()
  627. await cold.session.resync()
  628. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  629. })
  630. it('re-mints a replayed requested frame as a fresh wait with the same key (old reference superseded)', async () => {
  631. const { api, session } = makeSession()
  632. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  633. await session.open()
  634. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  635. const before = session.getSnapshot().pending[0]!
  636. await session.resync()
  637. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  638. const after = session.getSnapshot().pending[0]!
  639. expect(after).not.toBe(before)
  640. expect(after.key).toBe(before.key)
  641. // Superseded ≠ settled: an in-flight respond on the stale reference still reaches the host.
  642. await before.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } })
  643. expect(api.callsOf('respond')).toMatchObject([{ rpcId: 'rq-replay' }])
  644. })
  645. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  646. const { api, session } = makeSession()
  647. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  648. api.onHistory = () => stale.promise
  649. const firstOpen = session.open()
  650. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  651. const resynced = session.resync()
  652. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  653. await firstOpen
  654. await resynced
  655. const snapshot = session.getSnapshot()
  656. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  657. expect(snapshot.nodes.map(n => n.seq)).toEqual([7, 9])
  658. })
  659. })
  660. describe('run_code sub-dispatch indexing', () => {
  661. it('a start event lands as a running-shaped sub-call and its settle replaces it in place', async () => {
  662. const { api, session } = makeSession()
  663. api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答'))
  664. await session.open()
  665. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  666. feed(ev.turnStart(6, 1))
  667. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"d"}'))
  668. feed(ev.codeDispatchStart(8, 'p1', 1, 'bash', { command: 'sleep' }))
  669. feed(ev.codeDispatchStart(9, 'p1', 2, 'read', { path: 'a.txt' }))
  670. const live = session.getSnapshot().codeDispatches.get('p1')
  671. expect(live).toHaveLength(2)
  672. // Running shape (no 'kind'): the exact RunningToolCall form native rows use.
  673. expect(live?.[0]).toMatchObject({ callId: 'p1:code:1', name: 'bash', argsRaw: '{"command":"sleep"}' })
  674. expect(live?.[0] !== undefined && 'kind' in live[0]).toBe(false)
  675. // Settle out of order (parallel run): #2 first — replaces in place, keeping start order.
  676. feed(ev.codeDispatch(10, 'p1', 2, 'read', { path: 'a.txt' }, 'alpha'))
  677. const mixed = session.getSnapshot().codeDispatches.get('p1')
  678. expect(mixed?.map(sub => 'kind' in sub)).toEqual([false, true])
  679. expect(mixed?.[1]).toMatchObject({ callId: 'p1:code:2', content: [{ type: 'text', text: 'alpha' }] })
  680. // The settle carries the paired start's time as callTime (duration source).
  681. feed(ev.codeDispatch(11, 'p1', 1, 'bash', { command: 'sleep' }, 'done'))
  682. const settled = session.getSnapshot().codeDispatches.get('p1')
  683. expect(settled?.map(sub => 'kind' in sub)).toEqual([true, true])
  684. expect(settled?.[0]).toMatchObject({ callId: 'p1:code:1', callTime: 1_700_000_000_008 })
  685. })
  686. it('indexes live tool/code-dispatch events under their parent as native-shaped result nodes', async () => {
  687. const { api, session } = makeSession()
  688. api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答'))
  689. await session.open()
  690. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  691. feed(ev.turnStart(6, 1))
  692. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"return 1","description":"跑一个程序"}'))
  693. feed(ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls', description: '列目录' }, 'demo.txt'))
  694. feed(ev.codeDispatch(9, 'p1', 2, 'read', { path: 'a.txt' }, 'Error: ENOENT', true))
  695. const subs = session.getSnapshot().codeDispatches.get('p1')
  696. expect(subs).toHaveLength(2)
  697. expect(subs?.[0]).toMatchObject({
  698. kind: 'tool-result', callId: 'p1:code:1',
  699. call: { name: 'bash', argsRaw: '{"command":"ls","description":"列目录"}' },
  700. // The settle event carries no start time: callTime stays null (never a
  701. // fabricated zero-duration).
  702. callTime: null,
  703. isError: false, content: [{ type: 'text', text: 'demo.txt' }],
  704. })
  705. expect(subs?.[1]).toMatchObject({ callId: 'p1:code:2', isError: true })
  706. // No paired start in the window: duration is UNKNOWN (null), never a
  707. // fabricated zero-duration span.
  708. expect(subs?.[0]).toMatchObject({ callTime: null })
  709. // Sub-dispatches never join the surface flow.
  710. expect(session.getSnapshot().nodes.some(n => n.kind === 'tool-result' && n.callId.includes(':code:'))).toBe(false)
  711. })
  712. it('rebuilds the same index from a history window (replay parity)', async () => {
  713. const { api, session } = makeSession()
  714. api.onHistory = () => histResponse([
  715. ...plainTurn(0, 0, '问', '答'),
  716. ev.turnStart(6, 1),
  717. ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"return 1","description":"跑一个程序"}'),
  718. ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls' }, 'demo.txt'),
  719. ev.toolResult(9, 1, 'p1', '{"done":true}'),
  720. ev.turnEnd(10, 1),
  721. ])
  722. await session.open()
  723. const subs = session.getSnapshot().codeDispatches.get('p1')
  724. expect(subs).toHaveLength(1)
  725. expect(subs?.[0]).toMatchObject({ callId: 'p1:code:1', call: { name: 'bash' } })
  726. })
  727. it('keeps the dispatch map reference across unrelated changes and swaps it on a new dispatch', async () => {
  728. const { api, session } = makeSession()
  729. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  730. await session.open()
  731. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  732. feed(ev.turnStart(6, 1))
  733. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"d"}'))
  734. feed(ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls' }, 'x'))
  735. const before = session.getSnapshot()
  736. feed(ev.chunkStart(9, 1))
  737. feed(ev.chunkText(10, 1, '流式'))
  738. const after = session.getSnapshot()
  739. expect(after.codeDispatches).toBe(before.codeDispatches)
  740. feed(ev.codeDispatch(11, 'p1', 2, 'read', { path: 'a' }, 'y'))
  741. expect(session.getSnapshot().codeDispatches).not.toBe(after.codeDispatches)
  742. expect(session.getSnapshot().codeDispatches.get('p1')).toHaveLength(2)
  743. })
  744. })
  745. describe('reference stability (the memo contract)', () => {
  746. it('keeps unchanged node references across an append and swaps the snapshot object', async () => {
  747. const { api, session } = makeSession()
  748. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  749. await session.open()
  750. const before = session.getSnapshot()
  751. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(6, '追加') })
  752. const after = session.getSnapshot()
  753. expect(after).not.toBe(before) // top-level swap on change
  754. expect(after.nodes[0]).toBe(before.nodes[0]) // untouched nodes keep identity
  755. expect(after.nodes[1]).toBe(before.nodes[1])
  756. expect(after.nodes).toHaveLength(3)
  757. // No change → same snapshot reference.
  758. expect(session.getSnapshot()).toBe(after)
  759. })
  760. it('keeps untouched substructure arrays identical across unrelated changes (revision counters)', async () => {
  761. const { api, session } = makeSession()
  762. api.onHistory = () => histResponse(plainTurn(0, 0, '底', '座'))
  763. await session.open()
  764. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  765. feed(ev.turnStart(6, 1))
  766. feed(ev.toolCall(7, 1, 'c1', 'echo', '{}'))
  767. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  768. const before = session.getSnapshot()
  769. // A chunk storm touches partial/nodes only: runningCalls and pending must keep identity.
  770. feed(ev.chunkStart(8, 1))
  771. feed(ev.chunkText(9, 1, '与工具无关的流式'))
  772. const after = session.getSnapshot()
  773. expect(after).not.toBe(before)
  774. expect(after.runningCalls).toBe(before.runningCalls)
  775. expect(after.pending).toBe(before.pending)
  776. // And a mutation on the tracked domain swaps that array.
  777. feed(ev.toolResult(10, 1, 'c1', 'ECHO'))
  778. const resolved = session.getSnapshot()
  779. expect(resolved.runningCalls).not.toBe(after.runningCalls)
  780. expect(resolved.pending).toBe(after.pending)
  781. })
  782. })