session.client.spec.ts 33 KB

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