client-handler.spec.ts 38 KB

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