client-handler.spec.ts 21 KB

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