client-handler.spec.ts 23 KB

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