session.client.spec.ts 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. /** Session object lifecycle, event-window transport, commands, and resync behavior. */
  2. import { afterEach, describe, expect, it, vi } from 'vitest'
  3. import { Context } from '@deepseek-ai/cordis'
  4. import type { FileUploadService } from '@deepseek-ai/dsh-client-file-upload/client'
  5. import { SessionSeq, type SessionEvent } from '@deepseek-ai/dsh-session/types'
  6. import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'
  7. import { RemoteStreamCarrierError } from '@deepseek-ai/dsh-api-gateway/client'
  8. import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
  9. import { JUMP_PAGE_MESSAGES, Session, type SessionOptions } from '../src/client/sessions/session.ts'
  10. import { FakeApiClient, deferred, err, fakeRemote, ok } from './fake-api.client.ts'
  11. import { entries, ev, historyValue, plainTurn } from './event-script.client.ts'
  12. const SID = 'fk-s1' as SessionId
  13. const PARENT = 'fk-parent' as SessionId
  14. afterEach(() => {
  15. vi.unstubAllGlobals()
  16. })
  17. function makeSession(
  18. api = new FakeApiClient(),
  19. options: SessionOptions = {},
  20. ): { api: FakeApiClient; session: Session } {
  21. return { api, session: new Session(SID, fakeRemote(api), options) }
  22. }
  23. function bindFileUpload(
  24. session: Session,
  25. post: FileUploadService['post'],
  26. available = true,
  27. ): void {
  28. const ctx = new Context()
  29. ctx.reflect.provide('fileUpload', { available, post })
  30. session.bindScope(ctx)
  31. }
  32. function follow(
  33. api: FakeApiClient,
  34. event: SessionEvent,
  35. ): Promise<void> {
  36. return api.pushFollow(SID, {
  37. type: 'event',
  38. event: event as never,
  39. })
  40. }
  41. function windowEntries(session: Session) {
  42. return session.eventSource.getSnapshot().entries
  43. }
  44. function eventSeqs(session: Session): number[] {
  45. return windowEntries(session).map(entry => entry.event.seq)
  46. }
  47. function histResponse(events: SessionEvent[], hasMore = false) {
  48. return Promise.resolve(ok(historyValue(events, hasMore)))
  49. }
  50. describe('Session file upload', () => {
  51. it('uses the background body carrier, reports progress, and validates its receipt', async () => {
  52. const progress = vi.fn()
  53. const post = vi.fn(async (request: {
  54. path: string
  55. body: Blob | ReadableStream<Uint8Array>
  56. headers?: Readonly<Record<string, string>>
  57. signal?: AbortSignal
  58. onProgress?: (progress: { loaded: number; total?: number }) => void
  59. }) => {
  60. request.onProgress?.({ loaded: 2, total: 4 })
  61. return {
  62. status: 200,
  63. body: JSON.stringify({
  64. ok: true,
  65. value: {
  66. receiptId: 'receipt-1',
  67. file: { attachmentId: 'file-1', name: 'notes & refs.pdf', bytes: 4 },
  68. },
  69. }),
  70. }
  71. })
  72. const { api, session } = makeSession()
  73. bindFileUpload(session, post)
  74. const abort = new AbortController()
  75. const file = new Blob([Uint8Array.of(1, 2, 3, 4)])
  76. await expect(session.uploadFile(file, 'notes & refs.pdf', abort.signal, progress)).resolves.toEqual({
  77. ok: true,
  78. value: {
  79. receiptId: 'receipt-1',
  80. file: { attachmentId: 'file-1', name: 'notes & refs.pdf', bytes: 4 },
  81. },
  82. })
  83. expect(post).toHaveBeenCalledWith(expect.objectContaining({
  84. path: '/api/session/uploadFileBinary?sessionId=fk-s1&name=notes+%26+refs.pdf',
  85. body: file,
  86. headers: { 'content-type': 'application/octet-stream' },
  87. signal: abort.signal,
  88. }))
  89. expect(progress).toHaveBeenCalledWith({ loaded: 2, total: 4 })
  90. expect(api.callsOf('session.uploadFile')).toEqual([])
  91. })
  92. it('preserves a background business failure and supports unnamed files without observers', async () => {
  93. const post = vi.fn((_request: { readonly body: Blob }) => Promise.resolve({
  94. status: 200,
  95. body: JSON.stringify({
  96. ok: false,
  97. error: { code: 'session/attachment-invalid', message: 'denied', details: { reason: 'NOPE' } },
  98. }),
  99. }))
  100. const { session } = makeSession()
  101. bindFileUpload(session, post)
  102. await expect(session.uploadFile(new Blob([]))).resolves.toMatchObject({
  103. ok: false,
  104. error: { code: 'session/attachment-invalid', message: 'denied', details: { reason: 'NOPE' } },
  105. })
  106. const request = post.mock.calls[0]?.[0]
  107. expect(request).toMatchObject({
  108. path: '/api/session/uploadFileBinary?sessionId=fk-s1',
  109. headers: { 'content-type': 'application/octet-stream' },
  110. })
  111. expect(request?.body).toBeInstanceOf(Blob)
  112. })
  113. it('keeps byte and Blob fallback uploads on the generated Remote carrier', async () => {
  114. const { api, session } = makeSession()
  115. await expect(session.uploadFile(Uint8Array.of(0, 0, 0), 'bytes.bin')).resolves.toMatchObject({ ok: true })
  116. await expect(session.uploadFile(new Blob([Uint8Array.of(1)]))).resolves.toMatchObject({ ok: true })
  117. expect(api.callsOf('session.uploadFile')).toEqual([
  118. { sessionId: SID, data: 'AAAA', name: 'bytes.bin' },
  119. { sessionId: SID, data: 'AQ==' },
  120. ])
  121. })
  122. it('keeps fixture Blob fallback on the Remote and refuses an uncarried stream', async () => {
  123. const { api, session } = makeSession()
  124. const post = vi.fn<FileUploadService['post']>()
  125. bindFileUpload(session, post, false)
  126. await expect(session.uploadFile(new Blob([Uint8Array.of(1)]), 'fixture.bin'))
  127. .resolves.toMatchObject({ ok: true })
  128. const stream = new ReadableStream<Uint8Array>({ start(controller) { controller.close() } })
  129. await expect(session.uploadFile(stream, 'stream.bin'))
  130. .rejects.toThrow('stream file upload requires a bound Client file-upload service')
  131. expect(post).not.toHaveBeenCalled()
  132. expect(api.callsOf('session.uploadFile')).toEqual([
  133. { sessionId: SID, data: 'AQ==', name: 'fixture.bin' },
  134. ])
  135. })
  136. it('hands a one-shot ReadableStream to the scoped file-upload service', async () => {
  137. const post = vi.fn(() => Promise.resolve({
  138. status: 200,
  139. body: JSON.stringify({
  140. ok: true,
  141. value: {
  142. receiptId: 'stream-receipt',
  143. file: { attachmentId: 'stream-file', name: 'stream.bin', bytes: 3 },
  144. },
  145. }),
  146. }))
  147. const { session } = makeSession()
  148. bindFileUpload(session, post)
  149. const stream = new ReadableStream<Uint8Array>({
  150. start(controller) {
  151. controller.enqueue(Uint8Array.of(1, 2, 3))
  152. controller.close()
  153. },
  154. })
  155. await expect(session.uploadFile(stream, 'stream.bin')).resolves.toMatchObject({ ok: true })
  156. expect(post).toHaveBeenCalledWith(expect.objectContaining({
  157. path: '/api/session/uploadFileBinary?sessionId=fk-s1&name=stream.bin',
  158. body: stream,
  159. }))
  160. })
  161. it('refuses a stream when a bare Session has no scoped upload service', async () => {
  162. const { session } = makeSession()
  163. const stream = new ReadableStream<Uint8Array>({ start(controller) { controller.close() } })
  164. await expect(session.uploadFile(stream)).rejects.toThrow(
  165. 'stream file upload requires a bound Client file-upload service',
  166. )
  167. })
  168. it('folds non-200 and malformed background responses into transport failures', async () => {
  169. const bodies: unknown[] = [
  170. null,
  171. { ok: 'yes' },
  172. { ok: false, error: null },
  173. { ok: false, error: { code: 1, message: 'x', details: {} } },
  174. { ok: false, error: { code: 'x', message: 1, details: {} } },
  175. { ok: false, error: { code: 'x', message: 'x', details: null } },
  176. { ok: true, value: null },
  177. { ok: true, value: { receiptId: 1, file: {} } },
  178. { ok: true, value: { receiptId: 'r', file: null } },
  179. { ok: true, value: { receiptId: 'r', file: { attachmentId: 1, name: 'x', bytes: 1 } } },
  180. { ok: true, value: { receiptId: 'r', file: { attachmentId: 'a', name: 1, bytes: 1 } } },
  181. { ok: true, value: { receiptId: 'r', file: { attachmentId: 'a', name: 'x', bytes: '1' } } },
  182. { ok: true, value: { receiptId: 'r', file: { attachmentId: 'a', name: 'x', bytes: 1.5 } } },
  183. { ok: true, value: { receiptId: 'r', file: { attachmentId: 'a', name: 'x', bytes: -1 } } },
  184. ]
  185. for (const body of bodies) {
  186. const { session } = makeSession()
  187. bindFileUpload(session, () => Promise.resolve({ status: 200, body: JSON.stringify(body) }))
  188. await expect(session.uploadFile(new Blob([])))
  189. .rejects.toThrow(/file upload transport returned an invalid/)
  190. }
  191. const { session } = makeSession()
  192. bindFileUpload(session, () => Promise.resolve({ status: 503, body: 'unavailable' }))
  193. await expect(session.uploadFile(new Blob([])))
  194. .rejects.toThrow('file upload transport failed with HTTP 503')
  195. })
  196. it('refuses a direct file upload for a continuable subagent before either carrier runs', async () => {
  197. const post = vi.fn()
  198. const api = new FakeApiClient()
  199. const session = new Session(SID, fakeRemote(api), {
  200. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  201. })
  202. bindFileUpload(session, post)
  203. await expect(session.uploadFile(new Blob([]))).resolves.toMatchObject({
  204. ok: false,
  205. error: { code: 'subagent/attachment-invalid', details: { reason: 'SUBAGENT_FILE_UNSUPPORTED' } },
  206. })
  207. expect(post).not.toHaveBeenCalled()
  208. expect(api.callsOf('session.uploadFile')).toEqual([])
  209. })
  210. })
  211. describe('Session open', () => {
  212. it('keeps a bare Session blank until an authoritative lifecycle signal arrives', () => {
  213. const { session } = makeSession()
  214. expect(session.getSnapshot()).toMatchObject({ blank: true, promptAttempted: false, running: false })
  215. session.handleRunning(true)
  216. expect(session.getSnapshot()).toMatchObject({ blank: false, running: true })
  217. })
  218. it('installs the tail page: cold → loading → open with window and nodes in place', async () => {
  219. const { api, session } = makeSession()
  220. const page = plainTurn(SessionSeq(10), 3, '问', '答')
  221. api.onHistory = () => histResponse(page, true)
  222. expect(session.getSnapshot().openState).toBe('cold')
  223. const opening = session.open()
  224. expect(session.getSnapshot().openState).toBe('loading')
  225. await opening
  226. const snapshot = session.getSnapshot()
  227. expect(snapshot.openState).toBe('open')
  228. expect(snapshot.hasMore).toBe(true)
  229. expect(eventSeqs(session)).toEqual([10, 11, 12, 13, 14, 15])
  230. expect(session.eventSource.getSnapshot().change).toMatchObject({ kind: 'replace' })
  231. })
  232. it('is idempotent: concurrent opens share one follow, reopening when open is a no-op', async () => {
  233. const { api, session } = makeSession()
  234. await Promise.all([session.open(), session.open()])
  235. await session.open()
  236. expect(api.callsOf('session.follow')).toHaveLength(1)
  237. expect(api.callsOf('session.history')).toEqual([])
  238. })
  239. it('lands an error result in openState=error with the Remote failure kept', async () => {
  240. const { api, session } = makeSession()
  241. api.onHistory = () => Promise.resolve(err(new RemoteError('session/not-found', 'gone', { sessionId: SID })))
  242. await session.open()
  243. const snapshot = session.getSnapshot()
  244. expect(snapshot.openState).toBe('error')
  245. expect(snapshot.openError?.code).toBe('session/not-found')
  246. })
  247. it('lands exhausted carrier retries in openState=error as gateway/internal', async () => {
  248. const { api, session } = makeSession()
  249. // Two consecutive carrier losses before any opening is accepted exhaust the
  250. // Gateway's retry budget; the escaping failure crosses the stream boundary marked.
  251. api.onHistory = () => Promise.reject(new RemoteStreamCarrierError('history carrier down'))
  252. await session.open()
  253. expect(session.getSnapshot().openState).toBe('error')
  254. expect(session.getSnapshot().openError).toMatchObject({
  255. code: 'gateway/internal', message: 'history carrier down',
  256. })
  257. expect(api.followStarts).toHaveLength(2)
  258. })
  259. it('lands a packed live record in openState=error instead of crashing the stream loop', async () => {
  260. const { api, session } = makeSession()
  261. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  262. await session.open()
  263. expect(session.getSnapshot().openState).toBe('open')
  264. // The live tail may carry only events; a packed record breaks that contract.
  265. await api.pushFollow(SID, {
  266. type: 'chunks',
  267. event: {
  268. type: 'chunkrow/text-chunks',
  269. seq: 6,
  270. time: 6,
  271. data: { turn: 1, step: 1, index: 0, texts: ['a'], dt: [] },
  272. },
  273. } as never)
  274. await vi.waitFor(() => { expect(session.getSnapshot().openState).toBe('error') })
  275. expect(session.getSnapshot().openError).toMatchObject({
  276. code: 'gateway/internal', message: 'session live stream emitted a packed history record',
  277. })
  278. })
  279. it('lands a Gateway-marked stream failure in openState=error', async () => {
  280. const { api, session } = makeSession()
  281. api.onHistory = () => Promise.reject(new Error('socket died'))
  282. await session.open()
  283. expect(session.getSnapshot().openState).toBe('error')
  284. expect(session.getSnapshot().openError).toMatchObject({ code: 'gateway/internal', message: 'socket died' })
  285. })
  286. it('stitches live frames arriving while history is pending, dropping the page overlap', async () => {
  287. const { api, session } = makeSession()
  288. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  289. api.onHistory = () => gate.promise
  290. const opening = session.open()
  291. // Three live frames land while the opening snapshot is pending; seq 15 overlaps its tail.
  292. const page = plainTurn(SessionSeq(10), 0, '早', '安')
  293. const deliveries = [
  294. follow(api, ev.turnStart(SessionSeq(15), 1)),
  295. follow(api, ev.user(SessionSeq(16), '插进来的')),
  296. ]
  297. gate.resolve(ok({
  298. records: entries(page) as never[],
  299. hasMore: false,
  300. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  301. }))
  302. await Promise.all([opening, ...deliveries])
  303. const seqs = eventSeqs(session)
  304. // Overlapping seq-15 frame (== page tail turn/end) was dropped; 16 appended once.
  305. expect(seqs).toEqual([10, 11, 12, 13, 14, 15, 16])
  306. })
  307. })
  308. describe('live event path', () => {
  309. async function opened(events: SessionEvent[] = plainTurn(SessionSeq(0), 0, 'a', 'b')) {
  310. const { api, session } = makeSession()
  311. api.onHistory = () => histResponse(events)
  312. await session.open()
  313. return { api, session }
  314. }
  315. it('drops replayed frames at or below the window tail', async () => {
  316. const { api, session } = await opened()
  317. const before = session.eventSource.getSnapshot()
  318. await follow(api, ev.user(SessionSeq(3), '重放'))
  319. expect(session.eventSource.getSnapshot()).toBe(before)
  320. })
  321. it('keeps the authoritative host blank bit across unrelated log events', async () => {
  322. const { api, session } = await opened([])
  323. session.handleBlank(true)
  324. await Promise.all([
  325. follow(api, ev.commandRun(SessionSeq(0), 'cmd-perm', 'permission', ' danger-full-access')),
  326. follow(api, ev.commandDone(SessionSeq(1), 'cmd-perm', 'success', 'preset danger-full-access')),
  327. ])
  328. const snapshot = session.getSnapshot()
  329. expect(eventSeqs(session)).toEqual([0, 1])
  330. expect(snapshot.blank).toBe(true)
  331. })
  332. it('repairs a seq gap by repulling the tail page instead of appending a hole', async () => {
  333. const { api, session } = await opened(plainTurn(SessionSeq(0), 0, 'a', 'b')) // tail seq = 5
  334. const repaired = [...plainTurn(SessionSeq(0), 0, 'a', 'b'), ...plainTurn(SessionSeq(6), 1, 'c', 'd')]
  335. api.onHistory = () => histResponse(repaired)
  336. // seq 9 with tail 5 → gap; the event detours to the buffer and one history refetch fires.
  337. await follow(api, ev.assistant(SessionSeq(9), 1, 'd'))
  338. await vi.waitFor(() => {
  339. expect(api.callsOf('session.history')).toHaveLength(1)
  340. })
  341. await vi.waitFor(() => {
  342. expect(eventSeqs(session)).toEqual(
  343. repaired.filter(event => event.seq <= 9).map(event => event.seq),
  344. )
  345. })
  346. })
  347. })
  348. describe('paging', () => {
  349. it('prepends an older page and keeps seq continuity', async () => {
  350. const older = plainTurn(SessionSeq(0), 0, '旧问', '旧答')
  351. const newer = plainTurn(SessionSeq(6), 1, '新问', '新答')
  352. const { api, session } = makeSession()
  353. api.onHistory = payload => payload.beforeSeq === undefined
  354. ? histResponse(newer, true)
  355. : histResponse(older, false)
  356. await session.open()
  357. await session.loadOlder()
  358. const snapshot = session.getSnapshot()
  359. expect(api.callsOf('session.follow')).toHaveLength(1)
  360. expect(api.callsOf('session.history')).toMatchObject([
  361. { sessionId: SID, throughSeq: 11, beforeSeq: 6 },
  362. ])
  363. expect(snapshot.hasMore).toBe(false)
  364. expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq))
  365. })
  366. it('installs a page without interpreting business replacement metadata', async () => {
  367. const { api, session } = makeSession()
  368. api.onHistory = () => histResponse([
  369. ev.compactSummary(SessionSeq(80), '窗外范围的摘要', SessionSeq(3), SessionSeq(40)),
  370. ev.compactCheckpoint(SessionSeq(81), SessionSeq(80), SessionSeq(3), SessionSeq(40)),
  371. ev.user(SessionSeq(82), '压缩后的新问题'),
  372. ], true)
  373. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  374. try {
  375. await session.open()
  376. const snapshot = session.getSnapshot()
  377. expect(snapshot.openState).toBe('open')
  378. expect(eventSeqs(session)).toEqual([80, 81, 82])
  379. expect(errorSpy).not.toHaveBeenCalled()
  380. } finally {
  381. errorSpy.mockRestore()
  382. }
  383. })
  384. it('drops a discontinuous older page fail-soft (window unchanged, hasMore cleared)', async () => {
  385. const { api, session } = makeSession()
  386. api.onHistory = payload => payload.beforeSeq === undefined
  387. ? histResponse(plainTurn(SessionSeq(10), 1, '新', '页'), true)
  388. : histResponse(plainTurn(SessionSeq(0), 0, '断', '层'), true) // tail seq 5, but baseSeq is 10 → hole
  389. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  390. try {
  391. await session.open()
  392. const windowBefore = session.eventSource.getSnapshot()
  393. await session.loadOlder()
  394. const snapshot = session.getSnapshot()
  395. expect(session.eventSource.getSnapshot().entries).toEqual(windowBefore.entries)
  396. expect(snapshot.hasMore).toBe(false)
  397. } finally {
  398. errorSpy.mockRestore()
  399. }
  400. })
  401. it('loadThrough pages repeatedly until the window covers the target seq', async () => {
  402. const oldest = plainTurn(SessionSeq(0), 0, '最旧问', '最旧答')
  403. const middle = plainTurn(SessionSeq(6), 1, '中问', '中答')
  404. const newest = plainTurn(SessionSeq(12), 2, '新问', '新答')
  405. const { api, session } = makeSession()
  406. api.onHistory = (payload) => {
  407. if (payload.beforeSeq === undefined) return histResponse(newest, true)
  408. return payload.beforeSeq === 12 ? histResponse(middle, true) : histResponse(oldest, false)
  409. }
  410. await session.open()
  411. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  412. api.onHistory = (payload) => {
  413. api.onHistory = payload2 => payload2.beforeSeq === 12 ? histResponse(middle, true) : histResponse(oldest, false)
  414. void payload
  415. return gate.promise
  416. }
  417. const jump = session.loadThrough(SessionSeq(0))
  418. expect(session.getSnapshot().loadingOlder).toBe(true)
  419. gate.resolve(ok(historyValue(middle, true)))
  420. await jump
  421. const snapshot = session.getSnapshot()
  422. expect(snapshot.loadingOlder).toBe(false)
  423. expect(eventSeqs(session)).toEqual([...oldest, ...middle, ...newest].map(event => event.seq))
  424. expect(api.callsOf('session.history')).toMatchObject([
  425. { beforeSeq: 12, maxMessages: JUMP_PAGE_MESSAGES },
  426. { beforeSeq: 6, maxMessages: JUMP_PAGE_MESSAGES },
  427. ])
  428. })
  429. it('loadThrough is a no-op when the window already covers the target or the session is not open', async () => {
  430. const { api, session } = makeSession()
  431. await session.loadThrough(SessionSeq(0)) // cold: no-op
  432. expect(api.calls).toEqual([])
  433. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, 'x', 'y'), true)
  434. await session.open()
  435. const calls = api.calls.length
  436. await session.loadThrough(SessionSeq(6)) // baseSeq is already 6
  437. await session.loadThrough(SessionSeq(9)) // inside the window
  438. expect(api.calls.length).toBe(calls)
  439. })
  440. it('loadThrough retargets a running jump to the lowest requested seq and shares its completion', async () => {
  441. const oldest = plainTurn(SessionSeq(0), 0, 'a', 'b')
  442. const middle = plainTurn(SessionSeq(6), 1, 'c', 'd')
  443. const { api, session } = makeSession()
  444. api.onHistory = () => histResponse(plainTurn(SessionSeq(12), 2, 'e', 'f'), true)
  445. await session.open()
  446. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  447. api.onHistory = () => {
  448. api.onHistory = () => histResponse(oldest, false)
  449. return gate.promise
  450. }
  451. const first = session.loadThrough(SessionSeq(6))
  452. const second = session.loadThrough(SessionSeq(0))
  453. gate.resolve(ok(historyValue(middle, true)))
  454. await Promise.all([first, second])
  455. expect(eventSeqs(session)).toEqual([
  456. ...[...oldest, ...middle].map(event => event.seq),
  457. 12, 13, 14, 15, 16, 17,
  458. ])
  459. expect(api.callsOf('session.history')).toHaveLength(2)
  460. })
  461. it('loadThrough refused by a busy pager leaves no target behind for later jumps', async () => {
  462. const middle = plainTurn(SessionSeq(6), 1, 'c', 'd')
  463. const { api, session } = makeSession()
  464. api.onHistory = () => histResponse(plainTurn(SessionSeq(12), 2, 'e', 'f'), true)
  465. await session.open()
  466. // A plain single-page pull holds the busy flag while the jump is refused.
  467. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  468. api.onHistory = () => gate.promise
  469. const older = session.loadOlder()
  470. await session.loadThrough(SessionSeq(0)) // refused: must not park seq 0 anywhere
  471. gate.resolve(ok(historyValue(middle, true)))
  472. await older
  473. // A later jump to a nearer seq pages exactly to it — a leaked 0 target
  474. // would keep pulling three-event pages all the way to the head.
  475. api.onHistory = (payload) => {
  476. const start = ((payload as { beforeSeq?: number }).beforeSeq ?? 0) - 3
  477. return histResponse(
  478. [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)}`)],
  479. start > 0,
  480. )
  481. }
  482. await session.loadThrough(SessionSeq(4))
  483. // Covered at seq 3 (≤ 4) after one page; a leaked 0 target would add a
  484. // third call at beforeSeq 3 and pull the head to 0.
  485. expect(api.callsOf('session.history').map(call => (call as { beforeSeq?: number }).beforeSeq))
  486. .toEqual([12, 6])
  487. expect(eventSeqs(session)[0]).toBe(3)
  488. })
  489. it('loadThrough stops paging when the event stream generation moves mid-loop', async () => {
  490. const { api, session } = makeSession()
  491. api.onHistory = () => histResponse(plainTurn(SessionSeq(12), 2, 'x', 'y'), true)
  492. await session.open()
  493. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  494. api.onHistory = () => gate.promise
  495. const jump = session.loadThrough(SessionSeq(0))
  496. // The address is rebuilt while the first page is in flight.
  497. api.onHistory = () => histResponse(plainTurn(SessionSeq(12), 2, 'x', 'y'), true)
  498. const rebuilt = session.resync()
  499. gate.resolve(ok(historyValue(plainTurn(SessionSeq(6), 1, 'c', 'd'), true)))
  500. await jump
  501. await rebuilt
  502. // The stale loop must not page the new generation toward its old target:
  503. // history calls are the gated page and the resync tail only.
  504. expect(api.callsOf('session.history')).toHaveLength(1)
  505. expect(session.getSnapshot().loadingOlder).toBe(false)
  506. })
  507. it('loadThrough stops on a page that makes no progress instead of looping', async () => {
  508. const { api, session } = makeSession()
  509. api.onHistory = payload => payload.beforeSeq === undefined
  510. ? histResponse(plainTurn(SessionSeq(12), 2, 'x', 'y'), true)
  511. : histResponse([], true) // empty page still claiming more history
  512. await session.open()
  513. await session.loadThrough(SessionSeq(0))
  514. expect(session.getSnapshot().loadingOlder).toBe(false)
  515. expect(api.callsOf('session.history')).toHaveLength(1)
  516. })
  517. it('loadThrough fails soft on a thrown page and clears its busy state', async () => {
  518. const { api, session } = makeSession()
  519. api.onHistory = () => histResponse(plainTurn(SessionSeq(12), 2, 'x', 'y'), true)
  520. await session.open()
  521. api.onHistory = () => Promise.reject(new Error('page wire down'))
  522. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  523. try {
  524. await session.loadThrough(SessionSeq(0))
  525. expect(errorSpy).toHaveBeenCalled()
  526. expect(session.getSnapshot().loadingOlder).toBe(false)
  527. } finally {
  528. errorSpy.mockRestore()
  529. }
  530. })
  531. it('ignores loadOlder while one is in flight (single request)', async () => {
  532. const { api, session } = makeSession()
  533. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, 'x', 'y'), true)
  534. await session.open()
  535. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  536. api.onHistory = () => gate.promise
  537. const first = session.loadOlder()
  538. const second = session.loadOlder()
  539. gate.resolve(ok({
  540. records: entries(plainTurn(SessionSeq(0), 0, 'a', 'b')) as never[],
  541. hasMore: false,
  542. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  543. }))
  544. await Promise.all([first, second])
  545. expect(api.callsOf('session.follow')).toHaveLength(1)
  546. expect(api.callsOf('session.history')).toHaveLength(1)
  547. })
  548. })
  549. describe('prompt and cancel errors', () => {
  550. it('routes an addressed child through non-activating history, continuation prompt, and interrupt only', async () => {
  551. const api = new FakeApiClient()
  552. const session = new Session(SID, fakeRemote(api), {
  553. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  554. parentAvailable: true,
  555. })
  556. await session.open()
  557. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  558. const cancelled = await session.cancel()
  559. expect(prompted).toEqual({ ok: true, value: { accepted: true } })
  560. expect(cancelled).toEqual({ ok: true, value: { accepted: true } })
  561. expect(api.callsOf('session.follow')).toEqual([
  562. {
  563. address: {
  564. kind: 'subagent', parentSessionId: PARENT, childSessionId: SID, mode: 'continuable',
  565. },
  566. maxMessages: 50,
  567. },
  568. ])
  569. expect(api.callsOf('subagent.history')).toEqual([])
  570. expect(api.callsOf('subagents.prompt')).toEqual([
  571. {
  572. requestId: expect.any(String) as unknown as string,
  573. parentSessionId: PARENT, childSessionId: SID,
  574. mode: 'continuable',
  575. content: [{ type: 'text', text: '继续' }],
  576. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  577. },
  578. ])
  579. expect(api.callsOf('subagents.interruptByParent')).toEqual([
  580. { childSessionId: SID, parentSessionId: PARENT, mode: 'continuable' },
  581. ])
  582. expect(api.callsOf('session.history')).toEqual([])
  583. expect(api.callsOf('session.prompt')).toEqual([])
  584. expect(api.callsOf('session.cancel')).toEqual([])
  585. // A successful interrupt leaves no stop error behind.
  586. expect(session.getSnapshot().promptError).toBeNull()
  587. expect(session.getSnapshot().subagent).toEqual({
  588. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  589. parentAvailable: true,
  590. })
  591. })
  592. it('forwards continuation image parts to the subagent prompt Remote unstripped', async () => {
  593. const api = new FakeApiClient()
  594. const session = new Session(SID, fakeRemote(api), {
  595. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  596. parentAvailable: true,
  597. })
  598. await session.open()
  599. const content = [
  600. { type: 'text' as const, text: '看这张图' },
  601. { type: 'image' as const, mediaType: 'image/png' as const, data: 'aGk=', name: 'shot.png' },
  602. ]
  603. const prompted = await session.prompt(content, 'queue')
  604. expect(prompted).toEqual({ ok: true, value: { accepted: true } })
  605. expect(api.callsOf('subagents.prompt')).toEqual([
  606. {
  607. requestId: expect.any(String) as unknown as string,
  608. parentSessionId: PARENT, childSessionId: SID,
  609. mode: 'continuable',
  610. content,
  611. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  612. },
  613. ])
  614. expect(session.getSnapshot().promptError).toBeNull()
  615. })
  616. it('lands an interrupt business failure in promptError with op=stop', async () => {
  617. const api = new FakeApiClient()
  618. api.onSubagentInterrupt = () => Promise.resolve(err(new RemoteError('subagent/unauthorized', 'nope', { childSessionId: SID })))
  619. const session = new Session(SID, fakeRemote(api), {
  620. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  621. parentAvailable: true,
  622. })
  623. await session.open()
  624. const cancelled = await session.cancel()
  625. expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent/unauthorized' } })
  626. expect(session.getSnapshot().promptError).toMatchObject({
  627. op: 'stop', error: { code: 'subagent/unauthorized' },
  628. })
  629. })
  630. it('rejects staged files instead of dropping them from subagent continuations', async () => {
  631. const api = new FakeApiClient()
  632. const session = new Session(SID, fakeRemote(api), {
  633. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  634. parentAvailable: true,
  635. })
  636. await session.open()
  637. const prompted = await session.prompt([
  638. { type: 'file', receiptId: 'receipt' as never },
  639. { type: 'text', text: '继续' },
  640. ], 'queue')
  641. expect(prompted).toMatchObject({
  642. ok: false,
  643. error: {
  644. code: 'subagent/attachment-invalid',
  645. details: { reason: 'SUBAGENT_FILE_UNSUPPORTED' },
  646. },
  647. })
  648. expect(api.callsOf('subagents.prompt')).toEqual([])
  649. })
  650. it('sends a one-shot address to the Host under the continuable marker', async () => {
  651. const api = new FakeApiClient()
  652. api.onSubagentPrompt = () => Promise.resolve(err(new RemoteError(
  653. 'subagent/not-resumable', 'subagent cannot be resumed', { childSessionId: SID },
  654. )))
  655. const session = new Session(SID, fakeRemote(api), {
  656. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot' },
  657. })
  658. await session.open()
  659. const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue')
  660. const cancelled = await session.cancel()
  661. // The Host reads the durable descriptor; the wire marker stays 'continuable'.
  662. expect(prompted).toMatchObject({ ok: false, error: { code: 'subagent/not-resumable' } })
  663. expect(cancelled).toEqual({ ok: true, value: { accepted: true } })
  664. expect(api.callsOf('subagents.prompt')).toMatchObject([
  665. { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  666. ])
  667. expect(api.callsOf('subagents.interruptByParent')).toEqual([
  668. { childSessionId: SID, parentSessionId: PARENT, mode: 'continuable' },
  669. ])
  670. expect(api.callsOf('session.follow')).toEqual([
  671. {
  672. address: {
  673. kind: 'subagent', parentSessionId: PARENT, childSessionId: SID, mode: 'one-shot',
  674. },
  675. maxMessages: 50,
  676. },
  677. ])
  678. expect(api.callsOf('subagent.history')).toEqual([])
  679. expect(api.callsOf('session.cancel')).toEqual([])
  680. })
  681. it('delivers an image continuation to the Host without narrowing its upload parts', async () => {
  682. const api = new FakeApiClient()
  683. const session = new Session(SID, fakeRemote(api), {
  684. address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' },
  685. })
  686. await session.open()
  687. const prompted = await session.prompt(
  688. [{ type: 'text', text: '看图' }, { type: 'image', mediaType: 'image/png', data: 'AA==' }],
  689. 'queue',
  690. )
  691. expect(prompted).toEqual({ ok: true, value: { accepted: true } })
  692. expect(api.callsOf('subagents.prompt')).toMatchObject([
  693. { content: [{ type: 'text' }, { type: 'image', mediaType: 'image/png', data: 'AA==' }] },
  694. ])
  695. })
  696. it('publishes the first-prompt lifecycle synchronously before the Remote settles', async () => {
  697. const { api, session } = makeSession()
  698. session.handleBlank(true)
  699. expect(session.getSnapshot()).toMatchObject({
  700. blank: true, promptAttempted: false, awaitingFirstTurn: false,
  701. })
  702. const inFlight = session.prompt([{ type: 'text', text: '要发的' }], 'queue')
  703. expect(session.getSnapshot()).toMatchObject({
  704. blank: true, promptAttempted: true, awaitingFirstTurn: true,
  705. })
  706. const result = await inFlight
  707. expect(result.ok).toBe(true)
  708. expect(session.getSnapshot()).toMatchObject({
  709. blank: false, promptAttempted: true, awaitingFirstTurn: true,
  710. })
  711. expect(api.callsOf('session.prompt')).toMatchObject([{
  712. sessionId: SID,
  713. mode: 'queue',
  714. content: [{ type: 'text', text: '要发的' }],
  715. clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone,
  716. }])
  717. session.handleRunning(true)
  718. expect(session.getSnapshot()).toMatchObject({ running: true, awaitingFirstTurn: false })
  719. })
  720. it('keeps the attempted-first-prompt state when the Host rejects the prompt', async () => {
  721. const { api, session } = makeSession()
  722. session.handleBlank(true)
  723. api.onPrompt = () => Promise.resolve(err(new RemoteError('session/agent-busy', 'busy', { reason: 'x' })))
  724. const result = await session.prompt([{ type: 'text', text: '失败的' }], 'queue')
  725. expect(result.ok).toBe(false)
  726. expect(session.getSnapshot().promptError).toMatchObject({ op: 'send', error: { code: 'session/agent-busy' } })
  727. expect(session.getSnapshot()).toMatchObject({
  728. blank: true, promptAttempted: true, awaitingFirstTurn: true,
  729. })
  730. })
  731. it('propagates a non-Remote throw raised while cancelling', async () => {
  732. const { api, session } = makeSession()
  733. api.onCancel = () => Promise.reject(new Error('cancel transport down'))
  734. await expect(session.cancel()).rejects.toThrow('cancel transport down')
  735. expect(session.getSnapshot().promptError).toBeNull()
  736. })
  737. it('reads session-authorized attachment bytes and keeps the opaque id on the wire', async () => {
  738. const { api, session } = makeSession()
  739. const result = await session.readAttachment('attachment-1' as never)
  740. expect(result).toEqual({
  741. ok: true,
  742. value: {
  743. attachment: { attachmentId: 'a', mediaType: 'image/png', bytes: 1, width: 1, height: 1 },
  744. data: Uint8Array.of(0),
  745. },
  746. })
  747. expect(api.callsOf('session.attachment')).toEqual([{
  748. sessionId: SID, attachmentId: 'attachment-1',
  749. }])
  750. })
  751. })
  752. describe('rename', () => {
  753. it('settles the title projection cell from the unary response (higher-seq-wins vs the push frame)', async () => {
  754. const { api, session } = makeSession()
  755. api.onRename = () => Promise.resolve(ok({ title: '正名', seq: 7 }))
  756. const result = await session.rename(' 正名 ')
  757. expect(result).toMatchObject({ ok: true, value: { title: '正名', seq: 7 } })
  758. expect(api.callsOf('session.rename')).toMatchObject([{ sessionId: SID, title: ' 正名 ' }])
  759. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  760. // A stale lower-seq apply (the push-frame path routes into this same
  761. // store) must not roll the settled value back.
  762. session.projections.apply('title', '旧名', SessionSeq(3))
  763. expect(session.projections.faceOf('title').getSnapshot()).toBe('正名')
  764. })
  765. it('returns the business error untouched and folds a transport throw to internal', async () => {
  766. const { api, session } = makeSession()
  767. api.onRename = () => Promise.resolve(err(new RemoteError('session/title-invalid', 'empty', { sessionId: SID })))
  768. const rejected = await session.rename(' ')
  769. expect(rejected).toMatchObject({ ok: false, error: { code: 'session/title-invalid' } })
  770. expect(session.projections.faceOf('title').getSnapshot()).toBeUndefined()
  771. api.onRename = () => Promise.reject(new Error('rename transport down'))
  772. await expect(session.rename('x')).rejects.toThrow('rename transport down')
  773. })
  774. })
  775. describe('remaining branches', () => {
  776. it('propagates a non-Remote throw raised while prompting', async () => {
  777. const { api, session } = makeSession()
  778. api.onPrompt = () => Promise.reject(new Error('prompt wire down'))
  779. await expect(session.prompt([{ type: 'text', text: 'x' }], 'queue')).rejects.toThrow('prompt wire down')
  780. expect(session.getSnapshot().promptError).toBeNull()
  781. })
  782. it('cancel business error also lands op=stop promptError', async () => {
  783. const { api, session } = makeSession()
  784. api.onCancel = () => Promise.resolve(err(new RemoteError('session/agent-busy', 'nope', { reason: 'r' })))
  785. await session.cancel()
  786. expect(session.getSnapshot().promptError).toMatchObject({ op: 'stop', error: { code: 'session/agent-busy' } })
  787. })
  788. it('loadOlder guards: not-open/no-hasMore no-op, err result kept window, empty page updates hasMore, throw fail-soft', async () => {
  789. const { api, session } = makeSession()
  790. await session.loadOlder() // cold: no-op, zero calls
  791. expect(api.calls).toEqual([])
  792. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, 'x', 'y'), true)
  793. await session.open()
  794. // err result: window unchanged
  795. api.onHistory = () => Promise.resolve(err(new RemoteError('gateway/internal', 'x', {})))
  796. await session.loadOlder()
  797. expect(eventSeqs(session)).toHaveLength(6)
  798. expect(session.getSnapshot().hasMore).toBe(true)
  799. // empty page: hasMore adopts the response
  800. api.onHistory = () => histResponse([], false)
  801. await session.loadOlder()
  802. expect(session.getSnapshot().hasMore).toBe(false)
  803. // hasMore false now: further loadOlder is a guard no-op
  804. const calls = api.calls.length
  805. await session.loadOlder()
  806. expect(api.calls.length).toBe(calls)
  807. // throw path: fail-soft with console.error
  808. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  809. try {
  810. await session.resync()
  811. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, 'x', 'y'), true)
  812. await session.resync()
  813. api.onHistory = () => Promise.reject(new Error('page wire down'))
  814. await session.loadOlder()
  815. expect(errorSpy).toHaveBeenCalled()
  816. expect(session.getSnapshot().loadingOlder).toBe(false)
  817. } finally {
  818. errorSpy.mockRestore()
  819. }
  820. })
  821. it('subscribe delivers snapshot-change notifications and unsubscribes', async () => {
  822. const { api, session } = makeSession()
  823. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  824. let notified = 0
  825. const unsubscribe = session.subscribe(() => { notified++ })
  826. await session.open()
  827. await new Promise(resolve => setTimeout(resolve, 0))
  828. expect(notified).toBeGreaterThan(0)
  829. const seen = notified
  830. unsubscribe()
  831. session.handleRunning(true) // any snapshot mutation; the listener must stay silent
  832. await new Promise(resolve => setTimeout(resolve, 0))
  833. expect(notified).toBe(seen)
  834. })
  835. it('rejects an opening page that does not end at the opening cursor', async () => {
  836. const { api, session } = makeSession()
  837. let call = 0
  838. api.onHistory = () => {
  839. call++
  840. return histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  841. }
  842. api.followCursor = 11
  843. await session.open()
  844. expect(call).toBe(1)
  845. const snapshot = session.getSnapshot()
  846. expect(snapshot.openState).toBe('error')
  847. expect(snapshot.openError).toMatchObject({
  848. code: 'gateway/internal', message: 'session event stream page did not end at its requested cursor',
  849. })
  850. expect(eventSeqs(session)).toEqual([])
  851. })
  852. it('deduplicates repeated running flips and records removal', () => {
  853. const { session } = makeSession()
  854. const before = session.getSnapshot()
  855. session.handleRunning(false) // already false: dedup branch
  856. expect(session.getSnapshot()).toBe(before)
  857. session.handleRemoved()
  858. expect(session.getSnapshot().removed).toBe(true)
  859. })
  860. it('drops live events while cold/error (no window upkeep)', async () => {
  861. const { api, session } = makeSession()
  862. await follow(api, ev.user(SessionSeq(0), '冷态帧'))
  863. expect(eventSeqs(session)).toEqual([])
  864. api.onHistory = () => Promise.resolve(err(new RemoteError('gateway/internal', 'x', {})))
  865. await session.open()
  866. await follow(api, ev.user(SessionSeq(0), '错态帧'))
  867. expect(eventSeqs(session)).toEqual([])
  868. })
  869. it('preserves a Host-reported failure that terminates the live source', async () => {
  870. const { api, session } = makeSession()
  871. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  872. await session.open()
  873. const failure = new RemoteError('session/not-found', 'session disappeared', { sessionId: SID })
  874. api.failStreams(failure)
  875. await vi.waitFor(() => { expect(session.getSnapshot().openState).toBe('error') })
  876. expect(session.getSnapshot().openError).toMatchObject({
  877. code: failure.code, message: failure.message, details: failure.details,
  878. })
  879. })
  880. it('coalesces queued gap frames behind one repair and exposes a failed repair', async () => {
  881. const { api, session } = makeSession()
  882. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  883. await session.open()
  884. const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  885. let repairs = 0
  886. api.onHistory = () => {
  887. repairs++
  888. return gate.promise
  889. }
  890. const deliveries = Promise.all([
  891. follow(api, ev.user(SessionSeq(9), '洞一')),
  892. follow(api, ev.user(SessionSeq(10), '洞二')),
  893. ])
  894. await vi.waitFor(() => { expect(repairs).toBe(1) })
  895. gate.reject(new RemoteError('gateway/internal', 'repair wire down', {}))
  896. await deliveries
  897. await vi.waitFor(() => { expect(session.getSnapshot().openState).toBe('error') })
  898. expect(session.getSnapshot().openError).toMatchObject({ code: 'gateway/internal', message: 'repair wire down' })
  899. expect(eventSeqs(session)).toHaveLength(6)
  900. })
  901. it('doOpen transport throw of a stale generation is swallowed (generation guard in catch)', async () => {
  902. const { api, session } = makeSession()
  903. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  904. api.onHistory = () => stale.promise
  905. const opening = session.open()
  906. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  907. const resynced = session.resync()
  908. stale.reject(new Error('stale wire'))
  909. await Promise.all([opening, resynced])
  910. expect(session.getSnapshot().openState).toBe('open') // stale catch did not write error
  911. })
  912. it('drops a stale doOpen whose history resolved successfully after resync superseded it', async () => {
  913. const { api, session } = makeSession()
  914. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  915. api.onHistory = () => stale.promise
  916. const opening = session.open()
  917. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, '新', '代'))
  918. const resynced = session.resync()
  919. stale.resolve(ok({
  920. records: entries(plainTurn(SessionSeq(0), 0, '旧', '代')) as never[],
  921. hasMore: false,
  922. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  923. })) // success, but its generation is gone
  924. await Promise.all([opening, resynced])
  925. expect(eventSeqs(session)).toEqual(plainTurn(SessionSeq(6), 1, '新', '代').map(event => event.seq))
  926. })
  927. it('drops a gap repair superseded by a full resync while its pull was in flight', async () => {
  928. const { api, session } = makeSession()
  929. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  930. await session.open()
  931. const repairPull = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  932. api.onHistory = () => repairPull.promise
  933. const delivery = follow(api, ev.user(SessionSeq(9), '洞'))
  934. await vi.waitFor(() => { expect(api.callsOf('session.history')).toHaveLength(1) })
  935. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, 'c', 'd'))
  936. const resynced = session.resync() // bumps the generation
  937. repairPull.resolve(ok({
  938. records: entries(plainTurn(SessionSeq(0), 0, '旧', '页')) as never[],
  939. hasMore: false,
  940. modelSelection: { provider: 'deepseek-official', model: 'stale' },
  941. })) // repair result: stale, dropped
  942. await Promise.all([delivery, resynced])
  943. expect(eventSeqs(session)).toEqual(plainTurn(SessionSeq(6), 1, 'c', 'd').map(event => event.seq))
  944. })
  945. it('successful cancel leaves no promptError', async () => {
  946. const { api, session } = makeSession()
  947. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  948. await session.open()
  949. const result = await session.cancel()
  950. expect(result.ok).toBe(true)
  951. expect(session.getSnapshot().promptError).toBeNull()
  952. })
  953. it('dispose is a reserved no-op on resident instances', async () => {
  954. const { session } = makeSession()
  955. await expect(session.dispose()).resolves.toBeUndefined()
  956. })
  957. it('carries raw history and follow events through the event feed', async () => {
  958. const { api, session } = makeSession()
  959. const historyCall = ev.toolCall(SessionSeq(6), 1, 'h1', 'bash', '{"cmd":"pwd"}')
  960. const historyResult = ev.toolResult(SessionSeq(7), 1, 'h1', 'done')
  961. api.onHistory = () => Promise.resolve(ok({
  962. records: [
  963. ...entries(plainTurn(SessionSeq(0), 0, 'a', 'b')),
  964. { type: 'event', event: historyCall },
  965. { type: 'event', event: historyResult },
  966. ] as never[],
  967. hasMore: false,
  968. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  969. }))
  970. await session.open()
  971. expect(windowEntries(session).slice(-2)).toEqual([
  972. { type: 'event', event: historyCall },
  973. { type: 'event', event: historyResult },
  974. ])
  975. const liveCall = ev.toolCall(SessionSeq(8), 2, 'l1', 'write', '{"file_path":"a.ts"}')
  976. await follow(api, liveCall)
  977. expect(windowEntries(session).at(-1)).toEqual({ type: 'event', event: liveCall })
  978. const liveResult = ev.toolResult(SessionSeq(9), 2, 'l1', 'ok')
  979. await follow(api, liveResult)
  980. expect(windowEntries(session).at(-1)).toEqual({ type: 'event', event: liveResult })
  981. })
  982. })
  983. describe('resync', () => {
  984. it('keeps the old feed until the reconnect snapshot, then repairs queued live gaps', async () => {
  985. const { api, session } = makeSession()
  986. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, '旧', '窗'))
  987. await session.open()
  988. const oldWindow = session.eventSource.getSnapshot()
  989. const replacement = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  990. api.followCursor = 15
  991. api.onHistory = () => replacement.promise
  992. const publications: ReturnType<Session['eventSource']['getSnapshot']>[] = []
  993. const off = session.eventSource.subscribe(() => {
  994. publications.push(session.eventSource.getSnapshot())
  995. })
  996. const syncing = session.resync()
  997. await vi.waitFor(() => { expect(api.callsOf('session.follow')).toHaveLength(2) })
  998. expect(session.eventSource.getSnapshot()).toBe(oldWindow)
  999. expect(publications).toEqual([])
  1000. api.onHistory = () => histResponse([
  1001. ...plainTurn(SessionSeq(10), 2, '终', '页'),
  1002. ev.user(SessionSeq(16), '后到低位'),
  1003. ev.user(SessionSeq(17), '后到高位'),
  1004. ])
  1005. const liveDeliveries = Promise.all([
  1006. follow(api, ev.user(SessionSeq(17), '后到高位')),
  1007. follow(api, ev.user(SessionSeq(16), '后到低位')),
  1008. ])
  1009. expect(session.eventSource.getSnapshot()).toBe(oldWindow)
  1010. replacement.resolve(ok({
  1011. records: entries(plainTurn(SessionSeq(10), 2, '终', '页')) as never[],
  1012. hasMore: false,
  1013. modelSelection: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  1014. }))
  1015. await Promise.all([syncing, liveDeliveries])
  1016. await vi.waitFor(() => {
  1017. expect(eventSeqs(session)).toEqual([10, 11, 12, 13, 14, 15, 16, 17])
  1018. })
  1019. expect(publications).toHaveLength(2)
  1020. expect(publications.map(snapshot => snapshot.change.kind)).toEqual(['replace', 'replace'])
  1021. expect(publications[0]?.entries.map(entry => entry.event.seq)).toEqual([10, 11, 12, 13, 14, 15])
  1022. expect(publications[1]?.entries.map(entry => entry.event.seq)).toEqual([10, 11, 12, 13, 14, 15, 16, 17])
  1023. off()
  1024. })
  1025. it('rebuilds the window without clearing control state; cold instances no-op', async () => {
  1026. const { api, session } = makeSession()
  1027. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, 'a', 'b'))
  1028. await session.open()
  1029. session.handleRunning(true)
  1030. session.handleAgentError('still visible')
  1031. api.onHistory = () => histResponse([...plainTurn(SessionSeq(0), 0, 'a', 'b'), ...plainTurn(SessionSeq(6), 1, 'c', 'd')])
  1032. await session.resync()
  1033. const snapshot = session.getSnapshot()
  1034. expect(snapshot.openState).toBe('open')
  1035. expect(snapshot.running).toBe(true)
  1036. expect(snapshot.lastAgentError).toBe('still visible')
  1037. expect(eventSeqs(session)).toHaveLength(12)
  1038. const cold = makeSession()
  1039. await cold.session.resync()
  1040. expect(cold.api.calls).toEqual([]) // never opened: no traffic
  1041. })
  1042. it('drops a stale in-flight open superseded by resync (generation guard)', async () => {
  1043. const { api, session } = makeSession()
  1044. const stale = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
  1045. api.onHistory = () => stale.promise
  1046. const firstOpen = session.open()
  1047. api.onHistory = () => histResponse(plainTurn(SessionSeq(6), 1, '新', '代'))
  1048. const resynced = session.resync()
  1049. stale.reject(new Error('dead connection')) // the doomed pre-disconnect request fails late
  1050. await firstOpen
  1051. await resynced
  1052. const snapshot = session.getSnapshot()
  1053. expect(snapshot.openState).toBe('open') // stale failure did not settle the fresh generation into error
  1054. expect(eventSeqs(session)).toEqual(plainTurn(SessionSeq(6), 1, '新', '代').map(event => event.seq))
  1055. })
  1056. })
  1057. describe('snapshot ownership', () => {
  1058. it('publishes event-window appends without changing an unrelated Session snapshot', async () => {
  1059. const { api, session } = makeSession()
  1060. api.onHistory = () => histResponse(plainTurn(SessionSeq(0), 0, '稳', '定'))
  1061. await session.open()
  1062. const sessionBefore = session.getSnapshot()
  1063. const windowBefore = session.eventSource.getSnapshot()
  1064. const firstEntry = windowBefore.entries[0]
  1065. await follow(api, ev.user(SessionSeq(6), '追加'))
  1066. const windowAfter = session.eventSource.getSnapshot()
  1067. expect(session.getSnapshot()).toBe(sessionBefore)
  1068. expect(windowAfter).not.toBe(windowBefore)
  1069. expect(windowAfter.entries[0]).toBe(firstEntry)
  1070. expect(windowAfter.change).toMatchObject({ kind: 'append' })
  1071. })
  1072. })