session.spec.ts 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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 type { SessionId } from '@deepseek-ai/dsh-client-connection/client'
  11. import { Session } from '../src/client/sessions/session.ts'
  12. import { FakeApiClient, deferred, err, ok } from './fake-api.ts'
  13. import { entries, ev, plainTurn } from './event-script.ts'
  14. const at = (seq: number, e: Record<string, unknown>): SessionEvent =>
  15. ({ seq, time: 1_700_000_000_000 + seq, ...e }) as unknown as SessionEvent
  16. const SID = 'fk-s1' as SessionId
  17. function makeSession(api = new FakeApiClient()): { api: FakeApiClient; session: Session } {
  18. return { api, session: new Session(SID, api) }
  19. }
  20. function histResponse(events: SessionEvent[], hasMore = false) {
  21. // history now returns HistoryEntry[] ({event, view?}); these tests are view-less.
  22. return Promise.resolve(ok({ events: entries(events) as never[], hasMore }))
  23. }
  24. describe('open', () => {
  25. it('installs the tail page: cold → loading → open with window and nodes in place', async () => {
  26. const { api, session } = makeSession()
  27. const page = plainTurn(10, 3, '问', '答')
  28. api.onHistory = () => histResponse(page, true)
  29. expect(session.getSnapshot().openState).toBe('cold')
  30. const opening = session.open()
  31. expect(session.getSnapshot().openState).toBe('loading')
  32. await opening
  33. const snapshot = session.getSnapshot()
  34. expect(snapshot.openState).toBe('open')
  35. expect(snapshot.hasMore).toBe(true)
  36. expect(snapshot.nodes.map(n => n.kind)).toEqual(['user', 'assistant'])
  37. })
  38. it('is idempotent: concurrent opens share one history call, reopening when open is a no-op', async () => {
  39. const { api, session } = makeSession()
  40. await Promise.all([session.open(), session.open()])
  41. await session.open()
  42. expect(api.callsOf('session.history')).toHaveLength(1)
  43. })
  44. it('lands an error result in openState=error with the RpcError kept', async () => {
  45. const { api, session } = makeSession()
  46. api.onHistory = () => Promise.resolve(err({ code: 'session-not-found', message: 'gone', details: { sessionId: SID } }))
  47. await session.open()
  48. const snapshot = session.getSnapshot()
  49. expect(snapshot.openState).toBe('error')
  50. expect(snapshot.openError?.code).toBe('session-not-found')
  51. })
  52. it('folds a transport throw into openState=error / internal', async () => {
  53. const { api, session } = makeSession()
  54. api.onHistory = () => Promise.reject(new Error('socket died'))
  55. await session.open()
  56. expect(session.getSnapshot().openState).toBe('error')
  57. expect(session.getSnapshot().openError).toMatchObject({ code: 'internal', message: 'socket died' })
  58. })
  59. it('stitches live frames arriving while history is pending, dropping the page overlap', async () => {
  60. const { api, session } = makeSession()
  61. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  62. api.onHistory = () => gate.promise
  63. const opening = session.open()
  64. // Three live frames land mid-open; seq 15 overlaps the page tail (page covers 10..15).
  65. const page = plainTurn(10, 0, '早', '安')
  66. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.turnStart(15, 1) })
  67. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(16, '插进来的') })
  68. gate.resolve(ok({
  69. events: entries(page) as never[],
  70. hasMore: false,
  71. modelTarget: { provider: 'deepseek', model: 'deepseek-v4-flash' },
  72. }))
  73. await opening
  74. const seqs = session.getSnapshot().nodes.map(n => n.seq)
  75. // Overlapping seq-15 frame (== page tail turn/end) was dropped; 16 appended once.
  76. expect(seqs).toEqual([11, 13, 16])
  77. })
  78. })
  79. describe('live event path', () => {
  80. async function opened(events: SessionEvent[] = plainTurn(0, 0, 'a', 'b')) {
  81. const { api, session } = makeSession()
  82. api.onHistory = () => histResponse(events)
  83. await session.open()
  84. return { api, session }
  85. }
  86. it('drops replayed frames at or below the window tail', async () => {
  87. const { session } = await opened()
  88. const before = session.getSnapshot()
  89. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(3, '重放') })
  90. await Promise.resolve()
  91. expect(session.getSnapshot().nodes).toEqual(before.nodes)
  92. })
  93. it('materializes a command node from live lifecycle frames and reproduces it from a history window', async () => {
  94. // Live path: run mints an executing node, done settles it in the flow.
  95. const { session } = await opened()
  96. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  97. feed(ev.commandRun(6, 'cmd-live', 'plan'))
  98. let command = session.getSnapshot().nodes.at(-1)
  99. expect(command).toMatchObject({ kind: 'command', name: 'plan', args: '', outcome: null })
  100. feed(ev.commandDone(7, 'cmd-live', 'success', '已进入 plan mode'))
  101. command = session.getSnapshot().nodes.at(-1)
  102. expect(command).toMatchObject({ kind: 'command', seq: 6, outcome: { kind: 'success', text: '已进入 plan mode' } })
  103. // Replay path (refresh): the same pair inside the history window folds identically.
  104. const replayed = await opened([
  105. ...plainTurn(0, 0, 'a', 'b'),
  106. ev.commandRun(6, 'cmd-live', 'plan'),
  107. ev.commandDone(7, 'cmd-live', 'success', '已进入 plan mode'),
  108. ])
  109. expect(replayed.session.getSnapshot().nodes.at(-1)).toMatchObject({
  110. kind: 'command', seq: 6, name: 'plan', outcome: { kind: 'success', text: '已进入 plan mode' },
  111. })
  112. })
  113. it('accumulates chunks into partial, then finalize swaps partial out as the node lands', async () => {
  114. const { session } = await opened()
  115. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  116. feed(ev.turnStart(6, 1))
  117. feed(ev.user(7, '流式问'))
  118. feed(ev.chunkStart(8, 1))
  119. feed(ev.chunkText(9, 1, '半截'))
  120. let snapshot = session.getSnapshot()
  121. expect(snapshot.partial).toMatchObject({ turn: 1, blocks: [{ kind: 'text', text: '半截' }] })
  122. feed(ev.chunkText(10, 1, '回复'))
  123. expect(session.getSnapshot().partial?.blocks).toEqual([{ kind: 'text', text: '半截回复' }])
  124. feed(ev.assistant(11, 1, '半截回复'))
  125. feed(ev.turnEnd(12, 1))
  126. snapshot = session.getSnapshot()
  127. expect(snapshot.partial).toBeNull()
  128. const last = snapshot.nodes.at(-1)
  129. expect(last).toMatchObject({ kind: 'assistant', blocks: [{ kind: 'text', text: '半截回复' }] })
  130. expect((last as { interrupted?: true }).interrupted).toBeUndefined()
  131. })
  132. it('freezes an unfinalized partial into an interrupted node on turn/end (cancel path)', async () => {
  133. const { session } = await opened()
  134. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  135. feed(ev.turnStart(6, 1))
  136. feed(ev.user(7, '要被打断的'))
  137. feed(ev.chunkStart(8, 1))
  138. feed(ev.chunkText(9, 1, '说到一半'))
  139. feed(ev.turnEnd(10, 1, 'cancelled')) // no assistant/message ever arrives
  140. const snapshot = session.getSnapshot()
  141. expect(snapshot.partial).toBeNull()
  142. const frozen = snapshot.nodes.at(-1)
  143. expect(frozen).toMatchObject({ kind: 'assistant', interrupted: true, blocks: [{ kind: 'text', text: '说到一半' }] })
  144. // Ordered inside the flow: after the user message (seq 7), before any later turn.
  145. expect((frozen as { seq: number }).seq).toBeGreaterThan(7)
  146. })
  147. it('tracks tool calls in runningCalls and converts orphans to interrupted tool-result cards on turn/end', async () => {
  148. const { session } = await opened()
  149. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  150. feed(ev.turnStart(6, 1))
  151. feed(ev.toolCall(7, 1, 'c1', 'echo', '{"a":1}'))
  152. expect(session.getSnapshot().runningCalls).toMatchObject([{ callId: 'c1', name: 'echo' }])
  153. feed(ev.toolResult(8, 1, 'c1', 'ECHO'))
  154. expect(session.getSnapshot().runningCalls).toEqual([])
  155. // Second call never resolves: turn/end freezes it as an error card.
  156. feed(ev.toolCall(9, 1, 'c2', 'slow_tool', '{}'))
  157. feed(ev.turnEnd(10, 1, 'cancelled'))
  158. const snapshot = session.getSnapshot()
  159. expect(snapshot.runningCalls).toEqual([])
  160. expect(snapshot.nodes.at(-1)).toMatchObject({
  161. kind: 'tool-result', callId: 'c2', isError: true, error: { code: 'interrupted' },
  162. })
  163. })
  164. it('repairs a seq gap by repulling the tail page instead of appending a hole', async () => {
  165. const { api, session } = await opened(plainTurn(0, 0, 'a', 'b')) // tail seq = 5
  166. const repaired = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  167. api.onHistory = () => histResponse(repaired)
  168. // seq 9 with tail 5 → gap; the event detours to the buffer and one history refetch fires.
  169. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.assistant(9, 1, 'd') })
  170. await vi.waitFor(() => {
  171. expect(api.callsOf('session.history').length).toBe(2)
  172. })
  173. await Promise.resolve()
  174. const seqs = session.getSnapshot().nodes.map(n => n.seq)
  175. expect(seqs).toEqual([1, 3, 7, 9]) // both turns' user/assistant, no hole, no duplicate 9
  176. })
  177. })
  178. describe('paging', () => {
  179. it('prepends an older page and keeps seq continuity', async () => {
  180. const older = plainTurn(0, 0, '旧问', '旧答')
  181. const newer = plainTurn(6, 1, '新问', '新答')
  182. const { api, session } = makeSession()
  183. api.onHistory = payload => payload.beforeSeq === undefined
  184. ? histResponse(newer, true)
  185. : histResponse(older, false)
  186. await session.open()
  187. await session.loadOlder()
  188. const snapshot = session.getSnapshot()
  189. expect(api.callsOf('session.history')).toMatchObject([{}, { beforeSeq: 6 }].map(p => ({ sessionId: SID, ...p })))
  190. expect(snapshot.hasMore).toBe(false)
  191. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  192. })
  193. it('drops a discontinuous older page fail-soft (window unchanged, hasMore cleared)', async () => {
  194. const { api, session } = makeSession()
  195. api.onHistory = payload => payload.beforeSeq === undefined
  196. ? histResponse(plainTurn(10, 1, '新', '页'), true)
  197. : histResponse(plainTurn(0, 0, '断', '层'), true) // tail seq 5, but baseSeq is 10 → hole
  198. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  199. try {
  200. await session.open()
  201. const nodesBefore = session.getSnapshot().nodes
  202. await session.loadOlder()
  203. const snapshot = session.getSnapshot()
  204. expect(snapshot.nodes).toEqual(nodesBefore)
  205. expect(snapshot.hasMore).toBe(false)
  206. } finally {
  207. errorSpy.mockRestore()
  208. }
  209. })
  210. it('ignores loadOlder while one is in flight (single request)', async () => {
  211. const { api, session } = makeSession()
  212. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  213. await session.open()
  214. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  215. api.onHistory = () => gate.promise
  216. const first = session.loadOlder()
  217. const second = session.loadOlder()
  218. gate.resolve(ok({
  219. events: entries(plainTurn(0, 0, 'a', 'b')) as never[],
  220. hasMore: false,
  221. modelTarget: { provider: 'deepseek', model: 'deepseek-v4-flash' },
  222. }))
  223. await Promise.all([first, second])
  224. expect(api.callsOf('session.history')).toHaveLength(2) // open + one page, not two
  225. })
  226. })
  227. describe('prompt and cancel errors', () => {
  228. it('sends content through session.prompt; composerPhase steps blank → engaging synchronously at send entry', async () => {
  229. const { api, session } = makeSession()
  230. // The blank → engaging edge fires before the RPC settles: the first-send
  231. // flow reads the phase on the session area's first frame to keep the
  232. // guidance hero from flashing back in.
  233. expect(session.getSnapshot().composerPhase).toBe('blank')
  234. const inFlight = session.prompt([{ type: 'text', text: '要发的' }], 'queue')
  235. expect(session.getSnapshot().composerPhase).toBe('engaging')
  236. const result = await inFlight
  237. expect(result.ok).toBe(true)
  238. // Monotone: settlement alone does not step the phase anywhere.
  239. expect(session.getSnapshot().composerPhase).toBe('engaging')
  240. expect(api.callsOf('session.prompt')).toMatchObject([{ sessionId: SID, mode: 'queue', content: [{ type: 'text', text: '要发的' }] }])
  241. // First content lands (running turn): engaging → active.
  242. session.handleRunning(true)
  243. expect(session.getSnapshot().composerPhase).toBe('active')
  244. })
  245. it('business failure lands in promptError with op=send; the phase stays engaging (retry, no hero bounce)', async () => {
  246. const { api, session } = makeSession()
  247. api.onPrompt = () => Promise.resolve(err({ code: 'agent-busy', message: 'busy', details: { reason: 'x' } }))
  248. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue')
  249. expect(result.ok).toBe(false)
  250. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'agent-busy' } })
  251. // Failed first prompt: composer + error strip is the retry surface —
  252. // blank is unreachable once a send was initiated.
  253. expect(session.getSnapshot().composerPhase).toBe('engaging')
  254. })
  255. it('lands cancel failures in promptError with op=stop', async () => {
  256. const { api, session } = makeSession()
  257. api.onCancel = () => Promise.reject(new Error('cancel transport down'))
  258. const result = await session.cancel()
  259. expect(result.ok).toBe(false)
  260. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'internal' } })
  261. })
  262. })
  263. describe('pending interactions', () => {
  264. it('adds approval/question on requested and removes them on resolved', async () => {
  265. const { session } = makeSession()
  266. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  267. session.handleMuxEnvelope('rq' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  268. expect(session.getSnapshot().pending.map(p => p.kind).sort()).toEqual(['approval', 'question'])
  269. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap1' as never, outcome: 'approved' as never })
  270. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq' as never, outcome: 'answered' })
  271. expect(session.getSnapshot().pending).toEqual([])
  272. })
  273. it('mints waits whose respond() backfills the requested rpcId into the client-response envelope', async () => {
  274. const { api, session } = makeSession()
  275. session.handleMuxEnvelope('rq-answer' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  276. const wait = session.getSnapshot().pending[0]!
  277. expect(wait).toMatchObject({ kind: 'question', key: 'q:rq-answer', sessionId: SID, payload: { questions: [] } })
  278. const receipt = await wait.respond({
  279. ok: true,
  280. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  281. })
  282. expect(receipt).toEqual({ accepted: true })
  283. expect(api.callsOf('respond')).toEqual([{
  284. type: 'client-response', rpcId: 'rq-answer',
  285. result: {
  286. ok: true,
  287. value: { sessionId: SID, answer: { answers: [{ id: 'mode', selected: ['Fast'] }] } },
  288. },
  289. }])
  290. })
  291. it('settles the wait on the authoritative resolved frame: respond() then throws synchronously', async () => {
  292. const { api, session } = makeSession()
  293. session.handleMuxEnvelope('rq1' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  294. const wait = session.getSnapshot().pending[0]!
  295. session.handleMuxEnvelope('ry' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'rq1' as never, outcome: 'answered' })
  296. expect(session.getSnapshot().pending).toEqual([])
  297. expect(() => wait.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } }))
  298. .toThrow('already settled')
  299. expect(api.callsOf('respond')).toEqual([])
  300. })
  301. })
  302. describe('remaining branches', () => {
  303. it('prompt transport throw folds to internal promptError', async () => {
  304. const { api, session } = makeSession()
  305. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  306. const result = await session.prompt([{ type: 'text', text: 'x' }], 'queue')
  307. expect(result.ok).toBe(false)
  308. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'internal', message: 'prompt wire down' } })
  309. })
  310. it('cancel business error also lands op=stop promptError', async () => {
  311. const { api, session } = makeSession()
  312. api.onCancel = () => Promise.resolve(err({ code: 'agent-busy', message: 'nope', details: { reason: 'r' } }))
  313. await session.cancel()
  314. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'agent-busy' } })
  315. })
  316. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  317. const { api, session } = makeSession()
  318. await session.loadOlder() // cold: no-op, zero calls
  319. expect(api.calls).toEqual([])
  320. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  321. await session.open()
  322. // err result: window unchanged
  323. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  324. await session.loadOlder()
  325. expect(session.getSnapshot().nodes).toHaveLength(2)
  326. expect(session.getSnapshot().hasMore).toBe(true)
  327. // empty page: hasMore adopts the response
  328. api.onHistory = () => histResponse([], false)
  329. await session.loadOlder()
  330. expect(session.getSnapshot().hasMore).toBe(false)
  331. // hasMore false now: further loadOlder is a guard no-op
  332. const calls = api.calls.length
  333. await session.loadOlder()
  334. expect(api.calls.length).toBe(calls)
  335. // throw path: fail-soft with console.error
  336. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  337. try {
  338. await session.resync()
  339. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  340. await session.resync()
  341. api.onHistory = () => Promise.reject(new Error('page wire down'))
  342. await session.loadOlder()
  343. expect(errorSpy).toHaveBeenCalled()
  344. expect(session.getSnapshot().loadingOlder).toBe(false)
  345. } finally {
  346. errorSpy.mockRestore()
  347. }
  348. })
  349. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  350. const { api, session } = makeSession()
  351. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  352. let notified = 0
  353. const unsubscribe = session.subscribe(() => { notified++ })
  354. await session.open()
  355. await new Promise(resolve => setTimeout(resolve, 0))
  356. expect(notified).toBeGreaterThan(0)
  357. const seen = notified
  358. unsubscribe()
  359. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  360. await new Promise(resolve => setTimeout(resolve, 0))
  361. expect(notified).toBe(seen)
  362. })
  363. it('subscribed baseline past the window tail triggers the second stitch pull in doOpen', async () => {
  364. const { api, session } = makeSession()
  365. const full = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  366. let call = 0
  367. api.onHistory = () => {
  368. call++
  369. return histResponse(call === 1 ? plainTurn(0, 0, 'a', 'b') : full)
  370. }
  371. // Baseline arrives before open: lastSeq 11 > first page tail 5 → doOpen repulls once.
  372. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  373. await session.open()
  374. expect(call).toBe(2)
  375. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([1, 3, 7, 9])
  376. })
  377. it('a failed second stitch pull keeps the first window and still opens', async () => {
  378. const { api, session } = makeSession()
  379. let call = 0
  380. api.onHistory = () => {
  381. call++
  382. return call === 1
  383. ? histResponse(plainTurn(0, 0, 'a', 'b'))
  384. : Promise.resolve(err({ code: 'internal', message: 'stitch pull down', details: {} }))
  385. }
  386. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  387. await session.open()
  388. expect(call).toBe(2)
  389. const snapshot = session.getSnapshot()
  390. expect(snapshot.openState).toBe('open') // stitch-pull failure is not an open failure
  391. expect(snapshot.nodes.map(n => n.seq)).toEqual([1, 3]) // first window kept
  392. })
  393. it('approval frame with callId/reason keeps the optional fields; duplicate resolved is a no-op', () => {
  394. const { session } = makeSession()
  395. session.handleMuxEnvelope('ra' as never, {
  396. type: 'approval/requested', sessionId: SID, approvalId: 'ap2' as never, toolName: 'rm', callId: 'c1' as never, reason: '危险',
  397. })
  398. expect(session.getSnapshot().pending[0]).toMatchObject({ kind: 'approval', payload: { callId: 'c1', reason: '危险' } })
  399. session.handleMuxEnvelope('rx' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  400. session.handleMuxEnvelope('rx2' as never, { type: 'approval/resolved', sessionId: SID, approvalId: 'ap2' as never, outcome: 'approved' as never })
  401. session.handleMuxEnvelope('ry2' as never, { type: 'question/resolved', sessionId: SID, questionRpcId: 'never-was' as never, outcome: 'cancelled' })
  402. expect(session.getSnapshot().pending).toEqual([])
  403. })
  404. it('ignores unknown mux frame types and repeated running flips (documented defaults)', () => {
  405. const { session } = makeSession()
  406. const before = session.getSnapshot()
  407. session.handleMuxEnvelope('rz' as never, { type: 'future/frame' } as never)
  408. session.handleRunning(false) // already false: dedup branch
  409. expect(session.getSnapshot()).toBe(before)
  410. session.handleRemoved()
  411. expect(session.getSnapshot().removed).toBe(true)
  412. })
  413. it('drops live events while cold/error (no window upkeep)', async () => {
  414. const { api, session } = makeSession()
  415. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '冷态帧') })
  416. expect(session.getSnapshot().nodes).toEqual([])
  417. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  418. await session.open()
  419. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(0, '错态帧') })
  420. expect(session.getSnapshot().nodes).toEqual([])
  421. })
  422. it('repairGap failure logs and clears stitching; concurrent gaps coalesce into one repair', async () => {
  423. const { api, session } = makeSession()
  424. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  425. await session.open()
  426. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  427. let repairs = 0
  428. api.onHistory = () => {
  429. repairs++
  430. return gate.promise
  431. }
  432. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  433. try {
  434. session.handleMuxEnvelope('r1' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞一') })
  435. session.handleMuxEnvelope('r2' as never, { type: 'session/event', sessionId: SID, event: ev.user(10, '洞二') }) // stitching: detours, no second repair
  436. expect(repairs).toBe(1)
  437. gate.reject(new Error('repair wire down'))
  438. await vi.waitFor(() => { expect(errorSpy).toHaveBeenCalled() })
  439. // Window unchanged; a later successful repull still lands the buffered frames.
  440. expect(session.getSnapshot().nodes).toHaveLength(2)
  441. } finally {
  442. errorSpy.mockRestore()
  443. }
  444. })
  445. it('freezes only content-bearing partials; a content-free partial is dropped outright', async () => {
  446. const { api, session } = makeSession()
  447. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  448. await session.open()
  449. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  450. feed(ev.turnStart(6, 1))
  451. feed(ev.chunkStart(7, 1)) // empty text block only, no delta
  452. feed(ev.turnEnd(8, 1, 'cancelled'))
  453. const snapshot = session.getSnapshot()
  454. expect(snapshot.partial).toBeNull()
  455. expect(snapshot.nodes.filter(n => n.kind === 'assistant' && (n as { interrupted?: true }).interrupted)).toEqual([])
  456. })
  457. it('turn/end sweeps only same-turn open calls; other turns keep running', async () => {
  458. const { api, session } = makeSession()
  459. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  460. await session.open()
  461. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  462. feed(ev.turnStart(6, 1))
  463. feed(ev.toolCall(7, 1, 'turn1-call', 'echo', '{}'))
  464. feed(ev.toolCall(8, 2, 'turn2-call', 'echo', '{}')) // stray call attributed to a later turn
  465. feed(ev.turnEnd(9, 1, 'cancelled'))
  466. const snapshot = session.getSnapshot()
  467. expect(snapshot.runningCalls.map(c => c.callId)).toEqual(['turn2-call'])
  468. expect(snapshot.nodes.at(-1)).toMatchObject({ kind: 'tool-result', callId: 'turn1-call', isError: true })
  469. })
  470. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  471. const { api, session } = makeSession()
  472. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  473. api.onHistory = () => stale.promise
  474. const opening = session.open()
  475. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  476. const resynced = session.resync()
  477. stale.reject(new Error('stale wire'))
  478. await Promise.all([opening, resynced])
  479. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  480. })
  481. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  482. const { api, session } = makeSession()
  483. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  484. api.onHistory = () => stale.promise
  485. const opening = session.open()
  486. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  487. const resynced = session.resync()
  488. stale.resolve(ok({
  489. events: entries(plainTurn(0, 0, '旧', '代')) as never[],
  490. hasMore: false,
  491. modelTarget: { provider: 'deepseek', model: 'stale' },
  492. })) // success, but its generation is gone
  493. await Promise.all([opening, resynced])
  494. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9]) // only the fresh generation's window
  495. })
  496. it('drops a stale stitch pull (second doOpen fetch) superseded mid-flight by resync', async () => {
  497. const { api, session } = makeSession()
  498. const secondPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  499. let call = 0
  500. api.onHistory = () => {
  501. call++
  502. if (call === 1) return histResponse(plainTurn(0, 0, 'a', 'b')) // first page: tail 5
  503. if (call === 2) return secondPull.promise // gap-stitch pull: held
  504. return histResponse(plainTurn(6, 1, 'c', 'd'))
  505. }
  506. session.handleMuxEnvelope('rs' as never, { type: 'session/subscribed', sessionId: SID, lastSeq: 11 })
  507. const opening = session.open() // triggers the second pull, which parks
  508. await vi.waitFor(() => { expect(call).toBe(2) })
  509. const resynced = session.resync()
  510. secondPull.resolve(ok({
  511. events: entries([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]) as never[],
  512. hasMore: false,
  513. modelTarget: { provider: 'deepseek', model: 'stale' },
  514. }))
  515. await Promise.all([opening, resynced])
  516. expect(session.getSnapshot().openState).toBe('open')
  517. })
  518. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  519. const { api, session } = makeSession()
  520. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  521. await session.open()
  522. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  523. api.onHistory = () => repairPull.promise
  524. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(9, '洞') }) // starts repairGap
  525. api.onHistory = () => histResponse(plainTurn(6, 1, 'c', 'd'))
  526. const resynced = session.resync() // bumps the generation
  527. repairPull.resolve(ok({
  528. events: entries(plainTurn(0, 0, '旧', '页')) as never[],
  529. hasMore: false,
  530. modelTarget: { provider: 'deepseek', model: 'stale' },
  531. })) // repair result: stale, dropped
  532. await resynced
  533. expect(session.getSnapshot().nodes.map(n => n.seq)).toEqual([7, 9])
  534. })
  535. it('successful cancel leaves no promptError; tool/result for an unknown callId is a no-op', async () => {
  536. const { api, session } = makeSession()
  537. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  538. await session.open()
  539. const result = await session.cancel()
  540. expect(result.ok).toBe(true)
  541. expect(session.getSnapshot().promptError).toBeNull()
  542. const callsBefore = session.getSnapshot().runningCalls
  543. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.toolResult(6, 0, 'never-called', 'x') })
  544. expect(session.getSnapshot().runningCalls).toBe(callsBefore) // callsRev untouched: same reference
  545. })
  546. it('freezes a tool-call-only partial (visible through the non-text arm)', async () => {
  547. const { api, session } = makeSession()
  548. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  549. await session.open()
  550. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  551. feed(ev.turnStart(6, 1))
  552. feed(at(7, { type: 'assistant/chunk', data: { turn: 1, step: 0, chunk: { type: 'tool-call-delta', index: 0, id: 'c1', name: 'echo', argumentsDelta: '{' } } }))
  553. feed(ev.turnEnd(8, 1, 'cancelled'))
  554. const frozen = session.getSnapshot().nodes.at(-1)
  555. expect(frozen).toMatchObject({ kind: 'assistant', interrupted: true, blocks: [{ kind: 'tool-call', callId: 'c1' }] })
  556. })
  557. it('dispose is a reserved no-op on resident instances', () => {
  558. const { session } = makeSession()
  559. expect(() => { session.dispose() }).not.toThrow()
  560. })
  561. it('carries mux-frame views into runningCalls and tool-result nodes, and history-entry views through open', async () => {
  562. const { api, session } = makeSession()
  563. const callView = { for: 'call', view: { card: 'generic', title: '历史卡' } }
  564. api.onHistory = () => Promise.resolve(ok({
  565. events: [
  566. ...entries(plainTurn(0, 0, 'a', 'b')),
  567. { event: ev.toolCall(6, 1, 'h1', 'bash', '{}'), view: callView },
  568. { event: ev.toolResult(7, 1, 'h1', 'done'), view: { for: 'result', view: { card: 'generic', title: '历史果' } } },
  569. ] as never[],
  570. hasMore: false,
  571. modelTarget: { provider: 'deepseek', model: 'deepseek-v4-flash' },
  572. }))
  573. await session.open()
  574. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  575. kind: 'tool-result', callView: { title: '历史卡' }, resultView: { title: '历史果' },
  576. })
  577. // Live path: the frame's view slot reaches runningCalls, then the result node.
  578. session.handleMuxEnvelope('rv1' as never, {
  579. type: 'session/event', sessionId: SID, event: ev.toolCall(8, 2, 'l1', 'write', '{}'),
  580. view: { for: 'call', view: { card: 'generic', title: '直播卡' } },
  581. } as never)
  582. expect(session.getSnapshot().runningCalls).toMatchObject([{ callId: 'l1', callView: { title: '直播卡' } }])
  583. session.handleMuxEnvelope('rv2' as never, {
  584. type: 'session/event', sessionId: SID, event: ev.toolResult(9, 2, 'l1', 'ok'),
  585. view: { for: 'result', view: { card: 'generic', title: '直播果' } },
  586. } as never)
  587. expect(session.getSnapshot().nodes.at(-1)).toMatchObject({
  588. kind: 'tool-result', callView: { title: '直播卡' }, resultView: { title: '直播果' },
  589. })
  590. })
  591. })
  592. describe('resync', () => {
  593. it('rebuilds the window and clears pending; cold instances no-op', async () => {
  594. const { api, session } = makeSession()
  595. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  596. await session.open()
  597. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  598. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')])
  599. await session.resync()
  600. const snapshot = session.getSnapshot()
  601. expect(snapshot.openState).toBe('open')
  602. expect(snapshot.pending).toEqual([]) // baseline replay re-sends still-pending frames
  603. expect(snapshot.nodes).toHaveLength(4)
  604. const cold = makeSession()
  605. await cold.session.resync()
  606. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  607. })
  608. it('re-mints a replayed requested frame as a fresh wait with the same key (old reference superseded)', async () => {
  609. const { api, session } = makeSession()
  610. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  611. await session.open()
  612. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  613. const before = session.getSnapshot().pending[0]!
  614. await session.resync()
  615. session.handleMuxEnvelope('rq-replay' as never, { type: 'question/requested', sessionId: SID, questions: [] })
  616. const after = session.getSnapshot().pending[0]!
  617. expect(after).not.toBe(before)
  618. expect(after.key).toBe(before.key)
  619. // Superseded ≠ settled: an in-flight respond on the stale reference still reaches the host.
  620. await before.respond({ ok: false, error: { code: 'internal', message: 'x', details: {} } })
  621. expect(api.callsOf('respond')).toMatchObject([{ rpcId: 'rq-replay' }])
  622. })
  623. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  624. const { api, session } = makeSession()
  625. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  626. api.onHistory = () => stale.promise
  627. const firstOpen = session.open()
  628. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  629. const resynced = session.resync()
  630. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  631. await firstOpen
  632. await resynced
  633. const snapshot = session.getSnapshot()
  634. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  635. expect(snapshot.nodes.map(n => n.seq)).toEqual([7, 9])
  636. })
  637. })
  638. describe('run_code sub-dispatch indexing', () => {
  639. it('a start event lands as a running-shaped sub-call and its settle replaces it in place', async () => {
  640. const { api, session } = makeSession()
  641. api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答'))
  642. await session.open()
  643. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  644. feed(ev.turnStart(6, 1))
  645. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"d"}'))
  646. feed(ev.codeDispatchStart(8, 'p1', 1, 'bash', { command: 'sleep' }))
  647. feed(ev.codeDispatchStart(9, 'p1', 2, 'read', { path: 'a.txt' }))
  648. const live = session.getSnapshot().codeDispatches.get('p1')
  649. expect(live).toHaveLength(2)
  650. // Running shape (no 'kind'): the exact RunningToolCall form native rows use.
  651. expect(live?.[0]).toMatchObject({ callId: 'p1:code:1', name: 'bash', argsRaw: '{"command":"sleep"}' })
  652. expect(live?.[0] !== undefined && 'kind' in live[0]).toBe(false)
  653. // Settle out of order (parallel run): #2 first — replaces in place, keeping start order.
  654. feed(ev.codeDispatch(10, 'p1', 2, 'read', { path: 'a.txt' }, 'alpha'))
  655. const mixed = session.getSnapshot().codeDispatches.get('p1')
  656. expect(mixed?.map(sub => 'kind' in sub)).toEqual([false, true])
  657. expect(mixed?.[1]).toMatchObject({ callId: 'p1:code:2', content: [{ type: 'text', text: 'alpha' }] })
  658. // The settle carries the paired start's time as callTime (duration source).
  659. feed(ev.codeDispatch(11, 'p1', 1, 'bash', { command: 'sleep' }, 'done'))
  660. const settled = session.getSnapshot().codeDispatches.get('p1')
  661. expect(settled?.map(sub => 'kind' in sub)).toEqual([true, true])
  662. expect(settled?.[0]).toMatchObject({ callId: 'p1:code:1', callTime: 1_700_000_000_008 })
  663. })
  664. it('indexes live tool/code-dispatch events under their parent as native-shaped result nodes', async () => {
  665. const { api, session } = makeSession()
  666. api.onHistory = () => histResponse(plainTurn(0, 0, '问', '答'))
  667. await session.open()
  668. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  669. feed(ev.turnStart(6, 1))
  670. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"return 1","description":"跑一个程序"}'))
  671. feed(ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls', description: '列目录' }, 'demo.txt'))
  672. feed(ev.codeDispatch(9, 'p1', 2, 'read', { path: 'a.txt' }, 'Error: ENOENT', true))
  673. const subs = session.getSnapshot().codeDispatches.get('p1')
  674. expect(subs).toHaveLength(2)
  675. expect(subs?.[0]).toMatchObject({
  676. kind: 'tool-result', callId: 'p1:code:1',
  677. call: { name: 'bash', argsRaw: '{"command":"ls","description":"列目录"}' },
  678. // The settle event carries no start time: callTime stays null (never a
  679. // fabricated zero-duration).
  680. callTime: null,
  681. isError: false, content: [{ type: 'text', text: 'demo.txt' }],
  682. })
  683. expect(subs?.[1]).toMatchObject({ callId: 'p1:code:2', isError: true })
  684. // No paired start in the window: duration is UNKNOWN (null), never a
  685. // fabricated zero-duration span.
  686. expect(subs?.[0]).toMatchObject({ callTime: null })
  687. // Sub-dispatches never join the surface flow.
  688. expect(session.getSnapshot().nodes.some(n => n.kind === 'tool-result' && n.callId.includes(':code:'))).toBe(false)
  689. })
  690. it('rebuilds the same index from a history window (replay parity)', async () => {
  691. const { api, session } = makeSession()
  692. api.onHistory = () => histResponse([
  693. ...plainTurn(0, 0, '问', '答'),
  694. ev.turnStart(6, 1),
  695. ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"return 1","description":"跑一个程序"}'),
  696. ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls' }, 'demo.txt'),
  697. ev.toolResult(9, 1, 'p1', '{"done":true}'),
  698. ev.turnEnd(10, 1),
  699. ])
  700. await session.open()
  701. const subs = session.getSnapshot().codeDispatches.get('p1')
  702. expect(subs).toHaveLength(1)
  703. expect(subs?.[0]).toMatchObject({ callId: 'p1:code:1', call: { name: 'bash' } })
  704. })
  705. it('keeps the dispatch map reference across unrelated changes and swaps it on a new dispatch', async () => {
  706. const { api, session } = makeSession()
  707. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  708. await session.open()
  709. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  710. feed(ev.turnStart(6, 1))
  711. feed(ev.toolCall(7, 1, 'p1', 'run_code', '{"code":"1","description":"d"}'))
  712. feed(ev.codeDispatch(8, 'p1', 1, 'bash', { command: 'ls' }, 'x'))
  713. const before = session.getSnapshot()
  714. feed(ev.chunkStart(9, 1))
  715. feed(ev.chunkText(10, 1, '流式'))
  716. const after = session.getSnapshot()
  717. expect(after.codeDispatches).toBe(before.codeDispatches)
  718. feed(ev.codeDispatch(11, 'p1', 2, 'read', { path: 'a' }, 'y'))
  719. expect(session.getSnapshot().codeDispatches).not.toBe(after.codeDispatches)
  720. expect(session.getSnapshot().codeDispatches.get('p1')).toHaveLength(2)
  721. })
  722. })
  723. describe('reference stability (the memo contract)', () => {
  724. it('keeps unchanged node references across an append and swaps the snapshot object', async () => {
  725. const { api, session } = makeSession()
  726. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  727. await session.open()
  728. const before = session.getSnapshot()
  729. session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event: ev.user(6, '追加') })
  730. const after = session.getSnapshot()
  731. expect(after).not.toBe(before) // top-level swap on change
  732. expect(after.nodes[0]).toBe(before.nodes[0]) // untouched nodes keep identity
  733. expect(after.nodes[1]).toBe(before.nodes[1])
  734. expect(after.nodes).toHaveLength(3)
  735. // No change → same snapshot reference.
  736. expect(session.getSnapshot()).toBe(after)
  737. })
  738. it('keeps untouched substructure arrays identical across unrelated changes (revision counters)', async () => {
  739. const { api, session } = makeSession()
  740. api.onHistory = () => histResponse(plainTurn(0, 0, '底', '座'))
  741. await session.open()
  742. const feed = (event: SessionEvent) => { session.handleMuxEnvelope('r' as never, { type: 'session/event', sessionId: SID, event }) }
  743. feed(ev.turnStart(6, 1))
  744. feed(ev.toolCall(7, 1, 'c1', 'echo', '{}'))
  745. session.handleMuxEnvelope('ra' as never, { type: 'approval/requested', sessionId: SID, approvalId: 'ap1' as never, toolName: 'rm' })
  746. const before = session.getSnapshot()
  747. // A chunk storm touches partial/nodes only: runningCalls and pending must keep identity.
  748. feed(ev.chunkStart(8, 1))
  749. feed(ev.chunkText(9, 1, '与工具无关的流式'))
  750. const after = session.getSnapshot()
  751. expect(after).not.toBe(before)
  752. expect(after.runningCalls).toBe(before.runningCalls)
  753. expect(after.pending).toBe(before.pending)
  754. // And a mutation on the tracked domain swaps that array.
  755. feed(ev.toolResult(10, 1, 'c1', 'ECHO'))
  756. const resolved = session.getSnapshot()
  757. expect(resolved.runningCalls).not.toBe(after.runningCalls)
  758. expect(resolved.pending).toBe(after.pending)
  759. })
  760. })