session.client.spec.ts 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. /** Session object lifecycle, event-window transport, commands, and resync behavior. */
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { SessionSeq, 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 { JUMP_PAGE_MESSAGES, 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(SessionSeq(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(SessionSeq(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(SessionSeq(10), 0, '早', '安')
  121. const deliveries = [
  122. follow(api, ev.turnStart(SessionSeq(15), 1)),
  123. follow(api, ev.user(SessionSeq(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(SessionSeq(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(SessionSeq(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(SessionSeq(0), 'cmd-perm', 'permission', ' danger-full-access')),
  154. follow(api, ev.commandDone(SessionSeq(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(SessionSeq(0), 0, 'a', 'b')) // tail seq = 5
  162. const repaired = [...plainTurn(SessionSeq(0), 0, 'a', 'b'), ...plainTurn(SessionSeq(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(SessionSeq(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(SessionSeq(0), 0, '旧问', '旧答')
  179. const newer = plainTurn(SessionSeq(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(SessionSeq(80), '窗外范围的摘要', SessionSeq(3), SessionSeq(40)),
  198. ev.compactCheckpoint(SessionSeq(81), SessionSeq(80), SessionSeq(3), SessionSeq(40)),
  199. ev.user(SessionSeq(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(SessionSeq(10), 1, '新', '页'), true)
  216. : histResponse(plainTurn(SessionSeq(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('loadThrough pages repeatedly until the window covers the target seq', async () => {
  230. const oldest = plainTurn(SessionSeq(0), 0, '最旧问', '最旧答')
  231. const middle = plainTurn(SessionSeq(6), 1, '中问', '中答')
  232. const newest = plainTurn(SessionSeq(12), 2, '新问', '新答')
  233. const { api, session } = makeSession()
  234. api.onHistory = (payload) => {
  235. if (payload.beforeSeq === undefined) return histResponse(newest, true)
  236. return payload.beforeSeq === 12 ? histResponse(middle, true) : histResponse(oldest, false)
  237. }
  238. await session.open()
  239. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  240. api.onHistory = (payload) => {
  241. api.onHistory = payload2 => payload2.beforeSeq === 12 ? histResponse(middle, true) : histResponse(oldest, false)
  242. void payload
  243. return gate.promise
  244. }
  245. const jump = session.loadThrough(SessionSeq(0))
  246. expect(session.getSnapshot().loadingOlder).toBe(true)
  247. gate.resolve(ok(historyValue(middle, true)))
  248. await jump
  249. const snapshot = session.getSnapshot()
  250. expect(snapshot.loadingOlder).toBe(false)
  251. expect(eventSeqs(session)).toEqual([...oldest, ...middle, ...newest].map(event => event.seq))
  252. expect(api.callsOf('session.history')).toMatchObject([
  253. { beforeSeq: 12, maxMessages: JUMP_PAGE_MESSAGES },
  254. { beforeSeq: 6, maxMessages: JUMP_PAGE_MESSAGES },
  255. ])
  256. })
  257. it('loadThrough is a no-op when the window already covers the target or the session is not open', async () => {
  258. const { api, session } = makeSession()
  259. await session.loadThrough(SessionSeq(0)) // cold: no-op
  260. expect(api.calls).toEqual([])
  261. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, 'x', 'y'), true)
  262. await session.open()
  263. const calls = api.calls.length
  264. await session.loadThrough(SessionSeq(6)) // baseSeq is already 6
  265. await session.loadThrough(SessionSeq(9)) // inside the window
  266. expect(api.calls.length).toBe(calls)
  267. })
  268. it('loadThrough retargets a running jump to the lowest requested seq and shares its completion', async () => {
  269. const oldest = plainTurn(SessionSeq(0), 0, 'a', 'b')
  270. const middle = plainTurn(SessionSeq(6), 1, 'c', 'd')
  271. const { api, session } = makeSession()
  272. api.onHistory = () => histResponse(plainTurn(SessionSeq(12), 2, 'e', 'f'), true)
  273. await session.open()
  274. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  275. api.onHistory = () => {
  276. api.onHistory = () => histResponse(oldest, false)
  277. return gate.promise
  278. }
  279. const first = session.loadThrough(SessionSeq(6))
  280. const second = session.loadThrough(SessionSeq(0))
  281. gate.resolve(ok(historyValue(middle, true)))
  282. await Promise.all([first, second])
  283. expect(eventSeqs(session)).toEqual([
  284. ...[...oldest, ...middle].map(event => event.seq),
  285. 12, 13, 14, 15, 16, 17,
  286. ])
  287. expect(api.callsOf('session.history')).toHaveLength(2)
  288. })
  289. it('loadThrough refused by a busy pager leaves no target behind for later jumps', async () => {
  290. const middle = plainTurn(SessionSeq(6), 1, 'c', 'd')
  291. const { api, session } = makeSession()
  292. api.onHistory = () => histResponse(plainTurn(SessionSeq(12), 2, 'e', 'f'), true)
  293. await session.open()
  294. // A plain single-page pull holds the busy flag while the jump is refused.
  295. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  296. api.onHistory = () => gate.promise
  297. const older = session.loadOlder()
  298. await session.loadThrough(SessionSeq(0)) // refused: must not park seq 0 anywhere
  299. gate.resolve(ok(historyValue(middle, true)))
  300. await older
  301. // A later jump to a nearer seq pages exactly to it — a leaked 0 target
  302. // would keep pulling three-event pages all the way to the head.
  303. api.onHistory = (payload) => {
  304. const start = ((payload as { beforeSeq?: number }).beforeSeq ?? 0) - 3
  305. return histResponse(
  306. [ev.user(SessionSeq(start), `u${String(start)}`), ev.user(SessionSeq(start + 1), `u${String(start + 1)}`), ev.user(SessionSeq(start + 2), `u${String(start + 2)}`)],
  307. start > 0,
  308. )
  309. }
  310. await session.loadThrough(SessionSeq(4))
  311. // Covered at seq 3 (≤ 4) after one page; a leaked 0 target would add a
  312. // third call at beforeSeq 3 and pull the head to 0.
  313. expect(api.callsOf('session.history').map(call => (call as { beforeSeq?: number }).beforeSeq))
  314. .toEqual([12, 6])
  315. expect(eventSeqs(session)[0]).toBe(3)
  316. })
  317. it('loadThrough stops paging when the event stream generation moves mid-loop', async () => {
  318. const { api, session } = makeSession()
  319. api.onHistory = () => histResponse(plainTurn(SessionSeq(12), 2, 'x', 'y'), true)
  320. await session.open()
  321. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  322. api.onHistory = () => gate.promise
  323. const jump = session.loadThrough(SessionSeq(0))
  324. // The address is rebuilt while the first page is in flight.
  325. api.onHistory = () => histResponse(plainTurn(SessionSeq(12), 2, 'x', 'y'), true)
  326. const rebuilt = session.resync()
  327. gate.resolve(ok(historyValue(plainTurn(SessionSeq(6), 1, 'c', 'd'), true)))
  328. await jump
  329. await rebuilt
  330. // The stale loop must not page the new generation toward its old target:
  331. // history calls are the gated page and the resync tail only.
  332. expect(api.callsOf('session.history')).toHaveLength(1)
  333. expect(session.getSnapshot().loadingOlder).toBe(false)
  334. })
  335. it('loadThrough stops on a page that makes no progress instead of looping', async () => {
  336. const { api, session } = makeSession()
  337. api.onHistory = payload => payload.beforeSeq === undefined
  338. ? histResponse(plainTurn(SessionSeq(12), 2, 'x', 'y'), true)
  339. : histResponse([], true) // empty page still claiming more history
  340. await session.open()
  341. await session.loadThrough(SessionSeq(0))
  342. expect(session.getSnapshot().loadingOlder).toBe(false)
  343. expect(api.callsOf('session.history')).toHaveLength(1)
  344. })
  345. it('loadThrough fails soft on a thrown page and clears its busy state', async () => {
  346. const { api, session } = makeSession()
  347. api.onHistory = () => histResponse(plainTurn(SessionSeq(12), 2, 'x', 'y'), true)
  348. await session.open()
  349. api.onHistory = () => Promise.reject(new Error('page wire down'))
  350. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  351. try {
  352. await session.loadThrough(SessionSeq(0))
  353. expect(errorSpy).toHaveBeenCalled()
  354. expect(session.getSnapshot().loadingOlder).toBe(false)
  355. } finally {
  356. errorSpy.mockRestore()
  357. }
  358. })
  359. it('ignores loadOlder while one is in flight (single request)', async () => {
  360. const { api, session } = makeSession()
  361. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, 'x', 'y'), true)
  362. await session.open()
  363. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  364. api.onHistory = () => gate.promise
  365. const first = session.loadOlder()
  366. const second = session.loadOlder()
  367. gate.resolve(ok({
  368. records: entries(plainTurn(SessionSeq(0), 0, 'a', 'b')) as never[],
  369. hasMore: false,
  370. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  371. }))
  372. await Promise.all([first, second])
  373. expect(api.callsOf('session.follow')).toHaveLength(1)
  374. expect(api.callsOf('session.history')).toHaveLength(1)
  375. })
  376. })
  377. describe('prompt and cancel errors', () => {
  378. it('routes an addressed child through non-activating history, continuation prompt, and interrupt only', async () => {
  379. const api = new FakeApiClient()
  380. const session = new Session(SID, fakeRemote(api), {
  381. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  382. parentAvailable: true,
  383. })
  384. await session.open()
  385. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  386. const cancelled = await session.cancel()
  387. expect(prompted).toEqual({ ok: true, value: { accepted: true } })
  388. expect(cancelled).toEqual({ ok: true, value: { accepted: true } })
  389. expect(api.callsOf('session.follow')).toEqual([
  390. {
  391. address: {
  392. kind: 'subagent', parentSessionId: PARENT, childSessionId: SID, mode: 'continuable',
  393. },
  394. maxMessages: 50,
  395. },
  396. ])
  397. expect(api.callsOf('subagent.history')).toEqual([])
  398. expect(api.callsOf('subagents.prompt')).toEqual([
  399. {
  400. requestId: expect.any(String) as unknown as string,
  401. parentSessionId: PARENT, childSessionId: SID,
  402. mode: 'continuable',
  403. content: [{ type: 'text', text: '继续' }],
  404. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  405. },
  406. ])
  407. expect(api.callsOf('subagents.interruptByParent')).toEqual([
  408. { childSessionId: SID, parentSessionId: PARENT, mode: 'continuable' },
  409. ])
  410. expect(api.callsOf('session.history')).toEqual([])
  411. expect(api.callsOf('session.prompt')).toEqual([])
  412. expect(api.callsOf('session.cancel')).toEqual([])
  413. // A successful interrupt leaves no stop error behind.
  414. expect(session.getSnapshot().promptError).toBeNull()
  415. expect(session.getSnapshot().subagent).toEqual({
  416. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  417. parentAvailable: true,
  418. })
  419. })
  420. it('forwards continuation image parts to the subagent prompt Remote unstripped', async () => {
  421. const api = new FakeApiClient()
  422. const session = new Session(SID, fakeRemote(api), {
  423. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  424. parentAvailable: true,
  425. })
  426. await session.open()
  427. const content = [
  428. { type: 'text' as const, text: '看这张图' },
  429. { type: 'image' as const, mediaType: 'image/png' as const, data: 'aGk=', name: 'shot.png' },
  430. ]
  431. const prompted = await session.prompt(content, 'queue')
  432. expect(prompted).toEqual({ ok: true, value: { accepted: true } })
  433. expect(api.callsOf('subagents.prompt')).toEqual([
  434. {
  435. requestId: expect.any(String) as unknown as string,
  436. parentSessionId: PARENT, childSessionId: SID,
  437. mode: 'continuable',
  438. content,
  439. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  440. },
  441. ])
  442. expect(session.getSnapshot().promptError).toBeNull()
  443. })
  444. it('lands an interrupt business failure in promptError with op=stop', async () => {
  445. const api = new FakeApiClient()
  446. api.onSubagentInterrupt = () => Promise.resolve(err(new RemoteError('subagent/unauthorized', 'nope', { childSessionId: SID })))
  447. const session = new Session(SID, fakeRemote(api), {
  448. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  449. parentAvailable: true,
  450. })
  451. await session.open()
  452. const cancelled = await session.cancel()
  453. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent/unauthorized' } })
  454. expect(session.getSnapshot().promptError).toMatchObject({
  455. op: 'stop', error: { code: 'subagent/unauthorized' },
  456. })
  457. })
  458. it('rejects staged files instead of dropping them from subagent continuations', async () => {
  459. const api = new FakeApiClient()
  460. const session = new Session(SID, fakeRemote(api), {
  461. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  462. parentAvailable: true,
  463. })
  464. await session.open()
  465. const prompted = await session.prompt([
  466. { type: 'file', receiptId: 'receipt' as never },
  467. { type: 'text', text: '继续' },
  468. ], 'queue')
  469. expect(prompted).toMatchObject({
  470. ok: false,
  471. error: {
  472. code: 'subagent/attachment-invalid',
  473. details: { reason: 'SUBAGENT_FILE_UNSUPPORTED' },
  474. },
  475. })
  476. expect(api.callsOf('subagents.prompt')).toEqual([])
  477. })
  478. it('sends a one-shot address to the Host under the continuable marker', async () => {
  479. const api = new FakeApiClient()
  480. api.onSubagentPrompt = () => Promise.resolve(err(new RemoteError(
  481. 'subagent/not-resumable', 'subagent cannot be resumed', { childSessionId: SID },
  482. )))
  483. const session = new Session(SID, fakeRemote(api), {
  484. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot' },
  485. })
  486. await session.open()
  487. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  488. const cancelled = await session.cancel()
  489. // The Host reads the durable descriptor; the wire marker stays 'continuable'.
  490. expect(prompted).toMatchObject({ ok: false, error: { code: 'subagent/not-resumable' } })
  491. expect(cancelled).toEqual({ ok: true, value: { accepted: true } })
  492. expect(api.callsOf('subagents.prompt')).toMatchObject([
  493. { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  494. ])
  495. expect(api.callsOf('subagents.interruptByParent')).toEqual([
  496. { childSessionId: SID, parentSessionId: PARENT, mode: 'continuable' },
  497. ])
  498. expect(api.callsOf('session.follow')).toEqual([
  499. {
  500. address: {
  501. kind: 'subagent', parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot',
  502. },
  503. maxMessages: 50,
  504. },
  505. ])
  506. expect(api.callsOf('subagent.history')).toEqual([])
  507. expect(api.callsOf('session.cancel')).toEqual([])
  508. })
  509. it('delivers an image continuation to the Host without narrowing its upload parts', async () => {
  510. const api = new FakeApiClient()
  511. const session = new Session(SID, fakeRemote(api), {
  512. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  513. })
  514. await session.open()
  515. const prompted = await session.prompt(
  516. [{ type: 'text', text: '看图' }, { type: 'image', mediaType: 'image/png', data: 'AA==' }],
  517. 'queue',
  518. )
  519. expect(prompted).toEqual({ ok: true, value: { accepted: true } })
  520. expect(api.callsOf('subagents.prompt')).toMatchObject([
  521. { content: [{ type: 'text' }, { type: 'image', mediaType: 'image/png', data: 'AA==' }] },
  522. ])
  523. })
  524. it('publishes the first-prompt lifecycle synchronously before the Remote settles', async () => {
  525. const { api, session } = makeSession()
  526. session.handleBlank(true)
  527. expect(session.getSnapshot()).toMatchObject({
  528. blank: true, promptAttempted: false, awaitingFirstTurn: false,
  529. })
  530. const inFlight = session.prompt([{ type: 'text', text: '要发的' }], 'queue')
  531. expect(session.getSnapshot()).toMatchObject({
  532. blank: true, promptAttempted: true, awaitingFirstTurn: true,
  533. })
  534. const result = await inFlight
  535. expect(result.ok).toBe(true)
  536. expect(session.getSnapshot()).toMatchObject({
  537. blank: false, promptAttempted: true, awaitingFirstTurn: true,
  538. })
  539. expect(api.callsOf('session.prompt')).toMatchObject([{
  540. sessionId: SID,
  541. mode: 'queue',
  542. content: [{ type: 'text', text: '要发的' }],
  543. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  544. }])
  545. session.handleRunning(true)
  546. expect(session.getSnapshot()).toMatchObject({ running: true, awaitingFirstTurn: false })
  547. })
  548. it('keeps the attempted-first-prompt state when the Host rejects the prompt', async () => {
  549. const { api, session } = makeSession()
  550. session.handleBlank(true)
  551. api.onPrompt = () => Promise.resolve(err(new RemoteError('session/agent-busy', 'busy', { reason: 'x' })))
  552. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue')
  553. expect(result.ok).toBe(false)
  554. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'session/agent-busy' } })
  555. expect(session.getSnapshot()).toMatchObject({
  556. blank: true, promptAttempted: true, awaitingFirstTurn: true,
  557. })
  558. })
  559. it('propagates a non-Remote throw raised while cancelling', async () => {
  560. const { api, session } = makeSession()
  561. api.onCancel = () => Promise.reject(new Error('cancel transport down'))
  562. await expect(session.cancel()).rejects.toThrow('cancel transport down')
  563. expect(session.getSnapshot().promptError).toBeNull()
  564. })
  565. it('reads session-authorized attachment bytes and keeps the opaque id on the wire', async () => {
  566. const { api, session } = makeSession()
  567. const result = await session.readAttachment('attachment-1' as never)
  568. expect(result).toEqual({
  569. ok: true,
  570. value: {
  571. attachment: { attachmentId: 'a', mediaType: 'image/png', bytes: 1, width: 1, height: 1 },
  572. data: Uint8Array.of(0),
  573. },
  574. })
  575. expect(api.callsOf('session.attachment')).toEqual([{
  576. sessionId: SID, attachmentId: 'attachment-1',
  577. }])
  578. })
  579. })
  580. describe('rename', () => {
  581. it('settles the title projection cell from the unary response (higher-seq-wins vs the push frame)', async () => {
  582. const { api, session } = makeSession()
  583. api.onRename = () => Promise.resolve(ok({ title: '正名', seq: 7 }))
  584. const result = await session.rename(' 正名 ')
  585. expect(result).toMatchObject({ ok: true, value: { title: '正名', seq: 7 } })
  586. expect(api.callsOf('session.rename')).toMatchObject([{ sessionId: SID, title: ' 正名 ' }])
  587. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  588. // A stale lower-seq apply (the push-frame path routes into this same
  589. // store) must not roll the settled value back.
  590. session.projections.apply('title', '旧名', SessionSeq(3))
  591. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  592. })
  593. it('returns the business error untouched and folds a transport throw to internal', async () => {
  594. const { api, session } = makeSession()
  595. api.onRename = () => Promise.resolve(err(new RemoteError('session/title-invalid', 'empty', { sessionId: SID })))
  596. const rejected = await session.rename(' ')
  597. expect(rejected).toMatchObject({ ok: false, error: { code: 'session/title-invalid' } })
  598. expect(session.projections.faceOf('title').getSnapshot()).toBeUndefined()
  599. api.onRename = () => Promise.reject(new Error('rename transport down'))
  600. await expect(session.rename('x')).rejects.toThrow('rename transport down')
  601. })
  602. })
  603. describe('remaining branches', () => {
  604. it('propagates a non-Remote throw raised while prompting', async () => {
  605. const { api, session } = makeSession()
  606. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  607. await expect(session.prompt([{ type: 'text', text: 'x' }], 'queue')).rejects.toThrow('prompt wire down')
  608. expect(session.getSnapshot().promptError).toBeNull()
  609. })
  610. it('cancel business error also lands op=stop promptError', async () => {
  611. const { api, session } = makeSession()
  612. api.onCancel = () => Promise.resolve(err(new RemoteError('session/agent-busy', 'nope', { reason: 'r' })))
  613. await session.cancel()
  614. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'session/agent-busy' } })
  615. })
  616. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  617. const { api, session } = makeSession()
  618. await session.loadOlder() // cold: no-op, zero calls
  619. expect(api.calls).toEqual([])
  620. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, 'x', 'y'), true)
  621. await session.open()
  622. // err result: window unchanged
  623. api.onHistory = () => Promise.resolve(err(new RemoteError('gateway/internal', 'x', {})))
  624. await session.loadOlder()
  625. expect(eventSeqs(session)).toHaveLength(6)
  626. expect(session.getSnapshot().hasMore).toBe(true)
  627. // empty page: hasMore adopts the response
  628. api.onHistory = () => histResponse([], false)
  629. await session.loadOlder()
  630. expect(session.getSnapshot().hasMore).toBe(false)
  631. // hasMore false now: further loadOlder is a guard no-op
  632. const calls = api.calls.length
  633. await session.loadOlder()
  634. expect(api.calls.length).toBe(calls)
  635. // throw path: fail-soft with console.error
  636. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  637. try {
  638. await session.resync()
  639. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, 'x', 'y'), true)
  640. await session.resync()
  641. api.onHistory = () => Promise.reject(new Error('page wire down'))
  642. await session.loadOlder()
  643. expect(errorSpy).toHaveBeenCalled()
  644. expect(session.getSnapshot().loadingOlder).toBe(false)
  645. } finally {
  646. errorSpy.mockRestore()
  647. }
  648. })
  649. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  650. const { api, session } = makeSession()
  651. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  652. let notified = 0
  653. const unsubscribe = session.subscribe(() => { notified++ })
  654. await session.open()
  655. await new Promise(resolve => setTimeout(resolve, 0))
  656. expect(notified).toBeGreaterThan(0)
  657. const seen = notified
  658. unsubscribe()
  659. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  660. await new Promise(resolve => setTimeout(resolve, 0))
  661. expect(notified).toBe(seen)
  662. })
  663. it('rejects an opening page that does not end at the opening cursor', async () => {
  664. const { api, session } = makeSession()
  665. let call = 0
  666. api.onHistory = () => {
  667. call++
  668. return histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  669. }
  670. api.followCursor = 11
  671. await session.open()
  672. expect(call).toBe(1)
  673. const snapshot = session.getSnapshot()
  674. expect(snapshot.openState).toBe('error')
  675. expect(snapshot.openError).toMatchObject({
  676. code: 'gateway/internal', message: 'session event stream page did not end at its requested cursor',
  677. })
  678. expect(eventSeqs(session)).toEqual([])
  679. })
  680. it('deduplicates repeated running flips and records removal', () => {
  681. const { session } = makeSession()
  682. const before = session.getSnapshot()
  683. session.handleRunning(false) // already false: dedup branch
  684. expect(session.getSnapshot()).toBe(before)
  685. session.handleRemoved()
  686. expect(session.getSnapshot().removed).toBe(true)
  687. })
  688. it('drops live events while cold/error (no window upkeep)', async () => {
  689. const { api, session } = makeSession()
  690. await follow(api, ev.user(SessionSeq(0), '冷态帧'))
  691. expect(eventSeqs(session)).toEqual([])
  692. api.onHistory = () => Promise.resolve(err(new RemoteError('gateway/internal', 'x', {})))
  693. await session.open()
  694. await follow(api, ev.user(SessionSeq(0), '错态帧'))
  695. expect(eventSeqs(session)).toEqual([])
  696. })
  697. it('preserves a Host-reported failure that terminates the live source', async () => {
  698. const { api, session } = makeSession()
  699. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  700. await session.open()
  701. const failure = new RemoteError('session/not-found', 'session disappeared', { sessionId: SID })
  702. api.failStreams(failure)
  703. await vi.waitFor(() => { expect(session.getSnapshot().openState).toBe('error') })
  704. expect(session.getSnapshot().openError).toMatchObject({
  705. code: failure.code, message: failure.message, details: failure.details,
  706. })
  707. })
  708. it('coalesces queued gap frames behind one repair and exposes a failed repair', async () => {
  709. const { api, session } = makeSession()
  710. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  711. await session.open()
  712. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  713. let repairs = 0
  714. api.onHistory = () => {
  715. repairs++
  716. return gate.promise
  717. }
  718. const deliveries = Promise.all([
  719. follow(api, ev.user(SessionSeq(9), '洞一')),
  720. follow(api, ev.user(SessionSeq(10), '洞二')),
  721. ])
  722. await vi.waitFor(() => { expect(repairs).toBe(1) })
  723. gate.reject(new RemoteError('gateway/internal', 'repair wire down', {}))
  724. await deliveries
  725. await vi.waitFor(() => { expect(session.getSnapshot().openState).toBe('error') })
  726. expect(session.getSnapshot().openError).toMatchObject({ code: 'gateway/internal', message: 'repair wire down' })
  727. expect(eventSeqs(session)).toHaveLength(6)
  728. })
  729. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  730. const { api, session } = makeSession()
  731. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  732. api.onHistory = () => stale.promise
  733. const opening = session.open()
  734. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  735. const resynced = session.resync()
  736. stale.reject(new Error('stale wire'))
  737. await Promise.all([opening, resynced])
  738. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  739. })
  740. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  741. const { api, session } = makeSession()
  742. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  743. api.onHistory = () => stale.promise
  744. const opening = session.open()
  745. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, '新', '代'))
  746. const resynced = session.resync()
  747. stale.resolve(ok({
  748. records: entries(plainTurn(SessionSeq(0), 0, '旧', '代')) as never[],
  749. hasMore: false,
  750. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  751. })) // success, but its generation is gone
  752. await Promise.all([opening, resynced])
  753. expect(eventSeqs(session)).toEqual(plainTurn(SessionSeq(6), 1, '新', '代').map(event => event.seq))
  754. })
  755. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  756. const { api, session } = makeSession()
  757. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  758. await session.open()
  759. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  760. api.onHistory = () => repairPull.promise
  761. const delivery = follow(api, ev.user(SessionSeq(9), '洞'))
  762. await vi.waitFor(() => { expect(api.callsOf('session.history')).toHaveLength(1) })
  763. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, 'c', 'd'))
  764. const resynced = session.resync() // bumps the generation
  765. repairPull.resolve(ok({
  766. records: entries(plainTurn(SessionSeq(0), 0, '旧', '页')) as never[],
  767. hasMore: false,
  768. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  769. })) // repair result: stale, dropped
  770. await Promise.all([delivery, resynced])
  771. expect(eventSeqs(session)).toEqual(plainTurn(SessionSeq(6), 1, 'c', 'd').map(event => event.seq))
  772. })
  773. it('successful cancel leaves no promptError', async () => {
  774. const { api, session } = makeSession()
  775. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  776. await session.open()
  777. const result = await session.cancel()
  778. expect(result.ok).toBe(true)
  779. expect(session.getSnapshot().promptError).toBeNull()
  780. })
  781. it('dispose is a reserved no-op on resident instances', async () => {
  782. const { session } = makeSession()
  783. await expect(session.dispose()).resolves.toBeUndefined()
  784. })
  785. it('carries raw history and follow events through the event feed', async () => {
  786. const { api, session } = makeSession()
  787. const historyCall = ev.toolCall(SessionSeq(6), 1, 'h1', 'bash', '{"cmd":"pwd"}')
  788. const historyResult = ev.toolResult(SessionSeq(7), 1, 'h1', 'done')
  789. api.onHistory = () => Promise.resolve(ok({
  790. records: [
  791. ...entries(plainTurn(SessionSeq(0), 0, 'a', 'b')),
  792. { type: 'event', event: historyCall },
  793. { type: 'event', event: historyResult },
  794. ] as never[],
  795. hasMore: false,
  796. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  797. }))
  798. await session.open()
  799. expect(windowEntries(session).slice(-2)).toEqual([
  800. { type: 'event', event: historyCall },
  801. { type: 'event', event: historyResult },
  802. ])
  803. const liveCall = ev.toolCall(SessionSeq(8), 2, 'l1', 'write', '{"file_path":"a.ts"}')
  804. await follow(api, liveCall)
  805. expect(windowEntries(session).at(-1)).toEqual({ type: 'event', event: liveCall })
  806. const liveResult = ev.toolResult(SessionSeq(9), 2, 'l1', 'ok')
  807. await follow(api, liveResult)
  808. expect(windowEntries(session).at(-1)).toEqual({ type: 'event', event: liveResult })
  809. })
  810. })
  811. describe('resync', () => {
  812. it('keeps the old feed until the reconnect snapshot, then repairs queued live gaps', async () => {
  813. const { api, session } = makeSession()
  814. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, '旧', '窗'))
  815. await session.open()
  816. const oldWindow = session.eventSource.getSnapshot()
  817. const replacement = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  818. api.followCursor = 15
  819. api.onHistory = () => replacement.promise
  820. const publications: ReturnType<Session['eventSource']['getSnapshot']>[] = []
  821. const off = session.eventSource.subscribe(() => {
  822. publications.push(session.eventSource.getSnapshot())
  823. })
  824. const syncing = session.resync()
  825. await vi.waitFor(() => { expect(api.callsOf('session.follow')).toHaveLength(2) })
  826. expect(session.eventSource.getSnapshot()).toBe(oldWindow)
  827. expect(publications).toEqual([])
  828. api.onHistory = () => histResponse([
  829. ...plainTurn(SessionSeq(10), 2, '终', '页'),
  830. ev.user(SessionSeq(16), '后到低位'),
  831. ev.user(SessionSeq(17), '后到高位'),
  832. ])
  833. const liveDeliveries = Promise.all([
  834. follow(api, ev.user(SessionSeq(17), '后到高位')),
  835. follow(api, ev.user(SessionSeq(16), '后到低位')),
  836. ])
  837. expect(session.eventSource.getSnapshot()).toBe(oldWindow)
  838. replacement.resolve(ok({
  839. records: entries(plainTurn(SessionSeq(10), 2, '终', '页')) as never[],
  840. hasMore: false,
  841. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  842. }))
  843. await Promise.all([syncing, liveDeliveries])
  844. await vi.waitFor(() => {
  845. expect(eventSeqs(session)).toEqual([10, 11, 12, 13, 14, 15, 16, 17])
  846. })
  847. expect(publications).toHaveLength(2)
  848. expect(publications.map(snapshot => snapshot.change.kind)).toEqual(['replace', 'replace'])
  849. expect(publications[0]?.entries.map(entry => entry.event.seq)).toEqual([10, 11, 12, 13, 14, 15])
  850. expect(publications[1]?.entries.map(entry => entry.event.seq)).toEqual([10, 11, 12, 13, 14, 15, 16, 17])
  851. off()
  852. })
  853. it('rebuilds the window without clearing control state; cold instances no-op', async () => {
  854. const { api, session } = makeSession()
  855. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  856. await session.open()
  857. session.handleRunning(true)
  858. session.handleAgentError('still visible')
  859. api.onHistory = () => histResponse([...plainTurn(SessionSeq(0), 0, 'a', 'b'), ...plainTurn(SessionSeq(6), 1, 'c', 'd')])
  860. await session.resync()
  861. const snapshot = session.getSnapshot()
  862. expect(snapshot.openState).toBe('open')
  863. expect(snapshot.running).toBe(true)
  864. expect(snapshot.lastAgentError).toBe('still visible')
  865. expect(eventSeqs(session)).toHaveLength(12)
  866. const cold = makeSession()
  867. await cold.session.resync()
  868. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  869. })
  870. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  871. const { api, session } = makeSession()
  872. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  873. api.onHistory = () => stale.promise
  874. const firstOpen = session.open()
  875. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, '新', '代'))
  876. const resynced = session.resync()
  877. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  878. await firstOpen
  879. await resynced
  880. const snapshot = session.getSnapshot()
  881. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  882. expect(eventSeqs(session)).toEqual(plainTurn(SessionSeq(6), 1, '新', '代').map(event => event.seq))
  883. })
  884. })
  885. describe('snapshot ownership', () => {
  886. it('publishes event-window appends without changing an unrelated Session snapshot', async () => {
  887. const { api, session } = makeSession()
  888. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, '稳', '定'))
  889. await session.open()
  890. const sessionBefore = session.getSnapshot()
  891. const windowBefore = session.eventSource.getSnapshot()
  892. const firstEntry = windowBefore.entries[0]
  893. await follow(api, ev.user(SessionSeq(6), '追加'))
  894. const windowAfter = session.eventSource.getSnapshot()
  895. expect(session.getSnapshot()).toBe(sessionBefore)
  896. expect(windowAfter).not.toBe(windowBefore)
  897. expect(windowAfter.entries[0]).toBe(firstEntry)
  898. expect(windowAfter.change).toMatchObject({ kind: 'append' })
  899. })
  900. })