session.spec.ts 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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 { afterEach, 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 type {
  13. ChatConversationViewNode, ChatLocationNodeIndex, ChatNodeStore, ChatSnapshot,
  14. ConversationEventInput, ConversationNode, ConversationNodeDefinition,
  15. ConversationRuntime, ConversationSnapshot, ConversationTimelineSnapshot,
  16. ConversationViewDefinition,
  17. } from '../src/client/index.ts'
  18. import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
  19. import { entries, ev, plainTurn } from './event-script.ts'
  20. const SID = 'fk-s1' as SessionId
  21. const PARENT = 'fk-parent' as SessionId
  22. afterEach(() => {
  23. vi.unstubAllGlobals()
  24. })
  25. const EMPTY: readonly never[] = []
  26. interface TestEventState extends ConversationEventInput {}
  27. class TestNodeStore implements ChatNodeStore {
  28. private readonly nodes = new Map<string, ChatConversationViewNode>()
  29. private cache: readonly ChatConversationViewNode[] = EMPTY
  30. get(key: string): ChatConversationViewNode | undefined {
  31. return this.nodes.get(key)
  32. }
  33. values(): readonly ChatConversationViewNode[] {
  34. return this.cache
  35. }
  36. replace(nodes: readonly ChatConversationViewNode[]): void {
  37. this.nodes.clear()
  38. for (const node of nodes) this.nodes.set(node.key, node)
  39. this.cache = [...this.nodes.values()]
  40. }
  41. upsert(nodes: readonly ChatConversationViewNode[]): void {
  42. if (nodes.length === 0) return
  43. for (const node of nodes) this.nodes.set(node.key, node)
  44. this.cache = [...this.nodes.values()]
  45. }
  46. }
  47. const TEST_LOCATIONS: ChatLocationNodeIndex = {
  48. getTurn: () => EMPTY,
  49. getStep: () => EMPTY,
  50. }
  51. function testLegacy(
  52. nodes: readonly ChatConversationViewNode[],
  53. timeline: ConversationTimelineSnapshot,
  54. ): ChatSnapshot['legacy'] {
  55. const legacyNodes = nodes.flatMap((node): ConversationNode[] => {
  56. const event = (node.data as TestEventState).event
  57. if (event.type === 'user/message') return [{ kind: 'user', seq: event.seq } as ConversationNode]
  58. if (event.type === 'assistant/message') return [{ kind: 'assistant', seq: event.seq } as ConversationNode]
  59. return []
  60. })
  61. const turnTimings = new Map<number, { startTime: number; endTime?: number }>()
  62. const turnEnds = new Map<number, number>()
  63. for (const turn of timeline.turns.values()) {
  64. if (turn.start !== undefined) {
  65. turnTimings.set(turn.turn, turn.end === undefined
  66. ? { startTime: turn.start.time }
  67. : { startTime: turn.start.time, endTime: turn.end.time })
  68. }
  69. if (turn.end !== undefined) turnEnds.set(turn.turn, turn.end.seq)
  70. }
  71. return { nodes: legacyNodes, turnTimings, turnEnds, partial: null, runningCalls: EMPTY }
  72. }
  73. function testViewDefinition(): ConversationViewDefinition<ChatConversationViewNode, ChatSnapshot> {
  74. return {
  75. target: 'chat',
  76. create: () => {
  77. const store = new TestNodeStore()
  78. let current: ChatSnapshot = {
  79. order: EMPTY,
  80. nodes: store,
  81. locations: TEST_LOCATIONS,
  82. timeline: { turnOrder: EMPTY, turns: new Map() },
  83. legacy: testLegacy(EMPTY, { turnOrder: EMPTY, turns: new Map() }),
  84. }
  85. const build = (timeline: ConversationTimelineSnapshot): ChatSnapshot => {
  86. const nodes = [...store.values()].sort((left, right) => left.anchorSeq - right.anchorSeq)
  87. current = {
  88. order: nodes.map(node => node.key),
  89. nodes: store,
  90. locations: TEST_LOCATIONS,
  91. timeline,
  92. legacy: testLegacy(nodes, timeline),
  93. }
  94. return current
  95. }
  96. return {
  97. empty: current,
  98. replace: ({ nodes, timeline }) => {
  99. store.replace(nodes)
  100. return build(timeline)
  101. },
  102. apply: ({ upserts, timeline }) => {
  103. store.upsert(upserts)
  104. return build(timeline)
  105. },
  106. }
  107. },
  108. }
  109. }
  110. const TEST_EVENT_DEFINITION: ConversationNodeDefinition<TestEventState> = {
  111. kind: 'runtime-test-event',
  112. target: 'chat',
  113. match: event => ({ id: String(event.seq), role: 'start' }),
  114. start: (_context, match) => ({ event: match.event, view: match.view }),
  115. update: context => context.state,
  116. publication: match => match.event.type === 'assistant/chunk' ? 'animation-frame' : 'immediate',
  117. buildViewNode: (context) => {
  118. if (context.state === undefined || context.start === undefined) return null
  119. return {
  120. key: context.key,
  121. kind: 'runtime-test-event',
  122. id: context.id,
  123. target: 'chat',
  124. anchorSeq: context.start.event.seq,
  125. location: context.start.location,
  126. visibility: 'visible',
  127. data: context.state,
  128. }
  129. },
  130. }
  131. const TEST_CONVERSATION: ConversationRuntime = {
  132. events: {
  133. entries: () => [TEST_EVENT_DEFINITION],
  134. fallbackEntry: () => undefined,
  135. } as unknown as ConversationRuntime['events'],
  136. views: {
  137. entries: () => [testViewDefinition()],
  138. } as unknown as ConversationRuntime['views'],
  139. }
  140. function makeSession(api = new FakeApiClient()): { api: FakeApiClient; session: Session } {
  141. return { api, session: new Session(SID, api, { conversation: TEST_CONVERSATION }) }
  142. }
  143. function chatEvents(snapshot: ConversationSnapshot): readonly TestEventState[] {
  144. return snapshot.chat.order.map(key => snapshot.chat.nodes.get(key)?.data as TestEventState)
  145. }
  146. function chatSeqs(snapshot: ConversationSnapshot): number[] {
  147. return chatEvents(snapshot).map(item => item.event.seq)
  148. }
  149. function histResponse(events: SessionEvent[], hasMore = false) {
  150. // history returns HistoryEntry[] ({event, view?}); these tests are view-less.
  151. return Promise.resolve(ok({ events: entries(events) as never[], hasMore }))
  152. }
  153. describe('open', () => {
  154. it('keeps a bare Session blank until an authoritative lifecycle signal arrives', () => {
  155. const { session } = makeSession()
  156. expect(session.getSnapshot()).toMatchObject({ blank: true, composerPhase: 'blank' })
  157. session.handleRunning(true)
  158. expect(session.getSnapshot()).toMatchObject({ blank: false, composerPhase: 'active' })
  159. })
  160. it('installs the tail page: cold → loading → open with window and nodes in place', async () => {
  161. const { api, session } = makeSession()
  162. const page = plainTurn(10, 3, '问', '答')
  163. api.onHistory = () => histResponse(page, true)
  164. expect(session.getSnapshot().openState).toBe('cold')
  165. const opening = session.open()
  166. expect(session.getSnapshot().openState).toBe('loading')
  167. await opening
  168. const snapshot = session.getSnapshot()
  169. expect(snapshot.openState).toBe('open')
  170. expect(snapshot.hasMore).toBe(true)
  171. expect(snapshot.nodes.map(n => n.kind)).toEqual(['user', 'assistant'])
  172. expect(snapshot.turnTimings.get(3)).toEqual({
  173. startTime: 1_700_000_000_010,
  174. endTime: 1_700_000_000_015,
  175. })
  176. expect(snapshot.turnEnds.get(3)).toBe(15)
  177. })
  178. it('is idempotent: concurrent opens share one history call, reopening when open is a no-op', async () => {
  179. const { api, session } = makeSession()
  180. await Promise.all([session.open(), session.open()])
  181. await session.open()
  182. expect(api.callsOf('session.history')).toHaveLength(1)
  183. })
  184. it('lands an error result in openState=error with the RpcError kept', async () => {
  185. const { api, session } = makeSession()
  186. api.onHistory = () => Promise.resolve(err({ code: 'session-not-found', message: 'gone', details: { sessionId: SID } }))
  187. await session.open()
  188. const snapshot = session.getSnapshot()
  189. expect(snapshot.openState).toBe('error')
  190. expect(snapshot.openError?.code).toBe('session-not-found')
  191. })
  192. it('folds a transport throw into openState=error / internal', async () => {
  193. const { api, session } = makeSession()
  194. api.onHistory = () => Promise.reject(new Error('socket died'))
  195. await session.open()
  196. expect(session.getSnapshot().openState).toBe('error')
  197. expect(session.getSnapshot().openError).toMatchObject({ code: 'internal', message: 'socket died' })
  198. })
  199. it('stitches live frames arriving while history is pending, dropping the page overlap', async () => {
  200. const { api, session } = makeSession()
  201. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  202. api.onHistory = () => gate.promise
  203. const opening = session.open()
  204. // Three live frames land mid-open; seq 15 overlaps the page tail (page covers 10..15).
  205. const page = plainTurn(10, 0, '早', '安')
  206. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.turnStart(15, 1) })
  207. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(16, '插进来的') })
  208. gate.resolve(ok({
  209. events: entries(page) as never[],
  210. hasMore: false,
  211. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  212. }))
  213. await opening
  214. const seqs = session.getSnapshot().nodes.map(n => n.seq)
  215. // Overlapping seq-15 frame (== page tail turn/end) was dropped; 16 appended once.
  216. expect(seqs).toEqual([11, 13, 16])
  217. })
  218. })
  219. describe('live event path', () => {
  220. async function opened(events: SessionEvent[] = plainTurn(0, 0, 'a', 'b')) {
  221. const { api, session } = makeSession()
  222. api.onHistory = () => histResponse(events)
  223. await session.open()
  224. return { api, session }
  225. }
  226. it('drops replayed frames at or below the window tail', async () => {
  227. const { session } = await opened()
  228. const before = session.getSnapshot()
  229. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(3, '重放') })
  230. await Promise.resolve()
  231. expect(session.getSnapshot().nodes).toEqual(before.nodes)
  232. })
  233. it('keeps the authoritative host blank bit across unrelated log events', async () => {
  234. const { session } = await opened([])
  235. session.handleBlank(true)
  236. expect(session.getSnapshot().composerPhase).toBe('blank')
  237. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  238. feed(ev.commandRun(0, 'cmd-perm', 'permission', ' danger-full-access'))
  239. feed(ev.commandDone(1, 'cmd-perm', 'success', 'preset danger-full-access'))
  240. const snapshot = session.getSnapshot()
  241. expect(chatSeqs(snapshot)).toEqual([0, 1])
  242. expect(snapshot.composerPhase).toBe('blank')
  243. })
  244. it('publishes animation-frame Definitions once per frame and lets an immediate event supersede the pending frame', async () => {
  245. const frames: FrameRequestCallback[] = []
  246. vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
  247. frames.push(callback)
  248. return frames.length
  249. })
  250. const { session } = await opened()
  251. const published: number[][] = []
  252. session.subscribe(() => {
  253. published.push(chatSeqs(session.getSnapshot()))
  254. })
  255. const feed = (event: SessionEvent) => {
  256. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event })
  257. }
  258. feed(ev.chunkStart(6, 1))
  259. feed(ev.chunkText(7, 1, '累'))
  260. feed(ev.chunkText(8, 1, '计'))
  261. expect(published).toEqual([])
  262. expect(frames).toHaveLength(1)
  263. frames.shift()!(0)
  264. expect(published).toEqual([[0, 1, 2, 3, 4, 5, 6, 7, 8]])
  265. feed(ev.chunkText(9, 1, '完成'))
  266. feed(ev.assistant(10, 1, '累计完成'))
  267. await Promise.resolve()
  268. expect(published).toEqual([
  269. [0, 1, 2, 3, 4, 5, 6, 7, 8],
  270. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  271. ])
  272. frames.shift()!(0)
  273. expect(published).toHaveLength(2)
  274. })
  275. it('publishes a timeline-only boundary even when no Definition claims the event', async () => {
  276. const api = new FakeApiClient()
  277. api.onHistory = () => histResponse([])
  278. const conversation: ConversationRuntime = {
  279. events: {
  280. entries: () => [],
  281. fallbackEntry: () => undefined,
  282. } as unknown as ConversationRuntime['events'],
  283. views: {
  284. entries: () => [testViewDefinition()],
  285. } as unknown as ConversationRuntime['views'],
  286. }
  287. const session = new Session(SID, api, { conversation })
  288. await session.open()
  289. const snapshots: ConversationSnapshot[] = []
  290. session.subscribe(() => { snapshots.push(session.getSnapshot()) })
  291. session.handleMuxEnvelope('timeline' as never, {
  292. type: 'session/event',
  293. sessionId: SID,
  294. event: ev.turnStart(0, 1),
  295. })
  296. await Promise.resolve()
  297. expect(snapshots).toHaveLength(1)
  298. expect(snapshots[0]?.chat.timeline.turns.get(1)?.status).toBe('open')
  299. })
  300. it('repairs a seq gap by repulling the tail page instead of appending a hole', async () => {
  301. const { api, session } = await opened(plainTurn(0, 0, 'a', 'b')) // tail seq = 5
  302. const repaired = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  303. api.onHistory = () => histResponse(repaired)
  304. // seq 9 with tail 5 → gap; the event detours to the buffer and one history refetch fires.
  305. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.assistant(9, 1, 'd') })
  306. await vi.waitFor(() => {
  307. expect(api.callsOf('session.history').length).toBe(2)
  308. })
  309. await Promise.resolve()
  310. const seqs = session.getSnapshot().nodes.map(n => n.seq)
  311. expect(seqs).toEqual([1, 3, 7, 9]) // both turns' user/assistant, no hole, no duplicate 9
  312. })
  313. })
  314. describe('paging', () => {
  315. it('prepends an older page and keeps seq continuity', async () => {
  316. const older = plainTurn(0, 0, '旧问', '旧答')
  317. const newer = plainTurn(6, 1, '新问', '新答')
  318. const { api, session } = makeSession()
  319. api.onHistory = payload => payload.beforeSeq === undefined
  320. ? histResponse(newer, true)
  321. : histResponse(older, false)
  322. await session.open()
  323. await session.loadOlder()
  324. const snapshot = session.getSnapshot()
  325. expect(api.callsOf('session.history')).toMatchObject([{}, { beforeSeq: 6 }].map(p => ({ sessionId: SID, ...p })))
  326. expect(snapshot.hasMore).toBe(false)
  327. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  328. })
  329. it('installs a page without interpreting business replacement metadata', async () => {
  330. const { api, session } = makeSession()
  331. api.onHistory = () => histResponse([
  332. ev.compactSummary(80, '窗外范围的摘要', 3, 40),
  333. ev.compactCheckpoint(81, 80, 3, 40),
  334. ev.user(82, '压缩后的新问题'),
  335. ], true)
  336. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  337. try {
  338. await session.open()
  339. const snapshot = session.getSnapshot()
  340. expect(snapshot.openState).toBe('open')
  341. expect(chatSeqs(snapshot)).toEqual([80, 81, 82])
  342. expect(errorSpy).not.toHaveBeenCalled()
  343. } finally {
  344. errorSpy.mockRestore()
  345. }
  346. })
  347. it('drops a discontinuous older page fail-soft (window unchanged, hasMore cleared)', async () => {
  348. const { api, session } = makeSession()
  349. api.onHistory = payload => payload.beforeSeq === undefined
  350. ? histResponse(plainTurn(10, 1, '新', '页'), true)
  351. : histResponse(plainTurn(0, 0, '断', '层'), true) // tail seq 5, but baseSeq is 10 → hole
  352. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  353. try {
  354. await session.open()
  355. const nodesBefore = session.getSnapshot().nodes
  356. await session.loadOlder()
  357. const snapshot = session.getSnapshot()
  358. expect(snapshot.nodes).toEqual(nodesBefore)
  359. expect(snapshot.hasMore).toBe(false)
  360. } finally {
  361. errorSpy.mockRestore()
  362. }
  363. })
  364. it('ignores loadOlder while one is in flight (single request)', async () => {
  365. const { api, session } = makeSession()
  366. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  367. await session.open()
  368. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  369. api.onHistory = () => gate.promise
  370. const first = session.loadOlder()
  371. const second = session.loadOlder()
  372. gate.resolve(ok({
  373. events: entries(plainTurn(0, 0, 'a', 'b')) as never[],
  374. hasMore: false,
  375. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  376. }))
  377. await Promise.all([first, second])
  378. expect(api.callsOf('session.history')).toHaveLength(2) // open + one page, not two
  379. })
  380. })
  381. describe('prompt and cancel errors', () => {
  382. it('routes an addressed child through non-activating history, continuation prompt, and interrupt only', async () => {
  383. const api = new FakeApiClient()
  384. const session = new Session(SID, api, {
  385. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  386. parentAvailable: true,
  387. })
  388. await session.open()
  389. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  390. const cancelled = await session.cancel()
  391. expect(prompted).toEqual({ ok: true, value: { accepted: true } })
  392. expect(cancelled).toEqual({ ok: true, value: { accepted: true } })
  393. expect(api.callsOf('subagent.history')).toEqual([
  394. { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable', maxMessages: 50 },
  395. ])
  396. expect(api.callsOf('subagent.prompt')).toEqual([
  397. {
  398. parentSessionId: PARENT, childSessionId: SID, mode: 'continuable',
  399. content: [{ type: 'text', text: '继续' }],
  400. },
  401. ])
  402. expect(api.callsOf('subagent.interrupt')).toEqual([
  403. { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  404. ])
  405. expect(api.callsOf('session.history')).toEqual([])
  406. expect(api.callsOf('session.prompt')).toEqual([])
  407. expect(api.callsOf('session.cancel')).toEqual([])
  408. // A successful interrupt leaves no stop error behind.
  409. expect(session.getSnapshot().promptError).toBeNull()
  410. expect(session.getSnapshot().subagent).toEqual({
  411. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  412. parentAvailable: true,
  413. })
  414. })
  415. it('lands an interrupt business failure in promptError with op=stop', async () => {
  416. const api = new FakeApiClient()
  417. api.onSubagentInterrupt = () => Promise.resolve(err({
  418. code: 'subagent-unauthorized', message: 'nope', details: { childSessionId: SID },
  419. }) as never)
  420. const session = new Session(SID, api, {
  421. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  422. parentAvailable: true,
  423. })
  424. await session.open()
  425. const cancelled = await session.cancel()
  426. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent-unauthorized' } })
  427. expect(session.getSnapshot().promptError).toMatchObject({
  428. op: 'stop', error: { code: 'subagent-unauthorized' },
  429. })
  430. })
  431. it('keeps one-shot history readable without exposing prompt or cancel transport', async () => {
  432. const api = new FakeApiClient()
  433. const session = new Session(SID, api, {
  434. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot' },
  435. })
  436. await session.open()
  437. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  438. const cancelled = await session.cancel()
  439. expect(prompted).toMatchObject({ ok: false, error: { code: 'subagent-not-resumable' } })
  440. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent-delivery-unavailable' } })
  441. expect(api.callsOf('subagent.history')).toEqual([
  442. { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot', maxMessages: 50 },
  443. ])
  444. expect(api.callsOf('subagent.prompt')).toEqual([])
  445. expect(api.callsOf('subagent.interrupt')).toEqual([])
  446. expect(api.callsOf('session.cancel')).toEqual([])
  447. })
  448. it('sends content through session.prompt; composerPhase steps blank → engaging synchronously at send entry', async () => {
  449. const { api, session } = makeSession()
  450. session.handleBlank(true)
  451. // The blank → engaging edge fires before the RPC settles: the first-send
  452. // flow reads the phase on the session area's first frame to keep the
  453. // guidance hero from flashing back in.
  454. expect(session.getSnapshot().composerPhase).toBe('blank')
  455. const inFlight = session.prompt([{ type: 'text', text: '要发的' }], 'queue')
  456. expect(session.getSnapshot().composerPhase).toBe('engaging')
  457. const result = await inFlight
  458. expect(result.ok).toBe(true)
  459. // Monotone: settlement alone does not step the phase anywhere.
  460. expect(session.getSnapshot().composerPhase).toBe('engaging')
  461. expect(api.callsOf('session.prompt')).toMatchObject([{ sessionId: SID, mode: 'queue', content: [{ type: 'text', text: '要发的' }] }])
  462. // First content lands (running turn): engaging → active.
  463. session.handleRunning(true)
  464. expect(session.getSnapshot().composerPhase).toBe('active')
  465. })
  466. it('business failure lands in promptError with op=send; the phase stays engaging (retry, no hero bounce)', async () => {
  467. const { api, session } = makeSession()
  468. session.handleBlank(true)
  469. api.onPrompt = () => Promise.resolve(err({ code: 'agent-busy', message: 'busy', details: { reason: 'x' } }))
  470. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue')
  471. expect(result.ok).toBe(false)
  472. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'agent-busy' } })
  473. // Failed first prompt: composer + error strip is the retry surface —
  474. // blank is unreachable once a send was initiated.
  475. expect(session.getSnapshot().composerPhase).toBe('engaging')
  476. })
  477. it('lands cancel failures in promptError with op=stop', async () => {
  478. const { api, session } = makeSession()
  479. api.onCancel = () => Promise.reject(new Error('cancel transport down'))
  480. const result = await session.cancel()
  481. expect(result.ok).toBe(false)
  482. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'internal' } })
  483. })
  484. it('reads session-authorized attachment bytes and keeps the opaque id on the wire', async () => {
  485. const { api, session } = makeSession()
  486. const result = await session.readAttachment('attachment-1' as never)
  487. expect(result).toEqual({
  488. ok: true,
  489. value: {
  490. attachment: { attachmentId: 'a', mediaType: 'image/png', bytes: 1, width: 1, height: 1 },
  491. data: Uint8Array.of(0),
  492. },
  493. })
  494. expect(api.callsOf('session.attachment')).toEqual([{
  495. sessionId: SID, attachmentId: 'attachment-1',
  496. }])
  497. })
  498. })
  499. describe('rename', () => {
  500. it('settles the title projection cell from the unary response (higher-seq-wins vs the push frame)', async () => {
  501. const { api, session } = makeSession()
  502. api.onRename = () => Promise.resolve(ok({ title: '正名', seq: 7 }))
  503. const result = await session.rename(' 正名 ')
  504. expect(result).toMatchObject({ ok: true, value: { title: '正名', seq: 7 } })
  505. expect(api.callsOf('session.rename')).toMatchObject([{ sessionId: SID, title: ' 正名 ' }])
  506. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  507. // A stale lower-seq apply (the push-frame path routes into this same
  508. // store) must not roll the settled value back.
  509. session.projections.apply('title', '旧名', 3)
  510. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  511. })
  512. it('returns the business error untouched and folds a transport throw to internal', async () => {
  513. const { api, session } = makeSession()
  514. api.onRename = () => Promise.resolve(err({ code: 'title-invalid', message: 'empty', details: { sessionId: SID } }))
  515. const rejected = await session.rename(' ')
  516. expect(rejected).toMatchObject({ ok: false, error: { code: 'title-invalid' } })
  517. expect(session.projections.faceOf('title').getSnapshot()).toBeUndefined()
  518. api.onRename = () => Promise.reject(new Error('rename transport down'))
  519. const folded = await session.rename('x')
  520. expect(folded).toMatchObject({ ok: false, error: { code: 'internal' } })
  521. })
  522. })
  523. describe('pending interactions', () => {
  524. it('adds approval/question on requested and removes them on resolved', async () => {
  525. const { session } = makeSession()
  526. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  527. session.handleMuxEnvelope('rq' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  528. expect(session.getSnapshot().pending.map(p => p.kind).sort()).toEqual(['approval', 'question'])
  529. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap1' as never, outcome: 'approved' as never })
  530. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq' as never, outcome: 'answered' })
  531. expect(session.getSnapshot().pending).toEqual([])
  532. })
  533. it('mints waits whose respond() backfills the requested rpcId into the client-response envelope', async () => {
  534. const { api, session } = makeSession()
  535. session.handleMuxEnvelope('rq-answer' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  536. const wait = session.getSnapshot().pending[0]!
  537. expect(wait).toMatchObject({ kind: 'question', key: 'q:rq-answer', sessionId: SID, payload: { questions: [] } })
  538. const receipt = await wait.respond({
  539. ok: true,
  540. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  541. })
  542. expect(receipt).toEqual({ accepted: true })
  543. expect(api.callsOf('respond')).toEqual([{
  544. type: 'client-response', rpcId: 'rq-answer',
  545. result: {
  546. ok: true,
  547. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  548. },
  549. }])
  550. })
  551. it('settles the wait on the authoritative resolved frame: respond() then throws synchronously', async () => {
  552. const { api, session } = makeSession()
  553. session.handleMuxEnvelope('rq1' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  554. const wait = session.getSnapshot().pending[0]!
  555. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq1' as never, outcome: 'answered' })
  556. expect(session.getSnapshot().pending).toEqual([])
  557. expect(() => wait.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } }))
  558. .toThrow('already settled')
  559. expect(api.callsOf('respond')).toEqual([])
  560. })
  561. })
  562. describe('remaining branches', () => {
  563. it('prompt transport throw folds to internal promptError', async () => {
  564. const { api, session } = makeSession()
  565. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  566. const result = await session.prompt([{ type: 'text', text: 'x' }], 'queue')
  567. expect(result.ok).toBe(false)
  568. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'internal', message: 'prompt wire down' } })
  569. })
  570. it('cancel business error also lands op=stop promptError', async () => {
  571. const { api, session } = makeSession()
  572. api.onCancel = () => Promise.resolve(err({ code: 'agent-busy', message: 'nope', details: { reason: 'r' } }))
  573. await session.cancel()
  574. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'agent-busy' } })
  575. })
  576. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  577. const { api, session } = makeSession()
  578. await session.loadOlder() // cold: no-op, zero calls
  579. expect(api.calls).toEqual([])
  580. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  581. await session.open()
  582. // err result: window unchanged
  583. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  584. await session.loadOlder()
  585. expect(session.getSnapshot().nodes).toHaveLength(2)
  586. expect(session.getSnapshot().hasMore).toBe(true)
  587. // empty page: hasMore adopts the response
  588. api.onHistory = () => histResponse([], false)
  589. await session.loadOlder()
  590. expect(session.getSnapshot().hasMore).toBe(false)
  591. // hasMore false now: further loadOlder is a guard no-op
  592. const calls = api.calls.length
  593. await session.loadOlder()
  594. expect(api.calls.length).toBe(calls)
  595. // throw path: fail-soft with console.error
  596. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  597. try {
  598. await session.resync()
  599. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  600. await session.resync()
  601. api.onHistory = () => Promise.reject(new Error('page wire down'))
  602. await session.loadOlder()
  603. expect(errorSpy).toHaveBeenCalled()
  604. expect(session.getSnapshot().loadingOlder).toBe(false)
  605. } finally {
  606. errorSpy.mockRestore()
  607. }
  608. })
  609. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  610. const { api, session } = makeSession()
  611. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  612. let notified = 0
  613. const unsubscribe = session.subscribe(() => { notified++ })
  614. await session.open()
  615. await new Promise(resolve => setTimeout(resolve, 0))
  616. expect(notified).toBeGreaterThan(0)
  617. const seen = notified
  618. unsubscribe()
  619. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  620. await new Promise(resolve => setTimeout(resolve, 0))
  621. expect(notified).toBe(seen)
  622. })
  623. it('subscribed baseline past the window tail triggers the second stitch pull in doOpen', async () => {
  624. const { api, session } = makeSession()
  625. const full = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  626. let call = 0
  627. api.onHistory = () => {
  628. call++
  629. return histResponse(call === 1 ? plainTurn(0, 0, 'a', 'b') : full)
  630. }
  631. // Baseline arrives before open: lastSeq 11 > first page tail 5 → doOpen repulls once.
  632. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  633. await session.open()
  634. expect(call).toBe(2)
  635. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  636. })
  637. it('a failed second stitch pull keeps the first window and still opens', async () => {
  638. const { api, session } = makeSession()
  639. let call = 0
  640. api.onHistory = () => {
  641. call++
  642. return call === 1
  643. ? histResponse(plainTurn(0, 0, 'a', 'b'))
  644. : Promise.resolve(err({ code: 'internal', message: 'stitch pull down', details: {} }))
  645. }
  646. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  647. await session.open()
  648. expect(call).toBe(2)
  649. const snapshot = session.getSnapshot()
  650. expect(snapshot.openState).toBe('open') // stitch-pull failure is not an open failure
  651. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3]) // first window kept
  652. })
  653. it('approval frame with callId/reason keeps the optional fields; duplicate resolved is a no-op', () => {
  654. const { session } = makeSession()
  655. session.handleMuxEnvelope('ra' as never, {
  656. type: 'approval/requested', sessionId: SID, approvalId: 'ap2' as never, toolName: 'rm', callId: 'c1' as never, reason: '危险',
  657. })
  658. expect(session.getSnapshot().pending[0]).toMatchObject({ kind: 'approval', payload: { callId: 'c1', reason: '危险' } })
  659. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  660. session.handleMuxEnvelope('rx2' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  661. session.handleMuxEnvelope('ry2' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'never-was' as never, outcome: 'cancelled' })
  662. expect(session.getSnapshot().pending).toEqual([])
  663. })
  664. it('ignores unknown mux frame types and repeated running flips (documented defaults)', () => {
  665. const { session } = makeSession()
  666. const before = session.getSnapshot()
  667. session.handleMuxEnvelope('rz' as never, { type: 'future/frame' } as never)
  668. session.handleRunning(false) // already false: dedup branch
  669. expect(session.getSnapshot()).toBe(before)
  670. session.handleRemoved()
  671. expect(session.getSnapshot().removed).toBe(true)
  672. })
  673. it('drops live events while cold/error (no window upkeep)', async () => {
  674. const { api, session } = makeSession()
  675. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '冷态帧') })
  676. expect(session.getSnapshot().nodes).toEqual([])
  677. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  678. await session.open()
  679. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '错态帧') })
  680. expect(session.getSnapshot().nodes).toEqual([])
  681. })
  682. it('repairGap failure logs and clears stitching; concurrent gaps coalesce into one repair', async () => {
  683. const { api, session } = makeSession()
  684. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  685. await session.open()
  686. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  687. let repairs = 0
  688. api.onHistory = () => {
  689. repairs++
  690. return gate.promise
  691. }
  692. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  693. try {
  694. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞一') })
  695. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(10, '洞二') }) // stitching: detours, no second repair
  696. expect(repairs).toBe(1)
  697. gate.reject(new Error('repair wire down'))
  698. await vi.waitFor(() => { expect(errorSpy).toHaveBeenCalled() })
  699. // Window unchanged; a later successful repull still lands the buffered frames.
  700. expect(session.getSnapshot().nodes).toHaveLength(2)
  701. } finally {
  702. errorSpy.mockRestore()
  703. }
  704. })
  705. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  706. const { api, session } = makeSession()
  707. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  708. api.onHistory = () => stale.promise
  709. const opening = session.open()
  710. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  711. const resynced = session.resync()
  712. stale.reject(new Error('stale wire'))
  713. await Promise.all([opening, resynced])
  714. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  715. })
  716. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  717. const { api, session } = makeSession()
  718. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  719. api.onHistory = () => stale.promise
  720. const opening = session.open()
  721. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  722. const resynced = session.resync()
  723. stale.resolve(ok({
  724. events: entries(plainTurn(0, 0, '旧', '代')) as never[],
  725. hasMore: false,
  726. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  727. })) // success, but its generation is gone
  728. await Promise.all([opening, resynced])
  729. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9]) // only the fresh generation's window
  730. })
  731. it('drops a stale stitch pull (second doOpen fetch) superseded mid-flight by resync', async () => {
  732. const { api, session } = makeSession()
  733. const secondPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  734. let call = 0
  735. api.onHistory = () => {
  736. call++
  737. if (call === 1) return histResponse(plainTurn(0, 0, 'a', 'b')) // first page: tail 5
  738. if (call === 2) return secondPull.promise // gap-stitch pull: held
  739. return histResponse(plainTurn(6, 1, 'c', 'd'))
  740. }
  741. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  742. const opening = session.open() // triggers the second pull, which parks
  743. await vi.waitFor(() => { expect(call).toBe(2) })
  744. const resynced = session.resync()
  745. secondPull.resolve(ok({
  746. events: entries([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]) as never[],
  747. hasMore: false,
  748. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  749. }))
  750. await Promise.all([opening, resynced])
  751. expect(session.getSnapshot().openState).toBe('open')
  752. })
  753. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  754. const { api, session } = makeSession()
  755. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  756. await session.open()
  757. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  758. api.onHistory = () => repairPull.promise
  759. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞') }) // starts repairGap
  760. api.onHistory = () => histResponse(plainTurn(6, 1, 'c', 'd'))
  761. const resynced = session.resync() // bumps the generation
  762. repairPull.resolve(ok({
  763. events: entries(plainTurn(0, 0, '旧', '页')) as never[],
  764. hasMore: false,
  765. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  766. })) // repair result: stale, dropped
  767. await resynced
  768. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9])
  769. })
  770. it('successful cancel leaves no promptError', async () => {
  771. const { api, session } = makeSession()
  772. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  773. await session.open()
  774. const result = await session.cancel()
  775. expect(result.ok).toBe(true)
  776. expect(session.getSnapshot().promptError).toBeNull()
  777. })
  778. it('dispose is a reserved no-op on resident instances', () => {
  779. const { session } = makeSession()
  780. expect(() => { session.dispose() }).not.toThrow()
  781. })
  782. it('carries history-entry and mux-frame views into the business-neutral Event input', async () => {
  783. const { api, session } = makeSession()
  784. const callView = { for: 'call', view: { card: 'generic', title: '历史卡' } }
  785. api.onHistory = () => Promise.resolve(ok({
  786. events: [
  787. ...entries(plainTurn(0, 0, 'a', 'b')),
  788. { event: ev.toolCall(6, 1, 'h1', 'bash', '{}'), view: callView },
  789. { event: ev.toolResult(7, 1, 'h1', 'done'), view: { for: 'result', view: { card: 'generic', title: '历史果' } } },
  790. ] as never[],
  791. hasMore: false,
  792. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  793. }))
  794. await session.open()
  795. expect(chatEvents(session.getSnapshot()).slice(-2).map(item => item.view)).toEqual([
  796. callView,
  797. { for: 'result', view: { card: 'generic', title: '历史果' } },
  798. ])
  799. session.handleMuxEnvelope('rv1' as never, {
  800. type: 'session/event', sessionId: SID, event: ev.toolCall(8, 2, 'l1', 'write', '{}'),
  801. view: { for: 'call', view: { card: 'generic', title: '直播卡' } },
  802. } as never)
  803. expect(chatEvents(session.getSnapshot()).at(-1)?.view).toEqual({
  804. for: 'call', view: { card: 'generic', title: '直播卡' },
  805. })
  806. session.handleMuxEnvelope('rv2' as never, {
  807. type: 'session/event', sessionId: SID, event: ev.toolResult(9, 2, 'l1', 'ok'),
  808. view: { for: 'result', view: { card: 'generic', title: '直播果' } },
  809. } as never)
  810. expect(chatEvents(session.getSnapshot()).at(-1)?.view).toEqual({
  811. for: 'result', view: { card: 'generic', title: '直播果' },
  812. })
  813. })
  814. })
  815. describe('resync', () => {
  816. it('rebuilds the window and clears pending; cold instances no-op', async () => {
  817. const { api, session } = makeSession()
  818. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  819. await session.open()
  820. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  821. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')])
  822. await session.resync()
  823. const snapshot = session.getSnapshot()
  824. expect(snapshot.openState).toBe('open')
  825. expect(snapshot.pending).toEqual([]) // baseline replay re-sends still-pending frames
  826. expect(snapshot.nodes).toHaveLength(4)
  827. const cold = makeSession()
  828. await cold.session.resync()
  829. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  830. })
  831. it('re-mints a replayed requested frame as a fresh wait with the same key (old reference superseded)', async () => {
  832. const { api, session } = makeSession()
  833. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  834. await session.open()
  835. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  836. const before = session.getSnapshot().pending[0]!
  837. await session.resync()
  838. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  839. const after = session.getSnapshot().pending[0]!
  840. expect(after).not.toBe(before)
  841. expect(after.key).toBe(before.key)
  842. // Superseded ≠ settled: an in-flight respond on the stale reference still reaches the host.
  843. await before.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } })
  844. expect(api.callsOf('respond')).toMatchObject([{ rpcId: 'rq-replay' }])
  845. })
  846. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  847. const { api, session } = makeSession()
  848. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  849. api.onHistory = () => stale.promise
  850. const firstOpen = session.open()
  851. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  852. const resynced = session.resync()
  853. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  854. await firstOpen
  855. await resynced
  856. const snapshot = session.getSnapshot()
  857. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  858. expect(snapshot.nodes.map(n => n.seq)).toEqual([7, 9])
  859. })
  860. })
  861. describe('reference stability (the memo contract)', () => {
  862. it('keeps unchanged node references across an append and swaps the snapshot object', async () => {
  863. const { api, session } = makeSession()
  864. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  865. await session.open()
  866. const before = session.getSnapshot()
  867. const firstKey = before.chat.order[0]!
  868. const secondKey = before.chat.order[1]!
  869. const first = before.chat.nodes.get(firstKey)
  870. const second = before.chat.nodes.get(secondKey)
  871. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(6, '追加') })
  872. const after = session.getSnapshot()
  873. expect(after).not.toBe(before) // top-level swap on change
  874. expect(after.chat.nodes.get(firstKey)).toBe(first)
  875. expect(after.chat.nodes.get(secondKey)).toBe(second)
  876. expect(after.chat.order).toHaveLength(7)
  877. // No change → same snapshot reference.
  878. expect(session.getSnapshot()).toBe(after)
  879. })
  880. it('keeps unrelated Session arrays and settled Chat Nodes stable across Event updates', async () => {
  881. const { api, session } = makeSession()
  882. api.onHistory = () => histResponse(plainTurn(0, 0, '底', '座'))
  883. await session.open()
  884. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  885. feed(ev.turnStart(6, 1))
  886. feed(ev.stepStart(7, 1))
  887. feed(ev.toolCall(8, 1, 'c1', 'echo', '{}'))
  888. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  889. const before = session.getSnapshot()
  890. const settledKey = before.chat.order[0]!
  891. const settledNode = before.chat.nodes.get(settledKey)
  892. feed(ev.chunkStart(9, 1))
  893. feed(ev.chunkText(10, 1, '与工具无关的流式'))
  894. const after = session.getSnapshot()
  895. expect(after).not.toBe(before)
  896. expect(after.runningCalls).toBe(before.runningCalls)
  897. expect(after.pending).toBe(before.pending)
  898. expect(after.chat.nodes.get(settledKey)).toBe(settledNode)
  899. feed(ev.toolResult(11, 1, 'c1', 'ECHO'))
  900. const resolved = session.getSnapshot()
  901. expect(resolved.pending).toBe(after.pending)
  902. expect(resolved.chat.nodes.get(settledKey)).toBe(settledNode)
  903. feed(ev.assistant(12, 1, '完成'))
  904. expect(session.getSnapshot()).not.toBe(resolved)
  905. })
  906. })