session.client.spec.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. /** Session object lifecycle, event-window transport, commands, and resync behavior. */
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { RemoteStreamError } from '@deepseek-ai/dsh-api-gateway/client'
  4. import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
  5. import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'
  6. import type { SessionToolView } from '@deepseek-ai/dsh-api-session-controller/types'
  7. import { Session, type SessionOptions } from '../src/client/sessions/session.ts'
  8. import { FakeApiClient, deferred, err, fakeRemote, ok } from './fake-api.client.ts'
  9. import { entries, ev, plainTurn } from './event-script.client.ts'
  10. const SID = 'fk-s1' as SessionId
  11. const PARENT = 'fk-parent' as SessionId
  12. afterEach(() => {
  13. vi.unstubAllGlobals()
  14. })
  15. function makeSession(
  16. api = new FakeApiClient(),
  17. options: SessionOptions = {},
  18. ): { api: FakeApiClient; session: Session } {
  19. return { api, session: new Session(SID, api, fakeRemote(api), options) }
  20. }
  21. function follow(
  22. api: FakeApiClient,
  23. event: SessionEvent,
  24. view?: SessionToolView,
  25. ): Promise<void> {
  26. return api.pushFollow(SID, {
  27. type: 'event',
  28. event: event as never,
  29. ...(view === undefined ? {} : { view }),
  30. })
  31. }
  32. function windowEntries(session: Session) {
  33. return session.eventSource.getSnapshot().entries
  34. }
  35. function eventSeqs(session: Session): number[] {
  36. return windowEntries(session).map(entry => entry.event.seq)
  37. }
  38. function histResponse(events: SessionEvent[], hasMore = false) {
  39. // history returns HistoryEntry[] ({event, view?}); these tests are view-less.
  40. return Promise.resolve(ok({ events: entries(events) as never[], hasMore }))
  41. }
  42. describe('Session open', () => {
  43. it('keeps a bare Session blank until an authoritative lifecycle signal arrives', () => {
  44. const { session } = makeSession()
  45. expect(session.getSnapshot()).toMatchObject({ blank: true, promptAttempted: false, running: false })
  46. session.handleRunning(true)
  47. expect(session.getSnapshot()).toMatchObject({ blank: false, running: true })
  48. })
  49. it('installs the tail page: cold → loading → open with window and nodes in place', async () => {
  50. const { api, session } = makeSession()
  51. const page = plainTurn(10, 3, '问', '答')
  52. api.onHistory = () => histResponse(page, true)
  53. expect(session.getSnapshot().openState).toBe('cold')
  54. const opening = session.open()
  55. expect(session.getSnapshot().openState).toBe('loading')
  56. await opening
  57. const snapshot = session.getSnapshot()
  58. expect(snapshot.openState).toBe('open')
  59. expect(snapshot.hasMore).toBe(true)
  60. expect(eventSeqs(session)).toEqual([10, 11, 12, 13, 14, 15])
  61. expect(session.eventSource.getSnapshot().change).toMatchObject({ kind: 'replace' })
  62. })
  63. it('is idempotent: concurrent opens share one history call, reopening when open is a no-op', async () => {
  64. const { api, session } = makeSession()
  65. await Promise.all([session.open(), session.open()])
  66. await session.open()
  67. expect(api.callsOf('session.history')).toHaveLength(1)
  68. })
  69. it('lands an error result in openState=error with the RpcError kept', async () => {
  70. const { api, session } = makeSession()
  71. api.onHistory = () => Promise.resolve(err({ code: 'session-not-found', message: 'gone', details: { sessionId: SID } }))
  72. await session.open()
  73. const snapshot = session.getSnapshot()
  74. expect(snapshot.openState).toBe('error')
  75. expect(snapshot.openError?.code).toBe('session-not-found')
  76. })
  77. it('folds a transport throw into openState=error / internal', async () => {
  78. const { api, session } = makeSession()
  79. api.onHistory = () => Promise.reject(new Error('socket died'))
  80. await session.open()
  81. expect(session.getSnapshot().openState).toBe('error')
  82. expect(session.getSnapshot().openError).toMatchObject({ code: 'internal', message: 'socket died' })
  83. })
  84. it('stitches live frames arriving while history is pending, dropping the page overlap', async () => {
  85. const { api, session } = makeSession()
  86. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  87. api.onHistory = () => gate.promise
  88. const opening = session.open()
  89. // Three live frames land mid-open; seq 15 overlaps the page tail (page covers 10..15).
  90. const page = plainTurn(10, 0, '早', '安')
  91. const deliveries = [
  92. follow(api, ev.turnStart(15, 1)),
  93. follow(api, ev.user(16, '插进来的')),
  94. ]
  95. gate.resolve(ok({
  96. events: entries(page) as never[],
  97. hasMore: false,
  98. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  99. }))
  100. await Promise.all([opening, ...deliveries])
  101. const seqs = eventSeqs(session)
  102. // Overlapping seq-15 frame (== page tail turn/end) was dropped; 16 appended once.
  103. expect(seqs).toEqual([10, 11, 12, 13, 14, 15, 16])
  104. })
  105. })
  106. describe('live event path', () => {
  107. async function opened(events: SessionEvent[] = plainTurn(0, 0, 'a', 'b')) {
  108. const { api, session } = makeSession()
  109. api.onHistory = () => histResponse(events)
  110. await session.open()
  111. return { api, session }
  112. }
  113. it('drops replayed frames at or below the window tail', async () => {
  114. const { api, session } = await opened()
  115. const before = session.eventSource.getSnapshot()
  116. await follow(api, ev.user(3, '重放'))
  117. expect(session.eventSource.getSnapshot()).toBe(before)
  118. })
  119. it('keeps the authoritative host blank bit across unrelated log events', async () => {
  120. const { api, session } = await opened([])
  121. session.handleBlank(true)
  122. await Promise.all([
  123. follow(api, ev.commandRun(0, 'cmd-perm', 'permission', ' danger-full-access')),
  124. follow(api, ev.commandDone(1, 'cmd-perm', 'success', 'preset danger-full-access')),
  125. ])
  126. const snapshot = session.getSnapshot()
  127. expect(eventSeqs(session)).toEqual([0, 1])
  128. expect(snapshot.blank).toBe(true)
  129. })
  130. it('repairs a seq gap by repulling the tail page instead of appending a hole', async () => {
  131. const { api, session } = await opened(plainTurn(0, 0, 'a', 'b')) // tail seq = 5
  132. const repaired = [...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')]
  133. api.onHistory = () => histResponse(repaired)
  134. // seq 9 with tail 5 → gap; the event detours to the buffer and one history refetch fires.
  135. await follow(api, ev.assistant(9, 1, 'd'))
  136. await vi.waitFor(() => {
  137. expect(api.callsOf('session.history').length).toBe(2)
  138. })
  139. await vi.waitFor(() => {
  140. expect(eventSeqs(session)).toEqual(
  141. repaired.filter(event => event.seq <= 9).map(event => event.seq),
  142. )
  143. })
  144. })
  145. })
  146. describe('paging', () => {
  147. it('prepends an older page and keeps seq continuity', async () => {
  148. const older = plainTurn(0, 0, '旧问', '旧答')
  149. const newer = plainTurn(6, 1, '新问', '新答')
  150. const { api, session } = makeSession()
  151. api.onHistory = payload => payload.beforeSeq === undefined
  152. ? histResponse(newer, true)
  153. : histResponse(older, false)
  154. await session.open()
  155. await session.loadOlder()
  156. const snapshot = session.getSnapshot()
  157. expect(api.callsOf('session.history')).toMatchObject([
  158. { sessionId: SID, throughSeq: 11 },
  159. { sessionId: SID, throughSeq: 11, beforeSeq: 6 },
  160. ])
  161. expect(snapshot.hasMore).toBe(false)
  162. expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq))
  163. })
  164. it('installs a page without interpreting business replacement metadata', async () => {
  165. const { api, session } = makeSession()
  166. api.onHistory = () => histResponse([
  167. ev.compactSummary(80, '窗外范围的摘要', 3, 40),
  168. ev.compactCheckpoint(81, 80, 3, 40),
  169. ev.user(82, '压缩后的新问题'),
  170. ], true)
  171. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  172. try {
  173. await session.open()
  174. const snapshot = session.getSnapshot()
  175. expect(snapshot.openState).toBe('open')
  176. expect(eventSeqs(session)).toEqual([80, 81, 82])
  177. expect(errorSpy).not.toHaveBeenCalled()
  178. } finally {
  179. errorSpy.mockRestore()
  180. }
  181. })
  182. it('drops a discontinuous older page fail-soft (window unchanged, hasMore cleared)', async () => {
  183. const { api, session } = makeSession()
  184. api.onHistory = payload => payload.beforeSeq === undefined
  185. ? histResponse(plainTurn(10, 1, '新', '页'), true)
  186. : histResponse(plainTurn(0, 0, '断', '层'), true) // tail seq 5, but baseSeq is 10 → hole
  187. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  188. try {
  189. await session.open()
  190. const windowBefore = session.eventSource.getSnapshot()
  191. await session.loadOlder()
  192. const snapshot = session.getSnapshot()
  193. expect(session.eventSource.getSnapshot().entries).toEqual(windowBefore.entries)
  194. expect(snapshot.hasMore).toBe(false)
  195. } finally {
  196. errorSpy.mockRestore()
  197. }
  198. })
  199. it('ignores loadOlder while one is in flight (single request)', async () => {
  200. const { api, session } = makeSession()
  201. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  202. await session.open()
  203. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  204. api.onHistory = () => gate.promise
  205. const first = session.loadOlder()
  206. const second = session.loadOlder()
  207. gate.resolve(ok({
  208. events: entries(plainTurn(0, 0, 'a', 'b')) as never[],
  209. hasMore: false,
  210. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  211. }))
  212. await Promise.all([first, second])
  213. expect(api.callsOf('session.history')).toHaveLength(2) // open + one page, not two
  214. })
  215. })
  216. describe('prompt and cancel errors', () => {
  217. it('routes an addressed child through non-activating history, continuation prompt, and interrupt only', async () => {
  218. const api = new FakeApiClient()
  219. const session = new Session(SID, api, fakeRemote(api), {
  220. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  221. parentAvailable: true,
  222. })
  223. await session.open()
  224. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  225. const cancelled = await session.cancel()
  226. expect(prompted).toEqual({ ok: true, value: { accepted: true } })
  227. expect(cancelled).toEqual({ ok: true, value: { accepted: true } })
  228. expect(api.callsOf('subagent.history')).toEqual([
  229. { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable', throughSeq: -1, maxMessages: 50 },
  230. ])
  231. expect(api.callsOf('subagent.prompt')).toEqual([
  232. {
  233. parentSessionId: PARENT, childSessionId: SID, mode: 'continuable',
  234. content: [{ type: 'text', text: '继续' }],
  235. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  236. },
  237. ])
  238. expect(api.callsOf('subagent.interrupt')).toEqual([
  239. { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  240. ])
  241. expect(api.callsOf('session.history')).toEqual([])
  242. expect(api.callsOf('session.prompt')).toEqual([])
  243. expect(api.callsOf('session.cancel')).toEqual([])
  244. // A successful interrupt leaves no stop error behind.
  245. expect(session.getSnapshot().promptError).toBeNull()
  246. expect(session.getSnapshot().subagent).toEqual({
  247. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  248. parentAvailable: true,
  249. })
  250. })
  251. it('lands an interrupt business failure in promptError with op=stop', async () => {
  252. const api = new FakeApiClient()
  253. api.onSubagentInterrupt = () => Promise.resolve(err({
  254. code: 'subagent-unauthorized', message: 'nope', details: { childSessionId: SID },
  255. }) as never)
  256. const session = new Session(SID, api, fakeRemote(api), {
  257. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  258. parentAvailable: true,
  259. })
  260. await session.open()
  261. const cancelled = await session.cancel()
  262. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent-unauthorized' } })
  263. expect(session.getSnapshot().promptError).toMatchObject({
  264. op: 'stop', error: { code: 'subagent-unauthorized' },
  265. })
  266. })
  267. it('keeps one-shot history readable without exposing prompt or cancel transport', async () => {
  268. const api = new FakeApiClient()
  269. const session = new Session(SID, api, fakeRemote(api), {
  270. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot' },
  271. })
  272. await session.open()
  273. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  274. const cancelled = await session.cancel()
  275. expect(prompted).toMatchObject({ ok: false, error: { code: 'subagent-not-resumable' } })
  276. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent-delivery-unavailable' } })
  277. expect(api.callsOf('subagent.history')).toEqual([
  278. { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot', throughSeq: -1, maxMessages: 50 },
  279. ])
  280. expect(api.callsOf('subagent.prompt')).toEqual([])
  281. expect(api.callsOf('subagent.interrupt')).toEqual([])
  282. expect(api.callsOf('session.cancel')).toEqual([])
  283. })
  284. it('publishes the first-prompt lifecycle synchronously before the Remote settles', async () => {
  285. const { api, session } = makeSession()
  286. session.handleBlank(true)
  287. expect(session.getSnapshot()).toMatchObject({
  288. blank: true, promptAttempted: false, awaitingFirstTurn: false,
  289. })
  290. const inFlight = session.prompt([{ type: 'text', text: '要发的' }], 'queue')
  291. expect(session.getSnapshot()).toMatchObject({
  292. blank: true, promptAttempted: true, awaitingFirstTurn: true,
  293. })
  294. const result = await inFlight
  295. expect(result.ok).toBe(true)
  296. expect(session.getSnapshot()).toMatchObject({
  297. blank: false, promptAttempted: true, awaitingFirstTurn: true,
  298. })
  299. expect(api.callsOf('session.prompt')).toMatchObject([{
  300. sessionId: SID,
  301. mode: 'queue',
  302. content: [{ type: 'text', text: '要发的' }],
  303. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  304. }])
  305. session.handleRunning(true)
  306. expect(session.getSnapshot()).toMatchObject({ running: true, awaitingFirstTurn: false })
  307. })
  308. it('keeps the attempted-first-prompt state when the Host rejects the prompt', async () => {
  309. const { api, session } = makeSession()
  310. session.handleBlank(true)
  311. api.onPrompt = () => Promise.resolve(err({ code: 'agent-busy', message: 'busy', details: { reason: 'x' } }))
  312. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue')
  313. expect(result.ok).toBe(false)
  314. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'agent-busy' } })
  315. expect(session.getSnapshot()).toMatchObject({
  316. blank: true, promptAttempted: true, awaitingFirstTurn: true,
  317. })
  318. })
  319. it('lands cancel failures in promptError with op=stop', async () => {
  320. const { api, session } = makeSession()
  321. api.onCancel = () => Promise.reject(new Error('cancel transport down'))
  322. const result = await session.cancel()
  323. expect(result.ok).toBe(false)
  324. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'internal' } })
  325. })
  326. it('reads session-authorized attachment bytes and keeps the opaque id on the wire', async () => {
  327. const { api, session } = makeSession()
  328. const result = await session.readAttachment('attachment-1' as never)
  329. expect(result).toEqual({
  330. ok: true,
  331. value: {
  332. attachment: { attachmentId: 'a', mediaType: 'image/png', bytes: 1, width: 1, height: 1 },
  333. data: Uint8Array.of(0),
  334. },
  335. })
  336. expect(api.callsOf('session.attachment')).toEqual([{
  337. sessionId: SID, attachmentId: 'attachment-1',
  338. }])
  339. })
  340. })
  341. describe('rename', () => {
  342. it('settles the title projection cell from the unary response (higher-seq-wins vs the push frame)', async () => {
  343. const { api, session } = makeSession()
  344. api.onRename = () => Promise.resolve(ok({ title: '正名', seq: 7 }))
  345. const result = await session.rename(' 正名 ')
  346. expect(result).toMatchObject({ ok: true, value: { title: '正名', seq: 7 } })
  347. expect(api.callsOf('session.rename')).toMatchObject([{ sessionId: SID, title: ' 正名 ' }])
  348. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  349. // A stale lower-seq apply (the push-frame path routes into this same
  350. // store) must not roll the settled value back.
  351. session.projections.apply('title', '旧名', 3)
  352. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  353. })
  354. it('returns the business error untouched and folds a transport throw to internal', async () => {
  355. const { api, session } = makeSession()
  356. api.onRename = () => Promise.resolve(err({
  357. code: 'title-invalid', message: 'empty', details: { sessionId: SID },
  358. } as never))
  359. const rejected = await session.rename(' ')
  360. expect(rejected).toMatchObject({ ok: false, error: { code: 'title-invalid' } })
  361. expect(session.projections.faceOf('title').getSnapshot()).toBeUndefined()
  362. api.onRename = () => Promise.reject(new Error('rename transport down'))
  363. const folded = await session.rename('x')
  364. expect(folded).toMatchObject({ ok: false, error: { code: 'internal' } })
  365. })
  366. })
  367. describe('remaining branches', () => {
  368. it('prompt transport throw folds to internal promptError', async () => {
  369. const { api, session } = makeSession()
  370. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  371. const result = await session.prompt([{ type: 'text', text: 'x' }], 'queue')
  372. expect(result.ok).toBe(false)
  373. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'internal', message: 'prompt wire down' } })
  374. })
  375. it('cancel business error also lands op=stop promptError', async () => {
  376. const { api, session } = makeSession()
  377. api.onCancel = () => Promise.resolve(err({ code: 'agent-busy', message: 'nope', details: { reason: 'r' } }))
  378. await session.cancel()
  379. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'agent-busy' } })
  380. })
  381. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  382. const { api, session } = makeSession()
  383. await session.loadOlder() // cold: no-op, zero calls
  384. expect(api.calls).toEqual([])
  385. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  386. await session.open()
  387. // err result: window unchanged
  388. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  389. await session.loadOlder()
  390. expect(eventSeqs(session)).toHaveLength(6)
  391. expect(session.getSnapshot().hasMore).toBe(true)
  392. // empty page: hasMore adopts the response
  393. api.onHistory = () => histResponse([], false)
  394. await session.loadOlder()
  395. expect(session.getSnapshot().hasMore).toBe(false)
  396. // hasMore false now: further loadOlder is a guard no-op
  397. const calls = api.calls.length
  398. await session.loadOlder()
  399. expect(api.calls.length).toBe(calls)
  400. // throw path: fail-soft with console.error
  401. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  402. try {
  403. await session.resync()
  404. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  405. await session.resync()
  406. api.onHistory = () => Promise.reject(new Error('page wire down'))
  407. await session.loadOlder()
  408. expect(errorSpy).toHaveBeenCalled()
  409. expect(session.getSnapshot().loadingOlder).toBe(false)
  410. } finally {
  411. errorSpy.mockRestore()
  412. }
  413. })
  414. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  415. const { api, session } = makeSession()
  416. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  417. let notified = 0
  418. const unsubscribe = session.subscribe(() => { notified++ })
  419. await session.open()
  420. await new Promise(resolve => setTimeout(resolve, 0))
  421. expect(notified).toBeGreaterThan(0)
  422. const seen = notified
  423. unsubscribe()
  424. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  425. await new Promise(resolve => setTimeout(resolve, 0))
  426. expect(notified).toBe(seen)
  427. })
  428. it('rejects an opening page that does not end at the opening cursor', async () => {
  429. const { api, session } = makeSession()
  430. let call = 0
  431. api.onHistory = () => {
  432. call++
  433. return histResponse(plainTurn(0, 0, 'a', 'b'))
  434. }
  435. api.followCursor = 11
  436. await session.open()
  437. expect(call).toBe(1)
  438. const snapshot = session.getSnapshot()
  439. expect(snapshot.openState).toBe('error')
  440. expect(snapshot.openError).toMatchObject({
  441. code: 'internal', message: 'session event stream page did not end at its requested cursor',
  442. })
  443. expect(eventSeqs(session)).toEqual([])
  444. })
  445. it('deduplicates repeated running flips and records removal', () => {
  446. const { session } = makeSession()
  447. const before = session.getSnapshot()
  448. session.handleRunning(false) // already false: dedup branch
  449. expect(session.getSnapshot()).toBe(before)
  450. session.handleRemoved()
  451. expect(session.getSnapshot().removed).toBe(true)
  452. })
  453. it('drops live events while cold/error (no window upkeep)', async () => {
  454. const { api, session } = makeSession()
  455. await follow(api, ev.user(0, '冷态帧'))
  456. expect(eventSeqs(session)).toEqual([])
  457. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  458. await session.open()
  459. await follow(api, ev.user(0, '错态帧'))
  460. expect(eventSeqs(session)).toEqual([])
  461. })
  462. it('preserves a Host-reported failure that terminates the live source', async () => {
  463. const { api, session } = makeSession()
  464. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  465. await session.open()
  466. const failure = {
  467. code: 'session-not-found',
  468. message: 'session disappeared',
  469. details: { sessionId: SID },
  470. }
  471. api.failStreams(new RemoteStreamError(failure.code, failure.message, failure.details))
  472. await vi.waitFor(() => { expect(session.getSnapshot().openState).toBe('error') })
  473. expect(session.getSnapshot().openError).toEqual(failure)
  474. })
  475. it('coalesces queued gap frames behind one repair and exposes a failed repair', async () => {
  476. const { api, session } = makeSession()
  477. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  478. await session.open()
  479. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  480. let repairs = 0
  481. api.onHistory = () => {
  482. repairs++
  483. return gate.promise
  484. }
  485. const deliveries = Promise.all([
  486. follow(api, ev.user(9, '洞一')),
  487. follow(api, ev.user(10, '洞二')),
  488. ])
  489. await vi.waitFor(() => { expect(repairs).toBe(1) })
  490. gate.reject(new Error('repair wire down'))
  491. await deliveries
  492. await vi.waitFor(() => { expect(session.getSnapshot().openState).toBe('error') })
  493. expect(session.getSnapshot().openError).toMatchObject({ code: 'internal', message: 'repair wire down' })
  494. expect(eventSeqs(session)).toHaveLength(6)
  495. })
  496. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  497. const { api, session } = makeSession()
  498. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  499. api.onHistory = () => stale.promise
  500. const opening = session.open()
  501. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  502. const resynced = session.resync()
  503. stale.reject(new Error('stale wire'))
  504. await Promise.all([opening, resynced])
  505. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  506. })
  507. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  508. const { api, session } = makeSession()
  509. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  510. api.onHistory = () => stale.promise
  511. const opening = session.open()
  512. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  513. const resynced = session.resync()
  514. stale.resolve(ok({
  515. events: entries(plainTurn(0, 0, '旧', '代')) as never[],
  516. hasMore: false,
  517. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  518. })) // success, but its generation is gone
  519. await Promise.all([opening, resynced])
  520. expect(eventSeqs(session)).toEqual(plainTurn(6, 1, '新', '代').map(event => event.seq))
  521. })
  522. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  523. const { api, session } = makeSession()
  524. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  525. await session.open()
  526. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  527. api.onHistory = () => repairPull.promise
  528. const delivery = follow(api, ev.user(9, '洞'))
  529. await vi.waitFor(() => { expect(api.callsOf('session.history')).toHaveLength(2) })
  530. api.onHistory = () => histResponse(plainTurn(6, 1, 'c', 'd'))
  531. const resynced = session.resync() // bumps the generation
  532. repairPull.resolve(ok({
  533. events: entries(plainTurn(0, 0, '旧', '页')) as never[],
  534. hasMore: false,
  535. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  536. })) // repair result: stale, dropped
  537. await Promise.all([delivery, resynced])
  538. expect(eventSeqs(session)).toEqual(plainTurn(6, 1, 'c', 'd').map(event => event.seq))
  539. })
  540. it('successful cancel leaves no promptError', async () => {
  541. const { api, session } = makeSession()
  542. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  543. await session.open()
  544. const result = await session.cancel()
  545. expect(result.ok).toBe(true)
  546. expect(session.getSnapshot().promptError).toBeNull()
  547. })
  548. it('dispose is a reserved no-op on resident instances', async () => {
  549. const { session } = makeSession()
  550. await expect(session.dispose()).resolves.toBeUndefined()
  551. })
  552. it('carries history-entry and follow-frame views through the event feed', async () => {
  553. const { api, session } = makeSession()
  554. const callView = { for: 'call', view: { card: 'generic', title: '历史卡' } }
  555. api.onHistory = () => Promise.resolve(ok({
  556. events: [
  557. ...entries(plainTurn(0, 0, 'a', 'b')),
  558. { event: ev.toolCall(6, 1, 'h1', 'bash', '{}'), view: callView },
  559. { event: ev.toolResult(7, 1, 'h1', 'done'), view: { for: 'result', view: { card: 'generic', title: '历史果' } } },
  560. ] as never[],
  561. hasMore: false,
  562. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  563. }))
  564. await session.open()
  565. expect(windowEntries(session).slice(-2).map(item => item.view)).toEqual([
  566. callView,
  567. { for: 'result', view: { card: 'generic', title: '历史果' } },
  568. ])
  569. await follow(
  570. api,
  571. ev.toolCall(8, 2, 'l1', 'write', '{}'),
  572. { for: 'call', view: { card: 'generic', title: '直播卡' } },
  573. )
  574. expect(windowEntries(session).at(-1)?.view).toEqual({
  575. for: 'call', view: { card: 'generic', title: '直播卡' },
  576. })
  577. await follow(
  578. api,
  579. ev.toolResult(9, 2, 'l1', 'ok'),
  580. { for: 'result', view: { card: 'generic', title: '直播果' } },
  581. )
  582. expect(windowEntries(session).at(-1)?.view).toEqual({
  583. for: 'result', view: { card: 'generic', title: '直播果' },
  584. })
  585. })
  586. })
  587. describe('resync', () => {
  588. it('keeps the old feed until one sorted page-and-live replacement is ready', async () => {
  589. const { api, session } = makeSession()
  590. api.onHistory = () => histResponse(plainTurn(0, 0, '旧', '窗'))
  591. await session.open()
  592. const oldWindow = session.eventSource.getSnapshot()
  593. const replacement = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  594. api.followCursor = 15
  595. api.onHistory = () => replacement.promise
  596. const publications: ReturnType<Session['eventSource']['getSnapshot']>[] = []
  597. const off = session.eventSource.subscribe(() => {
  598. publications.push(session.eventSource.getSnapshot())
  599. })
  600. const syncing = session.resync()
  601. await vi.waitFor(() => { expect(api.callsOf('session.history')).toHaveLength(2) })
  602. expect(session.eventSource.getSnapshot()).toBe(oldWindow)
  603. expect(publications).toEqual([])
  604. await Promise.all([
  605. follow(api, ev.user(17, '后到高位')),
  606. follow(api, ev.user(16, '后到低位')),
  607. ])
  608. expect(session.eventSource.getSnapshot()).toBe(oldWindow)
  609. replacement.resolve(ok({
  610. events: entries(plainTurn(10, 2, '终', '页')) as never[],
  611. hasMore: false,
  612. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  613. }))
  614. await syncing
  615. expect(publications).toHaveLength(1)
  616. expect(publications[0]?.entries).not.toHaveLength(0)
  617. expect(publications[0]?.change.kind).toBe('replace')
  618. expect(eventSeqs(session)).toEqual([10, 11, 12, 13, 14, 15, 16, 17])
  619. off()
  620. })
  621. it('rebuilds the window without clearing control state; cold instances no-op', async () => {
  622. const { api, session } = makeSession()
  623. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  624. await session.open()
  625. session.handleRunning(true)
  626. session.handleAgentError('still visible')
  627. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')])
  628. await session.resync()
  629. const snapshot = session.getSnapshot()
  630. expect(snapshot.openState).toBe('open')
  631. expect(snapshot.running).toBe(true)
  632. expect(snapshot.lastAgentError).toBe('still visible')
  633. expect(eventSeqs(session)).toHaveLength(12)
  634. const cold = makeSession()
  635. await cold.session.resync()
  636. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  637. })
  638. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  639. const { api, session } = makeSession()
  640. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  641. api.onHistory = () => stale.promise
  642. const firstOpen = session.open()
  643. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  644. const resynced = session.resync()
  645. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  646. await firstOpen
  647. await resynced
  648. const snapshot = session.getSnapshot()
  649. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  650. expect(eventSeqs(session)).toEqual(plainTurn(6, 1, '新', '代').map(event => event.seq))
  651. })
  652. })
  653. describe('snapshot ownership', () => {
  654. it('publishes event-window appends without changing an unrelated Session snapshot', async () => {
  655. const { api, session } = makeSession()
  656. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  657. await session.open()
  658. const sessionBefore = session.getSnapshot()
  659. const windowBefore = session.eventSource.getSnapshot()
  660. const firstEntry = windowBefore.entries[0]
  661. await follow(api, ev.user(6, '追加'))
  662. const windowAfter = session.eventSource.getSnapshot()
  663. expect(session.getSnapshot()).toBe(sessionBefore)
  664. expect(windowAfter).not.toBe(windowBefore)
  665. expect(windowAfter.entries[0]).toBe(firstEntry)
  666. expect(windowAfter.change).toMatchObject({ kind: 'append' })
  667. })
  668. })