client-handler.spec.ts 36 KB

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