1
0

session.spec.ts 57 KB

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