session.spec.ts 59 KB

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