session.client.spec.ts 46 KB

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