client-handler.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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, and rpcId discipline with no network or browser. Each case
  5. * scripts its own minimal ApiProxy.
  6. */
  7. import { describe, expect, it, vi } from 'vitest'
  8. import type { ApiProxy, RpcMessage, RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy'
  9. import { InProcessApiClient, RpcId, toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy'
  10. function ok<T>(request: RpcRequest<unknown>, value: T): Promise<RpcResponse<T>> {
  11. return Promise.resolve({ rpcId: request.rpcId, result: { ok: true, value } })
  12. }
  13. /** Scripted impl: every method resolves an empty-ish OK unless a case overrides it. */
  14. function scriptedApi(overrides: {
  15. host?: Partial<ApiProxy['host']>
  16. skills?: Partial<ApiProxy['skills']>
  17. agentPresets?: Partial<ApiProxy['agentPresets']>
  18. settings?: Partial<ApiProxy['settings']>
  19. credentials?: Partial<ApiProxy['credentials']>
  20. llm?: Partial<ApiProxy['llm']>
  21. } = {}): ApiProxy {
  22. const err = <T>(r: RpcRequest<unknown>): Promise<RpcResponse<T>> =>
  23. Promise.resolve({ rpcId: r.rpcId, result: { ok: false, error: { code: 'internal' as const, message: 'stub', details: {} } } })
  24. return {
  25. host: {
  26. describe: r => ok(r, {
  27. version: '0-test', cwd: '/t', attachedSessions: 0, home: '/h', canOpenPath: true,
  28. }),
  29. pickDirectory: r => ok(r, { path: null }),
  30. listDirectory: r => ok(r, { path: '/t', home: '/t', crumbs: [], entries: [], truncated: false }),
  31. createDirectory: r => ok(r, { path: '/t/new' }),
  32. openPath: r => ok(r, { opened: true as const }),
  33. ...overrides.host,
  34. },
  35. skills: { list: r => ok(r, { skills: [] }), ...overrides.skills },
  36. agentPresets: {
  37. openDocument: r => ok(r, { opened: true as const }),
  38. ...overrides.agentPresets,
  39. },
  40. settings: {
  41. describe: r => ok(r, { writable: true, hasDocument: false, namespaces: [] }),
  42. openDocument: r => ok(r, { opened: true as const }),
  43. update: err,
  44. replace: err,
  45. mutate: err,
  46. ...overrides.settings,
  47. },
  48. credentials: {
  49. describe: r => ok(r, { credentials: {} }),
  50. set: err,
  51. unset: err,
  52. ...overrides.credentials,
  53. },
  54. llm: {
  55. providers: r => ok(r, { providers: [] }),
  56. models: r => ok(r, {
  57. default: { provider: 'test', model: 'test' },
  58. routableProviders: [],
  59. groups: [],
  60. failures: [],
  61. }),
  62. discoverModels: err,
  63. ...overrides.llm,
  64. },
  65. downloads: { sessionLog: async () => new Response('stub', { status: 404 }) },
  66. }
  67. }
  68. function client(api: ApiProxy, timeoutMs?: number): InProcessApiClient {
  69. return new InProcessApiClient(toFetchHandler(api), timeoutMs)
  70. }
  71. /** Wrap one scripted method to record its invocation into `seen` before responding. */
  72. function recorderInto(seen: { method: string; payload: unknown }[]) {
  73. return <P, V>(method: string, respond: (r: RpcRequest<P>) => Promise<RpcResponse<V>>) =>
  74. (r: RpcRequest<P>): Promise<RpcResponse<V>> => {
  75. seen.push({ method, payload: r.payload })
  76. return respond(r)
  77. }
  78. }
  79. describe('unary round trip', () => {
  80. it('carries payload out and value back through the full wire form', async () => {
  81. let seen: RpcRequest<{}> | undefined
  82. const api = scriptedApi({
  83. host: {
  84. describe: (request) => {
  85. seen = request
  86. return ok(request, { version: '0-test', cwd: '/t', attachedSessions: 0, home: '/h', canOpenPath: true })
  87. },
  88. },
  89. })
  90. const response = await client(api).host.describe({})
  91. expect(seen?.payload).toEqual({})
  92. expect(seen?.rpcId).toBeTruthy()
  93. expect(response.rpcId).toBe(seen?.rpcId)
  94. expect(response.result).toMatchObject({ ok: true, value: { version: '0-test' } })
  95. })
  96. it('routes the agent-preset document opener through the wire', async () => {
  97. const opened = await client(scriptedApi()).agentPresets.openDocument({ agentPreset: 'mine' })
  98. expect(opened.result).toEqual({ ok: true, value: { opened: true } })
  99. })
  100. it('passes business errors through as 200 + err result, not a throw', async () => {
  101. const api = scriptedApi({
  102. host: {
  103. describe: request => Promise.resolve({
  104. rpcId: request.rpcId,
  105. result: { ok: false, error: { code: 'internal', message: 'nope', details: {} } },
  106. }),
  107. },
  108. })
  109. const response = await client(api).host.describe({})
  110. expect(response.result).toEqual({ ok: false, error: { code: 'internal', message: 'nope', details: {} } })
  111. })
  112. it('throws on rpcId echo mismatch', async () => {
  113. const api = scriptedApi({
  114. host: {
  115. describe: () => Promise.resolve({
  116. rpcId: RpcId('forged'),
  117. result: { ok: true, value: { version: '0-test', cwd: '/t', attachedSessions: 0, home: '/h', canOpenPath: true } },
  118. }),
  119. },
  120. })
  121. await expect(client(api).host.describe({})).rejects.toThrow(/rpcId mismatch/)
  122. })
  123. it('rejects a method/path mismatch as bad-request', async () => {
  124. const handler = toFetchHandler(scriptedApi())
  125. const body = { type: 'client-request', rpcId: 'r1', method: 'host.describe', payload: {} }
  126. const response = await handler.fetch('http://dsh.internal/api/skill.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
  127. expect(response.status).toBe(200)
  128. const parsed = await response.json() as { result: { ok: boolean; error?: { code: string; message: string } } }
  129. expect(parsed.result.ok).toBe(false)
  130. expect(parsed.result.error?.code).toBe('bad-request')
  131. expect(parsed.result.error?.message).toMatch(/does not match path/)
  132. })
  133. it('rejects a malformed envelope as bad-request, salvaging the rpcId or falling back to the sentinel', async () => {
  134. const handler = toFetchHandler(scriptedApi())
  135. // No salvageable rpcId → the fixed invalid-request sentinel keeps the response a valid ServerResponse.
  136. const noId = await handler.fetch('http://dsh.internal/api/host.describe', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ nonsense: true }) })
  137. expect(noId.status).toBe(200)
  138. const noIdParsed = await noId.json() as { rpcId: string; result: { ok: boolean } }
  139. expect(noIdParsed.result.ok).toBe(false)
  140. expect(noIdParsed.rpcId).toBe('invalid-request')
  141. // A string rpcId in the otherwise-bad body is salvaged for correlation.
  142. const withId = await handler.fetch('http://dsh.internal/api/host.describe', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ rpcId: 'salvage-me', nonsense: true }) })
  143. const withIdParsed = await withId.json() as { rpcId: string; result: { ok: boolean } }
  144. expect(withIdParsed.result.ok).toBe(false)
  145. expect(withIdParsed.rpcId).toBe('salvage-me')
  146. })
  147. it('maps carrier failures to HTTP statuses and the client throws transport failure', async () => {
  148. const handler = toFetchHandler(scriptedApi())
  149. // Unknown method → 404.
  150. const notFound = await handler.fetch('http://dsh.internal/api/no.such', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
  151. expect(notFound.status).toBe(404)
  152. // Non-JSON body → 400.
  153. const badBody = await handler.fetch('http://dsh.internal/api/host.describe', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{oops' })
  154. expect(badBody.status).toBe(400)
  155. // Impl crash → 500, and through the client that is a throw, not an err result.
  156. const crashing = scriptedApi({ host: { describe: () => { throw new Error('impl exploded') } } })
  157. await expect(client(crashing).host.describe({})).rejects.toThrow(/transport failure .*500/)
  158. })
  159. it('rejects non-JSON media types before executing anything (cross-site simple-request fence)', async () => {
  160. const describe = vi.fn((request: RpcRequest<{}>) => ok(request, {
  161. version: '0-test', cwd: '/t', attachedSessions: 0, home: '/h', canOpenPath: true,
  162. }))
  163. const handler = toFetchHandler(scriptedApi({ host: { describe } }))
  164. const body = JSON.stringify({ type: 'client-request', rpcId: 'r1', method: 'host.describe', payload: {} })
  165. // A "simple" browser POST (text/plain — sent with no CORS preflight) is
  166. // refused at the carrier before the impl runs.
  167. const plain = await handler.fetch('http://dsh.internal/api/host.describe', { method: 'POST', headers: { 'content-type': 'text/plain' }, body })
  168. expect(plain.status).toBe(415)
  169. // A string body with no explicit header defaults to text/plain — same fence.
  170. const unlabelled = await handler.fetch('http://dsh.internal/api/host.describe', { method: 'POST', body })
  171. expect(unlabelled.status).toBe(415)
  172. expect(describe).not.toHaveBeenCalled()
  173. // Media-type parameters pass: the fence checks the type, not the exact string.
  174. const charset = await handler.fetch('http://dsh.internal/api/host.describe', { method: 'POST', headers: { 'content-type': 'application/json; charset=utf-8' }, body })
  175. expect(charset.status).toBe(200)
  176. expect(describe).toHaveBeenCalledTimes(1)
  177. })
  178. it('rejects when the transport never resolves within timeoutMs', async () => {
  179. // AbortSignal.timeout is immune to fake timers; a short real timeout keeps this fast.
  180. const never = new InProcessApiClient({
  181. fetch: (_i: RequestInfo | URL, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
  182. init?.signal?.addEventListener('abort', () => { reject(new Error('aborted by timeout')) })
  183. }),
  184. }, 25)
  185. await expect(never.host.describe({})).rejects.toThrow()
  186. })
  187. it('aborts a unary call through the caller-supplied external signal', async () => {
  188. // Real-fetch semantics: on abort the rejection is the signal's reason, and the abort
  189. // works even when the transport ignores the signal entirely (hung impl).
  190. const gate = new AbortController()
  191. const hung = new InProcessApiClient({ fetch: () => new Promise<Response>(() => {}) }, 60_000)
  192. const call = hung.host.describe({}, gate.signal)
  193. gate.abort(new Error('externally aborted'))
  194. await expect(call).rejects.toThrow(/externally aborted/)
  195. })
  196. it('rejects an already-aborted signal before touching the transport, mapping a string reason to an Error', async () => {
  197. let touched = false
  198. const c = new InProcessApiClient({
  199. fetch: () => {
  200. touched = true
  201. return Promise.resolve(new Response('{}'))
  202. },
  203. }, 60_000)
  204. const gate = new AbortController()
  205. gate.abort('gone before start')
  206. await expect(c.host.describe({}, gate.signal)).rejects.toThrow('gone before start')
  207. expect(touched).toBe(false)
  208. })
  209. it('maps a non-Error, non-string abort reason to the default AbortError message', async () => {
  210. const gate = new AbortController()
  211. const hung = new InProcessApiClient({ fetch: () => new Promise<Response>(() => {}) }, 60_000)
  212. const call = hung.host.describe({}, gate.signal)
  213. gate.abort(42)
  214. await expect(call).rejects.toThrow('This operation was aborted')
  215. })
  216. it('passes a signal-less doFetch straight through to the handler', async () => {
  217. class Probe extends InProcessApiClient {
  218. direct(url: URL): Promise<Response> {
  219. return this.doFetch(url)
  220. }
  221. }
  222. const probe = new Probe({ fetch: () => Promise.resolve(new Response('raw')) })
  223. const response = await probe.direct(new URL('http://dsh.internal/probe'))
  224. expect(await response.text()).toBe('raw')
  225. })
  226. it('throws on an S→C ok value that fails the method value schema (second-level parse)', async () => {
  227. // Impl echoes rpcId but returns a wrong-shaped value: envelope parse passes, value parse must reject.
  228. const api = scriptedApi({
  229. host: { describe: request => Promise.resolve({ rpcId: request.rpcId, result: { ok: true, value: { version: 1 } } }) as never },
  230. })
  231. await expect(client(api).host.describe({})).rejects.toThrow()
  232. })
  233. })
  234. describe('envelope tap', () => {
  235. it('delivers one microtask batch of full forms per unary call', async () => {
  236. const api = scriptedApi()
  237. const tapped = client(api)
  238. const batches: (readonly RpcMessage[])[] = []
  239. tapped.subscribeEnvelopes(batch => batches.push(batch))
  240. await tapped.host.describe({})
  241. await vi.waitFor(() => { expect(batches.length).toBeGreaterThan(0) })
  242. const all = batches.flat()
  243. expect(all.map(m => m.type)).toEqual(['client-request', 'server-response'])
  244. expect(all[0]?.rpcId).toBe(all[1]?.rpcId)
  245. })
  246. it('isolates a throwing listener and keeps serving the call', async () => {
  247. const api = scriptedApi()
  248. const tapped = client(api)
  249. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  250. try {
  251. const good: string[] = []
  252. tapped.subscribeEnvelopes(() => { throw new Error('listener bug') })
  253. tapped.subscribeEnvelopes(batch => good.push(...batch.map(m => m.type)))
  254. const response = await tapped.host.describe({})
  255. expect(response.result.ok).toBe(true)
  256. await vi.waitFor(() => { expect(good).toContain('server-response') })
  257. } finally {
  258. errorSpy.mockRestore()
  259. }
  260. })
  261. it('buffers nothing with zero subscribers and unsubscribes cleanly', async () => {
  262. const api = scriptedApi()
  263. const tapped = client(api)
  264. await tapped.host.describe({}) // no subscribers: must not accumulate
  265. const batches: (readonly RpcMessage[])[] = []
  266. const unsubscribe = tapped.subscribeEnvelopes(batch => batches.push(batch))
  267. unsubscribe()
  268. await tapped.host.describe({})
  269. await new Promise(resolve => setTimeout(resolve, 0))
  270. expect(batches).toEqual([])
  271. })
  272. })
  273. describe('config unary surface', () => {
  274. it('round-trips every settings/credentials/llm method with its own payload and value shape', async () => {
  275. const seen: { method: string; payload: unknown }[] = []
  276. const record = recorderInto(seen)
  277. const view = {
  278. ns: 'llm-deepseek',
  279. schema: { uid: 1, refs: { 1: { type: 'object' } } },
  280. value: { baseURL: 'https://next' },
  281. user: { baseURL: 'https://next' },
  282. applies: 'live' as const,
  283. secrets: [{ path: ['apiKey'], set: true }],
  284. revision: 0,
  285. }
  286. const providerRow = {
  287. provider: 'openai',
  288. displayName: 'openai',
  289. settingsNs: 'llm-pi-ai',
  290. settingsPath: ['providers', 'openai'],
  291. active: false,
  292. }
  293. const group = { id: 'deepseek-official', name: 'DeepSeek', models: [{ id: 'deepseek-v4-flash', name: 'Flash' }] }
  294. const api = scriptedApi({
  295. settings: {
  296. describe: record('settings.describe', r => ok(r, { writable: true, hasDocument: false, namespaces: [view] })),
  297. openDocument: record('settings.openDocument', r => ok(r, { opened: true as const })),
  298. update: record('settings.update', r => ok(r, view)),
  299. replace: record('settings.replace', r => ok(r, view)),
  300. mutate: record('settings.mutate', r => ok(r, view)),
  301. },
  302. credentials: {
  303. describe: record('credentials.describe', r => ok(r, { credentials: { OPENAI_API_KEY: { configured: true, source: 'file', writable: true } } })),
  304. set: record('credentials.set', r => ok(r, {})),
  305. unset: record('credentials.unset', r => ok(r, {})),
  306. },
  307. llm: {
  308. providers: record('llm.providers', r => ok(r, { providers: [providerRow] })),
  309. models: record('llm.models', r => ok(r, {
  310. default: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  311. routableProviders: ['deepseek-official'],
  312. groups: [group],
  313. failures: [],
  314. })),
  315. discoverModels: record('llm.discoverModels', r => ok(r, { models: [{ id: 'acme-large', contextWindow: 65536 }] })),
  316. },
  317. })
  318. const c = client(api)
  319. const described = await c.settings.describe({})
  320. expect(described.result).toEqual({ ok: true, value: { writable: true, hasDocument: false, namespaces: [view] } })
  321. expect((await c.settings.openDocument({})).result).toEqual({ ok: true, value: { opened: true } })
  322. const updated = await c.settings.update({ ns: 'llm-deepseek', patch: { baseURL: 'https://next' } })
  323. expect(updated.result).toEqual({ ok: true, value: view })
  324. const replaced = await c.settings.replace({ ns: 'llm-deepseek', section: {} })
  325. expect(replaced.result).toEqual({ ok: true, value: view })
  326. const mutated = await c.settings.mutate({
  327. ns: 'llm-deepseek',
  328. ops: [{ op: 'unset', path: ['baseURL'] }],
  329. expectedRevision: 0,
  330. })
  331. expect(mutated.result).toEqual({ ok: true, value: view })
  332. const creds = await c.credentials.describe({ refs: ['OPENAI_API_KEY'] })
  333. expect(creds.result).toEqual({ ok: true, value: { credentials: { OPENAI_API_KEY: { configured: true, source: 'file', writable: true } } } })
  334. expect((await c.credentials.set({ ref: 'OPENAI_API_KEY', value: 'sk-x' })).result).toEqual({ ok: true, value: {} })
  335. expect((await c.credentials.unset({ ref: 'OPENAI_API_KEY' })).result).toEqual({ ok: true, value: {} })
  336. const providers = await c.llm.providers({})
  337. expect(providers.result).toEqual({ ok: true, value: { providers: [providerRow] } })
  338. const models = await c.llm.models({})
  339. expect(models.result).toEqual({
  340. ok: true,
  341. value: {
  342. default: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  343. routableProviders: ['deepseek-official'],
  344. groups: [group],
  345. failures: [],
  346. },
  347. })
  348. const discovered = await c.llm.discoverModels({
  349. settingsNs: 'llm-pi-ai',
  350. baseURL: 'https://gateway.acme.example/v1',
  351. api: 'openai-completions',
  352. apiKey: 'probe-key',
  353. })
  354. expect(discovered.result).toEqual({ ok: true, value: { models: [{ id: 'acme-large', contextWindow: 65536 }] } })
  355. expect(seen.map(call => call.method)).toEqual([
  356. 'settings.describe', 'settings.openDocument', 'settings.update', 'settings.replace', 'settings.mutate',
  357. 'credentials.describe', 'credentials.set', 'credentials.unset',
  358. 'llm.providers', 'llm.models', 'llm.discoverModels',
  359. ])
  360. expect(seen[2]?.payload).toEqual({ ns: 'llm-deepseek', patch: { baseURL: 'https://next' } })
  361. expect(seen[4]?.payload)
  362. .toEqual({ ns: 'llm-deepseek', ops: [{ op: 'unset', path: ['baseURL'] }], expectedRevision: 0 })
  363. expect(seen[6]?.payload).toEqual({ ref: 'OPENAI_API_KEY', value: 'sk-x' })
  364. // The draft crosses whole, credential included: the host needs it for this
  365. // one interrogation and stores none of it.
  366. expect(seen[10]?.payload).toEqual({
  367. settingsNs: 'llm-pi-ai',
  368. baseURL: 'https://gateway.acme.example/v1',
  369. api: 'openai-completions',
  370. apiKey: 'probe-key',
  371. })
  372. })
  373. it('rejects an invalid credential reference name at the carrier boundary', async () => {
  374. const api = scriptedApi()
  375. const response = await client(api).credentials.set({ ref: 'not a var', value: 'x' })
  376. expect(response.result.ok).toBe(false)
  377. if (response.result.ok) throw new Error('unreachable')
  378. expect(response.result.error.code).toBe('bad-request')
  379. })
  380. })