session.client.spec.ts 30 KB

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