client-handler.spec.ts 35 KB

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