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) {
  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-official', 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', '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-official', 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('rename', () => {
  278. it('settles the title projection cell from the unary response (higher-seq-wins vs the push frame)', async () => {
  279. const { api, session } = makeSession()
  280. api.onRename = () => Promise.resolve(ok({ title: '正名', seq: 7 }))
  281. const result = await session.rename(' 正名 ')
  282. expect(result).toMatchObject({ ok: true, value: { title: '正名', seq: 7 } })
  283. expect(api.callsOf('session.rename')).toMatchObject([{ sessionId: SID, title: ' 正名 ' }])
  284. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  285. // A stale lower-seq apply (the push-frame path routes into this same
  286. // store) must not roll the settled value back.
  287. session.projections.apply('title', '旧名', 3)
  288. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  289. })
  290. it('returns the business error untouched and folds a transport throw to internal', async () => {
  291. const { api, session } = makeSession()
  292. api.onRename = () => Promise.resolve(err({ code: 'title-invalid', message: 'empty', details: { sessionId: SID } }))
  293. const rejected = await session.rename(' ')
  294. expect(rejected).toMatchObject({ ok: false, error: { code: 'title-invalid' } })
  295. expect(session.projections.faceOf('title').getSnapshot()).toBeUndefined()
  296. api.onRename = () => Promise.reject(new Error('rename transport down'))
  297. const folded = await session.rename('x')
  298. expect(folded).toMatchObject({ ok: false, error: { code: 'internal' } })
  299. })
  300. })
  301. describe('pending interactions', () => {
  302. it('adds approval/question on requested and removes them on resolved', async () => {
  303. const { session } = makeSession()
  304. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  305. session.handleMuxEnvelope('rq' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  306. expect(session.getSnapshot().pending.map(p => p.kind).sort()).toEqual(['approval', 'question'])
  307. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap1' as never, outcome: 'approved' as never })
  308. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq' as never, outcome: 'answered' })
  309. expect(session.getSnapshot().pending).toEqual([])
  310. })
  311. it('mints waits whose respond() backfills the requested rpcId into the client-response envelope', async () => {
  312. const { api, session } = makeSession()
  313. session.handleMuxEnvelope('rq-answer' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  314. const wait = session.getSnapshot().pending[0]!
  315. expect(wait).toMatchObject({ kind: 'question', key: 'q:rq-answer', sessionId: SID, payload: { questions: [] } })
  316. const receipt = await wait.respond({
  317. ok: true,
  318. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  319. })
  320. expect(receipt).toEqual({ accepted: true })
  321. expect(api.callsOf('respond')).toEqual([{
  322. type: 'client-response', rpcId: 'rq-answer',
  323. result: {
  324. ok: true,
  325. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  326. },
  327. }])
  328. })
  329. it('settles the wait on the authoritative resolved frame: respond() then throws synchronously', async () => {
  330. const { api, session } = makeSession()
  331. session.handleMuxEnvelope('rq1' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  332. const wait = session.getSnapshot().pending[0]!
  333. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq1' as never, outcome: 'answered' })
  334. expect(session.getSnapshot().pending).toEqual([])
  335. expect(() => wait.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } }))
  336. .toThrow('already settled')
  337. expect(api.callsOf('respond')).toEqual([])
  338. })
  339. })
  340. describe('remaining branches', () => {
  341. it('prompt transport throw folds to internal promptError', async () => {
  342. const { api, session } = makeSession()
  343. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  344. const result = await session.prompt([{ type: 'text', text: 'x' }], 'queue')
  345. expect(result.ok).toBe(false)
  346. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'internal', message: 'prompt wire down' } })
  347. })
  348. it('cancel business error also lands op=stop promptError', async () => {
  349. const { api, session } = makeSession()
  350. api.onCancel = () => Promise.resolve(err({ code: 'agent-busy', message: 'nope', details: { reason: 'r' } }))
  351. await session.cancel()
  352. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'agent-busy' } })
  353. })
  354. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  355. const { api, session } = makeSession()
  356. await session.loadOlder() // cold: no-op, zero calls
  357. expect(api.calls).toEqual([])
  358. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  359. await session.open()
  360. // err result: window unchanged
  361. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  362. await session.loadOlder()
  363. expect(session.getSnapshot().nodes).toHaveLength(2)
  364. expect(session.getSnapshot().hasMore).toBe(true)
  365. // empty page: hasMore adopts the response
  366. api.onHistory = () => histResponse([], false)
  367. await session.loadOlder()
  368. expect(session.getSnapshot().hasMore).toBe(false)
  369. // hasMore false now: further loadOlder is a guard no-op
  370. const calls = api.calls.length
  371. await session.loadOlder()
  372. expect(api.calls.length).toBe(calls)
  373. // throw path: fail-soft with console.error
  374. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  375. try {
  376. await session.resync()
  377. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  378. await session.resync()
  379. api.onHistory = () => Promise.reject(new Error('page wire down'))
  380. await session.loadOlder()
  381. expect(errorSpy).toHaveBeenCalled()
  382. expect(session.getSnapshot().loadingOlder).toBe(false)
  383. } finally {
  384. errorSpy.mockRestore()
  385. }
  386. })
  387. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  388. const { api, session } = makeSession()
  389. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  390. let notified = 0
  391. const unsubscribe = session.subscribe(() => { notified++ })
  392. await session.open()
  393. await new Promise(resolve => setTimeout(resolve, 0))
  394. expect(notified).toBeGreaterThan(0)
  395. const seen = notified
  396. unsubscribe()
  397. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  398. await new Promise(resolve => setTimeout(resolve, 0))
  399. expect(notified).toBe(seen)
  400. })
  401. it('subscribed baseline past the window tail triggers the second stitch pull in doOpen', async () => {
  402. const { api, session } = makeSession()
  403. const full = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  404. let call = 0
  405. api.onHistory = () => {
  406. call++
  407. return histResponse(call === 1 ? plainTurn(0, 0, 'a', 'b') : full)
  408. }
  409. // Baseline arrives before open: lastSeq 11 > first page tail 5 → doOpen repulls once.
  410. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  411. await session.open()
  412. expect(call).toBe(2)
  413. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  414. })
  415. it('a failed second stitch pull keeps the first window and still opens', async () => {
  416. const { api, session } = makeSession()
  417. let call = 0
  418. api.onHistory = () => {
  419. call++
  420. return call === 1
  421. ? histResponse(plainTurn(0, 0, 'a', 'b'))
  422. : Promise.resolve(err({ code: 'internal', message: 'stitch pull down', details: {} }))
  423. }
  424. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  425. await session.open()
  426. expect(call).toBe(2)
  427. const snapshot = session.getSnapshot()
  428. expect(snapshot.openState).toBe('open') // stitch-pull failure is not an open failure
  429. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3]) // first window kept
  430. })
  431. it('approval frame with callId/reason keeps the optional fields; duplicate resolved is a no-op', () => {
  432. const { session } = makeSession()
  433. session.handleMuxEnvelope('ra' as never, {
  434. type: 'approval/requested', sessionId: SID, approvalId: 'ap2' as never, toolName: 'rm', callId: 'c1' as never, reason: '危险',
  435. })
  436. expect(session.getSnapshot().pending[0]).toMatchObject({ kind: 'approval', payload: { callId: 'c1', reason: '危险' } })
  437. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  438. session.handleMuxEnvelope('rx2' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  439. session.handleMuxEnvelope('ry2' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'never-was' as never, outcome: 'cancelled' })
  440. expect(session.getSnapshot().pending).toEqual([])
  441. })
  442. it('ignores unknown mux frame types and repeated running flips (documented defaults)', () => {
  443. const { session } = makeSession()
  444. const before = session.getSnapshot()
  445. session.handleMuxEnvelope('rz' as never, { type: 'future/frame' } as never)
  446. session.handleRunning(false) // already false: dedup branch
  447. expect(session.getSnapshot()).toBe(before)
  448. session.handleRemoved()
  449. expect(session.getSnapshot().removed).toBe(true)
  450. })
  451. it('drops live events while cold/error (no window upkeep)', async () => {
  452. const { api, session } = makeSession()
  453. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '冷态帧') })
  454. expect(session.getSnapshot().nodes).toEqual([])
  455. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  456. await session.open()
  457. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '错态帧') })
  458. expect(session.getSnapshot().nodes).toEqual([])
  459. })
  460. it('repairGap failure logs and clears stitching; concurrent gaps coalesce into one repair', async () => {
  461. const { api, session } = makeSession()
  462. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  463. await session.open()
  464. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  465. let repairs = 0
  466. api.onHistory = () => {
  467. repairs++
  468. return gate.promise
  469. }
  470. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  471. try {
  472. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞一') })
  473. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(10, '洞二') }) // stitching: detours, no second repair
  474. expect(repairs).toBe(1)
  475. gate.reject(new Error('repair wire down'))
  476. await vi.waitFor(() => { expect(errorSpy).toHaveBeenCalled() })
  477. // Window unchanged; a later successful repull still lands the buffered frames.
  478. expect(session.getSnapshot().nodes).toHaveLength(2)
  479. } finally {
  480. errorSpy.mockRestore()
  481. }
  482. })
  483. it('freezes only content-bearing partials; a content-free partial is dropped outright', async () => {
  484. const { api, session } = makeSession()
  485. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  486. await session.open()
  487. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  488. feed(ev.turnStart(6, 1))
  489. feed(ev.chunkStart(7, 1)) // empty text block only, no delta
  490. feed(ev.turnEnd(8, 1, 'cancelled'))
  491. const snapshot = session.getSnapshot()
  492. expect(snapshot.partial).toBeNull()
  493. expect(snapshot.nodes.filter(n => n.kind === 'assistant' && (n as { interrupted?: true }).interrupted)).toEqual([])
  494. })
  495. it('turn/end sweeps only same-turn open calls; other turns keep running', async () => {
  496. const { api, session } = makeSession()
  497. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  498. await session.open()
  499. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  500. feed(ev.turnStart(6, 1))
  501. feed(ev.toolCall(7, 1, 'turn1-call', 'echo', '{}'))
  502. feed(ev.toolCall(8, 2, 'turn2-call', 'echo', '{}')) // stray call attributed to a later turn
  503. feed(ev.turnEnd(9, 1, 'cancelled'))
  504. const snapshot = session.getSnapshot()
  505. expect(snapshot.runningCalls.map(c => c.callId)).toEqual(['turn2-call'])
  506. expect(snapshot.nodes.at(-1)).toMatchObject({ kind: 'tool-result', callId: 'turn1-call', isError: true })
  507. })
  508. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  509. const { api, session } = makeSession()
  510. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  511. api.onHistory = () => stale.promise
  512. const opening = session.open()
  513. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  514. const resynced = session.resync()
  515. stale.reject(new Error('stale wire'))
  516. await Promise.all([opening, resynced])
  517. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  518. })
  519. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  520. const { api, session } = makeSession()
  521. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  522. api.onHistory = () => stale.promise
  523. const opening = session.open()
  524. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  525. const resynced = session.resync()
  526. stale.resolve(ok({
  527. events: entries(plainTurn(0, 0, '旧', '代')) as never[],
  528. hasMore: false,
  529. modelTarget: { provider: 'deepseek-official', model: 'stale' },
  530. })) // success, but its generation is gone
  531. await Promise.all([opening, resynced])
  532. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9]) // only the fresh generation's window
  533. })
  534. it('drops a stale stitch pull (second doOpen fetch) superseded mid-flight by resync', async () => {
  535. const { api, session } = makeSession()
  536. const secondPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  537. let call = 0
  538. api.onHistory = () => {
  539. call++
  540. if (call === 1) return histResponse(plainTurn(0, 0, 'a', 'b')) // first page: tail 5
  541. if (call === 2) return secondPull.promise // gap-stitch pull: held
  542. return histResponse(plainTurn(6, 1, 'c', 'd'))
  543. }
  544. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  545. const opening = session.open() // triggers the second pull, which parks
  546. await vi.waitFor(() => { expect(call).toBe(2) })
  547. const resynced = session.resync()
  548. secondPull.resolve(ok({
  549. events: entries([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]) as never[],
  550. hasMore: false,
  551. modelTarget: { provider: 'deepseek-official', model: 'stale' },
  552. }))
  553. await Promise.all([opening, resynced])
  554. expect(session.getSnapshot().openState).toBe('open')
  555. })
  556. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  557. const { api, session } = makeSession()
  558. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  559. await session.open()
  560. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  561. api.onHistory = () => repairPull.promise
  562. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞') }) // starts repairGap
  563. api.onHistory = () => histResponse(plainTurn(6, 1, 'c', 'd'))
  564. const resynced = session.resync() // bumps the generation
  565. repairPull.resolve(ok({
  566. events: entries(plainTurn(0, 0, '旧', '页')) as never[],
  567. hasMore: false,
  568. modelTarget: { provider: 'deepseek-official', model: 'stale' },
  569. })) // repair result: stale, dropped
  570. await resynced
  571. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9])
  572. })
  573. it('successful cancel leaves no promptError; tool/result for an unknown callId is a no-op', async () => {
  574. const { api, session } = makeSession()
  575. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  576. await session.open()
  577. const result = await session.cancel()
  578. expect(result.ok).toBe(true)
  579. expect(session.getSnapshot().promptError).toBeNull()
  580. const callsBefore = session.getSnapshot().runningCalls
  581. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.toolResult(6, 0, 'never-called', 'x') })
  582. expect(session.getSnapshot().runningCalls).toBe(callsBefore) // callsRev untouched: same reference
  583. })
  584. it('freezes a tool-call-only partial (visible through the non-text arm)', async () => {
  585. const { api, session } = makeSession()
  586. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  587. await session.open()
  588. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  589. feed(ev.turnStart(6, 1))
  590. feed(at(7, { type: 'assistant/chunk', data: { turn: 1, step: 0, chunk: { type: 'tool-call-delta', index: 0, id: 'c1', name: 'echo', argumentsDelta: '{' } } }))
  591. feed(ev.turnEnd(8, 1, 'cancelled'))
  592. const frozen = session.getSnapshot().nodes.at(-1)
  593. expect(frozen).toMatchObject({ kind: 'assistant', interrupted: true, blocks: [{ kind: 'tool-call', callId: 'c1' }] })
  594. })
  595. it('dispose is a reserved no-op on resident instances', () => {
  596. const { session } = makeSession()
  597. expect(() => { session.dispose() }).not.toThrow()
  598. })
  599. it('carries mux-frame views into runningCalls and tool-result nodes, and history-entry views through open', async () => {
  600. const { api, session } = makeSession()
  601. const callView = { for: 'call', view: { card: 'generic', title: '历史卡' } }
  602. api.onHistory = () => Promise.resolve(ok({
  603. events: [
  604. ...entries(plainTurn(0, 0, 'a', 'b')),
  605. { event: ev.toolCall(6, 1, 'h1', 'bash', '{}'), view: callView },
  606. { event: ev.toolResult(7, 1, 'h1', 'done'), view: { for: 'result', view: { card: 'generic', title: '历史果' } } },
  607. ] as never[],
  608. hasMore: false,
  609. modelTarget: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  610. }))
  611. await session.open()
  612. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  613. kind: 'tool-result', callView: { title: '历史卡' }, resultView: { title: '历史果' },
  614. })
  615. // Live path: the frame's view slot reaches runningCalls, then the result node.
  616. session.handleMuxEnvelope('rv1' as never, {
  617. type: 'session/event', sessionId: SID, event: ev.toolCall(8, 2, 'l1', 'write', '{}'),
  618. view: { for: 'call', view: { card: 'generic', title: '直播卡' } },
  619. } as never)
  620. expect(session.getSnapshot().runningCalls).toMatchObject([{ callId: 'l1', callView: { title: '直播卡' } }])
  621. session.handleMuxEnvelope('rv2' as never, {
  622. type: 'session/event', sessionId: SID, event: ev.toolResult(9, 2, 'l1', 'ok'),
  623. view: { for: 'result', view: { card: 'generic', title: '直播果' } },
  624. } as never)
  625. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  626. kind: 'tool-result', callView: { title: '直播卡' }, resultView: { title: '直播果' },
  627. })
  628. })
  629. })
  630. describe('resync', () => {
  631. it('rebuilds the window and clears pending; cold instances no-op', async () => {
  632. const { api, session } = makeSession()
  633. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  634. await session.open()
  635. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  636. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')])
  637. await session.resync()
  638. const snapshot = session.getSnapshot()
  639. expect(snapshot.openState).toBe('open')
  640. expect(snapshot.pending).toEqual([]) // baseline replay re-sends still-pending frames
  641. expect(snapshot.nodes).toHaveLength(4)
  642. const cold = makeSession()
  643. await cold.session.resync()
  644. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  645. })
  646. it('re-mints a replayed requested frame as a fresh wait with the same key (old reference superseded)', async () => {
  647. const { api, session } = makeSession()
  648. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  649. await session.open()
  650. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  651. const before = session.getSnapshot().pending[0]!
  652. await session.resync()
  653. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  654. const after = session.getSnapshot().pending[0]!
  655. expect(after).not.toBe(before)
  656. expect(after.key).toBe(before.key)
  657. // Superseded ≠ settled: an in-flight respond on the stale reference still reaches the host.
  658. await before.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } })
  659. expect(api.callsOf('respond')).toMatchObject([{ rpcId: 'rq-replay' }])
  660. })
  661. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  662. const { api, session } = makeSession()
  663. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  664. api.onHistory = () => stale.promise
  665. const firstOpen = session.open()
  666. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  667. const resynced = session.resync()
  668. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  669. await firstOpen
  670. await resynced
  671. const snapshot = session.getSnapshot()
  672. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  673. expect(snapshot.nodes.map(n => n.seq)).toEqual([7, 9])
  674. })
  675. })
  676. describe('run_code sub-dispatch indexing', () => {
  677. it('a start event lands as a running-shaped sub-call and its settle replaces it in place', async () => {
  678. const { api, session } = makeSession()
  679. api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答'))
  680. await session.open()
  681. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  682. feed(ev.turnStart(6, 1))
  683. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"d"}'))
  684. feed(ev.codeDispatchStart(8, 'p1', 1, 'bash', { command: 'sleep' }))
  685. feed(ev.codeDispatchStart(9, 'p1', 2, 'read', { path: 'a.txt' }))
  686. const live = session.getSnapshot().codeDispatches.get('p1')
  687. expect(live).toHaveLength(2)
  688. // Running shape (no 'kind'): the exact RunningToolCall form native rows use.
  689. expect(live?.[0]).toMatchObject({ callId: 'p1:code:1', name: 'bash', argsRaw: '{"command":"sleep"}' })
  690. expect(live?.[0] !== undefined && 'kind' in live[0]).toBe(false)
  691. // Settle out of order (parallel run): #2 first — replaces in place, keeping start order.
  692. feed(ev.codeDispatch(10, 'p1', 2, 'read', { path: 'a.txt' }, 'alpha'))
  693. const mixed = session.getSnapshot().codeDispatches.get('p1')
  694. expect(mixed?.map(sub => 'kind' in sub)).toEqual([false, true])
  695. expect(mixed?.[1]).toMatchObject({ callId: 'p1:code:2', content: [{ type: 'text', text: 'alpha' }] })
  696. // The settle carries the paired start's time as callTime (duration source).
  697. feed(ev.codeDispatch(11, 'p1', 1, 'bash', { command: 'sleep' }, 'done'))
  698. const settled = session.getSnapshot().codeDispatches.get('p1')
  699. expect(settled?.map(sub => 'kind' in sub)).toEqual([true, true])
  700. expect(settled?.[0]).toMatchObject({ callId: 'p1:code:1', callTime: 1_700_000_000_008 })
  701. })
  702. it('indexes live tool/code-dispatch events under their parent as native-shaped result nodes', async () => {
  703. const { api, session } = makeSession()
  704. api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答'))
  705. await session.open()
  706. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  707. feed(ev.turnStart(6, 1))
  708. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"return 1","description":"跑一个程序"}'))
  709. feed(ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls', description: '列目录' }, 'demo.txt'))
  710. feed(ev.codeDispatch(9, 'p1', 2, 'read', { path: 'a.txt' }, 'Error: ENOENT', true))
  711. const subs = session.getSnapshot().codeDispatches.get('p1')
  712. expect(subs).toHaveLength(2)
  713. expect(subs?.[0]).toMatchObject({
  714. kind: 'tool-result', callId: 'p1:code:1',
  715. call: { name: 'bash', argsRaw: '{"command":"ls","description":"列目录"}' },
  716. // The settle event carries no start time: callTime stays null (never a
  717. // fabricated zero-duration).
  718. callTime: null,
  719. isError: false, content: [{ type: 'text', text: 'demo.txt' }],
  720. })
  721. expect(subs?.[1]).toMatchObject({ callId: 'p1:code:2', isError: true })
  722. // No paired start in the window: duration is UNKNOWN (null), never a
  723. // fabricated zero-duration span.
  724. expect(subs?.[0]).toMatchObject({ callTime: null })
  725. // Sub-dispatches never join the surface flow.
  726. expect(session.getSnapshot().nodes.some(n => n.kind === 'tool-result' && n.callId.includes(':code:'))).toBe(false)
  727. })
  728. it('rebuilds the same index from a history window (replay parity)', async () => {
  729. const { api, session } = makeSession()
  730. api.onHistory = () => histResponse([
  731. ...plainTurn(0, 0, '问', '答'),
  732. ev.turnStart(6, 1),
  733. ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"return 1","description":"跑一个程序"}'),
  734. ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls' }, 'demo.txt'),
  735. ev.toolResult(9, 1, 'p1', '{"done":true}'),
  736. ev.turnEnd(10, 1),
  737. ])
  738. await session.open()
  739. const subs = session.getSnapshot().codeDispatches.get('p1')
  740. expect(subs).toHaveLength(1)
  741. expect(subs?.[0]).toMatchObject({ callId: 'p1:code:1', call: { name: 'bash' } })
  742. })
  743. it('keeps the dispatch map reference across unrelated changes and swaps it on a new dispatch', async () => {
  744. const { api, session } = makeSession()
  745. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  746. await session.open()
  747. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  748. feed(ev.turnStart(6, 1))
  749. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"d"}'))
  750. feed(ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls' }, 'x'))
  751. const before = session.getSnapshot()
  752. feed(ev.chunkStart(9, 1))
  753. feed(ev.chunkText(10, 1, '流式'))
  754. const after = session.getSnapshot()
  755. expect(after.codeDispatches).toBe(before.codeDispatches)
  756. feed(ev.codeDispatch(11, 'p1', 2, 'read', { path: 'a' }, 'y'))
  757. expect(session.getSnapshot().codeDispatches).not.toBe(after.codeDispatches)
  758. expect(session.getSnapshot().codeDispatches.get('p1')).toHaveLength(2)
  759. })
  760. })
  761. describe('reference stability (the memo contract)', () => {
  762. it('keeps unchanged node references across an append and swaps the snapshot object', async () => {
  763. const { api, session } = makeSession()
  764. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  765. await session.open()
  766. const before = session.getSnapshot()
  767. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(6, '追加') })
  768. const after = session.getSnapshot()
  769. expect(after).not.toBe(before) // top-level swap on change
  770. expect(after.nodes[0]).toBe(before.nodes[0]) // untouched nodes keep identity
  771. expect(after.nodes[1]).toBe(before.nodes[1])
  772. expect(after.nodes).toHaveLength(3)
  773. // No change → same snapshot reference.
  774. expect(session.getSnapshot()).toBe(after)
  775. })
  776. it('keeps untouched substructure arrays identical across unrelated changes (revision counters)', async () => {
  777. const { api, session } = makeSession()
  778. api.onHistory = () => histResponse(plainTurn(0, 0, '底', '座'))
  779. await session.open()
  780. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  781. feed(ev.turnStart(6, 1))
  782. feed(ev.stepStart(7, 1))
  783. feed(ev.toolCall(8, 1, 'c1', 'echo', '{}'))
  784. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  785. const before = session.getSnapshot()
  786. // A chunk storm touches partial/nodes only: unrelated projections keep identity.
  787. feed(ev.chunkStart(9, 1))
  788. feed(ev.chunkText(10, 1, '与工具无关的流式'))
  789. const after = session.getSnapshot()
  790. expect(after).not.toBe(before)
  791. expect(after.runningCalls).toBe(before.runningCalls)
  792. expect(after.pending).toBe(before.pending)
  793. // And a mutation on the tracked domain swaps that array.
  794. feed(ev.toolResult(11, 1, 'c1', 'ECHO'))
  795. const resolved = session.getSnapshot()
  796. expect(resolved.runningCalls).not.toBe(after.runningCalls)
  797. expect(resolved.pending).toBe(after.pending)
  798. feed(ev.assistant(12, 1, '完成'))
  799. expect(session.getSnapshot()).not.toBe(resolved)
  800. })
  801. })