client-handler.spec.ts 38 KB

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