client-handler.spec.ts 38 KB

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