client-handler.spec.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /**
  2. * Wire-protocol coverage over the isomorphic point: InProcessApiClient →
  3. * toFetchHandler(scripted impl) runs the real envelope wrap/unwrap, zod
  4. * two-level parse, rpcId discipline, and SSE framing with no network and no
  5. * browser. Each case scripts its own minimal ApiProxy.
  6. */
  7. import { describe, expect, it, vi } from 'vitest'
  8. import type { SessionId } from '@deepseek-ai/dsh-session'
  9. import type { ApiProxy, HostFrame, MuxFrame, RpcMessage, RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy'
  10. import { InProcessApiClient, RpcId, toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy'
  11. const sid = (id: string): SessionId => id as SessionId
  12. function ok<T>(request: RpcRequest<unknown>, value: T): Promise<RpcResponse<T>> {
  13. return Promise.resolve({ rpcId: request.rpcId, result: { ok: true, value } })
  14. }
  15. /** Scripted impl: every method resolves an empty-ish OK unless a case overrides it. */
  16. function scriptedApi(overrides: {
  17. sessions?: Partial<ApiProxy['sessions']>
  18. host?: Partial<ApiProxy['host']>
  19. commands?: Partial<ApiProxy['commands']>
  20. skills?: Partial<ApiProxy['skills']>
  21. events?: Partial<ApiProxy['events']>
  22. respond?: ApiProxy['respond']
  23. } = {}): ApiProxy {
  24. async function *empty<F>(): AsyncGenerator<RpcRequest<F>> { /* no frames */ }
  25. return {
  26. sessions: {
  27. list: r => ok(r, { items: [] }),
  28. create: r => ok(r, { sessionId: sid('s-new') }),
  29. history: r => ok(r, {
  30. events: [],
  31. hasMore: false,
  32. modelTarget: { provider: 'deepseek', model: 'deepseek-v4-flash' },
  33. }),
  34. models: r => ok(r, {
  35. current: { provider: 'deepseek', model: 'deepseek-v4-flash' },
  36. groups: [],
  37. failures: [],
  38. }),
  39. selectModel: r => ok(r, {
  40. selected: { provider: r.payload.provider, model: r.payload.model },
  41. }),
  42. prompt: r => ok(r, { accepted: true as const }),
  43. cancel: r => ok(r, { accepted: true as const }),
  44. ...overrides.sessions,
  45. },
  46. host: {
  47. describe: r => ok(r, { version: '0-test', cwd: '/t', attachedSessions: 0 }),
  48. pickDirectory: r => ok(r, { path: null }),
  49. ...overrides.host,
  50. },
  51. workspace: {
  52. list: r => ok(r, { items: [] }),
  53. create: r => ok(r, { workspace: { workspaceId: 'w1' as never, path: '/t', title: 't', sessionIds: [], createdAt: '0', updatedAt: '0' }, created: true }),
  54. rename: r => ok(r, { workspace: { workspaceId: 'w1' as never, path: '/t', title: 't', sessionIds: [], createdAt: '0', updatedAt: '0' } }),
  55. delete: r => ok(r, { deleted: true as const }),
  56. insertSessionBefore: r => ok(r, { workspace: { workspaceId: 'w1' as never, path: '/t', title: 't', sessionIds: [], createdAt: '0', updatedAt: '0' } }),
  57. },
  58. commands: {
  59. list: r => ok(r, { commands: [] }),
  60. execute: r => ok(r, { matched: false }),
  61. ...overrides.commands,
  62. },
  63. skills: { list: r => ok(r, { skills: [] }), ...overrides.skills },
  64. events: { mux: () => empty<MuxFrame>(), host: () => empty<HostFrame>(), ...overrides.events },
  65. respond: overrides.respond ?? (() => Promise.resolve({ accepted: false as const, reason: 'not-pending' as const })),
  66. }
  67. }
  68. function client(api: ApiProxy, timeoutMs?: number): InProcessApiClient {
  69. return new InProcessApiClient(toFetchHandler(api), timeoutMs)
  70. }
  71. describe('unary round trip', () => {
  72. it('carries payload out and value back through the full wire form', async () => {
  73. let seen: RpcRequest<{ cursor?: string }> | undefined
  74. const api = scriptedApi({
  75. sessions: {
  76. list: (r) => {
  77. seen = r
  78. return ok(r, { items: [{ sessionId: sid('s1'), updatedAt: 7, running: false, blank: false }] })
  79. },
  80. },
  81. })
  82. const response = await client(api).sessions.list({ cursor: 'c1' })
  83. // Impl received the narrow form with a minted id; client returned the same id and value.
  84. expect(seen?.payload).toEqual({ cursor: 'c1' })
  85. expect(seen?.rpcId).toBeTruthy()
  86. expect(response.rpcId).toBe(seen?.rpcId)
  87. expect(response.result).toEqual({ ok: true, value: { items: [{ sessionId: 's1', updatedAt: 7, running: false, blank: false }] } })
  88. })
  89. it('routes workspace rename, delete, and insertSessionBefore through the wire', async () => {
  90. const api = scriptedApi()
  91. const c = client(api)
  92. const renamed = await c.workspace.rename({ workspaceId: 'w1' as never, title: 'next' })
  93. expect(renamed.result.ok).toBe(true)
  94. const blankTitle = await c.workspace.rename({ workspaceId: 'w1' as never, title: ' ' })
  95. expect(blankTitle.result).toMatchObject({ ok: false, error: { code: 'bad-request' } })
  96. const deleted = await c.workspace.delete({ workspaceId: 'w1' as never })
  97. expect(deleted.result).toEqual({ ok: true, value: { deleted: true } })
  98. const anchored = await c.workspace.insertSessionBefore({ workspaceId: 'w1' as never, sessionId: sid('s1'), beforeSessionId: sid('s2') })
  99. expect(anchored.result.ok).toBe(true)
  100. const appended = await c.workspace.insertSessionBefore({ workspaceId: 'w1' as never, sessionId: sid('s1') })
  101. expect(appended.result.ok).toBe(true)
  102. })
  103. it('passes business errors through as 200 + err result, not a throw', async () => {
  104. const api = scriptedApi({
  105. sessions: {
  106. cancel: r => Promise.resolve({ rpcId: r.rpcId, result: { ok: false, error: { code: 'session-not-found', message: 'nope', details: { sessionId: sid('sx') } } } }),
  107. },
  108. })
  109. const response = await client(api).sessions.cancel({ sessionId: sid('sx') })
  110. expect(response.result).toEqual({ ok: false, error: { code: 'session-not-found', message: 'nope', details: { sessionId: 'sx' } } })
  111. })
  112. it('throws on rpcId echo mismatch', async () => {
  113. const api = scriptedApi({
  114. sessions: { list: () => Promise.resolve({ rpcId: RpcId('forged'), result: { ok: true, value: { items: [] } } }) },
  115. })
  116. await expect(client(api).sessions.list({})).rejects.toThrow(/rpcId mismatch/)
  117. })
  118. it('rejects an invalid payload at the handler as 200 + bad-request with issues', async () => {
  119. const api = scriptedApi()
  120. const response = await client(api).sessions.history({ sessionId: 123 as unknown as SessionId })
  121. expect(response.result.ok).toBe(false)
  122. if (!response.result.ok) {
  123. expect(response.result.error.code).toBe('bad-request')
  124. expect((response.result.error.details as { issues: unknown[] }).issues.length).toBeGreaterThan(0)
  125. }
  126. })
  127. it('rejects a method/path mismatch as bad-request', async () => {
  128. const handler = toFetchHandler(scriptedApi())
  129. const body = { type: 'client-request', rpcId: 'r1', method: 'session.create', payload: {} }
  130. const response = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: JSON.stringify(body) })
  131. expect(response.status).toBe(200)
  132. const parsed = await response.json() as { result: { ok: boolean; error?: { code: string; message: string } } }
  133. expect(parsed.result.ok).toBe(false)
  134. expect(parsed.result.error?.code).toBe('bad-request')
  135. expect(parsed.result.error?.message).toMatch(/does not match path/)
  136. })
  137. it('rejects a malformed envelope as bad-request, salvaging the rpcId or falling back to the sentinel', async () => {
  138. const handler = toFetchHandler(scriptedApi())
  139. // No salvageable rpcId → the fixed invalid-request sentinel keeps the response a valid ServerResponse.
  140. const noId = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: JSON.stringify({ nonsense: true }) })
  141. expect(noId.status).toBe(200)
  142. const noIdParsed = await noId.json() as { rpcId: string; result: { ok: boolean } }
  143. expect(noIdParsed.result.ok).toBe(false)
  144. expect(noIdParsed.rpcId).toBe('invalid-request')
  145. // A string rpcId in the otherwise-bad body is salvaged for correlation.
  146. const withId = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: JSON.stringify({ rpcId: 'salvage-me', nonsense: true }) })
  147. const withIdParsed = await withId.json() as { rpcId: string; result: { ok: boolean } }
  148. expect(withIdParsed.result.ok).toBe(false)
  149. expect(withIdParsed.rpcId).toBe('salvage-me')
  150. })
  151. it('maps carrier failures to HTTP statuses and the client throws transport failure', async () => {
  152. const handler = toFetchHandler(scriptedApi())
  153. // Unknown method → 404.
  154. const notFound = await handler.fetch('http://dsh.internal/api/no.such', { method: 'POST', body: '{}' })
  155. expect(notFound.status).toBe(404)
  156. // Non-JSON body → 400.
  157. const badBody = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: '{oops' })
  158. expect(badBody.status).toBe(400)
  159. // Impl crash → 500, and through the client that is a throw, not an err result.
  160. const crashing = scriptedApi({ sessions: { list: () => { throw new Error('impl exploded') } } })
  161. await expect(client(crashing).sessions.list({})).rejects.toThrow(/transport failure .*500/)
  162. })
  163. it('rejects when the transport never resolves within timeoutMs', async () => {
  164. // AbortSignal.timeout is immune to fake timers; a short real timeout keeps this fast.
  165. const never = new InProcessApiClient({
  166. fetch: (_i: RequestInfo | URL, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
  167. init?.signal?.addEventListener('abort', () => { reject(new Error('aborted by timeout')) })
  168. }),
  169. }, 25)
  170. await expect(never.sessions.list({})).rejects.toThrow()
  171. })
  172. it('aborts a unary call through the caller-supplied external signal', async () => {
  173. // Real-fetch semantics: on abort the rejection is the signal's reason, and the abort
  174. // works even when the transport ignores the signal entirely (hung impl).
  175. const gate = new AbortController()
  176. const hung = new InProcessApiClient({ fetch: () => new Promise<Response>(() => {}) }, 60_000)
  177. const call = hung.sessions.list({}, gate.signal)
  178. gate.abort(new Error('externally aborted'))
  179. await expect(call).rejects.toThrow(/externally aborted/)
  180. })
  181. it('rejects an already-aborted signal before touching the transport, mapping a string reason to an Error', async () => {
  182. let touched = false
  183. const c = new InProcessApiClient({
  184. fetch: () => {
  185. touched = true
  186. return Promise.resolve(new Response('{}'))
  187. },
  188. }, 60_000)
  189. const gate = new AbortController()
  190. gate.abort('gone before start')
  191. await expect(c.sessions.list({}, gate.signal)).rejects.toThrow('gone before start')
  192. expect(touched).toBe(false)
  193. })
  194. it('maps a non-Error, non-string abort reason to the default AbortError message', async () => {
  195. const gate = new AbortController()
  196. const hung = new InProcessApiClient({ fetch: () => new Promise<Response>(() => {}) }, 60_000)
  197. const call = hung.sessions.list({}, gate.signal)
  198. gate.abort(42)
  199. await expect(call).rejects.toThrow('This operation was aborted')
  200. })
  201. it('passes a signal-less doFetch straight through to the handler', async () => {
  202. class Probe extends InProcessApiClient {
  203. direct(url: URL): Promise<Response> {
  204. return this.doFetch(url)
  205. }
  206. }
  207. const probe = new Probe({ fetch: () => Promise.resolve(new Response('raw')) })
  208. const response = await probe.direct(new URL('http://dsh.internal/probe'))
  209. expect(await response.text()).toBe('raw')
  210. })
  211. it('throws on an S→C ok value that fails the method value schema (second-level parse)', async () => {
  212. // Impl echoes rpcId but returns a wrong-shaped value: envelope parse passes, value parse must reject.
  213. const api = scriptedApi({
  214. sessions: { list: r => Promise.resolve({ rpcId: r.rpcId, result: { ok: true, value: { items: 'not-an-array' } } }) as never },
  215. })
  216. await expect(client(api).sessions.list({})).rejects.toThrow()
  217. })
  218. })
  219. describe('workspace domain round trip', () => {
  220. it('routes both workspace methods through their handler rows and value schemas', async () => {
  221. const c = client(scriptedApi())
  222. const list = await c.workspace.list({})
  223. expect(list.result).toEqual({ ok: true, value: { items: [] } })
  224. const created = await c.workspace.create({ path: '/t' })
  225. expect(created.result.ok).toBe(true)
  226. if (created.result.ok) expect(created.result.value.created).toBe(true)
  227. })
  228. it('rejects a create payload violating the exactly-one refine at the handler', async () => {
  229. const response = await client(scriptedApi()).workspace.create({})
  230. expect(response.result.ok).toBe(false)
  231. if (!response.result.ok) expect(response.result.error.code).toBe('bad-request')
  232. })
  233. })
  234. describe('SSE stream path', () => {
  235. it('yields frames in order and skips the comment preamble', async () => {
  236. const frames: MuxFrame[] = [
  237. { type: 'session/subscribed', sessionId: sid('s1'), lastSeq: 3 },
  238. { type: 'stream/error', error: { code: 'internal', message: 'x', details: {} } },
  239. ]
  240. const api = scriptedApi({
  241. events: {
  242. async *mux(request) {
  243. let n = 0
  244. for (const frame of frames) yield { rpcId: RpcId(`push-${n++}-${request.rpcId}`), payload: frame }
  245. },
  246. },
  247. })
  248. const seen: MuxFrame[] = []
  249. for await (const envelope of client(api).events.mux({}, new AbortController().signal)) {
  250. seen.push(envelope.payload)
  251. }
  252. expect(seen).toEqual(frames)
  253. })
  254. it('reassembles frames across arbitrary chunk boundaries', async () => {
  255. // Two SSE frames split so one frame spans chunks and one chunk carries parts of both.
  256. const f1 = { type: 'server-request', rpcId: 'a', method: 'session/subscribed', payload: { type: 'session/subscribed', sessionId: 's1', lastSeq: 1 } }
  257. const f2 = { type: 'server-request', rpcId: 'b', method: 'session/subscribed', payload: { type: 'session/subscribed', sessionId: 's2', lastSeq: 2 } }
  258. const wire = `: connected\n\ndata: ${JSON.stringify(f1)}\n\ndata: ${JSON.stringify(f2)}\n\n`
  259. const cuts = [5, 40, wire.indexOf('data: ', 40) + 3]
  260. const encoder = new TextEncoder()
  261. const doFetch = (): Promise<Response> => Promise.resolve(new Response(new ReadableStream<Uint8Array>({
  262. start(controller) {
  263. let prev = 0
  264. for (const cut of [...cuts, wire.length]) {
  265. controller.enqueue(encoder.encode(wire.slice(prev, cut)))
  266. prev = cut
  267. }
  268. controller.close()
  269. },
  270. }), { status: 200 }))
  271. const chopped = new InProcessApiClient({ fetch: doFetch })
  272. const seen: string[] = []
  273. for await (const envelope of chopped.events.mux({}, new AbortController().signal)) {
  274. seen.push((envelope.payload as { sessionId: string }).sessionId)
  275. expect(envelope.rpcId).toBe(seen.length === 1 ? 'a' : 'b')
  276. }
  277. expect(seen).toEqual(['s1', 's2'])
  278. })
  279. it('emits a stream/error frame then closes when the impl throws mid-stream', async () => {
  280. const api = scriptedApi({
  281. events: {
  282. async *host(request): AsyncGenerator<RpcRequest<HostFrame>> {
  283. yield { rpcId: RpcId(`p-${request.rpcId}`), payload: { type: 'host/session-added', sessionId: sid('s1'), blank: true } }
  284. throw new Error('impl died mid-stream')
  285. },
  286. },
  287. })
  288. const seen: HostFrame[] = []
  289. for await (const envelope of client(api).events.host({}, new AbortController().signal)) {
  290. seen.push(envelope.payload)
  291. }
  292. expect(seen.map(f => f.type)).toEqual(['host/session-added', 'stream/error'])
  293. const last = seen.at(-1)
  294. if (last?.type === 'stream/error') expect(last.error.message).toMatch(/impl died mid-stream/)
  295. })
  296. it('drops a malformed SSE frame and keeps the stream alive (S→C two-level parse)', async () => {
  297. const good = { type: 'server-request', rpcId: 'g1', method: 'session/subscribed', payload: { type: 'session/subscribed', sessionId: 's1', lastSeq: 1 } }
  298. const badEnvelope = { type: 'server-response', rpcId: 'x' } // wrong quadrant for a stream
  299. const badFrame = { type: 'server-request', rpcId: 'b1', method: 'nope', payload: { type: 'no/such-frame' } }
  300. const wire = [
  301. 'data: {oops', // not JSON
  302. `data: ${JSON.stringify(badEnvelope)}`,
  303. `data: ${JSON.stringify(badFrame)}`,
  304. `data: ${JSON.stringify(good)}`,
  305. ].map(l => `${l}\n\n`).join('')
  306. const doFetch = (): Promise<Response> => Promise.resolve(new Response(new ReadableStream<Uint8Array>({
  307. start(controller) {
  308. controller.enqueue(new TextEncoder().encode(wire))
  309. controller.close()
  310. },
  311. }), { status: 200 }))
  312. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  313. try {
  314. const seen: MuxFrame[] = []
  315. for await (const envelope of new InProcessApiClient({ fetch: doFetch }).events.mux({}, new AbortController().signal)) {
  316. seen.push(envelope.payload)
  317. }
  318. // The three corrupt frames are reported and skipped; the good one still arrives.
  319. expect(seen).toEqual([{ type: 'session/subscribed', sessionId: 's1', lastSeq: 1 }])
  320. expect(errorSpy.mock.calls.length).toBe(3)
  321. } finally {
  322. errorSpy.mockRestore()
  323. }
  324. })
  325. it('fires onOpen once headers are in, before the first frame, and not on transport failure', async () => {
  326. const api = scriptedApi({
  327. events: {
  328. async *mux(request): AsyncGenerator<RpcRequest<MuxFrame>> {
  329. yield { rpcId: RpcId(`p-${request.rpcId}`), payload: { type: 'session/subscribed', sessionId: sid('s1'), lastSeq: 0 } }
  330. },
  331. },
  332. })
  333. const order: string[] = []
  334. const iterator = client(api).events.mux({}, new AbortController().signal, () => order.push('open'))
  335. expect(order).toEqual([]) // lazy generator: no fetch (and no onOpen) before iteration
  336. for await (const _ of iterator) order.push('frame')
  337. expect(order).toEqual(['open', 'frame'])
  338. // Transport failure path: onOpen must not fire.
  339. const failing = new InProcessApiClient({ fetch: () => Promise.resolve(new Response('down', { status: 503 })) })
  340. const failOrder: string[] = []
  341. await expect((async () => {
  342. for await (const _ of failing.events.mux({}, new AbortController().signal, () => failOrder.push('open'))) { /* unreachable */ }
  343. })()).rejects.toThrow(/transport failure/)
  344. expect(failOrder).toEqual([])
  345. })
  346. it('stops consuming when the caller aborts', async () => {
  347. let implSawAbort = false
  348. const api = scriptedApi({
  349. events: {
  350. async *mux(_request, signal): AsyncGenerator<RpcRequest<MuxFrame>> {
  351. try {
  352. let n = 0
  353. while (true) {
  354. yield { rpcId: RpcId(`p${n}`), payload: { type: 'session/subscribed', sessionId: sid('s1'), lastSeq: n++ } }
  355. await new Promise(resolve => setTimeout(resolve, 5))
  356. if (signal.aborted) return
  357. }
  358. } finally {
  359. implSawAbort = true
  360. }
  361. },
  362. },
  363. })
  364. const abort = new AbortController()
  365. let count = 0
  366. // In-process abort ends the stream (impl returns on signal.aborted); over a real
  367. // network fetch the same abort surfaces as a rejection — both stop the loop.
  368. await (async () => {
  369. for await (const _ of client(api).events.mux({}, abort.signal)) {
  370. if (++count === 2) abort.abort()
  371. }
  372. })().catch(() => undefined)
  373. expect(count).toBe(2)
  374. // Generator teardown may lag the abort by a microtask; poll briefly.
  375. await vi.waitFor(() => { expect(implSawAbort).toBe(true) })
  376. })
  377. })
  378. describe('respond path', () => {
  379. it('round-trips a client-response to a receipt', async () => {
  380. const seen: unknown[] = []
  381. const api = scriptedApi({
  382. respond: (message) => {
  383. seen.push(message)
  384. return Promise.resolve({ accepted: true as const })
  385. },
  386. })
  387. const receipt = await client(api).respond({ type: 'client-response', rpcId: RpcId('req-1'), result: { ok: true, value: { behavior: 'allow' } } })
  388. expect(receipt).toEqual({ accepted: true })
  389. expect(seen).toEqual([{ type: 'client-response', rpcId: 'req-1', result: { ok: true, value: { behavior: 'allow' } } }])
  390. })
  391. it('returns bad-response for a malformed client-response without reaching the impl', async () => {
  392. const respond = vi.fn()
  393. const handler = toFetchHandler(scriptedApi({ respond }))
  394. const response = await handler.fetch('http://dsh.internal/api/respond', { method: 'POST', body: JSON.stringify({ type: 'client-response' }) })
  395. expect(await response.json()).toEqual({ accepted: false, reason: 'bad-response' })
  396. expect(respond).not.toHaveBeenCalled()
  397. })
  398. })
  399. describe('envelope tap', () => {
  400. it('delivers one microtask batch of full forms per unary call', async () => {
  401. const api = scriptedApi()
  402. const tapped = client(api)
  403. const batches: (readonly RpcMessage[])[] = []
  404. tapped.subscribeEnvelopes(batch => batches.push(batch))
  405. await tapped.sessions.list({})
  406. await vi.waitFor(() => { expect(batches.length).toBeGreaterThan(0) })
  407. const all = batches.flat()
  408. expect(all.map(m => m.type)).toEqual(['client-request', 'server-response'])
  409. expect(all[0]?.rpcId).toBe(all[1]?.rpcId)
  410. })
  411. it('isolates a throwing listener and keeps serving the call', async () => {
  412. const api = scriptedApi()
  413. const tapped = client(api)
  414. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  415. try {
  416. const good: string[] = []
  417. tapped.subscribeEnvelopes(() => { throw new Error('listener bug') })
  418. tapped.subscribeEnvelopes(batch => good.push(...batch.map(m => m.type)))
  419. const response = await tapped.sessions.list({})
  420. expect(response.result.ok).toBe(true)
  421. await vi.waitFor(() => { expect(good).toContain('server-response') })
  422. } finally {
  423. errorSpy.mockRestore()
  424. }
  425. })
  426. it('buffers nothing with zero subscribers and unsubscribes cleanly', async () => {
  427. const api = scriptedApi()
  428. const tapped = client(api)
  429. await tapped.sessions.list({}) // no subscribers: must not accumulate
  430. const batches: (readonly RpcMessage[])[] = []
  431. const unsubscribe = tapped.subscribeEnvelopes(batch => batches.push(batch))
  432. unsubscribe()
  433. await tapped.sessions.list({})
  434. await new Promise(resolve => setTimeout(resolve, 0))
  435. expect(batches).toEqual([])
  436. })
  437. })