session.client.spec.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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, remoteErr } from './fake-api.client.ts'
  8. import { entries, ev, historyValue, 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, 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. return Promise.resolve(ok(historyValue(events, hasMore)))
  37. }
  38. describe('Session open', () => {
  39. it('keeps a bare Session blank until an authoritative lifecycle signal arrives', () => {
  40. const { session } = makeSession()
  41. expect(session.getSnapshot()).toMatchObject({ blank: true, promptAttempted: false, running: false })
  42. session.handleRunning(true)
  43. expect(session.getSnapshot()).toMatchObject({ blank: false, running: true })
  44. })
  45. it('installs the tail page: cold → loading → open with window and nodes in place', async () => {
  46. const { api, session } = makeSession()
  47. const page = plainTurn(10, 3, '问', '答')
  48. api.onHistory = () => histResponse(page, true)
  49. expect(session.getSnapshot().openState).toBe('cold')
  50. const opening = session.open()
  51. expect(session.getSnapshot().openState).toBe('loading')
  52. await opening
  53. const snapshot = session.getSnapshot()
  54. expect(snapshot.openState).toBe('open')
  55. expect(snapshot.hasMore).toBe(true)
  56. expect(eventSeqs(session)).toEqual([10, 11, 12, 13, 14, 15])
  57. expect(session.eventSource.getSnapshot().change).toMatchObject({ kind: 'replace' })
  58. })
  59. it('is idempotent: concurrent opens share one follow, reopening when open is a no-op', async () => {
  60. const { api, session } = makeSession()
  61. await Promise.all([session.open(), session.open()])
  62. await session.open()
  63. expect(api.callsOf('session.follow')).toHaveLength(1)
  64. expect(api.callsOf('session.history')).toEqual([])
  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 while the opening snapshot is pending; seq 15 overlaps its tail.
  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. records: 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')).toHaveLength(1)
  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.follow')).toHaveLength(1)
  155. expect(api.callsOf('session.history')).toMatchObject([
  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. records: 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.follow')).toHaveLength(1)
  211. expect(api.callsOf('session.history')).toHaveLength(1)
  212. })
  213. })
  214. describe('prompt and cancel errors', () => {
  215. it('routes an addressed child through non-activating history, continuation prompt, and interrupt only', async () => {
  216. const api = new FakeApiClient()
  217. const session = new Session(SID, fakeRemote(api), {
  218. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  219. parentAvailable: true,
  220. })
  221. await session.open()
  222. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  223. const cancelled = await session.cancel()
  224. expect(prompted).toEqual({ ok: true, value: { accepted: true } })
  225. expect(cancelled).toEqual({ ok: true, value: { accepted: true } })
  226. expect(api.callsOf('session.follow')).toEqual([
  227. {
  228. address: {
  229. kind: 'subagent', parentSessionId: PARENT, childSessionId: SID, mode: 'continuable',
  230. },
  231. maxMessages: 50,
  232. },
  233. ])
  234. expect(api.callsOf('subagent.history')).toEqual([])
  235. expect(api.callsOf('subagents.prompt')).toEqual([
  236. {
  237. requestId: expect.any(String) as unknown as string,
  238. parentSessionId: PARENT, childSessionId: SID,
  239. mode: 'continuable',
  240. content: [{ type: 'text', text: '继续' }],
  241. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  242. },
  243. ])
  244. expect(api.callsOf('subagents.interruptByParent')).toEqual([
  245. { childSessionId: SID, parentSessionId: PARENT, mode: 'continuable' },
  246. ])
  247. expect(api.callsOf('session.history')).toEqual([])
  248. expect(api.callsOf('session.prompt')).toEqual([])
  249. expect(api.callsOf('session.cancel')).toEqual([])
  250. // A successful interrupt leaves no stop error behind.
  251. expect(session.getSnapshot().promptError).toBeNull()
  252. expect(session.getSnapshot().subagent).toEqual({
  253. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  254. parentAvailable: true,
  255. })
  256. })
  257. it('lands an interrupt business failure in promptError with op=stop', async () => {
  258. const api = new FakeApiClient()
  259. api.onSubagentInterrupt = () => Promise.resolve(remoteErr({
  260. code: 'subagent-unauthorized', message: 'nope', details: { childSessionId: SID },
  261. }))
  262. const session = new Session(SID, fakeRemote(api), {
  263. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  264. parentAvailable: true,
  265. })
  266. await session.open()
  267. const cancelled = await session.cancel()
  268. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent-unauthorized' } })
  269. expect(session.getSnapshot().promptError).toMatchObject({
  270. op: 'stop', error: { code: 'subagent-unauthorized' },
  271. })
  272. })
  273. it('keeps one-shot history readable without exposing prompt or cancel transport', async () => {
  274. const api = new FakeApiClient()
  275. const session = new Session(SID, fakeRemote(api), {
  276. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot' },
  277. })
  278. await session.open()
  279. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  280. const cancelled = await session.cancel()
  281. expect(prompted).toMatchObject({ ok: false, error: { code: 'subagent-not-resumable' } })
  282. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent-delivery-unavailable' } })
  283. expect(api.callsOf('session.follow')).toEqual([
  284. {
  285. address: {
  286. kind: 'subagent', parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot',
  287. },
  288. maxMessages: 50,
  289. },
  290. ])
  291. expect(api.callsOf('subagent.history')).toEqual([])
  292. expect(api.callsOf('subagents.prompt')).toEqual([])
  293. expect(api.callsOf('subagents.interruptByParent')).toEqual([])
  294. expect(api.callsOf('session.cancel')).toEqual([])
  295. })
  296. it('publishes the first-prompt lifecycle synchronously before the Remote settles', async () => {
  297. const { api, session } = makeSession()
  298. session.handleBlank(true)
  299. expect(session.getSnapshot()).toMatchObject({
  300. blank: true, promptAttempted: false, awaitingFirstTurn: false,
  301. })
  302. const inFlight = session.prompt([{ type: 'text', text: '要发的' }], 'queue')
  303. expect(session.getSnapshot()).toMatchObject({
  304. blank: true, promptAttempted: true, awaitingFirstTurn: true,
  305. })
  306. const result = await inFlight
  307. expect(result.ok).toBe(true)
  308. expect(session.getSnapshot()).toMatchObject({
  309. blank: false, promptAttempted: true, awaitingFirstTurn: true,
  310. })
  311. expect(api.callsOf('session.prompt')).toMatchObject([{
  312. sessionId: SID,
  313. mode: 'queue',
  314. content: [{ type: 'text', text: '要发的' }],
  315. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  316. }])
  317. session.handleRunning(true)
  318. expect(session.getSnapshot()).toMatchObject({ running: true, awaitingFirstTurn: false })
  319. })
  320. it('keeps the attempted-first-prompt state when the Host rejects the prompt', async () => {
  321. const { api, session } = makeSession()
  322. session.handleBlank(true)
  323. api.onPrompt = () => Promise.resolve(err({ code: 'agent-busy', message: 'busy', details: { reason: 'x' } }))
  324. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue')
  325. expect(result.ok).toBe(false)
  326. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'agent-busy' } })
  327. expect(session.getSnapshot()).toMatchObject({
  328. blank: true, promptAttempted: true, awaitingFirstTurn: true,
  329. })
  330. })
  331. it('lands cancel failures in promptError with op=stop', async () => {
  332. const { api, session } = makeSession()
  333. api.onCancel = () => Promise.reject(new Error('cancel transport down'))
  334. const result = await session.cancel()
  335. expect(result.ok).toBe(false)
  336. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'internal' } })
  337. })
  338. it('reads session-authorized attachment bytes and keeps the opaque id on the wire', async () => {
  339. const { api, session } = makeSession()
  340. const result = await session.readAttachment('attachment-1' as never)
  341. expect(result).toEqual({
  342. ok: true,
  343. value: {
  344. attachment: { attachmentId: 'a', mediaType: 'image/png', bytes: 1, width: 1, height: 1 },
  345. data: Uint8Array.of(0),
  346. },
  347. })
  348. expect(api.callsOf('session.attachment')).toEqual([{
  349. sessionId: SID, attachmentId: 'attachment-1',
  350. }])
  351. })
  352. })
  353. describe('rename', () => {
  354. it('settles the title projection cell from the unary response (higher-seq-wins vs the push frame)', async () => {
  355. const { api, session } = makeSession()
  356. api.onRename = () => Promise.resolve(ok({ title: '正名', seq: 7 }))
  357. const result = await session.rename(' 正名 ')
  358. expect(result).toMatchObject({ ok: true, value: { title: '正名', seq: 7 } })
  359. expect(api.callsOf('session.rename')).toMatchObject([{ sessionId: SID, title: ' 正名 ' }])
  360. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  361. // A stale lower-seq apply (the push-frame path routes into this same
  362. // store) must not roll the settled value back.
  363. session.projections.apply('title', '旧名', 3)
  364. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  365. })
  366. it('returns the business error untouched and folds a transport throw to internal', async () => {
  367. const { api, session } = makeSession()
  368. api.onRename = () => Promise.resolve(err({
  369. code: 'title-invalid', message: 'empty', details: { sessionId: SID },
  370. } as never))
  371. const rejected = await session.rename(' ')
  372. expect(rejected).toMatchObject({ ok: false, error: { code: 'title-invalid' } })
  373. expect(session.projections.faceOf('title').getSnapshot()).toBeUndefined()
  374. api.onRename = () => Promise.reject(new Error('rename transport down'))
  375. const folded = await session.rename('x')
  376. expect(folded).toMatchObject({ ok: false, error: { code: 'internal' } })
  377. })
  378. })
  379. describe('remaining branches', () => {
  380. it('prompt transport throw folds to internal promptError', async () => {
  381. const { api, session } = makeSession()
  382. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  383. const result = await session.prompt([{ type: 'text', text: 'x' }], 'queue')
  384. expect(result.ok).toBe(false)
  385. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'internal', message: 'prompt wire down' } })
  386. })
  387. it('cancel business error also lands op=stop promptError', async () => {
  388. const { api, session } = makeSession()
  389. api.onCancel = () => Promise.resolve(err({ code: 'agent-busy', message: 'nope', details: { reason: 'r' } }))
  390. await session.cancel()
  391. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'agent-busy' } })
  392. })
  393. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  394. const { api, session } = makeSession()
  395. await session.loadOlder() // cold: no-op, zero calls
  396. expect(api.calls).toEqual([])
  397. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  398. await session.open()
  399. // err result: window unchanged
  400. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  401. await session.loadOlder()
  402. expect(eventSeqs(session)).toHaveLength(6)
  403. expect(session.getSnapshot().hasMore).toBe(true)
  404. // empty page: hasMore adopts the response
  405. api.onHistory = () => histResponse([], false)
  406. await session.loadOlder()
  407. expect(session.getSnapshot().hasMore).toBe(false)
  408. // hasMore false now: further loadOlder is a guard no-op
  409. const calls = api.calls.length
  410. await session.loadOlder()
  411. expect(api.calls.length).toBe(calls)
  412. // throw path: fail-soft with console.error
  413. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  414. try {
  415. await session.resync()
  416. api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
  417. await session.resync()
  418. api.onHistory = () => Promise.reject(new Error('page wire down'))
  419. await session.loadOlder()
  420. expect(errorSpy).toHaveBeenCalled()
  421. expect(session.getSnapshot().loadingOlder).toBe(false)
  422. } finally {
  423. errorSpy.mockRestore()
  424. }
  425. })
  426. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  427. const { api, session } = makeSession()
  428. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  429. let notified = 0
  430. const unsubscribe = session.subscribe(() => { notified++ })
  431. await session.open()
  432. await new Promise(resolve => setTimeout(resolve, 0))
  433. expect(notified).toBeGreaterThan(0)
  434. const seen = notified
  435. unsubscribe()
  436. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  437. await new Promise(resolve => setTimeout(resolve, 0))
  438. expect(notified).toBe(seen)
  439. })
  440. it('rejects an opening page that does not end at the opening cursor', async () => {
  441. const { api, session } = makeSession()
  442. let call = 0
  443. api.onHistory = () => {
  444. call++
  445. return histResponse(plainTurn(0, 0, 'a', 'b'))
  446. }
  447. api.followCursor = 11
  448. await session.open()
  449. expect(call).toBe(1)
  450. const snapshot = session.getSnapshot()
  451. expect(snapshot.openState).toBe('error')
  452. expect(snapshot.openError).toMatchObject({
  453. code: 'internal', message: 'session event stream page did not end at its requested cursor',
  454. })
  455. expect(eventSeqs(session)).toEqual([])
  456. })
  457. it('deduplicates repeated running flips and records removal', () => {
  458. const { session } = makeSession()
  459. const before = session.getSnapshot()
  460. session.handleRunning(false) // already false: dedup branch
  461. expect(session.getSnapshot()).toBe(before)
  462. session.handleRemoved()
  463. expect(session.getSnapshot().removed).toBe(true)
  464. })
  465. it('drops live events while cold/error (no window upkeep)', async () => {
  466. const { api, session } = makeSession()
  467. await follow(api, ev.user(0, '冷态帧'))
  468. expect(eventSeqs(session)).toEqual([])
  469. api.onHistory = () => Promise.resolve(err({ code: 'internal', message: 'x', details: {} }))
  470. await session.open()
  471. await follow(api, ev.user(0, '错态帧'))
  472. expect(eventSeqs(session)).toEqual([])
  473. })
  474. it('preserves a Host-reported failure that terminates the live source', async () => {
  475. const { api, session } = makeSession()
  476. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  477. await session.open()
  478. const failure = {
  479. code: 'session-not-found',
  480. message: 'session disappeared',
  481. details: { sessionId: SID },
  482. }
  483. api.failStreams(new RemoteStreamError(failure.code, failure.message, failure.details))
  484. await vi.waitFor(() => { expect(session.getSnapshot().openState).toBe('error') })
  485. expect(session.getSnapshot().openError).toEqual(failure)
  486. })
  487. it('coalesces queued gap frames behind one repair and exposes a failed repair', async () => {
  488. const { api, session } = makeSession()
  489. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  490. await session.open()
  491. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  492. let repairs = 0
  493. api.onHistory = () => {
  494. repairs++
  495. return gate.promise
  496. }
  497. const deliveries = Promise.all([
  498. follow(api, ev.user(9, '洞一')),
  499. follow(api, ev.user(10, '洞二')),
  500. ])
  501. await vi.waitFor(() => { expect(repairs).toBe(1) })
  502. gate.reject(new Error('repair wire down'))
  503. await deliveries
  504. await vi.waitFor(() => { expect(session.getSnapshot().openState).toBe('error') })
  505. expect(session.getSnapshot().openError).toMatchObject({ code: 'internal', message: 'repair wire down' })
  506. expect(eventSeqs(session)).toHaveLength(6)
  507. })
  508. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  509. const { api, session } = makeSession()
  510. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  511. api.onHistory = () => stale.promise
  512. const opening = session.open()
  513. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  514. const resynced = session.resync()
  515. stale.reject(new Error('stale wire'))
  516. await Promise.all([opening, resynced])
  517. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  518. })
  519. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  520. const { api, session } = makeSession()
  521. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  522. api.onHistory = () => stale.promise
  523. const opening = session.open()
  524. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  525. const resynced = session.resync()
  526. stale.resolve(ok({
  527. records: entries(plainTurn(0, 0, '旧', '代')) as never[],
  528. hasMore: false,
  529. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  530. })) // success, but its generation is gone
  531. await Promise.all([opening, resynced])
  532. expect(eventSeqs(session)).toEqual(plainTurn(6, 1, '新', '代').map(event => event.seq))
  533. })
  534. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  535. const { api, session } = makeSession()
  536. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  537. await session.open()
  538. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  539. api.onHistory = () => repairPull.promise
  540. const delivery = follow(api, ev.user(9, '洞'))
  541. await vi.waitFor(() => { expect(api.callsOf('session.history')).toHaveLength(1) })
  542. api.onHistory = () => histResponse(plainTurn(6, 1, 'c', 'd'))
  543. const resynced = session.resync() // bumps the generation
  544. repairPull.resolve(ok({
  545. records: entries(plainTurn(0, 0, '旧', '页')) as never[],
  546. hasMore: false,
  547. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  548. })) // repair result: stale, dropped
  549. await Promise.all([delivery, resynced])
  550. expect(eventSeqs(session)).toEqual(plainTurn(6, 1, 'c', 'd').map(event => event.seq))
  551. })
  552. it('successful cancel leaves no promptError', async () => {
  553. const { api, session } = makeSession()
  554. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  555. await session.open()
  556. const result = await session.cancel()
  557. expect(result.ok).toBe(true)
  558. expect(session.getSnapshot().promptError).toBeNull()
  559. })
  560. it('dispose is a reserved no-op on resident instances', async () => {
  561. const { session } = makeSession()
  562. await expect(session.dispose()).resolves.toBeUndefined()
  563. })
  564. it('carries raw history and follow events through the event feed', async () => {
  565. const { api, session } = makeSession()
  566. const historyCall = ev.toolCall(6, 1, 'h1', 'bash', '{"cmd":"pwd"}')
  567. const historyResult = ev.toolResult(7, 1, 'h1', 'done')
  568. api.onHistory = () => Promise.resolve(ok({
  569. records: [
  570. ...entries(plainTurn(0, 0, 'a', 'b')),
  571. { type: 'event', event: historyCall },
  572. { type: 'event', event: historyResult },
  573. ] as never[],
  574. hasMore: false,
  575. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  576. }))
  577. await session.open()
  578. expect(windowEntries(session).slice(-2)).toEqual([
  579. { type: 'event', event: historyCall },
  580. { type: 'event', event: historyResult },
  581. ])
  582. const liveCall = ev.toolCall(8, 2, 'l1', 'write', '{"file_path":"a.ts"}')
  583. await follow(api, liveCall)
  584. expect(windowEntries(session).at(-1)).toEqual({ type: 'event', event: liveCall })
  585. const liveResult = ev.toolResult(9, 2, 'l1', 'ok')
  586. await follow(api, liveResult)
  587. expect(windowEntries(session).at(-1)).toEqual({ type: 'event', event: liveResult })
  588. })
  589. })
  590. describe('resync', () => {
  591. it('keeps the old feed until the reconnect snapshot, then repairs queued live gaps', async () => {
  592. const { api, session } = makeSession()
  593. api.onHistory = () => histResponse(plainTurn(0, 0, '旧', '窗'))
  594. await session.open()
  595. const oldWindow = session.eventSource.getSnapshot()
  596. const replacement = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  597. api.followCursor = 15
  598. api.onHistory = () => replacement.promise
  599. const publications: ReturnType<Session['eventSource']['getSnapshot']>[] = []
  600. const off = session.eventSource.subscribe(() => {
  601. publications.push(session.eventSource.getSnapshot())
  602. })
  603. const syncing = session.resync()
  604. await vi.waitFor(() => { expect(api.callsOf('session.follow')).toHaveLength(2) })
  605. expect(session.eventSource.getSnapshot()).toBe(oldWindow)
  606. expect(publications).toEqual([])
  607. api.onHistory = () => histResponse([
  608. ...plainTurn(10, 2, '终', '页'),
  609. ev.user(16, '后到低位'),
  610. ev.user(17, '后到高位'),
  611. ])
  612. const liveDeliveries = Promise.all([
  613. follow(api, ev.user(17, '后到高位')),
  614. follow(api, ev.user(16, '后到低位')),
  615. ])
  616. expect(session.eventSource.getSnapshot()).toBe(oldWindow)
  617. replacement.resolve(ok({
  618. records: entries(plainTurn(10, 2, '终', '页')) as never[],
  619. hasMore: false,
  620. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  621. }))
  622. await Promise.all([syncing, liveDeliveries])
  623. await vi.waitFor(() => {
  624. expect(eventSeqs(session)).toEqual([10, 11, 12, 13, 14, 15, 16, 17])
  625. })
  626. expect(publications).toHaveLength(2)
  627. expect(publications.map(snapshot => snapshot.change.kind)).toEqual(['replace', 'replace'])
  628. expect(publications[0]?.entries.map(entry => entry.event.seq)).toEqual([10, 11, 12, 13, 14, 15])
  629. expect(publications[1]?.entries.map(entry => entry.event.seq)).toEqual([10, 11, 12, 13, 14, 15, 16, 17])
  630. off()
  631. })
  632. it('rebuilds the window without clearing control state; cold instances no-op', async () => {
  633. const { api, session } = makeSession()
  634. api.onHistory = () => histResponse(plainTurn(0, 0, 'a', 'b'))
  635. await session.open()
  636. session.handleRunning(true)
  637. session.handleAgentError('still visible')
  638. api.onHistory = () => histResponse([...plainTurn(0, 0, 'a', 'b'), ...plainTurn(6, 1, 'c', 'd')])
  639. await session.resync()
  640. const snapshot = session.getSnapshot()
  641. expect(snapshot.openState).toBe('open')
  642. expect(snapshot.running).toBe(true)
  643. expect(snapshot.lastAgentError).toBe('still visible')
  644. expect(eventSeqs(session)).toHaveLength(12)
  645. const cold = makeSession()
  646. await cold.session.resync()
  647. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  648. })
  649. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  650. const { api, session } = makeSession()
  651. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  652. api.onHistory = () => stale.promise
  653. const firstOpen = session.open()
  654. api.onHistory = () => histResponse(plainTurn(6, 1, '新', '代'))
  655. const resynced = session.resync()
  656. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  657. await firstOpen
  658. await resynced
  659. const snapshot = session.getSnapshot()
  660. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  661. expect(eventSeqs(session)).toEqual(plainTurn(6, 1, '新', '代').map(event => event.seq))
  662. })
  663. })
  664. describe('snapshot ownership', () => {
  665. it('publishes event-window appends without changing an unrelated Session snapshot', async () => {
  666. const { api, session } = makeSession()
  667. api.onHistory = () => histResponse(plainTurn(0, 0, '稳', '定'))
  668. await session.open()
  669. const sessionBefore = session.getSnapshot()
  670. const windowBefore = session.eventSource.getSnapshot()
  671. const firstEntry = windowBefore.entries[0]
  672. await follow(api, ev.user(6, '追加'))
  673. const windowAfter = session.eventSource.getSnapshot()
  674. expect(session.getSnapshot()).toBe(sessionBefore)
  675. expect(windowAfter).not.toBe(windowBefore)
  676. expect(windowAfter.entries[0]).toBe(firstEntry)
  677. expect(windowAfter.change).toMatchObject({ kind: 'append' })
  678. })
  679. })