session-projections.host.spec.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. /**
  2. * Session Controller projection paths: the history tail page's
  3. * projections block reads the registry's watermark snapshot (asOfSeq = last
  4. * event seq, one consistent cut); loadOlder pages never carry the block; a
  5. * composition without the registry serves histories without it; a disposed
  6. * registration's key leaves subsequent responses; and every unit change is
  7. * pushed through the control stream.
  8. */
  9. import { describe, expect, it, vi } from 'vitest'
  10. import { Context } from '@deepseek-ai/cordis'
  11. import { z } from 'zod'
  12. import AgentRegistry, { Inbox } from '@deepseek-ai/dsh-agent'
  13. import { AttachmentStore } from '@deepseek-ai/dsh-attachment'
  14. import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-presets'
  15. import type { Agent } from '@deepseek-ai/dsh-agent'
  16. import { createUserMessage } from '@deepseek-ai/dsh-llm'
  17. import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
  18. import type { Session } from '@deepseek-ai/dsh-session'
  19. import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
  20. import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection'
  21. import { SessionControlController } from '@deepseek-ai/dsh-api-session-controller/src/control.ts'
  22. import type { SessionControlFrame, SessionFollowFrame } from '@deepseek-ai/dsh-api-session-controller/types'
  23. import { createSessionTestRemote, type TestSessionRemote } from './test-remote.ts'
  24. declare module '@deepseek-ai/dsh-session-projection/types' {
  25. interface SessionProjectionStateMap {
  26. 'test/last-user': LastUserState
  27. 'test/internal-count': number
  28. }
  29. interface SessionProjectionMap {
  30. 'test/last-user': { text: string } | null
  31. }
  32. }
  33. function request<P>(payload: P): P {
  34. return payload
  35. }
  36. function page(
  37. remote: TestSessionRemote,
  38. request: { sessionId: SessionId; throughSeq: number; beforeSeq?: number; maxMessages?: number },
  39. ) {
  40. return remote.page({
  41. address: { kind: 'session', sessionId: request.sessionId },
  42. throughSeq: request.throughSeq,
  43. ...(request.beforeSeq === undefined ? {} : { beforeSeq: request.beforeSeq }),
  44. ...(request.maxMessages === undefined ? {} : { maxMessages: request.maxMessages }),
  45. })
  46. }
  47. /** Read and close one snapshot-first follow generation. */
  48. async function opening(
  49. remote: TestSessionRemote,
  50. sessionId: SessionId,
  51. maxMessages?: number,
  52. ): Promise<Extract<SessionFollowFrame, { type: 'snapshot' }>> {
  53. const abort = new AbortController()
  54. const iterator = remote.follow({
  55. address: { kind: 'session', sessionId },
  56. ...(maxMessages === undefined ? {} : { maxMessages }),
  57. }, abort.signal)[Symbol.asyncIterator]()
  58. const first = await iterator.next()
  59. abort.abort()
  60. await iterator.return?.()
  61. if (first.done || first.value.type !== 'snapshot') throw new Error('follow did not open with a snapshot')
  62. return first.value
  63. }
  64. /** Whole-value unit folding the latest user/message text; null before the first. */
  65. type LastUserState = { text: string } | null
  66. const lastUserUnit = () => ({
  67. key: 'test/last-user',
  68. stateSchema: z.union([z.object({ text: z.string() }), z.null()]),
  69. init: () => null,
  70. apply: (state, event) => (event.type === 'user/message'
  71. ? { text: (event.data.content[0] as { text?: string }).text ?? '' }
  72. : state),
  73. wire: {
  74. viewSchema: z.union([z.object({ text: z.string() }), z.null()]),
  75. view: state => state,
  76. },
  77. stateVersion: 1,
  78. }) satisfies ProjectionDefinition<'test/last-user', LastUserState>
  79. const internalCountUnit = () => ({
  80. key: 'test/internal-count',
  81. stateSchema: z.number().int().nonnegative(),
  82. init: () => 0,
  83. apply: (state: number) => state + 1,
  84. stateVersion: 1,
  85. }) satisfies ProjectionDefinition<'test/internal-count', number>
  86. async function harness(withRegistry: boolean): Promise<{ ctx: Context; session: Session }> {
  87. const ctx = new Context()
  88. await ctx.plugin(SessionStore)
  89. await ctx.plugin(AgentRegistry)
  90. if (withRegistry) await ctx.plugin(SessionProjectionRegistry)
  91. const session = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } })
  92. // The gateway reads both the session and durable inbox baseline.
  93. ctx.agents.register({ id: session.id, session, inbox: new Inbox(session, { inserted: () => {}, discarded: () => {}, claimed: () => {} }), status: 'idle', ctx } as Agent)
  94. return { ctx, session }
  95. }
  96. /** Append `count` user messages so the log has paginable message boundaries. */
  97. function seedMessages(session: Session, count: number): void {
  98. for (let i = 0; i < count; i++) {
  99. session.append('user/message', createUserMessage({
  100. content: [{ type: 'text', text: `m${i}` }],
  101. source: { kind: 'user' },
  102. }), { surfaceOp: 'append' })
  103. }
  104. }
  105. const remote = (ctx: Context) => createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  106. describe('session.history projections block', () => {
  107. it('tracks pending and used model selections across repeated request headers', async () => {
  108. const { ctx, session } = await harness(true)
  109. remote(ctx)
  110. await new Promise(resolve => setTimeout(resolve, 0))
  111. const selected = { provider: 'p', model: 'next' }
  112. session.append('model/selection', selected)
  113. session.append('model/selection', selected)
  114. session.append('request/header', {
  115. header: { config: { provider: 'p', model: 'used' } }, reason: 'initial',
  116. })
  117. session.append('request/header', {
  118. header: { config: { provider: 'p', model: 'used' } }, reason: 'initial',
  119. })
  120. expect(ctx.sessionProjections.snapshot(session).values.modelSelection).toEqual({
  121. lastUsed: { provider: 'p', model: 'used' },
  122. next: selected,
  123. })
  124. session.append('request/header', {
  125. header: { config: selected }, reason: 'initial',
  126. })
  127. expect(ctx.sessionProjections.snapshot(session).values.modelSelection).toEqual({
  128. lastUsed: selected,
  129. next: selected,
  130. })
  131. })
  132. it('serves the unit value on the tail page with asOfSeq = last event seq', async () => {
  133. const { ctx, session } = await harness(true)
  134. ctx.sessionProjections.register(lastUserUnit())
  135. seedMessages(session, 3)
  136. const snapshot = await opening(remote(ctx), session.id)
  137. const { events, projections } = snapshot
  138. expect(projections.asOfSeq).toBe(session.seq - 1)
  139. expect(projections.values['test/last-user']).toEqual({ text: 'm2' })
  140. // asOfSeq IS the window tail: the last served event carries it.
  141. expect(events.at(-1)?.event.seq).toBe(projections.asOfSeq)
  142. })
  143. it('returns a complete current replacement cut on each follow generation', async () => {
  144. const { ctx, session } = await harness(true)
  145. ctx.sessionProjections.register(lastUserUnit())
  146. seedMessages(session, 2)
  147. const snapshot = await opening(remote(ctx), session.id)
  148. expect(snapshot.events.map(entry => entry.event.seq)).toEqual([0, 1])
  149. expect(snapshot.projections.asOfSeq).toBe(1)
  150. expect(snapshot.projections.values).toEqual(
  151. expect.objectContaining({ 'test/last-user': { text: 'm1' } }),
  152. )
  153. })
  154. it('projects an empty log at cursor -1', async () => {
  155. const { ctx, session } = await harness(true)
  156. ctx.sessionProjections.register(lastUserUnit())
  157. const snapshot = await opening(remote(ctx), session.id)
  158. expect(snapshot.events).toEqual([])
  159. expect(snapshot.projections.asOfSeq).toBe(-1)
  160. expect(snapshot.projections.values).toEqual(
  161. expect.objectContaining({ 'test/last-user': null }),
  162. )
  163. })
  164. it('publishes the attachments imageLimits as a constant unit while both seams are composed', async () => {
  165. const { ctx, session } = await harness(true)
  166. const limits = {
  167. maxImageBytes: 5 * 1024 * 1024,
  168. maxImagesPerMessage: 20,
  169. maxMessageImageBytes: 100 * 1024 * 1024,
  170. maxImagePixels: 40_000_000,
  171. maxImageDimension: 2000,
  172. mediaTypes: ['image/png'] as const,
  173. }
  174. await ctx.plugin(class extends AttachmentStore {
  175. readonly imageLimits = limits
  176. validateImage(): Promise<void> { return Promise.resolve() }
  177. saveImage(): Promise<never> { return Promise.reject(new Error('unused')) }
  178. readImage(): Promise<never> { return Promise.reject(new Error('unused')) }
  179. })
  180. const gateway = remote(ctx)
  181. await new Promise(resolve => setTimeout(resolve, 0))
  182. seedMessages(session, 2)
  183. const snapshot = await opening(gateway, session.id)
  184. expect(snapshot.projections.values['imageLimits']).toEqual(limits)
  185. // Constant unit: appending events must never broadcast an imageLimits projection.
  186. await new Promise(resolve => setTimeout(resolve, 0))
  187. const abort = new AbortController()
  188. const iterator = gateway.control(abort.signal)[Symbol.asyncIterator]()
  189. await iterator.next()
  190. const next = iterator.next()
  191. seedMessages(session, 1)
  192. await new Promise(resolve => setTimeout(resolve, 0))
  193. await expect(next).resolves.toMatchObject({
  194. done: false,
  195. value: { type: 'projection', key: 'sessionListMetadata' },
  196. })
  197. const extra = iterator.next()
  198. const quiet = Symbol('quiet')
  199. expect(await Promise.race([
  200. extra,
  201. new Promise<typeof quiet>(resolve => setTimeout(() => { resolve(quiet) }, 0)),
  202. ])).toBe(quiet)
  203. abort.abort()
  204. await expect(extra).resolves.toEqual({ done: true, value: undefined })
  205. })
  206. it('leaves the imageLimits key absent while no attachment service is composed', async () => {
  207. const { ctx, session } = await harness(true)
  208. seedMessages(session, 1)
  209. const snapshot = await opening(remote(ctx), session.id)
  210. expect('imageLimits' in snapshot.projections.values).toBe(false)
  211. })
  212. it('never carries the block on loadOlder pages (beforeSeq present)', async () => {
  213. const { ctx, session } = await harness(true)
  214. ctx.sessionProjections.register(lastUserUnit())
  215. seedMessages(session, 5)
  216. const older = await page(remote(ctx), request({
  217. sessionId: session.id, throughSeq: session.seq - 1, beforeSeq: 3, maxMessages: 2,
  218. }))
  219. expect(older.ok).toBe(true)
  220. if (!older.ok) throw new Error('unreachable')
  221. expect('projections' in older.value).toBe(false)
  222. })
  223. it('serves no block when the composition has no projection registry', async () => {
  224. const { ctx, session } = await harness(false)
  225. seedMessages(session, 2)
  226. const response = await page(remote(ctx), request({ sessionId: session.id, throughSeq: session.seq - 1 }))
  227. expect(response.ok).toBe(true)
  228. if (!response.ok) throw new Error('unreachable')
  229. expect('projections' in response.value).toBe(false)
  230. })
  231. it('never exposes a host-only unit through history, listing, or push frames', async () => {
  232. const { ctx, session } = await harness(true)
  233. ctx.sessionProjections.register(internalCountUnit())
  234. const proxy = remote(ctx)
  235. await new Promise(resolve => setTimeout(resolve, 0))
  236. const abort = new AbortController()
  237. const iterator = proxy.control(abort.signal)[Symbol.asyncIterator]()
  238. const baseline = await iterator.next()
  239. if (baseline.done || baseline.value.type !== 'baseline') {
  240. throw new Error('control stream ended before its baseline')
  241. }
  242. expect('test/internal-count' in (baseline.value.value.projections[session.id]?.values ?? {}))
  243. .toBe(false)
  244. seedMessages(session, 1)
  245. const changed = await iterator.next()
  246. expect(changed).toMatchObject({
  247. done: false,
  248. value: { type: 'projection', key: 'sessionListMetadata' },
  249. })
  250. abort.abort()
  251. await iterator.return?.()
  252. const history = await opening(proxy, session.id)
  253. expect('test/internal-count' in history.projections.values).toBe(false)
  254. const listing = await proxy.list(request({}))
  255. if (!listing.ok) throw new Error('listing failed')
  256. const row = listing.value.items.find(item => item.sessionId === session.id)
  257. expect('test/internal-count' in (row?.projections?.values ?? {})).toBe(false)
  258. })
  259. it('drops a disposed registration from subsequent tail pages (empty block, key absent)', async () => {
  260. const { ctx, session } = await harness(true)
  261. const dispose = ctx.sessionProjections.register(lastUserUnit())
  262. seedMessages(session, 1)
  263. const proxy = remote(ctx)
  264. const before = await opening(proxy, session.id)
  265. expect(before.projections.values['test/last-user']).toEqual({ text: 'm0' })
  266. dispose()
  267. const after = await opening(proxy, session.id)
  268. // The registry stays mounted; only the disposed key leaves while the
  269. // gateway-owned Session-list unit remains.
  270. expect(after.projections.asOfSeq).toBe(session.seq - 1)
  271. expect('test/last-user' in after.projections.values).toBe(false)
  272. expect(after.projections.values.sessionListMetadata).toEqual({
  273. blank: true,
  274. lastPromptAt: session.events.at(-1)?.time,
  275. })
  276. })
  277. it('removes the gateway-owned Session-list unit when the gateway fiber unloads', async () => {
  278. const { ctx, session } = await harness(true)
  279. expect('sessionListMetadata' in ctx.sessionProjections.snapshot(session).values).toBe(false)
  280. const fiber = ctx.plugin(Object.assign((gatewayCtx: Context) => {
  281. createSessionTestRemote(gatewayCtx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' })
  282. }, { inject: ['sessions', 'agents', 'sessionProjections'] }))
  283. await fiber.await()
  284. await vi.waitFor(() => {
  285. expect(ctx.sessionProjections.snapshot(session).values.sessionListMetadata)
  286. .toEqual({ blank: true, lastPromptAt: null })
  287. })
  288. await fiber.dispose()
  289. expect('sessionListMetadata' in ctx.sessionProjections.snapshot(session).values).toBe(false)
  290. })
  291. })
  292. describe('session.list projections column', () => {
  293. it('serves every already-materialized wire value from the live registry without folding', async () => {
  294. const { ctx, session } = await harness(true)
  295. ctx.sessionProjections.register(lastUserUnit())
  296. const gateway = remote(ctx)
  297. await new Promise(resolve => setTimeout(resolve, 0))
  298. session.append('turn/start', { turn: 1 })
  299. seedMessages(session, 1)
  300. const response = await gateway.list(request({}))
  301. if (!response.ok) throw new Error('unreachable')
  302. const row = response.value.items.find(item => item.sessionId === session.id)
  303. expect(row?.projections?.values['test/last-user']).toEqual({ text: 'm0' })
  304. expect(row?.projections?.values.sessionListMetadata).toEqual({
  305. blank: false,
  306. lastPromptAt: session.events.at(-1)?.time,
  307. })
  308. expect(row?.projections?.asOfSeq).toBe(session.seq - 1)
  309. })
  310. it('lists the latest preset selected by a blank Session instead of its creation preset', async () => {
  311. const { ctx } = await harness(true)
  312. const session = ctx.sessions.create(SessionId('preset-list'), {
  313. meta: { cwd: '/workspace', agentPreset: 'standard' },
  314. })
  315. ctx.sessionProjections.register(agentPresetProjectionDefinition)
  316. const gateway = remote(ctx)
  317. await new Promise(resolve => setTimeout(resolve, 0))
  318. session.append('agent-preset/selected', { agentPreset: 'minimal' })
  319. const response = await gateway.list(request({}))
  320. if (!response.ok) throw new Error('unreachable')
  321. const row = response.value.items.find(item => item.sessionId === session.id)
  322. expect(row?.projections?.values.agentPreset).toBe('minimal')
  323. })
  324. it('omits an unmaterialized live projection instead of folding history for listing', async () => {
  325. const { ctx, session } = await harness(true)
  326. seedMessages(session, 1)
  327. const unit = lastUserUnit()
  328. const apply = vi.fn(unit.apply)
  329. ctx.sessionProjections.register({ ...unit, apply })
  330. const response = await remote(ctx).list(request({}))
  331. if (!response.ok) throw new Error('unreachable')
  332. const row = response.value.items.find(item => item.sessionId === session.id)
  333. expect(row).toBeDefined()
  334. expect('test/last-user' in (row?.projections?.values ?? {})).toBe(false)
  335. expect(apply).not.toHaveBeenCalled()
  336. })
  337. it('omits the column entirely when no registry is mounted', async () => {
  338. const { ctx, session } = await harness(false)
  339. seedMessages(session, 1)
  340. const response = await remote(ctx).list(request({}))
  341. if (!response.ok) throw new Error('unreachable')
  342. const row = response.value.items.find(item => item.sessionId === session.id)
  343. expect(row).toBeDefined()
  344. expect(row !== undefined && 'projections' in row).toBe(false)
  345. })
  346. it('serves every available cold projection hint from the cache with zero log loads', async () => {
  347. const { ctx } = await harness(true)
  348. const coldId = SessionId('session-cold-listing')
  349. const load = () => { throw new Error('list must not load event logs') }
  350. ctx.provide('sessionPersistence', {
  351. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  352. locate: () => undefined,
  353. load,
  354. inspect: load,
  355. readFrom: load,
  356. } as never)
  357. ctx.provide('sessionProjectionCache', {
  358. // The carrier hands the listed header through as the identity witness.
  359. cachedSnapshot: (meta: { id: unknown; createdAt: number }) =>
  360. (meta.id === coldId && meta.createdAt === 5
  361. ? {
  362. asOfSeq: 7,
  363. values: {
  364. 'test/last-user': { text: 'cached' },
  365. sessionListMetadata: { blank: false, lastPromptAt: 6 },
  366. title: 'Cached title',
  367. },
  368. }
  369. : undefined),
  370. } as never)
  371. const response = await remote(ctx).list(request({}))
  372. if (!response.ok) throw new Error('unreachable')
  373. const row = response.value.items.find(item => item.sessionId === coldId)
  374. expect(row?.running).toBe(false)
  375. expect(row?.projections).toEqual({
  376. asOfSeq: 7,
  377. values: {
  378. 'test/last-user': { text: 'cached' },
  379. sessionListMetadata: { blank: false, lastPromptAt: 6 },
  380. title: 'Cached title',
  381. },
  382. })
  383. })
  384. it('cold rows without a cache plugin (or without a stored row) just lack the column', async () => {
  385. const { ctx } = await harness(true)
  386. const coldId = SessionId('session-cold-uncached')
  387. ctx.provide('sessionPersistence', {
  388. list: async () => [{ version: 0, id: coldId, createdAt: 5, cwd: '/tmp' }],
  389. locate: () => undefined,
  390. } as never)
  391. const response = await remote(ctx).list(request({}))
  392. if (!response.ok) throw new Error('unreachable')
  393. const row = response.value.items.find(item => item.sessionId === coldId)
  394. expect(row).toBeDefined()
  395. expect(row !== undefined && 'projections' in row).toBe(false)
  396. })
  397. it('a throwing column read degrades that row, never the listing', async () => {
  398. const { ctx, session } = await harness(true)
  399. ctx.sessionProjections.register({
  400. ...lastUserUnit(),
  401. wire: {
  402. viewSchema: z.union([z.object({ text: z.string() }), z.null()]),
  403. view: () => { throw new Error('unit exploded') },
  404. },
  405. })
  406. seedMessages(session, 1)
  407. const response = await remote(ctx).list(request({}))
  408. if (!response.ok) throw new Error('unreachable')
  409. const row = response.value.items.find(item => item.sessionId === session.id)
  410. expect(row).toBeDefined()
  411. expect(row !== undefined && 'projections' in row).toBe(false)
  412. })
  413. })
  414. describe('Session control projection frames', () => {
  415. /** Drain frames until `count` projection replacements arrive. */
  416. async function collect(
  417. iterable: AsyncIterable<SessionControlFrame>,
  418. count: number,
  419. abort: AbortController,
  420. ): Promise<SessionControlFrame[]> {
  421. const frames: SessionControlFrame[] = []
  422. for await (const frame of iterable) {
  423. frames.push(frame)
  424. if (frames.filter(candidate => candidate.type === 'projection').length >= count) abort.abort()
  425. }
  426. return frames
  427. }
  428. it('broadcasts a frame per changed unit with the causing seq, and none for same-reference applies', async () => {
  429. const { ctx, session } = await harness(true)
  430. ctx.sessionProjections.register(lastUserUnit())
  431. const proxy = remote(ctx)
  432. // The controller's onChanged subscription lives in an inject child whose
  433. // fiber activates asynchronously; yield until it lands before appending.
  434. await new Promise(resolve => setTimeout(resolve, 0))
  435. const abort = new AbortController()
  436. const stream = proxy.control(abort.signal)
  437. const collected = collect(stream, 5, abort)
  438. const now = vi.spyOn(Date, 'now').mockReturnValue(100)
  439. seedMessages(session, 1)
  440. now.mockReturnValue(200)
  441. session.append('turn/start', { turn: 1 })
  442. now.mockReturnValue(300)
  443. seedMessages(session, 1)
  444. now.mockRestore()
  445. const frames = await collected
  446. const pushes = frames.filter(
  447. (f): f is Extract<SessionControlFrame, { type: 'projection' }> =>
  448. f.type === 'projection' && f.key === 'test/last-user',
  449. )
  450. expect(pushes).toEqual([
  451. { type: 'projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 0 },
  452. { type: 'projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 2 },
  453. ])
  454. expect(frames.filter(
  455. (f): f is Extract<SessionControlFrame, { type: 'projection' }> =>
  456. f.type === 'projection' && f.key === 'sessionListMetadata',
  457. )).toEqual([
  458. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: true, lastPromptAt: 100 }, seq: 0 },
  459. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 100 }, seq: 1 },
  460. { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 300 }, seq: 2 },
  461. ])
  462. // Frame seq aligns with the tail block's asOfSeq vocabulary (higher-seq-wins compatible).
  463. const tail = await opening(proxy, session.id)
  464. expect(tail.projections.asOfSeq).toBe(pushes.at(-1)?.seq)
  465. })
  466. it('emits no projection frames when the composition has no registry', async () => {
  467. const { ctx, session } = await harness(false)
  468. const control = new SessionControlController(ctx)
  469. const abort = new AbortController()
  470. const iterator = control.control(abort.signal)[Symbol.asyncIterator]()
  471. const baseline = await iterator.next()
  472. const next = iterator.next()
  473. seedMessages(session, 2)
  474. await new Promise(resolve => setTimeout(resolve, 0))
  475. abort.abort()
  476. if (baseline.done) throw new Error('Control stream ended before its baseline')
  477. expect(baseline.value.type).toBe('baseline')
  478. await expect(next).resolves.toEqual({ done: true, value: undefined })
  479. })
  480. })