client-handler.spec.ts 33 KB

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