session.spec.ts 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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. modelSelection: { 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. modelSelection: { 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, continuation prompt, and interrupt 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).toEqual({ ok: true, value: { accepted: true } })
  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. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  613. },
  614. ])
  615. expect(api.callsOf('subagent.interrupt')).toEqual([
  616. { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  617. ])
  618. expect(api.callsOf('session.history')).toEqual([])
  619. expect(api.callsOf('session.prompt')).toEqual([])
  620. expect(api.callsOf('session.cancel')).toEqual([])
  621. // A successful interrupt leaves no stop error behind.
  622. expect(session.getSnapshot().promptError).toBeNull()
  623. expect(session.getSnapshot().subagent).toEqual({
  624. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  625. parentAvailable: true,
  626. })
  627. })
  628. it('lands an interrupt business failure in promptError with op=stop', async () => {
  629. const api = new FakeApiClient()
  630. api.onSubagentInterrupt = () => Promise.resolve(err({
  631. code: 'subagent-unauthorized', message: 'nope', details: { childSessionId: SID },
  632. }) as never)
  633. const session = new Session(SID, api, {
  634. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  635. parentAvailable: true,
  636. })
  637. await session.open()
  638. const cancelled = await session.cancel()
  639. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent-unauthorized' } })
  640. expect(session.getSnapshot().promptError).toMatchObject({
  641. op: 'stop', error: { code: 'subagent-unauthorized' },
  642. })
  643. })
  644. it('keeps one-shot history readable without exposing prompt or cancel transport', async () => {
  645. const api = new FakeApiClient()
  646. const session = new Session(SID, api, {
  647. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot' },
  648. })
  649. await session.open()
  650. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  651. const cancelled = await session.cancel()
  652. expect(prompted).toMatchObject({ ok: false, error: { code: 'subagent-not-resumable' } })
  653. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent-delivery-unavailable' } })
  654. expect(api.callsOf('subagent.history')).toEqual([
  655. { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot', maxMessages: 50 },
  656. ])
  657. expect(api.callsOf('subagent.prompt')).toEqual([])
  658. expect(api.callsOf('subagent.interrupt')).toEqual([])
  659. expect(api.callsOf('session.cancel')).toEqual([])
  660. })
  661. it('sends content through session.prompt; composerPhase steps blank → engaging synchronously at send entry', async () => {
  662. const { api, session } = makeSession()
  663. // The blank → engaging edge fires before the RPC settles: the first-send
  664. // flow reads the phase on the session area's first frame to keep the
  665. // guidance hero from flashing back in.
  666. expect(session.getSnapshot().composerPhase).toBe('blank')
  667. const inFlight = session.prompt([{ type: 'text', text: '要发的' }], 'queue')
  668. expect(session.getSnapshot().composerPhase).toBe('engaging')
  669. const result = await inFlight
  670. expect(result.ok).toBe(true)
  671. // Monotone: settlement alone does not step the phase anywhere.
  672. expect(session.getSnapshot().composerPhase).toBe('engaging')
  673. expect(api.callsOf('session.prompt')).toMatchObject([{
  674. sessionId: SID,
  675. mode: 'queue',
  676. content: [{ type: 'text', text: '要发的' }],
  677. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  678. }])
  679. // First content lands (running turn): engaging → active.
  680. session.handleRunning(true)
  681. expect(session.getSnapshot().composerPhase).toBe('active')
  682. })
  683. it('business failure lands in promptError with op=send; the phase stays engaging (retry, no hero bounce)', async () => {
  684. const { api, session } = makeSession()
  685. api.onPrompt = () => Promise.resolve(err({ code: 'agent-busy', message: 'busy', details: { reason: 'x' } }))
  686. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue')
  687. expect(result.ok).toBe(false)
  688. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'agent-busy' } })
  689. // Failed first prompt: composer + error strip is the retry surface —
  690. // blank is unreachable once a send was initiated.
  691. expect(session.getSnapshot().composerPhase).toBe('engaging')
  692. })
  693. it('lands cancel failures in promptError with op=stop', async () => {
  694. const { api, session } = makeSession()
  695. api.onCancel = () => Promise.reject(new Error('cancel transport down'))
  696. const result = await session.cancel()
  697. expect(result.ok).toBe(false)
  698. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'internal' } })
  699. })
  700. })
  701. describe('rename', () => {
  702. it('settles the title projection cell from the unary response (higher-seq-wins vs the push frame)', async () => {
  703. const { api, session } = makeSession()
  704. api.onRename = () => Promise.resolve(ok({ title: '正名', seq: 7 }))
  705. const result = await session.rename(' 正名 ')
  706. expect(result).toMatchObject({ ok: true, value: { title: '正名', seq: 7 } })
  707. expect(api.callsOf('session.rename')).toMatchObject([{ sessionId: SID, title: ' 正名 ' }])
  708. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  709. // A stale lower-seq apply (the push-frame path routes into this same
  710. // store) must not roll the settled value back.
  711. session.projections.apply('title', '旧名', 3)
  712. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  713. })
  714. it('returns the business error untouched and folds a transport throw to internal', async () => {
  715. const { api, session } = makeSession()
  716. api.onRename = () => Promise.resolve(err({ code: 'title-invalid', message: 'empty', details: { sessionId: SID } }))
  717. const rejected = await session.rename(' ')
  718. expect(rejected).toMatchObject({ ok: false, error: { code: 'title-invalid' } })
  719. expect(session.projections.faceOf('title').getSnapshot()).toBeUndefined()
  720. api.onRename = () => Promise.reject(new Error('rename transport down'))
  721. const folded = await session.rename('x')
  722. expect(folded).toMatchObject({ ok: false, error: { code: 'internal' } })
  723. })
  724. })
  725. describe('pending interactions', () => {
  726. it('adds approval/question on requested and removes them on resolved', async () => {
  727. const { session } = makeSession()
  728. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  729. session.handleMuxEnvelope('rq' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  730. expect(session.getSnapshot().pending.map(p => p.kind).sort()).toEqual(['approval', 'question'])
  731. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap1' as never, outcome: 'approved' as never })
  732. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq' as never, outcome: 'answered' })
  733. expect(session.getSnapshot().pending).toEqual([])
  734. })
  735. it('mints waits whose respond() backfills the requested rpcId into the client-response envelope', async () => {
  736. const { api, session } = makeSession()
  737. session.handleMuxEnvelope('rq-answer' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  738. const wait = session.getSnapshot().pending[0]!
  739. expect(wait).toMatchObject({ kind: 'question', key: 'q:rq-answer', sessionId: SID, payload: { questions: [] } })
  740. const receipt = await wait.respond({
  741. ok: true,
  742. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  743. })
  744. expect(receipt).toEqual({ accepted: true })
  745. expect(api.callsOf('respond')).toEqual([{
  746. type: 'client-response', rpcId: 'rq-answer',
  747. result: {
  748. ok: true,
  749. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  750. },
  751. }])
  752. })
  753. it('settles the wait on the authoritative resolved frame: respond() then throws synchronously', async () => {
  754. const { api, session } = makeSession()
  755. session.handleMuxEnvelope('rq1' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  756. const wait = session.getSnapshot().pending[0]!
  757. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq1' as never, outcome: 'answered' })
  758. expect(session.getSnapshot().pending).toEqual([])
  759. expect(() => wait.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } }))
  760. .toThrow('already settled')
  761. expect(api.callsOf('respond')).toEqual([])
  762. })
  763. })
  764. describe('remaining branches', () => {
  765. it('prompt transport throw folds to internal promptError', async () => {
  766. const { api, session } = makeSession()
  767. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  768. const result = await session.prompt([{ type: 'text', text: 'x' }], 'queue')
  769. expect(result.ok).toBe(false)
  770. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'internal', message: 'prompt wire down' } })
  771. })
  772. it('cancel business error also lands op=stop promptError', async () => {
  773. const { api, session } = makeSession()
  774. api.onCancel = () => Promise.resolve(err({ code: 'agent-busy', message: 'nope', details: { reason: 'r' } }))
  775. await session.cancel()
  776. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'agent-busy' } })
  777. })
  778. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  779. const { api, session } = makeSession()
  780. await session.loadOlder() // cold: no-op, zero calls
  781. expect(api.calls).toEqual([])
  782. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  783. await session.open()
  784. // err result: window unchanged
  785. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  786. await session.loadOlder()
  787. expect(session.getSnapshot().nodes).toHaveLength(2)
  788. expect(session.getSnapshot().hasMore).toBe(true)
  789. // empty page: hasMore adopts the response
  790. api.onHistory = () => histResponse([], false)
  791. await session.loadOlder()
  792. expect(session.getSnapshot().hasMore).toBe(false)
  793. // hasMore false now: further loadOlder is a guard no-op
  794. const calls = api.calls.length
  795. await session.loadOlder()
  796. expect(api.calls.length).toBe(calls)
  797. // throw path: fail-soft with console.error
  798. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  799. try {
  800. await session.resync()
  801. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  802. await session.resync()
  803. api.onHistory = () => Promise.reject(new Error('page wire down'))
  804. await session.loadOlder()
  805. expect(errorSpy).toHaveBeenCalled()
  806. expect(session.getSnapshot().loadingOlder).toBe(false)
  807. } finally {
  808. errorSpy.mockRestore()
  809. }
  810. })
  811. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  812. const { api, session } = makeSession()
  813. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  814. let notified = 0
  815. const unsubscribe = session.subscribe(() => { notified++ })
  816. await session.open()
  817. await new Promise(resolve => setTimeout(resolve, 0))
  818. expect(notified).toBeGreaterThan(0)
  819. const seen = notified
  820. unsubscribe()
  821. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  822. await new Promise(resolve => setTimeout(resolve, 0))
  823. expect(notified).toBe(seen)
  824. })
  825. it('subscribed baseline past the window tail triggers the second stitch pull in doOpen', async () => {
  826. const { api, session } = makeSession()
  827. const full = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  828. let call = 0
  829. api.onHistory = () => {
  830. call++
  831. return histResponse(call === 1 ? plainTurn(0, 0, 'a', 'b') : full)
  832. }
  833. // Baseline arrives before open: lastSeq 11 > first page tail 5 → doOpen repulls once.
  834. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  835. await session.open()
  836. expect(call).toBe(2)
  837. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  838. })
  839. it('a failed second stitch pull keeps the first window and still opens', async () => {
  840. const { api, session } = makeSession()
  841. let call = 0
  842. api.onHistory = () => {
  843. call++
  844. return call === 1
  845. ? histResponse(plainTurn(0, 0, 'a', 'b'))
  846. : Promise.resolve(err({ code: 'internal', message: 'stitch pull down', details: {} }))
  847. }
  848. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  849. await session.open()
  850. expect(call).toBe(2)
  851. const snapshot = session.getSnapshot()
  852. expect(snapshot.openState).toBe('open') // stitch-pull failure is not an open failure
  853. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3]) // first window kept
  854. })
  855. it('approval frame with callId/reason keeps the optional fields; duplicate resolved is a no-op', () => {
  856. const { session } = makeSession()
  857. session.handleMuxEnvelope('ra' as never, {
  858. type: 'approval/requested', sessionId: SID, approvalId: 'ap2' as never, toolName: 'rm', callId: 'c1' as never, reason: '危险',
  859. })
  860. expect(session.getSnapshot().pending[0]).toMatchObject({ kind: 'approval', payload: { callId: 'c1', reason: '危险' } })
  861. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  862. session.handleMuxEnvelope('rx2' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  863. session.handleMuxEnvelope('ry2' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'never-was' as never, outcome: 'cancelled' })
  864. expect(session.getSnapshot().pending).toEqual([])
  865. })
  866. it('ignores unknown mux frame types and repeated running flips (documented defaults)', () => {
  867. const { session } = makeSession()
  868. const before = session.getSnapshot()
  869. session.handleMuxEnvelope('rz' as never, { type: 'future/frame' } as never)
  870. session.handleRunning(false) // already false: dedup branch
  871. expect(session.getSnapshot()).toBe(before)
  872. session.handleRemoved()
  873. expect(session.getSnapshot().removed).toBe(true)
  874. })
  875. it('drops live events while cold/error (no window upkeep)', async () => {
  876. const { api, session } = makeSession()
  877. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '冷态帧') })
  878. expect(session.getSnapshot().nodes).toEqual([])
  879. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  880. await session.open()
  881. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '错态帧') })
  882. expect(session.getSnapshot().nodes).toEqual([])
  883. })
  884. it('repairGap failure logs and clears stitching; concurrent gaps coalesce into one repair', async () => {
  885. const { api, session } = makeSession()
  886. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  887. await session.open()
  888. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  889. let repairs = 0
  890. api.onHistory = () => {
  891. repairs++
  892. return gate.promise
  893. }
  894. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  895. try {
  896. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞一') })
  897. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(10, '洞二') }) // stitching: detours, no second repair
  898. expect(repairs).toBe(1)
  899. gate.reject(new Error('repair wire down'))
  900. await vi.waitFor(() => { expect(errorSpy).toHaveBeenCalled() })
  901. // Window unchanged; a later successful repull still lands the buffered frames.
  902. expect(session.getSnapshot().nodes).toHaveLength(2)
  903. } finally {
  904. errorSpy.mockRestore()
  905. }
  906. })
  907. it('freezes only content-bearing partials; a content-free partial is dropped outright', async () => {
  908. const { api, session } = makeSession()
  909. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  910. await session.open()
  911. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  912. feed(ev.turnStart(6, 1))
  913. feed(ev.chunkStart(7, 1)) // empty text block only, no delta
  914. feed(ev.turnEnd(8, 1, 'aborted'))
  915. const snapshot = session.getSnapshot()
  916. expect(snapshot.partial).toBeNull()
  917. expect(snapshot.nodes.filter(n => n.kind === 'assistant' && (n as { interrupted?: true }).interrupted)).toEqual([])
  918. })
  919. it('turn/end sweeps only same-turn open calls; other turns keep running', async () => {
  920. const { api, session } = makeSession()
  921. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  922. await session.open()
  923. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  924. feed(ev.turnStart(6, 1))
  925. feed(ev.toolCall(7, 1, 'turn1-call', 'echo', '{}'))
  926. feed(ev.toolCall(8, 2, 'turn2-call', 'echo', '{}')) // stray call attributed to a later turn
  927. feed(ev.turnEnd(9, 1, 'aborted'))
  928. const snapshot = session.getSnapshot()
  929. expect(snapshot.runningCalls.map(c => c.callId)).toEqual(['turn2-call'])
  930. expect(snapshot.nodes.at(-1)).toMatchObject({ kind: 'tool-result', callId: 'turn1-call', isError: true })
  931. })
  932. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  933. const { api, session } = makeSession()
  934. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  935. api.onHistory = () => stale.promise
  936. const opening = session.open()
  937. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  938. const resynced = session.resync()
  939. stale.reject(new Error('stale wire'))
  940. await Promise.all([opening, resynced])
  941. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  942. })
  943. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  944. const { api, session } = makeSession()
  945. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  946. api.onHistory = () => stale.promise
  947. const opening = session.open()
  948. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  949. const resynced = session.resync()
  950. stale.resolve(ok({
  951. events: entries(plainTurn(0, 0, '旧', '代')) as never[],
  952. hasMore: false,
  953. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  954. })) // success, but its generation is gone
  955. await Promise.all([opening, resynced])
  956. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9]) // only the fresh generation's window
  957. })
  958. it('drops a stale stitch pull (second doOpen fetch) superseded mid-flight by resync', async () => {
  959. const { api, session } = makeSession()
  960. const secondPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  961. let call = 0
  962. api.onHistory = () => {
  963. call++
  964. if (call === 1) return histResponse(plainTurn(0, 0, 'a', 'b')) // first page: tail 5
  965. if (call === 2) return secondPull.promise // gap-stitch pull: held
  966. return histResponse(plainTurn(6, 1, 'c', 'd'))
  967. }
  968. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  969. const opening = session.open() // triggers the second pull, which parks
  970. await vi.waitFor(() => { expect(call).toBe(2) })
  971. const resynced = session.resync()
  972. secondPull.resolve(ok({
  973. events: entries([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]) as never[],
  974. hasMore: false,
  975. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  976. }))
  977. await Promise.all([opening, resynced])
  978. expect(session.getSnapshot().openState).toBe('open')
  979. })
  980. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  981. const { api, session } = makeSession()
  982. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  983. await session.open()
  984. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  985. api.onHistory = () => repairPull.promise
  986. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞') }) // starts repairGap
  987. api.onHistory = () => histResponse(plainTurn(6, 1, 'c', 'd'))
  988. const resynced = session.resync() // bumps the generation
  989. repairPull.resolve(ok({
  990. events: entries(plainTurn(0, 0, '旧', '页')) as never[],
  991. hasMore: false,
  992. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  993. })) // repair result: stale, dropped
  994. await resynced
  995. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9])
  996. })
  997. it('successful cancel leaves no promptError; tool/result for an unknown callId is a no-op', async () => {
  998. const { api, session } = makeSession()
  999. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  1000. await session.open()
  1001. const result = await session.cancel()
  1002. expect(result.ok).toBe(true)
  1003. expect(session.getSnapshot().promptError).toBeNull()
  1004. const callsBefore = session.getSnapshot().runningCalls
  1005. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.toolResult(6, 0, 'never-called', 'x') })
  1006. expect(session.getSnapshot().runningCalls).toBe(callsBefore) // callsRev untouched: same reference
  1007. })
  1008. it('freezes a tool-call-only partial (visible through the non-text arm)', async () => {
  1009. const { api, session } = makeSession()
  1010. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  1011. await session.open()
  1012. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  1013. feed(ev.turnStart(6, 1))
  1014. feed(at(7, { type: 'assistant/chunk', data: { turn: 1, step: 0, chunk: { type: 'tool-call-delta', index: 0, id: 'c1', name: 'echo', argumentsDelta: '{' } } }))
  1015. feed(ev.turnEnd(8, 1, 'aborted'))
  1016. const frozen = session.getSnapshot().nodes.at(-1)
  1017. expect(frozen).toMatchObject({ kind: 'assistant', interrupted: true, blocks: [{ kind: 'tool-call', callId: 'c1' }] })
  1018. })
  1019. it('dispose is a reserved no-op on resident instances', () => {
  1020. const { session } = makeSession()
  1021. expect(() => { session.dispose() }).not.toThrow()
  1022. })
  1023. it('carries mux-frame views into runningCalls and tool-result nodes, and history-entry views through open', async () => {
  1024. const { api, session } = makeSession()
  1025. const callView = { for: 'call', view: { card: 'generic', title: '历史卡' } }
  1026. api.onHistory = () => Promise.resolve(ok({
  1027. events: [
  1028. ...entries(plainTurn(0, 0, 'a', 'b')),
  1029. { event: ev.toolCall(6, 1, 'h1', 'bash', '{}'), view: callView },
  1030. { event: ev.toolResult(7, 1, 'h1', 'done'), view: { for: 'result', view: { card: 'generic', title: '历史果' } } },
  1031. ] as never[],
  1032. hasMore: false,
  1033. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  1034. }))
  1035. await session.open()
  1036. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  1037. kind: 'tool-result', callView: { title: '历史卡' }, resultView: { title: '历史果' },
  1038. })
  1039. // Live path: the frame's view slot reaches runningCalls, then the result node.
  1040. session.handleMuxEnvelope('rv1' as never, {
  1041. type: 'session/event', sessionId: SID, event: ev.toolCall(8, 2, 'l1', 'write', '{}'),
  1042. view: { for: 'call', view: { card: 'generic', title: '直播卡' } },
  1043. } as never)
  1044. expect(session.getSnapshot().runningCalls).toMatchObject([{ callId: 'l1', callView: { title: '直播卡' } }])
  1045. session.handleMuxEnvelope('rv2' as never, {
  1046. type: 'session/event', sessionId: SID, event: ev.toolResult(9, 2, 'l1', 'ok'),
  1047. view: { for: 'result', view: { card: 'generic', title: '直播果' } },
  1048. } as never)
  1049. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  1050. kind: 'tool-result', callView: { title: '直播卡' }, resultView: { title: '直播果' },
  1051. })
  1052. })
  1053. })
  1054. describe('resync', () => {
  1055. it('rebuilds the window and clears pending; cold instances no-op', async () => {
  1056. const { api, session } = makeSession()
  1057. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  1058. await session.open()
  1059. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  1060. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')])
  1061. await session.resync()
  1062. const snapshot = session.getSnapshot()
  1063. expect(snapshot.openState).toBe('open')
  1064. expect(snapshot.pending).toEqual([]) // baseline replay re-sends still-pending frames
  1065. expect(snapshot.nodes).toHaveLength(4)
  1066. const cold = makeSession()
  1067. await cold.session.resync()
  1068. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  1069. })
  1070. it('re-mints a replayed requested frame as a fresh wait with the same key (old reference superseded)', async () => {
  1071. const { api, session } = makeSession()
  1072. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  1073. await session.open()
  1074. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  1075. const before = session.getSnapshot().pending[0]!
  1076. await session.resync()
  1077. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  1078. const after = session.getSnapshot().pending[0]!
  1079. expect(after).not.toBe(before)
  1080. expect(after.key).toBe(before.key)
  1081. // Superseded ≠ settled: an in-flight respond on the stale reference still reaches the host.
  1082. await before.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } })
  1083. expect(api.callsOf('respond')).toMatchObject([{ rpcId: 'rq-replay' }])
  1084. })
  1085. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  1086. const { api, session } = makeSession()
  1087. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  1088. api.onHistory = () => stale.promise
  1089. const firstOpen = session.open()
  1090. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  1091. const resynced = session.resync()
  1092. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  1093. await firstOpen
  1094. await resynced
  1095. const snapshot = session.getSnapshot()
  1096. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  1097. expect(snapshot.nodes.map(n => n.seq)).toEqual([7, 9])
  1098. })
  1099. })
  1100. describe('nested run_code sub-dispatches', () => {
  1101. const subCallsOf = (session: Session, callId: string) => {
  1102. const snapshot = session.getSnapshot()
  1103. const running = snapshot.runningCalls.find(call => call.callId === callId)
  1104. if (running !== undefined) return running.subCalls
  1105. for (const node of snapshot.nodes) {
  1106. if (node.kind === 'tool-result' && node.callId === callId) return node.subCalls
  1107. }
  1108. return undefined
  1109. }
  1110. it('a start event lands as a running-shaped sub-call and its settle replaces it in place', async () => {
  1111. const { api, session } = makeSession()
  1112. api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答'))
  1113. await session.open()
  1114. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  1115. feed(ev.turnStart(6, 1))
  1116. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"d"}'))
  1117. feed(ev.codeDispatchStart(8, 'p1', 1, 'bash', { command: 'sleep' }))
  1118. feed(ev.codeDispatchStart(9, 'p1', 2, 'read', { path: 'a.txt' }))
  1119. const live = subCallsOf(session, 'p1')
  1120. expect(live).toHaveLength(2)
  1121. // Running shape (no 'kind'): the exact RunningToolCall form native rows use.
  1122. expect(live?.[0]).toMatchObject({ callId: 'p1:code:1', name: 'bash', argsRaw: '{"command":"sleep"}' })
  1123. expect(live?.[0] !== undefined && 'kind' in live[0]).toBe(false)
  1124. // Settle out of order (parallel run): #2 first — replaces in place, keeping start order.
  1125. feed(ev.codeDispatch(10, 'p1', 2, 'read', { path: 'a.txt' }, 'alpha'))
  1126. const mixed = subCallsOf(session, 'p1')
  1127. expect(mixed?.map(sub => 'kind' in sub)).toEqual([false, true])
  1128. expect(mixed?.[1]).toMatchObject({ callId: 'p1:code:2', content: [{ type: 'text', text: 'alpha' }] })
  1129. // The settle carries the paired start's time as callTime (duration source).
  1130. feed(ev.codeDispatch(11, 'p1', 1, 'bash', { command: 'sleep' }, 'done'))
  1131. const settled = subCallsOf(session, 'p1')
  1132. expect(settled?.map(sub => 'kind' in sub)).toEqual([true, true])
  1133. expect(settled?.[0]).toMatchObject({ callId: 'p1:code:1', callTime: 1_700_000_000_008 })
  1134. })
  1135. it('indexes live tool/code-dispatch events under their parent as native-shaped result nodes', async () => {
  1136. const { api, session } = makeSession()
  1137. api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答'))
  1138. await session.open()
  1139. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  1140. feed(ev.turnStart(6, 1))
  1141. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"return 1","description":"跑一个程序"}'))
  1142. feed(ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls', description: '列目录' }, 'demo.txt'))
  1143. feed(ev.codeDispatch(9, 'p1', 2, 'read', { path: 'a.txt' }, 'Error: ENOENT', true))
  1144. const subs = subCallsOf(session, 'p1')
  1145. expect(subs).toHaveLength(2)
  1146. expect(subs?.[0]).toMatchObject({
  1147. kind: 'tool-result', callId: 'p1:code:1',
  1148. call: { name: 'bash', argsRaw: '{"command":"ls","description":"列目录"}' },
  1149. // The settle event carries no start time: callTime stays null (never a
  1150. // fabricated zero-duration).
  1151. callTime: null,
  1152. isError: false, content: [{ type: 'text', text: 'demo.txt' }],
  1153. })
  1154. expect(subs?.[1]).toMatchObject({ callId: 'p1:code:2', isError: true })
  1155. // No paired start in the window: duration is UNKNOWN (null), never a
  1156. // fabricated zero-duration span.
  1157. expect(subs?.[0]).toMatchObject({ callTime: null })
  1158. // Sub-dispatches never join the surface flow.
  1159. expect(session.getSnapshot().nodes.some(n => n.kind === 'tool-result' && n.callId.includes(':code:'))).toBe(false)
  1160. })
  1161. it('rebuilds the same nested tree from a history window (replay parity)', async () => {
  1162. const { api, session } = makeSession()
  1163. api.onHistory = () => histResponse([
  1164. ...plainTurn(0, 0, '问', '答'),
  1165. ev.turnStart(6, 1),
  1166. ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"return 1","description":"跑一个程序"}'),
  1167. ev.codeDispatchStart(8, 'p1', 1, 'run_code', { code: 'return tools.read({ path: "a.txt" })' }),
  1168. ev.codeDispatch(9, 'p1:code:1', 1, 'read', { path: 'a.txt' }, 'alpha'),
  1169. ev.codeDispatch(10, 'p1', 1, 'run_code', { code: 'return tools.read({ path: "a.txt" })' }, 'alpha'),
  1170. ev.toolResult(11, 1, 'p1', '{"done":true}'),
  1171. ev.turnEnd(12, 1),
  1172. ])
  1173. await session.open()
  1174. const subs = subCallsOf(session, 'p1')
  1175. expect(subs).toHaveLength(1)
  1176. expect(subs?.[0]).toMatchObject({
  1177. callId: 'p1:code:1',
  1178. call: { name: 'run_code' },
  1179. subCalls: [{ callId: 'p1:code:1:code:1', call: { name: 'read' } }],
  1180. })
  1181. })
  1182. it('keeps an unaffected root reference and path-copies it on a new child', async () => {
  1183. const { api, session } = makeSession()
  1184. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  1185. await session.open()
  1186. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  1187. feed(ev.turnStart(6, 1))
  1188. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"d"}'))
  1189. feed(ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls' }, 'x'))
  1190. const before = session.getSnapshot()
  1191. const beforeRoot = before.runningCalls.find(call => call.callId === 'p1')!
  1192. feed(ev.chunkStart(9, 1))
  1193. feed(ev.chunkText(10, 1, '流式'))
  1194. const after = session.getSnapshot()
  1195. const afterRoot = after.runningCalls.find(call => call.callId === 'p1')!
  1196. expect(afterRoot).toBe(beforeRoot)
  1197. feed(ev.codeDispatch(11, 'p1', 2, 'read', { path: 'a' }, 'y'))
  1198. const changedRoot = session.getSnapshot().runningCalls.find(call => call.callId === 'p1')!
  1199. expect(changedRoot).not.toBe(afterRoot)
  1200. expect(changedRoot.subCalls[0]).toBe(afterRoot.subCalls[0])
  1201. expect(changedRoot.subCalls).toHaveLength(2)
  1202. })
  1203. it('path-copies only the owning branch when a nested child changes', async () => {
  1204. const { api, session } = makeSession()
  1205. api.onHistory = () => histResponse(plainTurn(0, 0, '树', '结构'))
  1206. await session.open()
  1207. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  1208. feed(ev.turnStart(6, 1))
  1209. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"first"}'))
  1210. feed(ev.toolCall(8, 1, 'p2', 'run_code', '{"code":"2","description":"second"}'))
  1211. feed(ev.codeDispatch(9, 'p1', 1, 'run_code', { code: 'nested' }, 'child'))
  1212. feed(ev.codeDispatch(10, 'p1', 2, 'read', { path: 'sibling' }, 'sibling'))
  1213. feed(ev.codeDispatch(11, 'p2', 1, 'bash', { command: 'pwd' }, 'root two'))
  1214. const before = session.getSnapshot()
  1215. const beforeFirst = before.runningCalls.find(call => call.callId === 'p1')!
  1216. const beforeSecond = before.runningCalls.find(call => call.callId === 'p2')!
  1217. const beforeChild = beforeFirst.subCalls[0]!
  1218. const beforeSibling = beforeFirst.subCalls[1]!
  1219. feed(ev.codeDispatch(12, 'p1:code:1', 1, 'read', { path: 'nested' }, 'leaf'))
  1220. const after = session.getSnapshot()
  1221. const afterFirst = after.runningCalls.find(call => call.callId === 'p1')!
  1222. const afterSecond = after.runningCalls.find(call => call.callId === 'p2')!
  1223. expect(afterFirst).not.toBe(beforeFirst)
  1224. expect(afterSecond).toBe(beforeSecond)
  1225. expect(afterFirst.subCalls[0]).not.toBe(beforeChild)
  1226. expect(afterFirst.subCalls[1]).toBe(beforeSibling)
  1227. expect(afterFirst.subCalls[0]?.subCalls).toMatchObject([
  1228. { callId: 'p1:code:1:code:1', call: { name: 'read' } },
  1229. ])
  1230. })
  1231. })
  1232. describe('reference stability (the memo contract)', () => {
  1233. it('keeps unchanged node references across an append and swaps the snapshot object', async () => {
  1234. const { api, session } = makeSession()
  1235. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  1236. await session.open()
  1237. const before = session.getSnapshot()
  1238. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(6, '追加') })
  1239. const after = session.getSnapshot()
  1240. expect(after).not.toBe(before) // top-level swap on change
  1241. expect(after.nodes[0]).toBe(before.nodes[0]) // untouched nodes keep identity
  1242. expect(after.nodes[1]).toBe(before.nodes[1])
  1243. expect(after.nodes).toHaveLength(3)
  1244. // No change → same snapshot reference.
  1245. expect(session.getSnapshot()).toBe(after)
  1246. })
  1247. it('keeps untouched substructure arrays identical across unrelated changes (revision counters)', async () => {
  1248. const { api, session } = makeSession()
  1249. api.onHistory = () => histResponse(plainTurn(0, 0, '底', '座'))
  1250. await session.open()
  1251. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  1252. feed(ev.turnStart(6, 1))
  1253. feed(ev.stepStart(7, 1))
  1254. feed(ev.toolCall(8, 1, 'c1', 'echo', '{}'))
  1255. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  1256. const before = session.getSnapshot()
  1257. // A chunk storm touches partial/nodes only: unrelated projections keep identity.
  1258. feed(ev.chunkStart(9, 1))
  1259. feed(ev.chunkText(10, 1, '与工具无关的流式'))
  1260. const after = session.getSnapshot()
  1261. expect(after).not.toBe(before)
  1262. expect(after.runningCalls).toBe(before.runningCalls)
  1263. expect(after.pending).toBe(before.pending)
  1264. expect(after.turnTimings).toBe(before.turnTimings)
  1265. expect(after.turnEnds).toBe(before.turnEnds)
  1266. // And a mutation on the tracked domain swaps that array.
  1267. feed(ev.toolResult(11, 1, 'c1', 'ECHO'))
  1268. const resolved = session.getSnapshot()
  1269. expect(resolved.runningCalls).not.toBe(after.runningCalls)
  1270. expect(resolved.pending).toBe(after.pending)
  1271. feed(ev.assistant(12, 1, '完成'))
  1272. expect(session.getSnapshot()).not.toBe(resolved)
  1273. })
  1274. })