session.spec.ts 44 KB

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