session.client.spec.ts 32 KB

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