session.spec.ts 44 KB

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