client-handler.spec.ts 22 KB

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