session.spec.ts 45 KB

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