session.client.spec.ts 44 KB

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