session.client.spec.ts 31 KB

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