client-handler.spec.ts 34 KB

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