session.client.spec.ts 41 KB

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