session.client.spec.ts 31 KB

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