session.spec.ts 47 KB

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