client-handler.spec.ts 27 KB

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