session.spec.ts 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  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 { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
  11. import type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
  12. import { Session } from '../src/client/sessions/session.ts'
  13. import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
  14. import { entries, ev, plainTurn } from './event-script.ts'
  15. const at = (seq: number, e: Record<string, unknown>): SessionEvent =>
  16. ({ seq, time: 1_700_000_000_000 + seq, ...e }) as unknown as SessionEvent
  17. const SID = 'fk-s1' as SessionId
  18. const PARENT = 'fk-parent' as SessionId
  19. afterEach(() => {
  20. vi.unstubAllGlobals()
  21. })
  22. function makeSession(api = new FakeApiClient()): { api: FakeApiClient; session: Session } {
  23. return { api, session: new Session(SID, api) }
  24. }
  25. function histResponse(events: SessionEvent[], hasMore = false) {
  26. // history now returns HistoryEntry[] ({event, view?}); these tests are view-less.
  27. return Promise.resolve(ok({ events: entries(events) as never[], hasMore }))
  28. }
  29. describe('open', () => {
  30. it('installs the tail page: cold → loading → open with window and nodes in place', async () => {
  31. const { api, session } = makeSession()
  32. const page = plainTurn(10, 3, '问', '答')
  33. api.onHistory = () => histResponse(page, true)
  34. expect(session.getSnapshot().openState).toBe('cold')
  35. const opening = session.open()
  36. expect(session.getSnapshot().openState).toBe('loading')
  37. await opening
  38. const snapshot = session.getSnapshot()
  39. expect(snapshot.openState).toBe('open')
  40. expect(snapshot.hasMore).toBe(true)
  41. expect(snapshot.nodes.map(n => n.kind)).toEqual(['user', 'assistant'])
  42. expect(snapshot.turnTimings.get(3)).toEqual({
  43. startTime: 1_700_000_000_010,
  44. endTime: 1_700_000_000_015,
  45. })
  46. expect(snapshot.turnEnds.get(3)).toBe(15)
  47. })
  48. it('is idempotent: concurrent opens share one history call, reopening when open is a no-op', async () => {
  49. const { api, session } = makeSession()
  50. await Promise.all([session.open(), session.open()])
  51. await session.open()
  52. expect(api.callsOf('session.history')).toHaveLength(1)
  53. })
  54. it('lands an error result in openState=error with the RpcError kept', async () => {
  55. const { api, session } = makeSession()
  56. api.onHistory = () => Promise.resolve(err({ code: 'session-not-found', message: 'gone', details: { sessionId: SID } }))
  57. await session.open()
  58. const snapshot = session.getSnapshot()
  59. expect(snapshot.openState).toBe('error')
  60. expect(snapshot.openError?.code).toBe('session-not-found')
  61. })
  62. it('folds a transport throw into openState=error / internal', async () => {
  63. const { api, session } = makeSession()
  64. api.onHistory = () => Promise.reject(new Error('socket died'))
  65. await session.open()
  66. expect(session.getSnapshot().openState).toBe('error')
  67. expect(session.getSnapshot().openError).toMatchObject({ code: 'internal', message: 'socket died' })
  68. })
  69. it('stitches live frames arriving while history is pending, dropping the page overlap', async () => {
  70. const { api, session } = makeSession()
  71. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  72. api.onHistory = () => gate.promise
  73. const opening = session.open()
  74. // Three live frames land mid-open; seq 15 overlaps the page tail (page covers 10..15).
  75. const page = plainTurn(10, 0, '早', '安')
  76. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.turnStart(15, 1) })
  77. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(16, '插进来的') })
  78. gate.resolve(ok({
  79. events: entries(page) as never[],
  80. hasMore: false,
  81. modelTarget: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  82. }))
  83. await opening
  84. const seqs = session.getSnapshot().nodes.map(n => n.seq)
  85. // Overlapping seq-15 frame (== page tail turn/end) was dropped; 16 appended once.
  86. expect(seqs).toEqual([11, 13, 16])
  87. })
  88. })
  89. describe('live event path', () => {
  90. async function opened(events: SessionEvent[] = plainTurn(0, 0, 'a', 'b')) {
  91. const { api, session } = makeSession()
  92. api.onHistory = () => histResponse(events)
  93. await session.open()
  94. return { api, session }
  95. }
  96. it('drops replayed frames at or below the window tail', async () => {
  97. const { session } = await opened()
  98. const before = session.getSnapshot()
  99. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(3, '重放') })
  100. await Promise.resolve()
  101. expect(session.getSnapshot().nodes).toEqual(before.nodes)
  102. })
  103. it('materializes a command node from live lifecycle frames and reproduces it from a history window', async () => {
  104. // Live path: run mints an executing node, done settles it in the flow.
  105. const { session } = await opened()
  106. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  107. feed(ev.commandRun(6, 'cmd-live', 'plan'))
  108. let command = session.getSnapshot().nodes.at(-1)
  109. expect(command).toMatchObject({ kind: 'command', name: 'plan', args: '', outcome: null })
  110. feed(ev.commandDone(7, 'cmd-live', 'success', '已进入 plan mode'))
  111. command = session.getSnapshot().nodes.at(-1)
  112. expect(command).toMatchObject({ kind: 'command', seq: 6, outcome: { kind: 'success', text: '已进入 plan mode' } })
  113. // Replay path (refresh): the same pair inside the history window folds identically.
  114. const replayed = await opened([
  115. ...plainTurn(0, 0, 'a', 'b'),
  116. ev.commandRun(6, 'cmd-live', 'plan'),
  117. ev.commandDone(7, 'cmd-live', 'success', '已进入 plan mode'),
  118. ])
  119. expect(replayed.session.getSnapshot().nodes.at(-1)).toMatchObject({
  120. kind: 'command', seq: 6, name: 'plan', outcome: { kind: 'success', text: '已进入 plan mode' },
  121. })
  122. })
  123. it('command lifecycle rows alone keep the composer blank (hero survives a /permission or /plan switch)', async () => {
  124. // A fresh session whose only window content is a command pair (plus the
  125. // knob events a /permission switch appends — not surface-eligible, so
  126. // they never become nodes) stays phase 'blank': selecting a preset from
  127. // the hero must not enter the conversation view.
  128. const { session } = await opened([])
  129. expect(session.getSnapshot().composerPhase).toBe('blank')
  130. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  131. feed(ev.commandRun(0, 'cmd-perm', 'permission', ' danger-full-access'))
  132. feed(ev.commandDone(1, 'cmd-perm', 'success', 'preset danger-full-access'))
  133. const snapshot = session.getSnapshot()
  134. expect(snapshot.nodes.at(-1)).toMatchObject({ kind: 'command', name: 'permission' })
  135. expect(snapshot.composerPhase).toBe('blank')
  136. })
  137. it('accumulates chunks into partial, then finalize swaps partial out as the node lands', async () => {
  138. const { session } = await opened()
  139. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  140. feed(ev.turnStart(6, 1))
  141. feed(ev.user(7, '流式问'))
  142. feed(ev.chunkStart(8, 1))
  143. feed(ev.chunkText(9, 1, '半截'))
  144. let snapshot = session.getSnapshot()
  145. expect(snapshot.partial).toMatchObject({ turn: 1, blocks: [{ kind: 'text', text: '半截' }] })
  146. feed(ev.chunkText(10, 1, '回复'))
  147. expect(session.getSnapshot().partial?.blocks).toEqual([{ kind: 'text', text: '半截回复' }])
  148. feed(ev.assistant(11, 1, '半截回复'))
  149. feed(ev.turnEnd(12, 1))
  150. snapshot = session.getSnapshot()
  151. expect(snapshot.partial).toBeNull()
  152. const last = snapshot.nodes.at(-1)
  153. expect(last).toMatchObject({ kind: 'assistant', blocks: [{ kind: 'text', text: '半截回复' }] })
  154. expect((last as { interrupted?: true }).interrupted).toBeUndefined()
  155. })
  156. it('publishes cumulative chunks once per frame and lets finalization supersede the pending frame', async () => {
  157. const frames: FrameRequestCallback[] = []
  158. vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
  159. frames.push(callback)
  160. return frames.length
  161. })
  162. const { session } = await opened()
  163. const published: Array<string | null> = []
  164. session.subscribe(() => {
  165. const block = session.getSnapshot().partial?.blocks[0]
  166. published.push(block?.kind === 'text' ? block.text : null)
  167. })
  168. const feed = (event: SessionEvent) => {
  169. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event })
  170. }
  171. feed(ev.chunkStart(6, 1))
  172. feed(ev.chunkText(7, 1, '累'))
  173. feed(ev.chunkText(8, 1, '计'))
  174. expect(published).toEqual([])
  175. expect(frames).toHaveLength(1)
  176. frames.shift()!(0)
  177. expect(published).toEqual(['累计'])
  178. feed(ev.chunkText(9, 1, '完成'))
  179. feed(ev.assistant(10, 1, '累计完成'))
  180. await Promise.resolve()
  181. expect(published).toEqual(['累计', null])
  182. frames.shift()!(0)
  183. expect(published).toEqual(['累计', null])
  184. })
  185. it('retracts the failed-attempt partial and starts the retry on new chunk evidence', async () => {
  186. const { session } = await opened()
  187. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  188. const retryTurn = [
  189. ev.turnStart(6, 1),
  190. ev.user(7, '请重试'),
  191. ev.stepStart(8, 1),
  192. ev.chunkStart(9, 1),
  193. ev.chunkText(10, 1, '不完整回复'),
  194. ev.retry(11, 1, 0, 1, 2, 450, '连接被重置'),
  195. ev.chunkStart(12, 1),
  196. ev.assistant(13, 1, '完整回复'),
  197. ev.stepEnd(14, 1),
  198. ev.turnEnd(15, 1),
  199. ]
  200. for (const event of retryTurn.slice(0, 6)) feed(event)
  201. let snapshot = session.getSnapshot()
  202. expect(snapshot.partial).toBeNull()
  203. expect(snapshot.nodes.at(-1)).toMatchObject({
  204. kind: 'model-retry',
  205. retryState: 'scheduled',
  206. turn: 1,
  207. step: 0,
  208. provider: 'fake',
  209. mode: 'normal',
  210. policyKey: 'fake-normal',
  211. retry: 1,
  212. maxRetries: 2,
  213. delayMs: 450,
  214. failure: { code: 'TRANSPORT', message: '连接被重置' },
  215. })
  216. expect(JSON.stringify(snapshot.nodes)).not.toContain('不完整回复')
  217. for (const event of retryTurn.slice(6)) feed(event)
  218. snapshot = session.getSnapshot()
  219. expect(snapshot.nodes.slice(-2).map(node => node.kind)).toEqual(['model-retry', 'assistant'])
  220. expect(snapshot.nodes.some(node => node.kind === 'turn-error')).toBe(false)
  221. expect(snapshot.nodes.at(-2)).toMatchObject({ kind: 'model-retry', retryState: 'started' })
  222. expect(snapshot.nodes.at(-1)).toMatchObject({ kind: 'assistant', blocks: [{ kind: 'text', text: '完整回复' }] })
  223. const retryStart = retryTurn.find(event => event.type === 'turn/start')
  224. if (retryStart?.type !== 'turn/start') throw new Error('test fixture must include the retried turn start')
  225. const retryEnd = retryTurn.find(event =>
  226. event.type === 'turn/end' && event.data.turn === retryStart.data.turn)
  227. if (retryEnd?.type !== 'turn/end') throw new Error('test fixture must complete the retry turn')
  228. expect(snapshot.turnTimings.get(retryStart.data.turn)).toEqual({
  229. startTime: retryStart.time,
  230. endTime: retryEnd.time,
  231. })
  232. const replay = makeSession()
  233. replay.api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...retryTurn])
  234. await replay.session.open()
  235. expect(replay.session.getSnapshot().nodes).toEqual(snapshot.nodes)
  236. expect(replay.session.getSnapshot().turnTimings).toEqual(snapshot.turnTimings)
  237. expect(replay.session.getSnapshot().partial).toBeNull()
  238. })
  239. it('projects unretried terminal failures at turn/end and reproduces them from history', async () => {
  240. const { session } = await opened()
  241. const feed = (event: SessionEvent) => {
  242. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event })
  243. }
  244. const failedTurns = [
  245. ev.turnStart(6, 1),
  246. ev.user(7, '鉴权失败'),
  247. ev.stepStart(8, 1),
  248. at(9, {
  249. type: 'turn/end',
  250. data: { turn: 1, reason: { kind: 'error', error: {
  251. code: 'AUTH',
  252. message: 'Authentication Fails, Your api key: sk-preview-secret is invalid',
  253. },
  254. },
  255. },
  256. }),
  257. ev.turnStart(10, 2),
  258. ev.user(11, '内部失败'),
  259. ev.stepStart(12, 2, 1),
  260. at(13, {
  261. type: 'turn/end',
  262. data: { turn: 2, reason: { kind: 'error', error: { message: 'plugin exploded', code: 'UNKNOWN' } } },
  263. }),
  264. ]
  265. for (const event of failedTurns) feed(event)
  266. const errors = session.getSnapshot().nodes.filter(node => node.kind === 'turn-error')
  267. expect(errors).toMatchObject([
  268. { seq: 9, turn: 1, step: 0, code: 'AUTH', message: 'API key is invalid' },
  269. // Every failed turn carries a structured failure; unstructured errors
  270. // flatten to the UNKNOWN code.
  271. { seq: 13, turn: 2, step: 1, code: 'UNKNOWN', message: 'plugin exploded' },
  272. ])
  273. const replay = makeSession()
  274. replay.api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...failedTurns])
  275. await replay.session.open()
  276. expect(replay.session.getSnapshot().nodes).toEqual(session.getSnapshot().nodes)
  277. })
  278. it('rejects retry payloads outside the producer contract without retracting the current partial', async () => {
  279. const { session } = await opened()
  280. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  281. feed(ev.turnStart(6, 1))
  282. feed(ev.chunkStart(7, 1))
  283. feed(ev.chunkText(8, 1, '仍在生成'))
  284. const valid = {
  285. turn: 1, step: 0,
  286. provider: 'fake', mode: 'normal', policyKey: 'fake-normal',
  287. retry: 1, maxRetries: 2, delayMs: 500,
  288. failure: { code: 'TRANSPORT', message: 'temporary failure' },
  289. }
  290. const invalid = [
  291. { ...valid, turn: Number.MAX_SAFE_INTEGER + 1 },
  292. { ...valid, step: Number.MAX_SAFE_INTEGER + 1 },
  293. { ...valid, provider: '' },
  294. { ...valid, policyKey: '' },
  295. { ...valid, retry: Number.MAX_SAFE_INTEGER + 1 },
  296. { ...valid, maxRetries: Number.MAX_SAFE_INTEGER + 1 },
  297. { ...valid, delayMs: -1 },
  298. { ...valid, delayMs: Number.POSITIVE_INFINITY },
  299. { ...valid, delayMs: MAX_TIMER_DELAY_MS + 1 },
  300. { ...valid, failure: { ...valid.failure, message: '' } },
  301. { ...valid, failure: { ...valid.failure, code: '' } },
  302. { ...valid, failure: { ...valid.failure, status: '429' } },
  303. { ...valid, failure: { ...valid.failure, status: 99 } },
  304. { ...valid, failure: { ...valid.failure, status: 429.5 } },
  305. { ...valid, failure: { ...valid.failure, status: 600 } },
  306. { ...valid, failure: { ...valid.failure, providerRetryAfterMs: 0 } },
  307. { ...valid, failure: { ...valid.failure, providerRetryAfterMs: Number.POSITIVE_INFINITY } },
  308. { ...valid, failure: { ...valid.failure, requestId: 1 } },
  309. { ...valid, failure: { ...valid.failure, requestId: '' } },
  310. ]
  311. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  312. try {
  313. for (const [index, data] of invalid.entries()) {
  314. feed(at(9 + index, { type: 'llm/retry', data }))
  315. }
  316. expect(session.getSnapshot().partial?.blocks).toEqual([{ kind: 'text', text: '仍在生成' }])
  317. expect(session.getSnapshot().nodes.filter(node => node.kind === 'model-retry')).toEqual([])
  318. expect(errorSpy).toHaveBeenCalledTimes(invalid.length)
  319. expect(errorSpy).toHaveBeenCalledWith('[web-runtime] ignored malformed llm/retry event at seq 9')
  320. } finally {
  321. errorSpy.mockRestore()
  322. }
  323. })
  324. it('accepts complete retry payloads at the producer field boundaries', async () => {
  325. const { session } = await opened()
  326. session.handleMuxEnvelope('r' as never, {
  327. type: 'session/event',
  328. sessionId: SID,
  329. event: at(6, {
  330. type: 'llm/retry',
  331. data: {
  332. turn: Number.MAX_SAFE_INTEGER,
  333. step: Number.MAX_SAFE_INTEGER,
  334. provider: 'fake',
  335. mode: 'normal',
  336. policyKey: 'fake-normal',
  337. retry: Number.MAX_SAFE_INTEGER,
  338. maxRetries: Number.MAX_SAFE_INTEGER,
  339. delayMs: MAX_TIMER_DELAY_MS,
  340. failure: {
  341. code: 'RATE_LIMIT',
  342. message: 'provider busy',
  343. status: 599,
  344. providerRetryAfterMs: Number.MIN_VALUE,
  345. requestId: 'req-1',
  346. },
  347. },
  348. }),
  349. })
  350. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  351. kind: 'model-retry',
  352. retryState: 'scheduled',
  353. retry: Number.MAX_SAFE_INTEGER,
  354. delayMs: MAX_TIMER_DELAY_MS,
  355. failure: { status: 599, providerRetryAfterMs: Number.MIN_VALUE, requestId: 'req-1' },
  356. })
  357. })
  358. it('projects always-mode retries and rejects mode-specific maximums or unknown modes', async () => {
  359. const { session } = await opened()
  360. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  361. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  362. try {
  363. feed(at(6, {
  364. type: 'llm/retry',
  365. data: {
  366. turn: 1, step: 0,
  367. provider: 'fake', mode: 'always', policyKey: 'fake-always',
  368. retry: 3, delayMs: 500,
  369. failure: { code: 'TRANSPORT', message: 'retry forever' },
  370. },
  371. }))
  372. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  373. kind: 'model-retry',
  374. retryState: 'scheduled',
  375. mode: 'always',
  376. retry: 3,
  377. })
  378. feed(at(7, {
  379. type: 'llm/retry',
  380. data: {
  381. turn: 2, step: 0,
  382. provider: 'fake', mode: 'always', policyKey: 'fake-always',
  383. retry: 4, maxRetries: 4, delayMs: 500,
  384. failure: { code: 'TRANSPORT', message: 'unexpected maximum' },
  385. },
  386. }))
  387. feed(at(8, {
  388. type: 'llm/retry',
  389. data: {
  390. turn: 2, step: 0,
  391. provider: 'fake', mode: 'sometimes', policyKey: 'fake-unknown',
  392. retry: 4, delayMs: 500,
  393. failure: { code: 'TRANSPORT', message: 'unknown mode' },
  394. },
  395. }))
  396. expect(session.getSnapshot().nodes.filter(node => node.kind === 'model-retry')).toHaveLength(1)
  397. expect(errorSpy).toHaveBeenCalledTimes(2)
  398. } finally {
  399. errorSpy.mockRestore()
  400. }
  401. })
  402. it.each(['aborted', 'disposed'] as const)(
  403. 'marks a scheduled retry as cancelled when its failed turn receives the %s cause',
  404. async (reason) => {
  405. const { session } = await opened()
  406. const feed = (event: SessionEvent) => {
  407. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event })
  408. }
  409. feed(ev.turnStart(6, 1))
  410. feed(ev.retry(7, 1))
  411. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  412. kind: 'model-retry',
  413. retryState: 'scheduled',
  414. })
  415. feed(ev.turnEnd(8, 1, reason))
  416. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  417. kind: 'model-retry',
  418. retryState: 'cancelled',
  419. })
  420. },
  421. )
  422. it('marks a scheduled retry as started when its failed turn ends with an error', async () => {
  423. const { session } = await opened()
  424. const feed = (event: SessionEvent) => {
  425. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event })
  426. }
  427. feed(ev.turnStart(6, 1))
  428. feed(ev.retry(7, 1))
  429. feed(at(8, {
  430. type: 'turn/end',
  431. data: { turn: 1, reason: { kind: 'error', error: { message: 'retry failed', code: 'UNKNOWN' } } },
  432. }))
  433. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  434. kind: 'model-retry',
  435. retryState: 'started',
  436. })
  437. })
  438. it('freezes an unfinalized partial into an interrupted node on turn/end (cancel path)', async () => {
  439. const { session } = await opened()
  440. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  441. feed(ev.turnStart(6, 1))
  442. feed(ev.user(7, '要被打断的'))
  443. feed(ev.chunkStart(8, 1))
  444. feed(ev.chunkText(9, 1, '说到一半'))
  445. feed(ev.turnEnd(10, 1, 'aborted')) // no assistant/message ever arrives
  446. const snapshot = session.getSnapshot()
  447. expect(snapshot.partial).toBeNull()
  448. expect(snapshot.turnEnds.get(1)).toBe(10)
  449. const frozen = snapshot.nodes.at(-1)
  450. expect(frozen).toMatchObject({ kind: 'assistant', interrupted: true, blocks: [{ kind: 'text', text: '说到一半' }] })
  451. // Ordered inside the flow: after the user message (seq 7), before any later turn.
  452. expect((frozen as { seq: number }).seq).toBeGreaterThan(7)
  453. })
  454. it('tracks tool calls in runningCalls and converts orphans to interrupted tool-result cards on turn/end', async () => {
  455. const { session } = await opened()
  456. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  457. feed(ev.turnStart(6, 1))
  458. feed(ev.toolCall(7, 1, 'c1', 'echo', '{"a":1}'))
  459. expect(session.getSnapshot().runningCalls).toMatchObject([{ callId: 'c1', name: 'echo' }])
  460. feed(ev.toolResult(8, 1, 'c1', 'ECHO'))
  461. expect(session.getSnapshot().runningCalls).toEqual([])
  462. // Second call never resolves: turn/end freezes it as an error card.
  463. feed(ev.toolCall(9, 1, 'c2', 'slow_tool', '{}'))
  464. feed(ev.turnEnd(10, 1, 'aborted'))
  465. const snapshot = session.getSnapshot()
  466. expect(snapshot.runningCalls).toEqual([])
  467. expect(snapshot.nodes.at(-1)).toMatchObject({
  468. kind: 'tool-result', callId: 'c2', isError: true, error: { code: 'interrupted' },
  469. })
  470. })
  471. it('keeps compacted history and adds one marker, live and on replay alike', async () => {
  472. // A landed compaction must not erase conversation the reader already saw:
  473. // the shadowed messages stay at their own log positions and the checkpoint
  474. // contributes one marker after them.
  475. const { session } = await opened()
  476. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  477. feed(ev.compactSummary(6, '压缩摘要', 1, 3))
  478. feed(ev.compactCheckpoint(7, 6, 1, 3))
  479. const live = session.getSnapshot().nodes
  480. expect(live.map(n => [n.kind, n.seq])).toEqual([['user', 1], ['assistant', 3], ['compaction', 7]])
  481. expect(live.at(-1)).toMatchObject({ kind: 'compaction', summary: '压缩摘要' })
  482. const replayed = await opened([
  483. ...plainTurn(0, 0, 'a', 'b'),
  484. ev.compactSummary(6, '压缩摘要', 1, 3),
  485. ev.compactCheckpoint(7, 6, 1, 3),
  486. ])
  487. expect(replayed.session.getSnapshot().nodes).toEqual(live)
  488. })
  489. it('merges an interrupted frozen node by seq into the log-ordered transcript', async () => {
  490. // The transcript array is seq-monotonic, so the frozen node's fractional
  491. // seq lands it exactly where it happened — including after a compaction
  492. // checkpoint whose own seq is higher than the range it shadowed.
  493. const { session } = await opened()
  494. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  495. feed(ev.compactSummary(6, '压缩摘要', 1, 3))
  496. feed(ev.compactCheckpoint(7, 6, 1, 3))
  497. feed(ev.turnStart(8, 1))
  498. feed(ev.user(9, '压缩后的提问'))
  499. feed(ev.chunkStart(10, 1))
  500. feed(ev.chunkText(11, 1, '说到一半'))
  501. feed(ev.turnEnd(12, 1, 'aborted'))
  502. expect(session.getSnapshot().nodes.map(n => n.kind)).toEqual([
  503. 'user', 'assistant', 'compaction', 'user', 'assistant',
  504. ])
  505. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({ interrupted: true })
  506. })
  507. it('repairs a seq gap by repulling the tail page instead of appending a hole', async () => {
  508. const { api, session } = await opened(plainTurn(0, 0, 'a', 'b')) // tail seq = 5
  509. const repaired = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  510. api.onHistory = () => histResponse(repaired)
  511. // seq 9 with tail 5 → gap; the event detours to the buffer and one history refetch fires.
  512. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.assistant(9, 1, 'd') })
  513. await vi.waitFor(() => {
  514. expect(api.callsOf('session.history').length).toBe(2)
  515. })
  516. await Promise.resolve()
  517. const seqs = session.getSnapshot().nodes.map(n => n.seq)
  518. expect(seqs).toEqual([1, 3, 7, 9]) // both turns' user/assistant, no hole, no duplicate 9
  519. })
  520. })
  521. describe('paging', () => {
  522. it('prepends an older page and keeps seq continuity', async () => {
  523. const older = plainTurn(0, 0, '旧问', '旧答')
  524. const newer = plainTurn(6, 1, '新问', '新答')
  525. const { api, session } = makeSession()
  526. api.onHistory = payload => payload.beforeSeq === undefined
  527. ? histResponse(newer, true)
  528. : histResponse(older, false)
  529. await session.open()
  530. await session.loadOlder()
  531. const snapshot = session.getSnapshot()
  532. expect(api.callsOf('session.history')).toMatchObject([{}, { beforeSeq: 6 }].map(p => ({ sessionId: SID, ...p })))
  533. expect(snapshot.hasMore).toBe(false)
  534. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  535. })
  536. it('renders a page whose checkpoint shadows seqs below the window head, logging nothing', async () => {
  537. // Pagination no longer spends maxMessages quota on replacement copies, so a
  538. // page can carry a compaction checkpoint whose surfaceOp.start lies outside
  539. // the window. The old surface fold rejected that range and degraded with a
  540. // console error; the log-ordered transcript has no range to resolve.
  541. const { api, session } = makeSession()
  542. api.onHistory = () => histResponse([
  543. ev.compactSummary(80, '窗外范围的摘要', 3, 40),
  544. ev.compactCheckpoint(81, 80, 3, 40),
  545. ev.user(82, '压缩后的新问题'),
  546. ], true)
  547. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  548. try {
  549. await session.open()
  550. const snapshot = session.getSnapshot()
  551. expect(snapshot.openState).toBe('open')
  552. expect(snapshot.nodes.map(n => [n.kind, n.seq])).toEqual([['compaction', 81], ['user', 82]])
  553. expect(snapshot.nodes[0]).toMatchObject({ summary: '窗外范围的摘要' })
  554. expect(errorSpy).not.toHaveBeenCalled()
  555. } finally {
  556. errorSpy.mockRestore()
  557. }
  558. })
  559. it('drops a discontinuous older page fail-soft (window unchanged, hasMore cleared)', async () => {
  560. const { api, session } = makeSession()
  561. api.onHistory = payload => payload.beforeSeq === undefined
  562. ? histResponse(plainTurn(10, 1, '新', '页'), true)
  563. : histResponse(plainTurn(0, 0, '断', '层'), true) // tail seq 5, but baseSeq is 10 → hole
  564. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  565. try {
  566. await session.open()
  567. const nodesBefore = session.getSnapshot().nodes
  568. await session.loadOlder()
  569. const snapshot = session.getSnapshot()
  570. expect(snapshot.nodes).toEqual(nodesBefore)
  571. expect(snapshot.hasMore).toBe(false)
  572. } finally {
  573. errorSpy.mockRestore()
  574. }
  575. })
  576. it('ignores loadOlder while one is in flight (single request)', async () => {
  577. const { api, session } = makeSession()
  578. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  579. await session.open()
  580. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  581. api.onHistory = () => gate.promise
  582. const first = session.loadOlder()
  583. const second = session.loadOlder()
  584. gate.resolve(ok({
  585. events: entries(plainTurn(0, 0, 'a', 'b')) as never[],
  586. hasMore: false,
  587. modelTarget: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  588. }))
  589. await Promise.all([first, second])
  590. expect(api.callsOf('session.history')).toHaveLength(2) // open + one page, not two
  591. })
  592. })
  593. describe('prompt and cancel errors', () => {
  594. it('routes an addressed child through non-activating history and continuation prompt only', async () => {
  595. const api = new FakeApiClient()
  596. const session = new Session(SID, api, {
  597. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  598. parentAvailable: true,
  599. })
  600. await session.open()
  601. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  602. const cancelled = await session.cancel()
  603. expect(prompted).toEqual({ ok: true, value: { accepted: true } })
  604. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent-delivery-unavailable' } })
  605. expect(api.callsOf('subagent.history')).toEqual([
  606. { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable', maxMessages: 50 },
  607. ])
  608. expect(api.callsOf('subagent.prompt')).toEqual([
  609. {
  610. parentSessionId: PARENT, childSessionId: SID, mode: 'continuable',
  611. content: [{ type: 'text', text: '继续' }],
  612. },
  613. ])
  614. expect(api.callsOf('session.history')).toEqual([])
  615. expect(api.callsOf('session.prompt')).toEqual([])
  616. expect(api.callsOf('session.cancel')).toEqual([])
  617. expect(session.getSnapshot().subagent).toEqual({
  618. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  619. parentAvailable: true,
  620. })
  621. })
  622. it('keeps one-shot history readable without exposing prompt or cancel transport', async () => {
  623. const api = new FakeApiClient()
  624. const session = new Session(SID, api, {
  625. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot' },
  626. })
  627. await session.open()
  628. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  629. expect(prompted).toMatchObject({ ok: false, error: { code: 'subagent-not-resumable' } })
  630. expect(api.callsOf('subagent.history')).toEqual([
  631. { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot', maxMessages: 50 },
  632. ])
  633. expect(api.callsOf('subagent.prompt')).toEqual([])
  634. })
  635. it('sends content through session.prompt; composerPhase steps blank → engaging synchronously at send entry', async () => {
  636. const { api, session } = makeSession()
  637. // The blank → engaging edge fires before the RPC settles: the first-send
  638. // flow reads the phase on the session area's first frame to keep the
  639. // guidance hero from flashing back in.
  640. expect(session.getSnapshot().composerPhase).toBe('blank')
  641. const inFlight = session.prompt([{ type: 'text', text: '要发的' }], 'queue')
  642. expect(session.getSnapshot().composerPhase).toBe('engaging')
  643. const result = await inFlight
  644. expect(result.ok).toBe(true)
  645. // Monotone: settlement alone does not step the phase anywhere.
  646. expect(session.getSnapshot().composerPhase).toBe('engaging')
  647. expect(api.callsOf('session.prompt')).toMatchObject([{ sessionId: SID, mode: 'queue', content: [{ type: 'text', text: '要发的' }] }])
  648. // First content lands (running turn): engaging → active.
  649. session.handleRunning(true)
  650. expect(session.getSnapshot().composerPhase).toBe('active')
  651. })
  652. it('business failure lands in promptError with op=send; the phase stays engaging (retry, no hero bounce)', async () => {
  653. const { api, session } = makeSession()
  654. api.onPrompt = () => Promise.resolve(err({ code: 'agent-busy', message: 'busy', details: { reason: 'x' } }))
  655. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue')
  656. expect(result.ok).toBe(false)
  657. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'agent-busy' } })
  658. // Failed first prompt: composer + error strip is the retry surface —
  659. // blank is unreachable once a send was initiated.
  660. expect(session.getSnapshot().composerPhase).toBe('engaging')
  661. })
  662. it('lands cancel failures in promptError with op=stop', async () => {
  663. const { api, session } = makeSession()
  664. api.onCancel = () => Promise.reject(new Error('cancel transport down'))
  665. const result = await session.cancel()
  666. expect(result.ok).toBe(false)
  667. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'internal' } })
  668. })
  669. })
  670. describe('rename', () => {
  671. it('settles the title projection cell from the unary response (higher-seq-wins vs the push frame)', async () => {
  672. const { api, session } = makeSession()
  673. api.onRename = () => Promise.resolve(ok({ title: '正名', seq: 7 }))
  674. const result = await session.rename(' 正名 ')
  675. expect(result).toMatchObject({ ok: true, value: { title: '正名', seq: 7 } })
  676. expect(api.callsOf('session.rename')).toMatchObject([{ sessionId: SID, title: ' 正名 ' }])
  677. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  678. // A stale lower-seq apply (the push-frame path routes into this same
  679. // store) must not roll the settled value back.
  680. session.projections.apply('title', '旧名', 3)
  681. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  682. })
  683. it('returns the business error untouched and folds a transport throw to internal', async () => {
  684. const { api, session } = makeSession()
  685. api.onRename = () => Promise.resolve(err({ code: 'title-invalid', message: 'empty', details: { sessionId: SID } }))
  686. const rejected = await session.rename(' ')
  687. expect(rejected).toMatchObject({ ok: false, error: { code: 'title-invalid' } })
  688. expect(session.projections.faceOf('title').getSnapshot()).toBeUndefined()
  689. api.onRename = () => Promise.reject(new Error('rename transport down'))
  690. const folded = await session.rename('x')
  691. expect(folded).toMatchObject({ ok: false, error: { code: 'internal' } })
  692. })
  693. })
  694. describe('pending interactions', () => {
  695. it('adds approval/question on requested and removes them on resolved', async () => {
  696. const { session } = makeSession()
  697. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  698. session.handleMuxEnvelope('rq' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  699. expect(session.getSnapshot().pending.map(p => p.kind).sort()).toEqual(['approval', 'question'])
  700. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap1' as never, outcome: 'approved' as never })
  701. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq' as never, outcome: 'answered' })
  702. expect(session.getSnapshot().pending).toEqual([])
  703. })
  704. it('mints waits whose respond() backfills the requested rpcId into the client-response envelope', async () => {
  705. const { api, session } = makeSession()
  706. session.handleMuxEnvelope('rq-answer' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  707. const wait = session.getSnapshot().pending[0]!
  708. expect(wait).toMatchObject({ kind: 'question', key: 'q:rq-answer', sessionId: SID, payload: { questions: [] } })
  709. const receipt = await wait.respond({
  710. ok: true,
  711. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  712. })
  713. expect(receipt).toEqual({ accepted: true })
  714. expect(api.callsOf('respond')).toEqual([{
  715. type: 'client-response', rpcId: 'rq-answer',
  716. result: {
  717. ok: true,
  718. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  719. },
  720. }])
  721. })
  722. it('settles the wait on the authoritative resolved frame: respond() then throws synchronously', async () => {
  723. const { api, session } = makeSession()
  724. session.handleMuxEnvelope('rq1' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  725. const wait = session.getSnapshot().pending[0]!
  726. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq1' as never, outcome: 'answered' })
  727. expect(session.getSnapshot().pending).toEqual([])
  728. expect(() => wait.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } }))
  729. .toThrow('already settled')
  730. expect(api.callsOf('respond')).toEqual([])
  731. })
  732. })
  733. describe('remaining branches', () => {
  734. it('prompt transport throw folds to internal promptError', async () => {
  735. const { api, session } = makeSession()
  736. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  737. const result = await session.prompt([{ type: 'text', text: 'x' }], 'queue')
  738. expect(result.ok).toBe(false)
  739. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'internal', message: 'prompt wire down' } })
  740. })
  741. it('cancel business error also lands op=stop promptError', async () => {
  742. const { api, session } = makeSession()
  743. api.onCancel = () => Promise.resolve(err({ code: 'agent-busy', message: 'nope', details: { reason: 'r' } }))
  744. await session.cancel()
  745. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'agent-busy' } })
  746. })
  747. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  748. const { api, session } = makeSession()
  749. await session.loadOlder() // cold: no-op, zero calls
  750. expect(api.calls).toEqual([])
  751. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  752. await session.open()
  753. // err result: window unchanged
  754. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  755. await session.loadOlder()
  756. expect(session.getSnapshot().nodes).toHaveLength(2)
  757. expect(session.getSnapshot().hasMore).toBe(true)
  758. // empty page: hasMore adopts the response
  759. api.onHistory = () => histResponse([], false)
  760. await session.loadOlder()
  761. expect(session.getSnapshot().hasMore).toBe(false)
  762. // hasMore false now: further loadOlder is a guard no-op
  763. const calls = api.calls.length
  764. await session.loadOlder()
  765. expect(api.calls.length).toBe(calls)
  766. // throw path: fail-soft with console.error
  767. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  768. try {
  769. await session.resync()
  770. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  771. await session.resync()
  772. api.onHistory = () => Promise.reject(new Error('page wire down'))
  773. await session.loadOlder()
  774. expect(errorSpy).toHaveBeenCalled()
  775. expect(session.getSnapshot().loadingOlder).toBe(false)
  776. } finally {
  777. errorSpy.mockRestore()
  778. }
  779. })
  780. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  781. const { api, session } = makeSession()
  782. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  783. let notified = 0
  784. const unsubscribe = session.subscribe(() => { notified++ })
  785. await session.open()
  786. await new Promise(resolve => setTimeout(resolve, 0))
  787. expect(notified).toBeGreaterThan(0)
  788. const seen = notified
  789. unsubscribe()
  790. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  791. await new Promise(resolve => setTimeout(resolve, 0))
  792. expect(notified).toBe(seen)
  793. })
  794. it('subscribed baseline past the window tail triggers the second stitch pull in doOpen', async () => {
  795. const { api, session } = makeSession()
  796. const full = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  797. let call = 0
  798. api.onHistory = () => {
  799. call++
  800. return histResponse(call === 1 ? plainTurn(0, 0, 'a', 'b') : full)
  801. }
  802. // Baseline arrives before open: lastSeq 11 > first page tail 5 → doOpen repulls once.
  803. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  804. await session.open()
  805. expect(call).toBe(2)
  806. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  807. })
  808. it('a failed second stitch pull keeps the first window and still opens', async () => {
  809. const { api, session } = makeSession()
  810. let call = 0
  811. api.onHistory = () => {
  812. call++
  813. return call === 1
  814. ? histResponse(plainTurn(0, 0, 'a', 'b'))
  815. : Promise.resolve(err({ code: 'internal', message: 'stitch pull down', details: {} }))
  816. }
  817. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  818. await session.open()
  819. expect(call).toBe(2)
  820. const snapshot = session.getSnapshot()
  821. expect(snapshot.openState).toBe('open') // stitch-pull failure is not an open failure
  822. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3]) // first window kept
  823. })
  824. it('approval frame with callId/reason keeps the optional fields; duplicate resolved is a no-op', () => {
  825. const { session } = makeSession()
  826. session.handleMuxEnvelope('ra' as never, {
  827. type: 'approval/requested', sessionId: SID, approvalId: 'ap2' as never, toolName: 'rm', callId: 'c1' as never, reason: '危险',
  828. })
  829. expect(session.getSnapshot().pending[0]).toMatchObject({ kind: 'approval', payload: { callId: 'c1', reason: '危险' } })
  830. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  831. session.handleMuxEnvelope('rx2' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  832. session.handleMuxEnvelope('ry2' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'never-was' as never, outcome: 'cancelled' })
  833. expect(session.getSnapshot().pending).toEqual([])
  834. })
  835. it('ignores unknown mux frame types and repeated running flips (documented defaults)', () => {
  836. const { session } = makeSession()
  837. const before = session.getSnapshot()
  838. session.handleMuxEnvelope('rz' as never, { type: 'future/frame' } as never)
  839. session.handleRunning(false) // already false: dedup branch
  840. expect(session.getSnapshot()).toBe(before)
  841. session.handleRemoved()
  842. expect(session.getSnapshot().removed).toBe(true)
  843. })
  844. it('drops live events while cold/error (no window upkeep)', async () => {
  845. const { api, session } = makeSession()
  846. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '冷态帧') })
  847. expect(session.getSnapshot().nodes).toEqual([])
  848. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  849. await session.open()
  850. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '错态帧') })
  851. expect(session.getSnapshot().nodes).toEqual([])
  852. })
  853. it('repairGap failure logs and clears stitching; concurrent gaps coalesce into one repair', async () => {
  854. const { api, session } = makeSession()
  855. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  856. await session.open()
  857. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  858. let repairs = 0
  859. api.onHistory = () => {
  860. repairs++
  861. return gate.promise
  862. }
  863. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  864. try {
  865. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞一') })
  866. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(10, '洞二') }) // stitching: detours, no second repair
  867. expect(repairs).toBe(1)
  868. gate.reject(new Error('repair wire down'))
  869. await vi.waitFor(() => { expect(errorSpy).toHaveBeenCalled() })
  870. // Window unchanged; a later successful repull still lands the buffered frames.
  871. expect(session.getSnapshot().nodes).toHaveLength(2)
  872. } finally {
  873. errorSpy.mockRestore()
  874. }
  875. })
  876. it('freezes only content-bearing partials; a content-free partial is dropped outright', async () => {
  877. const { api, session } = makeSession()
  878. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  879. await session.open()
  880. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  881. feed(ev.turnStart(6, 1))
  882. feed(ev.chunkStart(7, 1)) // empty text block only, no delta
  883. feed(ev.turnEnd(8, 1, 'aborted'))
  884. const snapshot = session.getSnapshot()
  885. expect(snapshot.partial).toBeNull()
  886. expect(snapshot.nodes.filter(n => n.kind === 'assistant' && (n as { interrupted?: true }).interrupted)).toEqual([])
  887. })
  888. it('turn/end sweeps only same-turn open calls; other turns keep running', async () => {
  889. const { api, session } = makeSession()
  890. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  891. await session.open()
  892. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  893. feed(ev.turnStart(6, 1))
  894. feed(ev.toolCall(7, 1, 'turn1-call', 'echo', '{}'))
  895. feed(ev.toolCall(8, 2, 'turn2-call', 'echo', '{}')) // stray call attributed to a later turn
  896. feed(ev.turnEnd(9, 1, 'aborted'))
  897. const snapshot = session.getSnapshot()
  898. expect(snapshot.runningCalls.map(c => c.callId)).toEqual(['turn2-call'])
  899. expect(snapshot.nodes.at(-1)).toMatchObject({ kind: 'tool-result', callId: 'turn1-call', isError: true })
  900. })
  901. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  902. const { api, session } = makeSession()
  903. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  904. api.onHistory = () => stale.promise
  905. const opening = session.open()
  906. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  907. const resynced = session.resync()
  908. stale.reject(new Error('stale wire'))
  909. await Promise.all([opening, resynced])
  910. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  911. })
  912. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  913. const { api, session } = makeSession()
  914. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  915. api.onHistory = () => stale.promise
  916. const opening = session.open()
  917. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  918. const resynced = session.resync()
  919. stale.resolve(ok({
  920. events: entries(plainTurn(0, 0, '旧', '代')) as never[],
  921. hasMore: false,
  922. modelTarget: { provider: 'deepseek-official', model: 'stale' },
  923. })) // success, but its generation is gone
  924. await Promise.all([opening, resynced])
  925. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9]) // only the fresh generation's window
  926. })
  927. it('drops a stale stitch pull (second doOpen fetch) superseded mid-flight by resync', async () => {
  928. const { api, session } = makeSession()
  929. const secondPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  930. let call = 0
  931. api.onHistory = () => {
  932. call++
  933. if (call === 1) return histResponse(plainTurn(0, 0, 'a', 'b')) // first page: tail 5
  934. if (call === 2) return secondPull.promise // gap-stitch pull: held
  935. return histResponse(plainTurn(6, 1, 'c', 'd'))
  936. }
  937. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  938. const opening = session.open() // triggers the second pull, which parks
  939. await vi.waitFor(() => { expect(call).toBe(2) })
  940. const resynced = session.resync()
  941. secondPull.resolve(ok({
  942. events: entries([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]) as never[],
  943. hasMore: false,
  944. modelTarget: { provider: 'deepseek-official', model: 'stale' },
  945. }))
  946. await Promise.all([opening, resynced])
  947. expect(session.getSnapshot().openState).toBe('open')
  948. })
  949. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  950. const { api, session } = makeSession()
  951. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  952. await session.open()
  953. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  954. api.onHistory = () => repairPull.promise
  955. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞') }) // starts repairGap
  956. api.onHistory = () => histResponse(plainTurn(6, 1, 'c', 'd'))
  957. const resynced = session.resync() // bumps the generation
  958. repairPull.resolve(ok({
  959. events: entries(plainTurn(0, 0, '旧', '页')) as never[],
  960. hasMore: false,
  961. modelTarget: { provider: 'deepseek-official', model: 'stale' },
  962. })) // repair result: stale, dropped
  963. await resynced
  964. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9])
  965. })
  966. it('successful cancel leaves no promptError; tool/result for an unknown callId is a no-op', async () => {
  967. const { api, session } = makeSession()
  968. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  969. await session.open()
  970. const result = await session.cancel()
  971. expect(result.ok).toBe(true)
  972. expect(session.getSnapshot().promptError).toBeNull()
  973. const callsBefore = session.getSnapshot().runningCalls
  974. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.toolResult(6, 0, 'never-called', 'x') })
  975. expect(session.getSnapshot().runningCalls).toBe(callsBefore) // callsRev untouched: same reference
  976. })
  977. it('freezes a tool-call-only partial (visible through the non-text arm)', async () => {
  978. const { api, session } = makeSession()
  979. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  980. await session.open()
  981. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  982. feed(ev.turnStart(6, 1))
  983. feed(at(7, { type: 'assistant/chunk', data: { turn: 1, step: 0, chunk: { type: 'tool-call-delta', index: 0, id: 'c1', name: 'echo', argumentsDelta: '{' } } }))
  984. feed(ev.turnEnd(8, 1, 'aborted'))
  985. const frozen = session.getSnapshot().nodes.at(-1)
  986. expect(frozen).toMatchObject({ kind: 'assistant', interrupted: true, blocks: [{ kind: 'tool-call', callId: 'c1' }] })
  987. })
  988. it('dispose is a reserved no-op on resident instances', () => {
  989. const { session } = makeSession()
  990. expect(() => { session.dispose() }).not.toThrow()
  991. })
  992. it('carries mux-frame views into runningCalls and tool-result nodes, and history-entry views through open', async () => {
  993. const { api, session } = makeSession()
  994. const callView = { for: 'call', view: { card: 'generic', title: '历史卡' } }
  995. api.onHistory = () => Promise.resolve(ok({
  996. events: [
  997. ...entries(plainTurn(0, 0, 'a', 'b')),
  998. { event: ev.toolCall(6, 1, 'h1', 'bash', '{}'), view: callView },
  999. { event: ev.toolResult(7, 1, 'h1', 'done'), view: { for: 'result', view: { card: 'generic', title: '历史果' } } },
  1000. ] as never[],
  1001. hasMore: false,
  1002. modelTarget: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  1003. }))
  1004. await session.open()
  1005. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  1006. kind: 'tool-result', callView: { title: '历史卡' }, resultView: { title: '历史果' },
  1007. })
  1008. // Live path: the frame's view slot reaches runningCalls, then the result node.
  1009. session.handleMuxEnvelope('rv1' as never, {
  1010. type: 'session/event', sessionId: SID, event: ev.toolCall(8, 2, 'l1', 'write', '{}'),
  1011. view: { for: 'call', view: { card: 'generic', title: '直播卡' } },
  1012. } as never)
  1013. expect(session.getSnapshot().runningCalls).toMatchObject([{ callId: 'l1', callView: { title: '直播卡' } }])
  1014. session.handleMuxEnvelope('rv2' as never, {
  1015. type: 'session/event', sessionId: SID, event: ev.toolResult(9, 2, 'l1', 'ok'),
  1016. view: { for: 'result', view: { card: 'generic', title: '直播果' } },
  1017. } as never)
  1018. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  1019. kind: 'tool-result', callView: { title: '直播卡' }, resultView: { title: '直播果' },
  1020. })
  1021. })
  1022. })
  1023. describe('resync', () => {
  1024. it('rebuilds the window and clears pending; cold instances no-op', async () => {
  1025. const { api, session } = makeSession()
  1026. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  1027. await session.open()
  1028. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  1029. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')])
  1030. await session.resync()
  1031. const snapshot = session.getSnapshot()
  1032. expect(snapshot.openState).toBe('open')
  1033. expect(snapshot.pending).toEqual([]) // baseline replay re-sends still-pending frames
  1034. expect(snapshot.nodes).toHaveLength(4)
  1035. const cold = makeSession()
  1036. await cold.session.resync()
  1037. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  1038. })
  1039. it('re-mints a replayed requested frame as a fresh wait with the same key (old reference superseded)', async () => {
  1040. const { api, session } = makeSession()
  1041. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  1042. await session.open()
  1043. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  1044. const before = session.getSnapshot().pending[0]!
  1045. await session.resync()
  1046. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  1047. const after = session.getSnapshot().pending[0]!
  1048. expect(after).not.toBe(before)
  1049. expect(after.key).toBe(before.key)
  1050. // Superseded ≠ settled: an in-flight respond on the stale reference still reaches the host.
  1051. await before.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } })
  1052. expect(api.callsOf('respond')).toMatchObject([{ rpcId: 'rq-replay' }])
  1053. })
  1054. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  1055. const { api, session } = makeSession()
  1056. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  1057. api.onHistory = () => stale.promise
  1058. const firstOpen = session.open()
  1059. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  1060. const resynced = session.resync()
  1061. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  1062. await firstOpen
  1063. await resynced
  1064. const snapshot = session.getSnapshot()
  1065. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  1066. expect(snapshot.nodes.map(n => n.seq)).toEqual([7, 9])
  1067. })
  1068. })
  1069. describe('run_code sub-dispatch indexing', () => {
  1070. it('a start event lands as a running-shaped sub-call and its settle replaces it in place', async () => {
  1071. const { api, session } = makeSession()
  1072. api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答'))
  1073. await session.open()
  1074. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  1075. feed(ev.turnStart(6, 1))
  1076. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"d"}'))
  1077. feed(ev.codeDispatchStart(8, 'p1', 1, 'bash', { command: 'sleep' }))
  1078. feed(ev.codeDispatchStart(9, 'p1', 2, 'read', { path: 'a.txt' }))
  1079. const live = session.getSnapshot().codeDispatches.get('p1')
  1080. expect(live).toHaveLength(2)
  1081. // Running shape (no 'kind'): the exact RunningToolCall form native rows use.
  1082. expect(live?.[0]).toMatchObject({ callId: 'p1:code:1', name: 'bash', argsRaw: '{"command":"sleep"}' })
  1083. expect(live?.[0] !== undefined && 'kind' in live[0]).toBe(false)
  1084. // Settle out of order (parallel run): #2 first — replaces in place, keeping start order.
  1085. feed(ev.codeDispatch(10, 'p1', 2, 'read', { path: 'a.txt' }, 'alpha'))
  1086. const mixed = session.getSnapshot().codeDispatches.get('p1')
  1087. expect(mixed?.map(sub => 'kind' in sub)).toEqual([false, true])
  1088. expect(mixed?.[1]).toMatchObject({ callId: 'p1:code:2', content: [{ type: 'text', text: 'alpha' }] })
  1089. // The settle carries the paired start's time as callTime (duration source).
  1090. feed(ev.codeDispatch(11, 'p1', 1, 'bash', { command: 'sleep' }, 'done'))
  1091. const settled = session.getSnapshot().codeDispatches.get('p1')
  1092. expect(settled?.map(sub => 'kind' in sub)).toEqual([true, true])
  1093. expect(settled?.[0]).toMatchObject({ callId: 'p1:code:1', callTime: 1_700_000_000_008 })
  1094. })
  1095. it('indexes live tool/code-dispatch events under their parent as native-shaped result nodes', async () => {
  1096. const { api, session } = makeSession()
  1097. api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答'))
  1098. await session.open()
  1099. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  1100. feed(ev.turnStart(6, 1))
  1101. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"return 1","description":"跑一个程序"}'))
  1102. feed(ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls', description: '列目录' }, 'demo.txt'))
  1103. feed(ev.codeDispatch(9, 'p1', 2, 'read', { path: 'a.txt' }, 'Error: ENOENT', true))
  1104. const subs = session.getSnapshot().codeDispatches.get('p1')
  1105. expect(subs).toHaveLength(2)
  1106. expect(subs?.[0]).toMatchObject({
  1107. kind: 'tool-result', callId: 'p1:code:1',
  1108. call: { name: 'bash', argsRaw: '{"command":"ls","description":"列目录"}' },
  1109. // The settle event carries no start time: callTime stays null (never a
  1110. // fabricated zero-duration).
  1111. callTime: null,
  1112. isError: false, content: [{ type: 'text', text: 'demo.txt' }],
  1113. })
  1114. expect(subs?.[1]).toMatchObject({ callId: 'p1:code:2', isError: true })
  1115. // No paired start in the window: duration is UNKNOWN (null), never a
  1116. // fabricated zero-duration span.
  1117. expect(subs?.[0]).toMatchObject({ callTime: null })
  1118. // Sub-dispatches never join the surface flow.
  1119. expect(session.getSnapshot().nodes.some(n => n.kind === 'tool-result' && n.callId.includes(':code:'))).toBe(false)
  1120. })
  1121. it('rebuilds the same index from a history window (replay parity)', async () => {
  1122. const { api, session } = makeSession()
  1123. api.onHistory = () => histResponse([
  1124. ...plainTurn(0, 0, '问', '答'),
  1125. ev.turnStart(6, 1),
  1126. ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"return 1","description":"跑一个程序"}'),
  1127. ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls' }, 'demo.txt'),
  1128. ev.toolResult(9, 1, 'p1', '{"done":true}'),
  1129. ev.turnEnd(10, 1),
  1130. ])
  1131. await session.open()
  1132. const subs = session.getSnapshot().codeDispatches.get('p1')
  1133. expect(subs).toHaveLength(1)
  1134. expect(subs?.[0]).toMatchObject({ callId: 'p1:code:1', call: { name: 'bash' } })
  1135. })
  1136. it('keeps the dispatch map reference across unrelated changes and swaps it on a new dispatch', async () => {
  1137. const { api, session } = makeSession()
  1138. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  1139. await session.open()
  1140. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  1141. feed(ev.turnStart(6, 1))
  1142. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"d"}'))
  1143. feed(ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls' }, 'x'))
  1144. const before = session.getSnapshot()
  1145. feed(ev.chunkStart(9, 1))
  1146. feed(ev.chunkText(10, 1, '流式'))
  1147. const after = session.getSnapshot()
  1148. expect(after.codeDispatches).toBe(before.codeDispatches)
  1149. feed(ev.codeDispatch(11, 'p1', 2, 'read', { path: 'a' }, 'y'))
  1150. expect(session.getSnapshot().codeDispatches).not.toBe(after.codeDispatches)
  1151. expect(session.getSnapshot().codeDispatches.get('p1')).toHaveLength(2)
  1152. })
  1153. })
  1154. describe('reference stability (the memo contract)', () => {
  1155. it('keeps unchanged node references across an append and swaps the snapshot object', async () => {
  1156. const { api, session } = makeSession()
  1157. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  1158. await session.open()
  1159. const before = session.getSnapshot()
  1160. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(6, '追加') })
  1161. const after = session.getSnapshot()
  1162. expect(after).not.toBe(before) // top-level swap on change
  1163. expect(after.nodes[0]).toBe(before.nodes[0]) // untouched nodes keep identity
  1164. expect(after.nodes[1]).toBe(before.nodes[1])
  1165. expect(after.nodes).toHaveLength(3)
  1166. // No change → same snapshot reference.
  1167. expect(session.getSnapshot()).toBe(after)
  1168. })
  1169. it('keeps untouched substructure arrays identical across unrelated changes (revision counters)', async () => {
  1170. const { api, session } = makeSession()
  1171. api.onHistory = () => histResponse(plainTurn(0, 0, '底', '座'))
  1172. await session.open()
  1173. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  1174. feed(ev.turnStart(6, 1))
  1175. feed(ev.stepStart(7, 1))
  1176. feed(ev.toolCall(8, 1, 'c1', 'echo', '{}'))
  1177. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  1178. const before = session.getSnapshot()
  1179. // A chunk storm touches partial/nodes only: unrelated projections keep identity.
  1180. feed(ev.chunkStart(9, 1))
  1181. feed(ev.chunkText(10, 1, '与工具无关的流式'))
  1182. const after = session.getSnapshot()
  1183. expect(after).not.toBe(before)
  1184. expect(after.runningCalls).toBe(before.runningCalls)
  1185. expect(after.pending).toBe(before.pending)
  1186. expect(after.turnTimings).toBe(before.turnTimings)
  1187. expect(after.turnEnds).toBe(before.turnEnds)
  1188. // And a mutation on the tracked domain swaps that array.
  1189. feed(ev.toolResult(11, 1, 'c1', 'ECHO'))
  1190. const resolved = session.getSnapshot()
  1191. expect(resolved.runningCalls).not.toBe(after.runningCalls)
  1192. expect(resolved.pending).toBe(after.pending)
  1193. feed(ev.assistant(12, 1, '完成'))
  1194. expect(session.getSnapshot()).not.toBe(resolved)
  1195. })
  1196. })