session.client.spec.ts 34 KB

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