fetch-carrier.spec.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. import { CommandId } from '@deepseek-ai/dsh-commands/brand'
  2. import { describe, expect, it, vi } from 'vitest'
  3. import type { ApiProxy, HostFrame, MuxFrame } from '../src/api/index.ts'
  4. import type { ClientResponse, RpcMessage, RpcReceipt, RpcRequest } from '../src/api/rpc.ts'
  5. import { RpcId } from '../src/api/rpc.ts'
  6. import { toFetchHandler } from '../src/fetch/handler.ts'
  7. import { AbstractApiClient, InProcessApiClient } from '../src/fetch/client.ts'
  8. /** Minimal in-memory ApiProxy: echoes rpcIds, scripts one frame per stream. */
  9. function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFrame[]; crashOn: string }> = {}): ApiProxy {
  10. const muxFrames = overrides.muxFrames ?? [{ type: 'session/subscribed', sessionId: 's1' as never, lastSeq: -1 }]
  11. const hostFrames = overrides.hostFrames ?? [{ type: 'host/session-removed', sessionId: 's1' as never }]
  12. async function * stream<F>(frames: F[], signal: AbortSignal): AsyncGenerator<RpcRequest<F>> {
  13. for (const payload of frames) {
  14. if (signal.aborted) return
  15. yield { rpcId: RpcId(`frame-${String(frames.indexOf(payload))}`), payload }
  16. }
  17. }
  18. return {
  19. sessions: {
  20. async list(request) {
  21. if (overrides.crashOn === 'session.list') throw new Error('impl crashed')
  22. return { rpcId: request.rpcId, result: { ok: true, value: { items: [] } } }
  23. },
  24. async search(request, signal) {
  25. if (request.payload.query === 'hang') {
  26. if (!signal.aborted) {
  27. await new Promise<void>((resolve) => {
  28. signal.addEventListener('abort', () => { resolve() }, { once: true })
  29. })
  30. }
  31. return {
  32. rpcId: request.rpcId,
  33. result: { ok: false, error: { code: 'cancelled', message: 'aborted', details: {} } },
  34. }
  35. }
  36. return {
  37. rpcId: request.rpcId,
  38. result: {
  39. ok: true,
  40. value: { items: [{ sessionId: 's1' as never, snippet: 'fixture match' }], hasMore: false },
  41. },
  42. }
  43. },
  44. async create(request) {
  45. return { rpcId: request.rpcId, result: { ok: true, value: { sessionId: 's-new' as never } } }
  46. },
  47. async history(request) {
  48. if (request.payload.sessionId === ('with-projections' as never)) {
  49. return {
  50. rpcId: request.rpcId,
  51. result: { ok: true, value: { events: [], hasMore: false, projections: { asOfSeq: 9, values: { todos: [{ content: 'current', status: 'in_progress' as const }] } } } },
  52. }
  53. }
  54. return {
  55. rpcId: request.rpcId,
  56. result: { ok: false, error: { code: 'session-not-found', message: 'nope', details: { sessionId: request.payload.sessionId } } },
  57. }
  58. },
  59. async models(request) {
  60. return {
  61. rpcId: request.rpcId,
  62. result: {
  63. ok: true,
  64. value: {
  65. current: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
  66. groups: [],
  67. failures: [],
  68. },
  69. },
  70. }
  71. },
  72. async selectModel(request) {
  73. return {
  74. rpcId: request.rpcId,
  75. result: {
  76. ok: true,
  77. value: {
  78. selected: {
  79. provider: request.payload.provider,
  80. model: request.payload.model,
  81. ...request.payload.reasoningEffort === undefined
  82. ? {}
  83. : { reasoningEffort: request.payload.reasoningEffort },
  84. },
  85. },
  86. },
  87. }
  88. },
  89. async rename(request) {
  90. return { rpcId: request.rpcId, result: { ok: true, value: { title: request.payload.title, seq: 0 } } }
  91. },
  92. async fork(request) {
  93. return { rpcId: request.rpcId, result: { ok: true, value: { sessionId: 's-fork' as never } } }
  94. },
  95. async prompt(request) {
  96. return { rpcId: request.rpcId, result: { ok: true, value: { accepted: true as const } } }
  97. },
  98. async updateQueue(request) {
  99. return { rpcId: request.rpcId, result: { ok: true, value: { accepted: true as const } } }
  100. },
  101. async cancel(request) {
  102. return { rpcId: request.rpcId, result: { ok: true, value: { accepted: true as const } } }
  103. },
  104. },
  105. host: {
  106. async describe(request) {
  107. return { rpcId: request.rpcId, result: { ok: true, value: { version: 'v', cwd: '/w', attachedSessions: 0 } } }
  108. },
  109. async pickDirectory(request) {
  110. return { rpcId: request.rpcId, result: { ok: true, value: { path: null } } }
  111. },
  112. async listDirectory(request) {
  113. return { rpcId: request.rpcId, result: { ok: true, value: { path: '/w', home: '/w', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [], truncated: false } } }
  114. },
  115. async createDirectory(request) {
  116. return { rpcId: request.rpcId, result: { ok: true, value: { path: '/w/new' } } }
  117. },
  118. async openPath(request) {
  119. return { rpcId: request.rpcId, result: { ok: true, value: { opened: true as const } } }
  120. },
  121. },
  122. workspace: {
  123. async list(request) {
  124. return { rpcId: request.rpcId, result: { ok: true, value: { items: [], archivedSessionIds: [] } } }
  125. },
  126. async create(request) {
  127. return {
  128. rpcId: request.rpcId,
  129. result: { ok: true, value: { workspace: { workspaceId: 'w1' as never, path: '/w', title: 'w', sessionIds: [], createdAt: 't', updatedAt: 't' }, created: true } },
  130. }
  131. },
  132. async rename(request) {
  133. return {
  134. rpcId: request.rpcId,
  135. result: { ok: true, value: { workspace: { workspaceId: 'w1' as never, path: '/w', title: 'w', sessionIds: [], createdAt: 't', updatedAt: 't' } } },
  136. }
  137. },
  138. async delete(request) {
  139. return { rpcId: request.rpcId, result: { ok: true, value: { deleted: true as const } } }
  140. },
  141. async insertSessionBefore(request) {
  142. return {
  143. rpcId: request.rpcId,
  144. result: { ok: true, value: { workspace: { workspaceId: 'w1' as never, path: '/w', title: 'w', sessionIds: [], createdAt: 't', updatedAt: 't' } } },
  145. }
  146. },
  147. async archiveSession(request) {
  148. return { rpcId: request.rpcId, result: { ok: true, value: { archivedSessionIds: [request.payload.sessionId] } } }
  149. },
  150. },
  151. commands: {
  152. async list(request) {
  153. return { rpcId: request.rpcId, result: { ok: true, value: { commands: [{ name: 'plan', description: 'Toggle plan mode', input: { hint: 'on|off' } }] } } }
  154. },
  155. async execute(request, signal) {
  156. if (request.payload.line === '/hang') {
  157. // Cooperative hang: settles only through the carrier signal (sticky
  158. // abort checked first — listeners never fire retroactively).
  159. if (!signal.aborted) {
  160. await new Promise<void>((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) })
  161. }
  162. return { rpcId: request.rpcId, result: { ok: false, error: { code: 'cancelled', message: 'aborted', details: {} } } }
  163. }
  164. if (request.payload.line.startsWith('/plan')) {
  165. return { rpcId: request.rpcId, result: { ok: true, value: { matched: true, commandId: CommandId('cmd-x') } } }
  166. }
  167. return { rpcId: request.rpcId, result: { ok: true, value: { matched: false } } }
  168. },
  169. },
  170. skills: {
  171. async list(request) {
  172. return { rpcId: request.rpcId, result: { ok: true, value: { skills: [{ name: 'commit-helper', description: 'Git commits' }] } } }
  173. },
  174. },
  175. goals: {
  176. async create(request) {
  177. return { rpcId: request.rpcId, result: { ok: false, error: { code: 'internal', message: 'stub', details: {} } } }
  178. },
  179. async edit(request) {
  180. return { rpcId: request.rpcId, result: { ok: false, error: { code: 'internal', message: 'stub', details: {} } } }
  181. },
  182. async pause(request) {
  183. return { rpcId: request.rpcId, result: { ok: false, error: { code: 'internal', message: 'stub', details: {} } } }
  184. },
  185. async resume(request) {
  186. return { rpcId: request.rpcId, result: { ok: false, error: { code: 'internal', message: 'stub', details: {} } } }
  187. },
  188. async complete(request) {
  189. return { rpcId: request.rpcId, result: { ok: false, error: { code: 'internal', message: 'stub', details: {} } } }
  190. },
  191. async clear(request) {
  192. return { rpcId: request.rpcId, result: { ok: false, error: { code: 'internal', message: 'stub', details: {} } } }
  193. },
  194. },
  195. settings: {
  196. async describe(request) {
  197. return { rpcId: request.rpcId, result: { ok: true, value: { writable: true, namespaces: [] } } }
  198. },
  199. async update(request) {
  200. return { rpcId: request.rpcId, result: { ok: false, error: { code: 'settings-rejected', message: 'stub', details: { ns: request.payload.ns } } } }
  201. },
  202. async replace(request) {
  203. return { rpcId: request.rpcId, result: { ok: false, error: { code: 'settings-rejected', message: 'stub', details: { ns: request.payload.ns } } } }
  204. },
  205. async mutate(request) {
  206. return { rpcId: request.rpcId, result: { ok: false, error: { code: 'settings-rejected', message: 'stub', details: { ns: request.payload.ns } } } }
  207. },
  208. },
  209. credentials: {
  210. async describe(request) {
  211. return { rpcId: request.rpcId, result: { ok: true, value: { credentials: {} } } }
  212. },
  213. async set(request) {
  214. return { rpcId: request.rpcId, result: { ok: true, value: {} } }
  215. },
  216. async unset(request) {
  217. return { rpcId: request.rpcId, result: { ok: true, value: {} } }
  218. },
  219. },
  220. llm: {
  221. async providers(request) {
  222. return { rpcId: request.rpcId, result: { ok: true, value: { providers: [] } } }
  223. },
  224. async models(request) {
  225. return { rpcId: request.rpcId, result: { ok: true, value: { groups: [], failures: [] } } }
  226. },
  227. },
  228. events: {
  229. mux: (_request, signal) => stream(muxFrames, signal),
  230. host: (_request, signal) => stream(hostFrames, signal),
  231. },
  232. async respond(message: ClientResponse): Promise<RpcReceipt> {
  233. return message.rpcId === 'known' ? { accepted: true } : { accepted: false, reason: 'not-pending' }
  234. },
  235. }
  236. }
  237. function client(api: ApiProxy = fakeApi(), timeoutMs?: number): InProcessApiClient {
  238. return new InProcessApiClient(toFetchHandler(api), timeoutMs)
  239. }
  240. async function collect<F>(stream: AsyncIterable<RpcRequest<F>>): Promise<RpcRequest<F>[]> {
  241. const out: RpcRequest<F>[] = []
  242. for await (const envelope of stream) out.push(envelope)
  243. return out
  244. }
  245. describe('unary round trip (handler ⇄ client, no network)', () => {
  246. it('carries a success result and echoes the minted rpcId', async () => {
  247. const response = await client().sessions.list({})
  248. expect(response.result).toEqual({ ok: true, value: { items: [] } })
  249. expect(response.rpcId).toMatch(/[0-9a-f-]{36}/)
  250. })
  251. it('carries the tail-page projections block through the wire schema (Zod must not strip it)', async () => {
  252. const response = await client().sessions.history({ sessionId: 'with-projections' as never })
  253. expect(response.result.ok).toBe(true)
  254. if (response.result.ok) {
  255. expect(response.result.value.projections).toEqual(
  256. { asOfSeq: 9, values: { todos: [{ content: 'current', status: 'in_progress' }] } },
  257. )
  258. }
  259. })
  260. it('carries a business error as 200 + error result', async () => {
  261. const response = await client().sessions.history({ sessionId: 'missing' as never })
  262. expect(response.result.ok).toBe(false)
  263. if (!response.result.ok) expect(response.result.error.code).toBe('session-not-found')
  264. })
  265. it('covers create/prompt/updateQueue/cancel/describe passthrough', async () => {
  266. const c = client()
  267. expect((await c.sessions.search({ query: 'fixture' })).result).toEqual({
  268. ok: true,
  269. value: { items: [{ sessionId: 's1', snippet: 'fixture match' }], hasMore: false },
  270. })
  271. expect((await c.sessions.create({})).result.ok).toBe(true)
  272. expect((await c.sessions.models({ sessionId: 's' as never })).result.ok).toBe(true)
  273. const selected = await c.sessions.selectModel({
  274. sessionId: 's' as never,
  275. provider: 'deepseek-official',
  276. model: 'deepseek-v4-flash',
  277. reasoningEffort: 'max',
  278. })
  279. expect(selected.result).toMatchObject({
  280. ok: true,
  281. value: {
  282. selected: {
  283. provider: 'deepseek-official',
  284. model: 'deepseek-v4-flash',
  285. reasoningEffort: 'max',
  286. },
  287. },
  288. })
  289. const renamed = await c.sessions.rename({ sessionId: 's' as never, title: 'named' })
  290. expect(renamed.result).toMatchObject({ ok: true, value: { title: 'named', seq: 0 } })
  291. expect((await c.sessions.prompt({ sessionId: 's' as never, mode: 'queue', content: [{ type: 'text', text: 'x' }] })).result.ok).toBe(true)
  292. expect((await c.sessions.updateQueue({
  293. sessionId: 's' as never,
  294. itemId: 'item-1' as never,
  295. action: { kind: 'remove' },
  296. })).result.ok).toBe(true)
  297. expect((await c.sessions.cancel({ sessionId: 's' as never })).result.ok).toBe(true)
  298. expect((await c.host.describe({})).result.ok).toBe(true)
  299. })
  300. it('round-trips the native picker without the default unary timeout', async () => {
  301. const api = fakeApi()
  302. api.host.pickDirectory = async (request) => {
  303. await new Promise(resolve => setTimeout(resolve, 15))
  304. return { rpcId: request.rpcId, result: { ok: true, value: { path: '/tmp/project' } } }
  305. }
  306. const response = await client(api, 1).host.pickDirectory({})
  307. expect(response.result).toEqual({ ok: true, value: { path: '/tmp/project' } })
  308. })
  309. it('round-trips the browse listing and creation calls through the wire form', async () => {
  310. const c = client()
  311. const listed = await c.host.listDirectory({ path: '/w' })
  312. expect(listed.result).toEqual({
  313. ok: true,
  314. value: { path: '/w', home: '/w', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [], truncated: false },
  315. })
  316. const home = await c.host.listDirectory({})
  317. expect(home.result).toMatchObject({ ok: true, value: { home: '/w' } })
  318. const created = await c.host.createDirectory({ path: '/w', name: 'fresh' })
  319. expect(created.result).toEqual({ ok: true, value: { path: '/w/new' } })
  320. })
  321. it('round-trips host.openPath through the wire form', async () => {
  322. const api = fakeApi()
  323. let opened: string | undefined
  324. api.host.openPath = async (request) => {
  325. opened = request.payload.path
  326. return { rpcId: request.rpcId, result: { ok: true, value: { opened: true as const } } }
  327. }
  328. const response = await client(api).host.openPath({ path: '/tmp/a.txt' })
  329. expect(opened).toBe('/tmp/a.txt')
  330. expect(response.result).toEqual({ ok: true, value: { opened: true } })
  331. })
  332. it('round-trips command.list / command.execute / skill.list through the wire form', async () => {
  333. const c = client()
  334. const list = await c.commands.list({ sessionId: 's' as never })
  335. expect(list.result).toEqual({ ok: true, value: { commands: [{ name: 'plan', description: 'Toggle plan mode', input: { hint: 'on|off' } }] } })
  336. const hit = await c.commands.execute({ sessionId: 's' as never, line: '/plan off' })
  337. expect(hit.result).toEqual({ ok: true, value: { matched: true, commandId: 'cmd-x' } })
  338. const miss = await c.commands.execute({ sessionId: 's' as never, line: '/nope' })
  339. expect(miss.result).toEqual({ ok: true, value: { matched: false } })
  340. const skills = await c.skills.list({ sessionId: 's' as never })
  341. expect(skills.result).toEqual({ ok: true, value: { skills: [{ name: 'commit-helper', description: 'Git commits' }] } })
  342. })
  343. it('lets command.execute finish after the 30-second default unary deadline', async () => {
  344. vi.useFakeTimers()
  345. const timeoutSpy = vi.spyOn(AbortSignal, 'timeout').mockImplementation((milliseconds) => {
  346. const controller = new AbortController()
  347. setTimeout(() => {
  348. controller.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'))
  349. }, milliseconds)
  350. return controller.signal
  351. })
  352. try {
  353. const api = fakeApi()
  354. api.commands.execute = async (request) => {
  355. await new Promise(resolve => setTimeout(resolve, 30_001))
  356. return {
  357. rpcId: request.rpcId,
  358. result: { ok: true, value: { matched: true, commandId: CommandId('cmd-slow') } },
  359. }
  360. }
  361. const execution = client(api).commands.execute({ sessionId: 's' as never, line: '/slow' })
  362. const assertion = expect(execution).resolves.toMatchObject({
  363. result: { ok: true, value: { matched: true, commandId: 'cmd-slow' } },
  364. })
  365. await Promise.all([
  366. vi.advanceTimersByTimeAsync(30_001),
  367. assertion,
  368. ])
  369. expect(timeoutSpy).not.toHaveBeenCalled()
  370. } finally {
  371. timeoutSpy.mockRestore()
  372. vi.useRealTimers()
  373. }
  374. })
  375. it('keeps caller and connection aborts on command.execute', async () => {
  376. const api = fakeApi()
  377. const started = Promise.withResolvers<AbortSignal>()
  378. api.commands.execute = async (request, signal) => {
  379. started.resolve(signal)
  380. if (!signal.aborted) {
  381. await new Promise<void>((resolve) => {
  382. signal.addEventListener('abort', () => { resolve() }, { once: true })
  383. })
  384. }
  385. return {
  386. rpcId: request.rpcId,
  387. result: { ok: false, error: { code: 'cancelled', message: 'aborted', details: {} } },
  388. }
  389. }
  390. const controller = new AbortController()
  391. const execution = client(api).commands.execute(
  392. { sessionId: 's' as never, line: '/hang' },
  393. controller.signal,
  394. )
  395. const handlerSignal = await started.promise
  396. controller.abort(new Error('connection closed'))
  397. await expect(execution).rejects.toThrow('connection closed')
  398. expect(handlerSignal.aborted).toBe(true)
  399. })
  400. it('propagates the carrier Request signal into command.execute', async () => {
  401. const handler = toFetchHandler(fakeApi())
  402. const controller = new AbortController()
  403. const body = JSON.stringify({ type: 'client-request', rpcId: 'r-sig', method: 'command.execute', payload: { sessionId: 's', line: '/hang' } })
  404. // The fake's /hang settles only when the invoke-level signal aborts: a
  405. // completed response with the cancelled error proves req.signal reached it.
  406. const pending = handler.fetch(new Request('http://x/api/command.execute', { method: 'POST', headers: { 'content-type': 'application/json' }, body, signal: controller.signal }))
  407. controller.abort()
  408. const response = await pending
  409. const parsed = await response.json() as { rpcId: string; result: { ok: boolean; error?: { code: string } } }
  410. expect(parsed.rpcId).toBe('r-sig')
  411. expect(parsed.result.error?.code).toBe('cancelled')
  412. })
  413. it('propagates the carrier Request signal into session.search', async () => {
  414. const handler = toFetchHandler(fakeApi())
  415. const controller = new AbortController()
  416. const body = JSON.stringify({
  417. type: 'client-request',
  418. rpcId: 'r-search-sig',
  419. method: 'session.search',
  420. payload: { query: 'hang' },
  421. })
  422. const pending = handler.fetch(new Request(
  423. 'http://x/api/session.search',
  424. { method: 'POST', headers: { 'content-type': 'application/json' }, body, signal: controller.signal },
  425. ))
  426. controller.abort()
  427. const response = await pending
  428. const parsed = await response.json() as {
  429. rpcId: string
  430. result: { error?: { code: string } }
  431. }
  432. expect(parsed.rpcId).toBe('r-search-sig')
  433. expect(parsed.result.error?.code).toBe('cancelled')
  434. })
  435. it('propagates the carrier Request signal into host.pickDirectory', async () => {
  436. const api = fakeApi()
  437. api.host.pickDirectory = async (request, signal) => {
  438. if (!signal.aborted) {
  439. await new Promise<void>((resolve) => {
  440. signal.addEventListener('abort', () => { resolve() }, { once: true })
  441. })
  442. }
  443. return {
  444. rpcId: request.rpcId,
  445. result: { ok: false, error: { code: 'cancelled', message: 'aborted', details: {} } },
  446. }
  447. }
  448. const handler = toFetchHandler(api)
  449. const controller = new AbortController()
  450. const body = JSON.stringify({ type: 'client-request', rpcId: 'r-picker', method: 'host.pickDirectory', payload: {} })
  451. const pending = handler.fetch(new Request('http://x/api/host.pickDirectory', {
  452. method: 'POST', headers: { 'content-type': 'application/json' }, body, signal: controller.signal,
  453. }))
  454. controller.abort()
  455. const parsed = await (await pending).json() as { result: { error?: { code: string } } }
  456. expect(parsed.result.error?.code).toBe('cancelled')
  457. })
  458. })
  459. describe('handler carrier-layer statuses', () => {
  460. const handler = toFetchHandler(fakeApi())
  461. it('404s unknown paths and non-POST non-stream methods', async () => {
  462. expect((await handler.fetch(new Request('http://x/other', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' }))).status).toBe(404)
  463. expect((await handler.fetch(new Request('http://x/api/session.list', { method: 'GET' }))).status).toBe(404)
  464. expect((await handler.fetch(new Request('http://x/api/no.such', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ type: 'client-request', rpcId: 'r', method: 'no.such', payload: {} }) }))).status).toBe(404)
  465. })
  466. it('400s a non-JSON body', async () => {
  467. const response = await handler.fetch(new Request('http://x/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: 'not json' }))
  468. expect(response.status).toBe(400)
  469. })
  470. it('rejects a malformed envelope with bad-request and the invalid-request sentinel rpcId', async () => {
  471. const response = await handler.fetch(new Request('http://x/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ nope: true }) }))
  472. expect(response.status).toBe(200)
  473. const body = await response.json() as { rpcId: string; result: { ok: boolean; error?: { code: string } } }
  474. expect(body.rpcId).toBe('invalid-request')
  475. expect(body.result.error?.code).toBe('bad-request')
  476. })
  477. it('rejects a method/path mismatch echoing the envelope rpcId', async () => {
  478. const body = JSON.stringify({ type: 'client-request', rpcId: 'r-9', method: 'session.cancel', payload: {} })
  479. const response = await handler.fetch(new Request('http://x/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body }))
  480. const parsed = await response.json() as { rpcId: string; result: { error?: { message: string } } }
  481. expect(parsed.rpcId).toBe('r-9')
  482. expect(parsed.result.error?.message).toContain('does not match path')
  483. })
  484. it('rejects an invalid payload with the zod issues attached', async () => {
  485. const body = JSON.stringify({ type: 'client-request', rpcId: 'r-10', method: 'session.cancel', payload: {} })
  486. const response = await handler.fetch(new Request('http://x/api/session.cancel', { method: 'POST', headers: { 'content-type': 'application/json' }, body }))
  487. const parsed = await response.json() as { result: { error?: { code: string; details: { issues: unknown[] } } } }
  488. expect(parsed.result.error?.code).toBe('bad-request')
  489. expect(parsed.result.error?.details.issues.length).toBeGreaterThan(0)
  490. })
  491. it('500s when the impl itself throws', async () => {
  492. const crashing = toFetchHandler(fakeApi({ crashOn: 'session.list' }))
  493. const body = JSON.stringify({ type: 'client-request', rpcId: 'r-11', method: 'session.list', payload: {} })
  494. const response = await crashing.fetch(new Request('http://x/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body }))
  495. expect(response.status).toBe(500)
  496. expect(await response.text()).toContain('impl crashed')
  497. })
  498. it('routes /api/respond, rejecting malformed client-responses as a receipt', async () => {
  499. const good = JSON.stringify({ type: 'client-response', rpcId: 'known', result: { ok: true, value: null } })
  500. const goodReceipt: unknown = await (await handler.fetch(new Request('http://x/api/respond', { method: 'POST', headers: { 'content-type': 'application/json' }, body: good }))).json()
  501. expect(goodReceipt).toEqual({ accepted: true })
  502. const bad = JSON.stringify({ type: 'client-request', rpcId: 'r', method: 'x', payload: {} })
  503. const badReceipt: unknown = await (await handler.fetch(new Request('http://x/api/respond', { method: 'POST', headers: { 'content-type': 'application/json' }, body: bad }))).json()
  504. expect(badReceipt).toEqual({ accepted: false, reason: 'bad-response' })
  505. })
  506. it('accepts (url, init) form fetch invocation', async () => {
  507. const body = JSON.stringify({ type: 'client-request', rpcId: 'r-12', method: 'session.list', payload: {} })
  508. const response = await handler.fetch('http://x/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body })
  509. expect(response.status).toBe(200)
  510. })
  511. })
  512. describe('SSE streams through the carrier', () => {
  513. it('yields mux frames as ServerRequest narrow forms and completes', async () => {
  514. const ac = new AbortController()
  515. const frames = await collect(client().events.mux({}, ac.signal))
  516. expect(frames).toHaveLength(1)
  517. expect(frames[0]?.payload).toMatchObject({ type: 'session/subscribed' })
  518. expect(frames[0]?.rpcId).toBe('frame-0')
  519. })
  520. it('yields host frames', async () => {
  521. const ac = new AbortController()
  522. const frames = await collect(client().events.host({}, ac.signal))
  523. expect(frames[0]?.payload).toMatchObject({ type: 'host/session-removed' })
  524. })
  525. it('drops frames after the consumer aborts mid-stream', async () => {
  526. const many = Array.from({ length: 50 }, (_, i): MuxFrame => ({ type: 'session/subscribed', sessionId: `s${String(i)}` as never, lastSeq: i }))
  527. const ac = new AbortController()
  528. const received: RpcRequest<MuxFrame>[] = []
  529. for await (const envelope of client(fakeApi({ muxFrames: many })).events.mux({}, ac.signal)) {
  530. received.push(envelope)
  531. if (received.length === 2) break // generator return → reader.cancel path
  532. }
  533. expect(received).toHaveLength(2)
  534. })
  535. it('swallows a reader.cancel rejection on early exit', async () => {
  536. const encoder = new TextEncoder()
  537. const body = new ReadableStream<Uint8Array>({
  538. start(controller) {
  539. const frame = { type: 'server-request', rpcId: 'f0', method: 'session/subscribed', payload: { type: 'session/subscribed', sessionId: 's', lastSeq: -1 } }
  540. controller.enqueue(encoder.encode(`data: ${JSON.stringify(frame)}\n\n`))
  541. // stream intentionally left open: the consumer breaks first
  542. },
  543. cancel() {
  544. throw new Error('cancel refused')
  545. },
  546. })
  547. const c = new InProcessApiClient({ fetch: async () => new Response(body, { headers: { 'content-type': 'text/event-stream' } }) })
  548. const received: RpcRequest<MuxFrame>[] = []
  549. for await (const envelope of c.events.mux({}, new AbortController().signal)) {
  550. received.push(envelope)
  551. break
  552. }
  553. expect(received).toHaveLength(1)
  554. })
  555. it('surfaces a mid-stream impl failure as one stream/error frame, then the stream ends', async () => {
  556. const api = fakeApi()
  557. api.events.mux = (_request, _signal) => (async function * (): AsyncGenerator<RpcRequest<MuxFrame>> {
  558. yield { rpcId: RpcId('f0'), payload: { type: 'session/subscribed', sessionId: 's' as never, lastSeq: -1 } }
  559. throw new Error('stream source died')
  560. })()
  561. const frames = await collect(client(api).events.mux({}, new AbortController().signal))
  562. expect(frames).toHaveLength(2)
  563. expect(frames[1]?.payload).toMatchObject({ type: 'stream/error', error: { code: 'internal' } })
  564. })
  565. })
  566. describe('client respond and transport failures', () => {
  567. it('passes a client-response through and parses the receipt', async () => {
  568. const receipt = await client().respond({ type: 'client-response', rpcId: RpcId('known'), result: { ok: true, value: null } })
  569. expect(receipt).toEqual({ accepted: true })
  570. const late = await client().respond({ type: 'client-response', rpcId: RpcId('late'), result: { ok: true, value: null } })
  571. expect(late).toEqual({ accepted: false, reason: 'not-pending' })
  572. })
  573. it('throws on non-OK unary and respond and stream transport', async () => {
  574. const broken = new InProcessApiClient({ fetch: async () => new Response('down', { status: 503 }) })
  575. await expect(broken.sessions.list({})).rejects.toThrow('transport failure for /api/session.list: HTTP 503')
  576. await expect(broken.respond({ type: 'client-response', rpcId: RpcId('r'), result: { ok: true, value: null } }))
  577. .rejects.toThrow('transport failure for /api/respond')
  578. await expect(collect(broken.events.mux({}, new AbortController().signal))).rejects.toThrow('transport failure for /api/events.mux')
  579. })
  580. it('throws on an rpcId echo mismatch', async () => {
  581. const lying = new InProcessApiClient({
  582. fetch: async () => Response.json({ type: 'server-response', rpcId: 'someone-else', result: { ok: true, value: { items: [] } } }),
  583. })
  584. await expect(lying.sessions.list({})).rejects.toThrow('rpcId mismatch')
  585. })
  586. })
  587. describe('envelope observation', () => {
  588. it('batches envelopes per microtask and isolates a throwing listener', async () => {
  589. const c = client()
  590. const batches: (readonly RpcMessage[])[] = []
  591. const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
  592. const unsubscribeThrowing = c.subscribeEnvelopes(() => { throw new Error('observer bug') })
  593. const unsubscribe = c.subscribeEnvelopes((batch) => { batches.push(batch) })
  594. await c.sessions.list({})
  595. await new Promise((resolve) => { setTimeout(resolve, 0) })
  596. // request and response tap in separate microtask windows (the await between
  597. // them yields), so both arrive but batch count is timing-defined
  598. expect(batches.flatMap(batch => batch.map(message => message.type))).toEqual(['client-request', 'server-response'])
  599. expect(errorSpy).toHaveBeenCalled()
  600. unsubscribe()
  601. unsubscribeThrowing()
  602. errorSpy.mockRestore()
  603. })
  604. it('skips buffering entirely with no listeners and after unsubscribe', async () => {
  605. const c = client()
  606. const seen: RpcMessage[] = []
  607. const unsubscribe = c.subscribeEnvelopes((batch) => { seen.push(...batch) })
  608. unsubscribe()
  609. await c.sessions.list({})
  610. await new Promise((resolve) => { setTimeout(resolve, 0) })
  611. expect(seen).toHaveLength(0)
  612. })
  613. it('coalesces multiple calls in one microtask window into one flush', async () => {
  614. const c = client()
  615. const batches: (readonly RpcMessage[])[] = []
  616. c.subscribeEnvelopes((batch) => { batches.push(batch) })
  617. await Promise.all([c.sessions.list({}), c.host.describe({})])
  618. await new Promise((resolve) => { setTimeout(resolve, 0) })
  619. const total = batches.reduce((n, batch) => n + batch.length, 0)
  620. expect(total).toBe(4)
  621. })
  622. })
  623. describe('resolveBase', () => {
  624. it('prefers a real location.origin and falls back to the internal authority', async () => {
  625. class Probe extends AbstractApiClient {
  626. urls: string[] = []
  627. protected async doFetch(input: URL): Promise<Response> {
  628. this.urls.push(input.href)
  629. return Response.json({ type: 'server-response', rpcId: this.lastMinted, result: { ok: true, value: { items: [] } } })
  630. }
  631. lastMinted = ''
  632. protected override mintRpcId(): ReturnType<AbstractApiClient['mintRpcId']> {
  633. const id = super.mintRpcId()
  634. this.lastMinted = id
  635. return id
  636. }
  637. }
  638. const probe = new Probe()
  639. await probe.sessions.list({})
  640. expect(probe.urls[0]).toMatch(/^http:\/\/dsh\.internal\//)
  641. const globalWithLocation = globalThis as { location?: { origin?: string } }
  642. globalWithLocation.location = { origin: 'http://host.example' }
  643. try {
  644. const probe2 = new Probe()
  645. await probe2.sessions.list({})
  646. expect(probe2.urls[0]).toMatch(/^http:\/\/host\.example\//)
  647. globalWithLocation.location = { origin: 'null' } // sandboxed iframe shape
  648. const probe3 = new Probe()
  649. await probe3.sessions.list({})
  650. expect(probe3.urls[0]).toMatch(/^http:\/\/dsh\.internal\//)
  651. } finally {
  652. delete globalWithLocation.location
  653. }
  654. })
  655. })