session.spec.ts 44 KB

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