session.client.spec.ts 45 KB

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