session.spec.ts 52 KB

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