session.spec.ts 65 KB

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