session.spec.ts 42 KB

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