session.spec.ts 65 KB

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