session.spec.ts 61 KB

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