session.spec.ts 55 KB

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